1.

Thymeleaf 入門: Spring Boot 標準テンプレートの記法・レイアウト・JSP との違い

編集
この記事の要点
  • Thymeleaf は Spring Boot 標準のサーバーサイドテンプレートエンジン
  • HTML として開けるのが最大の特徴。デザイナーがそのまま編集可能
  • 基本属性: th:text / th:if / th:each / th:href
  • レイアウト: th:fragment + th:replace / th:insert
  • Spring MVC との連携: model.addAttribute("user", user)${user.name}

Thymeleaf とは

Thymeleaf は Spring Boot 標準のテンプレートエンジン。最大の特徴は th: 属性で記述するため素の HTML としてブラウザで開けること。デザイナーがそのまま編集できるため、JSP に比べて開発フローが分業しやすい。

項目ThymeleafJSP
HTML として開ける×
Spring Boot 標準△ (要設定)
記法HTML 属性 th:*カスタムタグ
レイアウトfragment / decoratorinclude / sitemesh
学習コスト低(HTML が分かれば)

セットアップ (Spring Boot)



    org.springframework.boot
    spring-boot-starter-thymeleaf
src/main/resources/
├── templates/        ← Thymeleaf テンプレート (デフォルト)
│   ├── index.html
│   └── user/
│       ├── list.html
│       └── detail.html
└── static/           ← CSS / JS / 画像
    ├── css/app.css
    └── js/app.js

基本記法




    
    タイトル
    




山田太郎

紹介文
詳細

管理者です

一般ユーザーです

管理者

ユーザー

ゲスト

  • 名前
1 名前

フォーム

エラー 利用規約に同意

Spring MVC との連携

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String list(Model model) {
        model.addAttribute("users", userService.findAll());
        model.addAttribute("title", "ユーザー一覧");
        return "user/list";   // → templates/user/list.html
    }

    @GetMapping("/new")
    public String form(Model model) {
        model.addAttribute("form", new UserForm());
        return "user/edit";
    }

    @PostMapping("/save")
    public String save(@Valid @ModelAttribute("form") UserForm form,
                       BindingResult result,
                       RedirectAttributes ra) {
        if (result.hasErrors()) return "user/edit";

        userService.save(form);
        ra.addFlashAttribute("message", "保存しました");
        return "redirect:/user";
    }
}

レイアウト (fragment)

共通ヘッダ・フッタを切り出して再利用:





    
    共通



サンプルサイト

© 2026 Example





    ユーザー一覧




ユーザー一覧

th:replaceth:insert の違い:

属性動作
th:replace呼び出し側のタグごと置換
th:insert呼び出し側のタグ中に挿入
th:includefragment の中身のみ挿入(非推奨、3.0+ で deprecated)

JS / CSS との連携





ユーティリティオブジェクト


2000/01/01


1,234.56


YAMADA
短縮...


10


000-0000

FAQ

Q: th:textth:utext の違い
A: th:text は HTML エスケープあり(XSS 安全)、th:utext はエスケープなし(XSS 注意、自己責任)。原則 th:text

Q: Thymeleaf 2 と 3 の違い
A: 3.0 から th:include 廃止、~{...} fragment 構文導入、HTML5 への移行など。Spring Boot 2.0+ は Thymeleaf 3 が標準。

Q: 開発中に変更が反映されない
A: spring.thymeleaf.cache=falseapplication.properties に。または DevTools を入れる。本番は cache=true。

編集
Post Share
子ページ
  1. 導入方法と基本動作
  2. メッセージ式
  3. テンプレートフラグメント(ヘッダー等の共有化)
同階層のページ

同階層のページはありません