@RequestParam
MainController.java
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class MainController { @RequestMapping("/input") public String input() { return "input"; } @RequestMapping(value = "/output", method = RequestMethod.GET) public String output(@RequestParam("inpMessage") String tmpMessage, Model model) { model.addAttribute("outMessage", tmpMessage); return "output"; } }
index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>入力画面</title> </head> <body> <form th:action="@{/output}" method="get"> <div> <p>メッセージを入力してください。</p> <input type="text" name="inpMessage" /> <button type="submit">送信</button> </div> </form> </body> </html>
output.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>出力画面</title> </head> <body> <p th:text="'入力されたメッセージ:' + ${outMessage}"/> </body> </html>
入力画面
出力画面
point
・パラメータが少ない場合に有効
・Formクラスを作成しないで良いので手軽
@ModelAttribute
MessageForm.java
package com.example.demo; public class MessageForm { private String message1; private String message2; public String getMessage1() { return message1; } public void setMessage1(String message1) { this.message1 = message1; } public String getMessage2() { return message2; } public void setMessage2(String message2) { this.message2 = message2; } }
MainController.java
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class MainController { @RequestMapping("/input") public String input() { return "input"; } @RequestMapping(value = "/output", method = RequestMethod.GET) public String output(@ModelAttribute MessageForm messageForm, Model model) { return "output"; } }
input.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>入力画面</title> </head> <body> <form th:action="@{/output}" method="get"> <div> <p>メッセージを入力してください。</p> <input type="text" name="message1" /> <input type="text" name="message2" /> <button type="submit">送信</button> </div> </form> </body> </html>
output.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>出力画面</title> </head> <body> <p th:text="'入力されたメッセージ1:' + ${messageForm.message1}"/> <p th:text="'入力されたメッセージ2:' + ${messageForm.message2}"/> </body> </html>
入力画面
出力画面
point
・パラメータが多い場合に有効
・htmlのnameとFormクラスの変数名は合わせること