【Spring Boot】Controllerでリクエストパラメーターを受け取る
フォームから送信された値をControllerクラスで受け取る
@RequestParamアノテーションの使い方についてメモします。
Thymeleafテンプレート
<form action="/result" method="post"> <input type="number" name="id"> <button type="submit"></button> </form>
※buttonに直接値を持たせる場合
(Thymeleafのth:value属性で値を指定する)
(Thymeleafのth:value属性で値を指定する)
<form action="/result" method="post"> <button type="submit" name="id" th:value="1"></button> </form>
コントローラークラス
@RequestParamアノテーションの()内の引数に、フォームからpostされるデータのname属性の値を指定する。postされるデータの値がアノテーションがつけられたInteger型引数idに渡される。
@Controller
@RequestMapping("/result")
public class ResultController {
@PostMapping
public String buyItem(@RequestParam("id")Integer id) {
//メソッド内で行う処理
return "result";
}
}
