春だから Spring やろうぜ(その 5)
フォームを利用してみる
今回は
- フォームから入力を受け付ける
- 入力された値はセッションに保存しておく
ところまでやってみる。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title th:text="${title}"/> <link th:href="@{/css/hello.css}" rel="stylesheet" /> </head> <body> <h1 th:text="${title}"/> <p th:text="${message}"/> <form method="post" action="/"> <input type="text" name="input1" /> <input type="submit" value="Click" /> </form> </body> </html>
フォームを用意する。
package jp.mydns.akanekodou.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; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; @Controller @SessionAttributes("message") public class HelloController { @ModelAttribute("message") String message() { return "これは初期メッセージです。"; } @RequestMapping(value="/", method=RequestMethod.GET) public String index(@ModelAttribute("message")String msg, Model model) { System.out.println("@ModelAttribute(\"message\") : " + msg); model.addAttribute("title", "Hello page"); return "hello"; } @RequestMapping(value="/", method=RequestMethod.POST) public String form(@ModelAttribute("message")String msg, @RequestParam("input1")String input1, Model model) { System.out.println("@ModelAttribute(\"message\") : " + msg); String res = "最後の入力 : " + input1; model.addAttribute("title", "Answer page"); model.addAttribute("message", res); return "hello"; } }
@SessionAttributes("message")
で message がセッション変数であることをコントローラーに教える。コントローラー内では @ModelAttribute("message")
を付けて参照ができるようになる。最初にファクトリメソッドで初期化をしている。
@RequestParam
でフォームから送られてきた値を参照できる。
コンソールには直前の値が出ている。