Spring Bootで作成したアプリケーションで、Getパラメータを取得する方法を紹介します。URIテンプレートを使用し、URLパラメータを取得する方法も紹介します。
目次
プロジェクトの作成
以下を参照してください。
あわせて読みたい
![](https://lifehack.world/wp-content/uploads/2023/01/code-html-digital-coding-web-1076536-1-300x169.jpg)
![](https://lifehack.world/wp-content/uploads/2023/01/code-html-digital-coding-web-1076536-1-300x169.jpg)
Java Spring Boot 3でWeb Applicationを作成する
Spring Boot 3でWeb Applicationを作成するチュートリアルです。IDEにはIntellij IDEAを、ビルドツールにはGradleを使用します。Hello Worldを作成し、ソースコードを修...
Getパラメータの取得
以下を追加します。
@RestController
public class HelloController {
@GetMapping("/hello2")
public String sayHello2(@RequestParam("name") String name, @RequestParam("age") int age) {
return String.format("ようこそ、%sさん!あなたは%d歳です。", name, age);
}
}
以下の書式です。
@RequestParam(“Getパラメータ名”) 型 Java内での変数名
ブラウザにアクセスしてみます。
nameとageで指定したGetパラメタを受け取って表示してくれました。
![](https://lifehack.world/wp-content/uploads/2023/03/DraggedImage.png)
@RequestParamアノテーションの省略
なお、以下のようにGetパラメータ名とJava内での変数名が等しい場合は、RequestParam
のアノテーションを省略することが可能です。
@GetMapping("/hello3")
public String sayHello3(String name, int age) {
return String.format("Hello, %s. Your age is %d", name, age);
}
![](https://lifehack.world/wp-content/uploads/2023/03/DraggedImage-1.png)
URLパラメータの取得
以下のようにすると、/hello4/ほげほげ
のようにURLから渡されたパラメータを取得することが可能です。
@GetMapping("/hello4/{name}")
public String sayHello4(@PathVariable("name") String name) {
return String.format("Hello, %s!", name);
}
![](https://lifehack.world/wp-content/uploads/2023/03/DraggedImage-2.png)
{xxx}
で指定した部分を、URIテンプレート変数と呼びます。