この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:7
ページ更新者:guest
更新日時:2026-06-11 07:12:00

タイトル: 導入方法と基本動作
SEOタイトル: Thymeleaf 導入と基本動作完全ガイド (Spring Boot 連携)

この記事の要点
  • Thymeleaf は HTML5 と互換のテンプレートエンジン。Spring Boot で最も使われる
  • 導入は pom.xmlspring-boot-starter-thymeleaf を追加するだけ
  • テンプレートは src/main/resources/templates/ に配置 → Controller 戻り値の文字列でファイル名指定
  • HTML タグに th:text / th:if / th:each / th:href 等の属性を追加して動的化
  • 名前空間 xmlns:th=&quot;http://www.thymeleaf.org&quot;<html> タグに宣言する (任意だが慣例)

Thymeleaf とは

Thymeleaf は HTML5 と互換のあるテンプレートエンジン。Spring Boot の標準的なビュー技術として広く使われます。最大の特徴は 「ブラウザでテンプレートを直接開いてもデザインが崩れない」こと (Natural Templates) で、JSP の代替としてデファクトの座にあります。

導入手順 (Spring Boot)

1. 依存関係の追加

<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- Spring Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Gradle の場合:

// build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

2. ディレクトリ構成

src/main/
├── java/com/example/demo/
│   ├── DemoApplication.java
│   └── HelloController.java
└── resources/
    ├── application.properties
    ├── static/
    │   └── css/style.css
    └── templates/
        ├── index.html
        └── layout/base.html

3. Controller

// HelloController.java
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping(&quot;/&quot;)
    public String index(Model model) {
        model.addAttribute(&quot;name&quot;, &quot;太郎&quot;);
        model.addAttribute(&quot;messages&quot;, List.of(&quot;こんにちは&quot;, &quot;Hello&quot;, &quot;Bonjour&quot;));
        return &quot;index&quot;;   // → src/main/resources/templates/index.html
    }
}

4. テンプレート (index.html)

<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf サンプル</title>
</head>
<body>
    <h1>こんにちは、<span th:text="${name}">ゲスト</span> さん</h1>

    <ul>
        <li th:each="msg : ${messages}" th:text="${msg}">メッセージ</li>
    </ul>
</body>
</html>

ブラウザで開くと「ゲスト」「メッセージ」と表示される (Natural Templates)。Spring Boot 経由なら動的に「太郎」「こんにちは / Hello / Bonjour」に置き換わります。

5. 起動と確認

# Maven
mvn spring-boot:run
# Gradle
./gradlew bootRun

# ブラウザで http://localhost:8080/ にアクセス

主要な Thymeleaf 属性

属性用途
th:textテキスト置換 (HTML エスケープ)<span th:text="${name}"></span>
th:utextテキスト置換 (エスケープなし)<div th:utext="${html}"></div>
th:if / th:unless条件分岐<p th:if="${user.admin}">管理者</p>
th:switch / th:caseswitch後述
th:each繰り返し<li th:each="m : ${list}"></li>
th:hrefリンク URL<a th:href="@{/users/{id}(id=${u.id})}">
th:src画像 URL<img th:src="@{/img/logo.png}">
th:actionフォーム action<form th:action="@{/login}">
th:valueinput の値<input th:value="${name}">
th:fieldフォームバインディング<input th:field="*{name}">
th:objectフォームオブジェクト<form th:object="${user}">
th:fragment断片定義<div th:fragment="header">
th:insert / th:replace断片の埋め込み<div th:replace="~{layout/base :: header}">
th:classclass 属性<div th:class="${active} ? 'active' : ''">

条件・繰り返しの例

<!-- if / unless -->
<p th:if="${user.admin}">管理者専用</p>
<p th:unless="${user.admin}">一般ユーザ向け</p>

<!-- switch -->
<div th:switch="${role}">
  <p th:case="'admin'">管理者</p>
  <p th:case="'user'">一般</p>
  <p th:case="*">ゲスト</p>   <!-- default -->
</div>

<!-- each + iterStat -->
<tr th:each="item, stat : ${items}">
  <td th:text="${stat.count}">1</td>     <!-- 1 始まりカウント -->
  <td th:text="${stat.index}">0</td>     <!-- 0 始まりインデックス -->
  <td th:text="${stat.size}">10</td>     <!-- 総数 -->
  <td th:text="${stat.first} ? '先頭' : ''"></td>
  <td th:text="${stat.last}  ? '末尾' : ''"></td>
  <td th:text="${item.name}"></td>
</tr>

URL 表現 @{...}

<!-- 静的リソース -->
<link rel="stylesheet" th:href="@{/css/style.css}">
<img th:src="@{/img/logo.png}">

<!-- パスパラメータ -->
<a th:href="@{/users/{id}(id=${user.id})}">詳細</a>
<!-- → /users/123 -->

<!-- クエリパラメータ -->
<a th:href="@{/search(q=${keyword},page=${page})}">検索</a>
<!-- → /search?q=java&page=2 -->

<!-- 外部 URL -->
<a th:href="@{https://example.com/(ref=${ref})}">外部</a>

レイアウト (Fragment)

<!-- templates/layout/base.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title th:text="${title}">タイトル</title>
</head>
<body>
  <header th:fragment="header">
    <h1>サイト名</h1>
    <nav>...</nav>
  </header>

  <footer th:fragment="footer">
    <p>&copy; 2026</p>
  </footer>
</body>
</html>

<!-- templates/index.html で利用 -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
  <div th:replace="~{layout/base :: header}"></div>

  <main>
    <h2>本文</h2>
  </main>

  <div th:replace="~{layout/base :: footer}"></div>
</body>
</html>

application.properties の設定

# キャッシュ (開発中は false)
spring.thymeleaf.cache=false

# テンプレートディレクトリ
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

# モード (LEGACYHTML5 で XHTML 強制を緩和)
spring.thymeleaf.mode=HTML

# 文字コード
spring.thymeleaf.encoding=UTF-8

# Content-Type
spring.thymeleaf.servlet.content-type=text/html

FAQ

Q: 変更がブラウザに反映されない
A: spring.thymeleaf.cache=false + Spring Boot DevTools 導入。

Q: テンプレートが見つからない
A: ファイルが src/main/resources/templates/ 下にあるか、Controller の戻り値の文字列とファイル名が一致しているか確認。拡張子は付けない。

Q: th:text と th:utext の使い分け
A: 通常は th:text (XSS 対策)。HTML を出力したい安全なデータだけ th:utext

📸 参考画像

※ 旧バージョンから引き継いだ参考画像です。手順・図解の補助としてご覧ください。

参考画像