Spring MVC with Thymeleaf¶
はじめに¶
Spring MVCのView部分にThymeleafを使用したサンプルプログラムを作成します。
Spring_MVC のViewをJSPからThymeleafに置き換えたものになります。
Thymeleafは、HTMLで記述しますが、動的な部分は 属性に記述するため、ThymeleafのHTMLファイルを直接Webブラウザで表示した際に動的な動き以外はほぼ表示することができます。
リクエスト | 処理するコントローラ | 処理後に表示するビュー |
---|---|---|
GET / | WelcomeController | index.html |
GET /echo | EchoController | input.html |
POST /echo | output.html |
Hello worldの表示¶
まず、SpringBootのGradleプロジェクト作成と、Hello worldを表示する次の部分を実装します。
リクエスト | 処理するコントローラ | 処理後に表示するビュー |
---|---|---|
GET / | WelcomeController | index.html |
新規プロジェクト作成¶
IntelliJ IDEA から、Spring Bootプロジェクトを生成します。
依存関係に、Spring WebとThymeleafをチェックします。
生成される build.gradle.ktsの依存関係定義は次です。
dependencies {
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
implementation("org.springframework.boot:spring-boot-starter-web")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
画面の作成¶
HTMLで、Hello worldメッセージを表示するビューを作成します。
. └─src ├─main │ ├─java : : │ └─resources │ ├─static │ └─templates └ index.html
index.html¶
まずは動的要素(Thymeleaf要素)のない素のHTMLを記述します。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h1>Hello Thymeleaf World!</h1>
</body>
</html>
WelcomeController.java¶
ルートパスにHTTPリクエストされると、indexビューを表示するコントローラーを作成します。
. └── src ├── main ├── java └── com └── torutk └── spring └── echo └── WelcomeController.java
package com.torutk.spring.echo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WelcomeController {
@RequestMapping("/")
public String home() {
return "index";
}
}
入力画面の追加¶
index.htmlをThymeleaf仕様に修正¶
<html lang="en" xmlns:th="http://www.thymeleaf.org">
:
<ul>
<li><a th:href="@{/echo}">Echo Application</a></li>
</ul>
html要素の属性に、Thymeleafの名前空間を定義します。
リンク要素に、th:href
でリンク先をコンテキストパスより下の要素を指定します。