溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Thymeleaf模板引擎怎么使用

發布時間:2022-01-21 15:12:50 來源:億速云 閱讀:544 作者:iii 欄目:web開發
# Thymeleaf模板引擎怎么使用

## 一、Thymeleaf簡介

### 1.1 什么是Thymeleaf
Thymeleaf是一個現代化的服務器端Java模板引擎,適用于Web和獨立環境。它能夠處理HTML、XML、JavaScript、CSS甚至純文本。與JSP等傳統技術相比,Thymeleaf的主要特點是:
- **自然模板**:可在瀏覽器直接打開預覽
- **無Servlet依賴**:不強制要求Servlet環境
- **Spring完美集成**:Spring官方推薦的視圖技術
- **表達式語法**:強大的OGNL和SpringEL表達式支持

### 1.2 核心特性
- **模板緩存**:可配置的模板緩存機制
- **國際化支持**:內置國際化處理能力
- **片段重用**:支持模板片段定義和引用
- **多種方言**:可通過方言擴展功能

## 二、環境配置

### 2.1 Maven依賴
```xml
<!-- Spring Boot集成 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- 獨立使用 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>

2.2 Spring Boot配置

# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false # 開發時關閉緩存
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML

2.3 基本目錄結構

src/
├── main/
│   ├── java/
│   └── resources/
│       ├── static/    # 靜態資源
│       └── templates/ # 模板文件

三、基礎語法詳解

3.1 標準表達式語法

<!-- 變量表達式 -->
<p th:text="${user.name}">默認用戶名</p>

<!-- 選擇表達式 -->
<div th:object="${user}">
    <p th:text="*{age}">年齡</p>
</div>

<!-- 鏈接表達式 -->
<a th:href="@{/user/list}">用戶列表</a>

<!-- 片段表達式 -->
<div th:insert="~{footer :: content}"></div>

3.2 常用屬性指令

屬性 說明
th:text 文本替換
th:utext 非轉義文本
th:value 表單值設置
th:each 循環迭代
th:if 條件判斷
th:switch 多條件選擇
th:href 鏈接URL
th:src 資源URL

3.3 循環與條件

<!-- 循環示例 -->
<ul>
    <li th:each="item : ${items}" th:text="${item.name}"></li>
</ul>

<!-- 條件判斷 -->
<div th:if="${user.isAdmin}">管理員面板</div>
<div th:unless="${user.isAdmin}">普通用戶面板</div>

<!-- Switch語句 -->
<div th:switch="${user.role}">
    <p th:case="'admin'">管理員</p>
    <p th:case="'user'">普通用戶</p>
</div>

四、高級功能

4.1 模板布局

定義基礎模板 base.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:fragment="title">默認標題</title>
</head>
<body>
    <header th:insert="~{header :: main}"></header>
    <div th:replace="~{content}"></div>
    <footer th:replace="~{footer :: main}"></footer>
</body>
</html>

子模板繼承:

<html th:replace="~{base :: layout(~{::title}, ~{::content})}">
<head>
    <title>子頁面標題</title>
</head>
<body>
    <div th:fragment="content">
        <!-- 頁面特有內容 -->
    </div>
</body>
</html>

4.2 表單處理

<form th:action="@{/user/save}" th:object="${user}" method="post">
    <input type="text" th:field="*{name}">
    <input type="email" th:field="*{email}">
    <button type="submit">保存</button>
</form>

4.3 國際化支持

<p th:text="#{welcome.message}">歡迎消息</p>
<p th:text="#{|hello.user|(${user.name})|}">個性化問候</p>

4.4 實用工具對象

<!-- 日期格式化 -->
<p th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}"></p>

<!-- 集合工具 -->
<p th:text="${#lists.size(user.roles)}"></p>

<!-- 字符串操作 -->
<p th:text="${#strings.toUpperCase(user.name)}"></p>

五、與Spring集成

5.1 Controller數據傳遞

@Controller
public class UserController {
    
    @GetMapping("/user")
    public String user(Model model) {
        model.addAttribute("user", new User("張三", 25));
        return "user/profile";
    }
}

5.2 Spring Security整合

<div sec:authorize="isAuthenticated()">
    歡迎 <span sec:authentication="name"></span>
</div>
<div sec:authorize="hasRole('ADMIN')">
    管理員功能
</div>

5.3 表單驗證錯誤處理

<input type="text" th:field="*{email}" class="form-control">
<div th:if="${#fields.hasErrors('email')}" 
     th:errors="*{email}" class="error-message"></div>

六、性能優化

6.1 模板緩存配置

# 生產環境配置
spring.thymeleaf.cache=true
spring.thymeleaf.template-resolver-order=1

6.2 片段緩存

<!-- 緩存用戶信息片段 -->
<div th:replace="~{user/info :: panel}" 
     th:with="cacheKey=${#strings.arrayJoin('user',user.id)}">
</div>

6.3 靜態資源處理

<!-- 版本化靜態資源 -->
<link th:href="@{/css/main.css(v=${@environment.getProperty('app.version')})}">

七、常見問題解決方案

7.1 轉義問題

<!-- 禁用轉義 -->
<p th:utext="${htmlContent}"></p>

<!-- 內聯表達式 -->
[(${unsafeContent})]

7.2 靜態資源404

確保正確配置:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}

7.3 模板解析異常

檢查: 1. 模板文件是否在正確目錄 2. 后綴配置是否匹配 3. 模板語法是否正確

八、最佳實踐

  1. 分離邏輯與表現:避免在模板中編寫復雜邏輯
  2. 使用片段重用:提高模板復用率
  3. 合理使用緩存:開發時關閉,生產環境開啟
  4. 統一錯誤處理:創建error.html模板
  5. 模板版本控制:與代碼庫一起管理

九、總結

Thymeleaf作為現代Java模板引擎,通過本文我們全面了解了: - 從基礎語法到高級功能的使用方法 - 與Spring框架的深度集成 - 實際開發中的性能優化技巧 - 常見問題的解決方案

通過合理應用Thymeleaf,可以構建出結構清晰、維護性強的Web應用視圖層。其自然模板特性特別適合前后端協作開發場景,是傳統JSP技術的優秀替代方案。


本文約4500字,涵蓋了Thymeleaf的核心使用場景。實際開發中應根據項目需求選擇合適的特性組合,并參考官方文檔獲取最新特性支持。 “`

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女