Spring Boot 整合 Thymeleaf 模板引擎:從零開始的完整指南

引言:為什么選擇 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,你將看到:

  1. "Hello, Thymeleaf!" 標題

  2. 格式化的當前時間

  3. 消息長度計算

  4. 指向關于頁面的鏈接

四、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>

八、進階學習資源

  1. 官方文檔

    • Thymeleaf 官方文檔

    • Spring Boot Thymeleaf 文檔

  2. 推薦書籍

    • "Thymeleaf: Practical Natural Templates" by José Samper

    • "Spring Boot in Action" by Craig Walls

  3. 實戰項目

    • GitHub 搜索 "spring-boot-thymeleaf-example"

    • Spring 官方示例項目

總結

Thymeleaf 作為 Spring Boot 的官方推薦模板引擎,提供了強大的功能和優雅的語法。通過本文的學習,你應該能夠:

  1. 搭建 Spring Boot + Thymeleaf 開發環境

  2. 使用基礎表達式和常用功能

  3. 實現復雜的頁面布局

  4. 處理表單和驗證

  5. 解決常見開發問題

Thymeleaf 的"自然模板"特性使其成為現代 Web 開發的理想選擇,它讓前后端協作更加高效。現在就開始在你的項目中嘗試使用 Thymeleaf 吧!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/95828.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/95828.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/95828.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

pytest介紹(python測試框架)(@pytest.mark.parametrize、@pytest.fixtures)

文章目錄**1. 核心特點**- **簡潔易用**&#xff1a;無需復雜的配置&#xff0c;只需編寫簡單的函數或類即可進行測試。- **豐富的斷言**&#xff1a;直接使用 Python 內置的 assert 語句&#xff0c;失敗時提供詳細的錯誤信息。- **自動發現測試**&#xff1a;通過約定的命名規…

[Python 基礎課程]繼承

在 Python 的面向對象編程&#xff08;OOP&#xff09;中&#xff0c;繼承&#xff08;Inheritance&#xff09; 是一種重要的機制&#xff0c;它允許一個類&#xff08;稱為子類或派生類&#xff09;從另一個類&#xff08;稱為父類、基類或超類&#xff09;中繼承屬性和方法。…

QT之設計器組件功能(8大類55個組件)

組件名稱 功能描述關鍵屬性1. Layouts&#xff08;布局組件&#xff09;(1) Vertical Layout&#xff08;垂直布局&#xff09;將子控件按垂直方向依次排列layoutSpacing&#xff1a;控件之間的間距layoutMargin&#xff1a;布局邊緣的邊距layoutStretch&#xff1a;設置各控件…

java中list的api詳細使用

在Java中&#xff0c;List是集合框架中最常用的接口之一&#xff0c;繼承自Collection&#xff0c;代表有序、可重復的元素集合&#xff08;允許null元素&#xff09;。其核心實現類有ArrayList&#xff08;數組實現&#xff0c;隨機訪問高效&#xff09;、LinkedList&#xff…

Azure AI Search 探索總結

Azure AI Search 原名 Azure Cognitive Service&#xff0c;是Azure中用來給AI項目構建知識庫的組件。知識庫本質和數據庫很像&#xff0c;但是內部的存儲結構和檢索算法不一樣。比如并不是知識庫的每一列都可以用來過濾、檢索或group by&#xff0c;而是要根據實際情況配置。A…

高效解決 pip install 報錯 SSLError: EOF occurred in violation of protocol

高效解決 pip install 報錯 SSLError: EOF occurred in violation of protocol 標簽&#xff1a; Python, pip, SSLError, Clash, 網絡代理, 問題解決 一、問題描述 在Python開發中&#xff0c;pip 是我們最親密的伙伴。然而&#xff0c;當你身處需要科學上網的環境&#xff0c…

CSS 核心知識點全解析:從基礎到實戰應用

大家好&#xff01;今天這篇文章將系統總結 CSS 的核心知識點&#xff0c;從最基礎的樣式引入到復雜的選擇器應用&#xff0c;再到盒子模型、文本處理等實戰技巧&#xff0c;全程結合代碼示例&#xff0c;讓你輕松掌握 CSS 的精髓。一、CSS 是什么&#xff1f;為什么需要它&…

ClickHouse的學習與了解

什么是ClickHouse&#xff1f; ClickHouse是一個用于聯機分析(OLAP)的列式數據庫管理系統(DBMS)。 在傳統的行式數據庫系統中&#xff0c;數據按如下順序存儲&#xff1a;RowWatchIDJavaEnableTitleGoodEventEventTime#0893543506621Investor Relations12016/5/18 5:19#1903295…

安卓11 12系統修改定制化_____修改系統 解鎖system分區 去除data加密 自由刪減系統應用

在定制化系統中。修改系統分區 解鎖system。讓用戶可以自由刪減應用。這個在定制化服務中比較常見。對于此項修改服務。需要我們了解基礎的分區常識以及常用的幾種基礎修改步驟。 通過博文了解?????? 1??????-----修改rom 解鎖 system 分區有什么意義 2????…

