Spring Getでパラメータを取得
戻る
公開日:2021/1/23
環境情報
Spring Boot | v2.4.2 |
java | 11.0.6 |
SpringでGetパラメータを取得するときは、こんな感じ
package com.example.demo.trySpring;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloController {
@GetMapping("/hello")
public String getHello(@RequestParam(required = false) String message,Model model) {
// GETで受け取ったmessageを画面に出すためにcompleteMessageにセット
model.addAttribute("completeMessage", message);
return "hello";
}
}
赤文字部分で指定しています。
required = falseを使わないと以下のエラーが出ます。
Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'message' is not present]「http://localhost:8080/hello?message=aiue」にアクセスると画面に出ました。
「http://localhost:8080/hello」でもエラーになりません。
ちなみにhello.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> hello</h1>
<p th:text="${completeMessage}">
</body>
</html>デフォルト値を指定する方法は以下
public String hello(@RequestParam(defaultValue = "aiue") String message,Model model) 戻る
