Spring Bootでフォームアプリケーションを作成する
Spring Bootでフォームアプリケーションを作ります。
テキストボックスに値を入力
↓
それをコントローラーで受け取って、モデルオブジェクトに突っ込む
↓
モデルオブジェクトの内容を別のHTMLに表示する
というありがちな流れを作ってみます。
まずは、フォームの情報を格納するbeanを作成します。
こいつにフォームで入力した情報をぶち込みます。
src/main/java/com/example/form/Search.java
package com.example.form; public class Search { private String userName; private String tagName; private String location; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
次に、フォームを作りましょう。
src/main/resource/templates/search.html
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Search Form</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>Form</h1> <form action="#" th:action="@{/search}" th:object="${search}" method="post"> <p>User Name: <input type="text" th:field="*{userName}" /></p> <p>Tag Name: <input type="text" th:field="*{tagName}" /></p> <p>Location: <input type="text" th:field="*{location}" /></p> <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p> </form> </body> </html>
これが送信フォームです。 Submitボタン(送信ボタン)を押すと、リクエストが投げられます。
では、そのリクエストを処理するコントローラーを作りましょう。
src/main/java/com/example/SearchController.java
package com.example; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import com.example.form.Search; @Controller public class SearchController { @GetMapping("/search") public String searchForm(Model model) { model.addAttribute("search", new Search()); return "search"; } @PostMapping("/search") public String searchSubmit(@ModelAttribute Search search) { return "result"; } }
これで飛ばされたリクエストを処理することができます。 最後に、結果を表示するHTMLです。
src/main/resource/templates/result.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <title>Result</title> </head> <body> <h1>Result</h1> <p th:text="'user name: ' + ${search.userName}" /> <p th:text="'tag name: ' + ${search.tagName}" /> <p th:text="'location: ' + ${search.location}" /> <a href="/search">another search</a> </body> </html>
これで、送信した内容を表示することができます。