引言:為什么選擇 Thymeleaf?
Thymeleaf 是一個現代化的服務器端 Java 模板引擎,專為 Web 開發而設計。與 JSP 不同,Thymeleaf 模板是純 HTML 文件,可以直接在瀏覽器中預覽,無需后端服務器支持。這種"自然模板"特性讓前端開發和后端開發可以無縫協作。Spring Boot 官方推薦使用 Thymeleaf 作為視圖技術,它提供了:
-
簡潔優雅的語法
-
強大的表達式語言
-
與 Spring 生態的完美集成
-
豐富的布局功能
-
開箱即用的國際化支持
本文將帶你從零開始,全面掌握 Spring Boot 中 Thymeleaf 的使用。
一、環境搭建
1. 創建 Spring Boot 項目
使用 Spring Initializr (https://start.spring.io/) 創建項目,選擇以下依賴:
-
Spring Web
-
Thymeleaf
2. Maven 依賴
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
</dependencies>
3. 目錄結構
src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ ├── controller
│ │ ├── model
│ │ └── DemoApplication.java
│ └── resources
│ ├── static # 靜態資源(CSS, JS, 圖片)
│ ├── templates # Thymeleaf 模板
│ └── application.properties
二、基礎配置
application.properties 配置
# Thymeleaf 配置
spring.thymeleaf.cache=false # 開發時關閉緩存
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8# 靜態資源路徑
spring.resources.static-locations=classpath:/static/
三、第一個 Thymeleaf 頁面
1. 創建控制器
@Controller
public class HomeController {@GetMapping("/")public String home(Model model) {model.addAttribute("message", "Hello, Thymeleaf!");model.addAttribute("currentDate", new Date());return "home"; // 對應 templates/home.html}
}
2. 創建模板文件 (templates/home.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Thymeleaf 入門</title>
</head>
<body><h1 th:text="${message}">默認標題</h1><p>當前時間:<span th:text="${#dates.format(currentDate, 'yyyy-MM-dd HH:mm:ss')}"></span></p><!-- 使用 Thymeleaf 表達式 --><div th:if="${not #strings.isEmpty(message)}"><p>消息長度:<span th:text="${#strings.length(message)}"></span></p></div><!-- 鏈接表達式 --><a th:href="@{/about}">關于我們</a>
</body>
</html>
3. 運行并訪問
啟動應用后訪問?http://localhost:8080,你將看到:
-
"Hello, Thymeleaf!" 標題
-
格式化的當前時間
-
消息長度計算
-
指向關于頁面的鏈接
四、Thymeleaf 核心語法
1. 變量表達式 (${...})
用于訪問模型中的數據:
<p th:text="${user.name}">用戶名</p>
<p th:text="${user.age > 18 ? '成年' : '未成年'}">年齡狀態</p>
2. 選擇表達式 (*{...})
與?th:object
?配合使用:
<div th:object="${user}"><p>姓名: <span th:text="*{name}"></span></p><p>郵箱: <span th:text="*{email}"></span></p>
</div>
3. 消息表達式 (#{...})
用于國際化:
<p th:text="#{welcome.message}">歡迎信息</p>
4. 鏈接表達式 (@{...})
生成正確的 URL:
<a th:href="@{/users/{id}/profile(id=${userId})}">用戶資料</a>
<img th:src="@{/images/logo.png}">
5. 片段表達式 (~{...})
包含模板片段:
<div th:insert="~{fragments/header :: header}"></div>
五、常用功能詳解
1. 條件判斷
<div th:if="${user.isAdmin}"><button>管理面板</button>
</div><div th:unless="${user.active}"><p class="warning">賬戶未激活</p>
</div><div th:switch="${user.role}"><p th:case="'admin'">管理員</p><p th:case="'user'">普通用戶</p><p th:case="*">未知角色</p>
</div>
2. 循環遍歷
<table><tr th:each="user, iterStat : ${users}"><td th:text="${iterStat.index + 1}">序號</td><td th:text="${user.name}">姓名</td><td th:text="${user.email}">郵箱</td><td><span th:if="${user.active}" th:text="激活"></span><span th:unless="${user.active}" th:text="未激活"></span></td></tr>
</table>
3. 表單處理
<form th:action="@{/users}" th:object="${user}" method="post"><input type="text" th:field="*{name}" placeholder="姓名"><input type="email" th:field="*{email}" placeholder="郵箱"><button type="submit">保存</button><!-- 顯示字段錯誤 --><div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="error"></div>
</form>
4. 布局模板
layout.html (布局文件)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title th:text="${title}">默認標題</title><th:block th:replace="fragments/head :: head"></th:block>
</head>
<body><header th:replace="fragments/header :: header"></header><main><!-- 內容區域 --><div th:replace="${view}"></div></main><footer th:replace="fragments/footer :: footer"></footer>
</body>
</html>
home.html (具體頁面)
<!DOCTYPE html>
<html th:replace="~{layout :: layout(~{::title}, ~{::main})}">
<head><title>首頁</title>
</head>
<body><main><h1>歡迎來到首頁</h1><p>這是主要內容區域</p></main>
</body>
</html>
六、實用技巧與最佳實踐
1. 工具對象
Thymeleaf 提供了一系列實用工具:
-
#dates
:日期格式化 -
#strings
:字符串操作 -
#numbers
:數字格式化 -
#lists
:集合操作 -
#arrays
:數組操作 -
#objects
:對象操作<p th:text="${#dates.format(user.birthday, 'yyyy年MM月dd日')}"></p> <p th:text="${#strings.capitalize(user.name)}"></p> <p th:text="${#lists.size(user.roles)}"></p>
2. 內聯表達式
使用?[[...]]
?或?[(...)]
?在 HTML 屬性中內聯表達式:
<script th:inline="javascript">var userId = [[${user.id}]];var userName = /*[[${user.name}]]*/ '默認名稱';
</script><p data-user-id="${user.id}">用戶ID: [[${user.id}]]</p>
3. 模板緩存管理
開發環境關閉緩存,生產環境開啟緩存:
# application-dev.properties
spring.thymeleaf.cache=false# application-prod.properties
spring.thymeleaf.cache=true
4. 自定義方言
創建自定義 Thymeleaf 處理器:
public class AlertDialect extends AbstractProcessorDialect {public AlertDialect() {super("Alert Dialect", "alert", 1000);}@Overridepublic Set<IProcessor> getProcessors(String dialectPrefix) {return Set.of(new AlertTagProcessor(dialectPrefix));}
}public class AlertTagProcessor extends AbstractElementTagProcessor {// 實現自定義標簽處理邏輯
}
注冊方言:
@Configuration
public class ThymeleafConfig {@Beanpublic AlertDialect alertDialect() {return new AlertDialect();}
}
七、常見問題解決
1. 靜態資源加載問題
確保路徑正確:
<!-- 正確方式 -->
<link th:href="@{/css/style.css}" rel="stylesheet"><!-- 錯誤方式 -->
<link href="/css/style.css" rel="stylesheet">
2. 表單綁定失敗
確保表單對象和字段名匹配:
// Controller
@PostMapping("/save")
public String saveUser(@ModelAttribute("userForm") User user) {// ...
}
<!-- 模板 -->
<form th:object="${userForm}"><input th:field="*{name}">
</form>
3. 國際化支持
配置消息源:
# application.properties
spring.messages.basename=messages
創建 messages.properties:
welcome.message=歡迎您, {0}!
在模板中使用:
<p th:text="#{welcome.message(${user.name})}"></p>
八、進階學習資源
-
官方文檔:
-
Thymeleaf 官方文檔
-
Spring Boot Thymeleaf 文檔
-
-
推薦書籍:
-
"Thymeleaf: Practical Natural Templates" by José Samper
-
"Spring Boot in Action" by Craig Walls
-
-
實戰項目:
-
GitHub 搜索 "spring-boot-thymeleaf-example"
-
Spring 官方示例項目
-
總結
Thymeleaf 作為 Spring Boot 的官方推薦模板引擎,提供了強大的功能和優雅的語法。通過本文的學習,你應該能夠:
-
搭建 Spring Boot + Thymeleaf 開發環境
-
使用基礎表達式和常用功能
-
實現復雜的頁面布局
-
處理表單和驗證
-
解決常見開發問題
Thymeleaf 的"自然模板"特性使其成為現代 Web 開發的理想選擇,它讓前后端協作更加高效。現在就開始在你的項目中嘗試使用 Thymeleaf 吧!