JetPack系列教程(八):PDF庫——讓Android應用也能優雅“翻頁”

JetPack系列教程&#xff08;八&#xff09;&#xff1a;PDF庫——讓Android應用也能優雅“翻頁” 在Android開發的世界里&#xff0c;加載PDF文件一直是個讓人又愛又恨的“小妖精”。愛它&#xff0c;因為PDF是文檔界的“萬能鑰匙”&#xff1b;恨它&#xff0c;因為原生Andr…

Three.js三大組件:場景(Scene)、相機(Camera)、渲染器(Renderer)

上一篇中我們學習了第一個Three.js場景"Hello World"。這一篇就來學習three.js的核心組件。 此圖來源&#xff08;Three.js中文網&#xff09; three.js的核心由三大組件構成&#xff1a;場景(Scene)、相機(Camera)和渲染器(Renderer)。下面我將詳細介紹這三大件的作…

AI幻覺終結之后:GPT-5開啟的“可靠性”新賽道與開發者生存指南

摘要&#xff1a; Sam Altman關于GPT-5將基本終結幻覺的宣告&#xff0c;不僅僅是一次技術升級&#xff0c;它標志著一個“萬物皆可AI&#xff0c;但萬事皆需驗證”的混亂時代的結束。本文將從一個全新的戰略視角出發&#xff0c;探討當“可靠性”取代“創造性”成為AI競賽的核…

ubuntu遠程桌面很卡怎么解決?

服務端方案 完成XRDP的性能優化配置&#xff1a; 1. 首先檢查當前的xrdp.ini文件 grep -n "tcp_send_buffer_bytes" /etc/xrdp/xrdp.ini2. 編輯xrdp.ini文件&#xff0c;修改TCP發送緩沖區大小 sudo sed -i s/#tcp_send_buffer_bytes32768/tcp_send_buffer_bytes4194…

[Linux] Linux系統負載監控 Linux服務管理

目錄 Linux系統負載監控 系統負載介紹 查看系統負載 負載解讀 top 命令 Linux服務管理 systemd 介紹 系統啟動管理進程 基本概念 systemd 架構 unit 類型 查看 unit 列表信息 查看單個 unit 信息 控制系統服務 systemctl 命令 unit 配置文件 例&#xff1a;開發…

vector 手動實現 及遇到的各種細節問題

之前對vector的一些功能使用了一下 接下來手動實現一下vector vector的實現和string還是有不小區別的 有很多地方都有細節的問題不同于string的成員變量一個指針一個size一個capacity的成員變量 vector里面存的是三個迭代器iterator 這的迭代器其實就是模版T的指針 這樣就…

OpenStack Neutron中的L2 Agent與L3 Agent:新手友好指南

引言&#xff1a;云網絡的幕后英雄 在當今的云計算世界中&#xff0c;OpenStack作為開源云平臺的佼佼者&#xff0c;為成千上萬的企業提供了靈活、可擴展的基礎設施服務。而在OpenStack的眾多組件中&#xff0c;Neutron&#xff08;網絡服務&#xff09;扮演著至關重要的角色—…

【自用】JavaSE--特殊文件Properties與XML、日志技術

特殊文件概述使用特殊文件可以存儲多個有關系的數據&#xff0c;作為系統的配置信息屬性文件類似于鍵值對&#xff0c;一一對應存儲數據(比如用戶名與密碼)XML文件存儲多個用戶的多個屬性更適合&#xff0c;適合存儲更復雜的數據Properties注&#xff1a;這個屬性文件的后綴即使…

中本聰思想與Web3的困境:從理論到現實的跨越

一、中本聰思想的核心精髓中本聰通過比特幣白皮書提出的核心思想&#xff0c;可歸納為三大支柱&#xff1a;去中心化貨幣體系目標&#xff1a;擺脫中央機構控制&#xff0c;避免通貨膨脹和政治干預&#xff08;如2008年金融危機暴露的中心化風險&#xff09;。實現路徑&#xf…

Centos 用戶管理

一.創建用戶 在 root賬戶 或 sudo 權限下 1. 創建用戶 useradd xiaoyangzi2.為該用戶設置密碼或修改密碼 passwd xiaoyangzi3. 將用戶加入wheel用戶組 在 CentOS 中&#xff0c;屬于 wheel 組的用戶默認可以使用 sudo 權限。 查看所屬用戶組: groups xiaoyangzi將 xiaoyangzi 加…

C++枚舉算法習題

1. 3的倍數枚舉&#xff08;基礎&#xff09;題目&#xff1a;在之間有10和50多少個數是3的倍數&#xff1f;列舉這些數。 解析&#xff1a;枚舉10到50之間的數&#xff0c;判斷是否能被3整除。優化&#xff1a;計算第一個≥10的3的倍數&#xff08;1234&#xff09;&#xff0…