Spring BootでThymeleafを使ってViewを実装してみる。
ThymeleafはWebアプリケーションと親和性の高いテンプレートエンジンです。 テンプレートエンジンとは、雛形となるドキュメントに対し、可変データを埋め込むことで動的にドキュメントを生成する仕組みのことです。
Themeleafを使ってViewを作ってみます。
pom.xmlは以下のように書きます。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
コントローラーは以下のように書きます。
src/main/java/com/example/EchoController.java
package com.example; 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 com.example.form.EchoForm; @Controller @RequestMapping("echo") public class EchoController { @RequestMapping(method = RequestMethod.GET) public String viewInput(Model model) { EchoForm form = new EchoForm(); model.addAttribute(form); return "echo/input"; } @RequestMapping(method = RequestMethod.POST) public String echo(EchoForm form) { return "echo/output"; } }
フォームクラスを作成します。
src/main/java/com/example/form/EchoForm.java
package com.example.form; import java.io.Serializable; public class EchoForm implements Serializable { private static final long serialVersionUID = 1L; private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } }
次にViewの部分です。
src/main/resources/templates/echo/input.html
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <body> <h2>Echo Application</h2> <form action="./output.html" th:action="@{/echo}" th:object="${echoForm}" method="POST"> <div>Input Text</div> <div> <input type="text" name="text" th:field="*{text}"/><br/> <span th:if="${#fields.hasErrors('text')}" th:errors="*{text}">error message</span> </div> <div> <button type="submit">Submit</button> </div> </form> </body> </html>
src/main/resources/templates/echo/output.html
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <body> <h2>出力画面</h2> <div>入力したテキストは...</div> <div> 「<span th:text="*{echoForm.text}">ここに入力した値が表示される</span>」 </div> <br/> <div>です</div> <div> <a href="../index.html" th:href="@{/}">トップ画面に戻る</a> </div> </body> </html>
テキストの出力
式の構文
名称 | 例 | 意味 |
---|---|---|
変数式 | ${echoForm.text} | Thymeleafが管理する変数へアクセスしたり、メソッドを実行できる。プロパティ名を指定することで、フォームオブジェクトなどのModelに格納された情報にアクセスできる。 |
選択変数式 | *{echoForm.text} | 特定のオブジェクトに対するプロパティに連続してアクセスしたい時、th:object="${echoForm}"などと組み合わせて使う。 |
メッセージ式 | #{status.reserved.message} | メッセージをkey-valueで管理するための仕組み |
リンクURL式 | @{/echo} | 指定したURLへのリンクを貼ることができる |