1、認識Thymeleaf
SpringBoot主要支持Thymeleaf、Freemarker、Mustache、 Groovy Templates等模板引擎。Thymeleaf可以輕易地與SpringMVC等Web框架進行集成。Thymeleaf語法並不會破壞文檔的結構,所以Thymeleaf模板依然是有效的HTML文檔。模板還可以被用作工作原型,Thymeleaf會在運行期內替換掉靜態值。它的模板文件能直接在瀏覽器中打開並正確顯示頁面,而不需要啓動整個Web應用程序。
Thymeleaf的使用非常簡單。比如,要輸出“pan_junbiao的博客”字符串,可以很簡單地在模板文件中加入以下代碼:
<p th:text="${userName}?:'pan_junbiao的博客'"></p>
其中,“<p th:text="${userName}>”用來接收控制器傳入的參數“userName”。如果控制器向模板傳入了參數,則Thymeleaf會用“userName”參數的值替換掉“pan_junbiao的博客”。
2、使用Thymeleaf
(1)引入依賴
使用Thymeleaf,首先需要引入依賴。直接在pom.xml文件中加入以下依賴即可。
<!-- 引入thymeleaf模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(2)在模板文件中加入解析
在加入依賴後,還需要在HTML文件中加入命名空間,這樣就能完成Thymeleaf的標籤的渲染。命名空間如下:
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
以下代碼是一個簡單完整的Thymeleaf模板文件。
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用戶信息</title>
</head>
<body>
<p th:text="${userName}?:'pan_junbiao的博客'"></p>
</body>
</html>
(3)配置視圖解析器
在application.properties配置文件中,可以配置Thymeleaf模板解析器屬性,如以下代碼:
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#爲便於測試,在開發時需要關閉緩存
spring.thymeleaf.cache=false
Thymeleaf檢查HTML格式很嚴格。如果HTML格式不對,則會報錯。如果想禁止這種嚴格的語法檢查模式,這可以在application.properties配置文件中加入“spring.thymeleaf.mode=LEGACYHTML5”來解決。在開發過程中,一般將Thymeleaf的模板緩存設置爲關閉,即在application.properties配置文件中加入“spring.thymeleaf.cache=false”。否則,修改之後可能不會及時顯示修改後的內容。
【示例】使用Thymeleaf模板引擎,顯示用戶信息。
(1)創建實體類
在SpringBoot項目中,創建entity目錄(實體類層),並創建User(用戶信息實體類)。
package com.pjb.thymeleafdemo.entity;
/**
* 用戶信息實體類
* @author pan_junbiao
**/
public class User
{
private int id; //用戶編號
private String userName; //用戶姓名
private String blogUrl; //博客地址
private String blogInfo; //博客信息
private String role; //用戶角色
//省略getter與setter方法...
}
(2)創建Controller控制器
創建controller目錄(控制器層),並創建UserController(用戶信息控制器類)。
package com.pjb.thymeleafdemo.controller;
import com.pjb.thymeleafdemo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 用戶信息控制器類
* @author pan_junbiao
**/
@Controller
@RequestMapping("/user")
public class UserController
{
/**
* 獲取用戶信息
*/
@RequestMapping("/getUser")
public String getUser(Model model)
{
//創建用戶信息
User user = new User();
user.setId(1);
user.setUserName("pan_junbiao的博客");
user.setBlogUrl("https://blog.csdn.net/pan_junbiao");
user.setBlogInfo("您好,歡迎訪問 pan_junbiao的博客");
user.setRole("admin");
//將用戶信息保存到Model對象中
model.addAttribute("user",user);
//返回頁面
return "/user/userInfo";
}
}
(2)創建HTML頁面
在resources/templates目錄下,創建user目錄,並在該目錄下創建userInfo.html(用戶信息頁面)。
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用戶信息</title>
<meta name="author" content="pan_junbiao的博客">
</head>
<body>
<h3>使用Thymeleaf模板引擎</h3>
用戶編號:<span th:text="${user.id}"></span><br/>
用戶姓名:<span th:text="${user.userName}"></span><br/>
博客地址:<span th:text="${user.blogUrl}"></span><br/>
博客信息:<span th:text="${user.blogInfo}"></span><br/>
</body>
</html>
執行結果:
3、基礎語法
3.1 常用th標籤
(1)th:text
<div th:text="${userName}"></div>
它用於顯示控制器傳入的userName值。
如果userName不存在,要顯示默認值,則使用以下代碼:
<div th:text="${userName}?:'pan_junbiao的博客'"></div>
(2)th:object
它用於接收後臺傳過來的對象,如以下代碼:
th:object="${userName}"
(3)th:action
它用來指定表單提交地址。
<form th:action="@{/user/}+${user.id}" method="post">
</form>
(4)th:value
它用對象將id的值替換爲value的屬性值。
<input type="text" th:value="${user.id}" name="id"/>
(5)th:field
它用來綁定後臺對象和表單對象數據。Thymeleaf裏的“th:field”等同於“th:name”和“th:value”。
<input type="text" id="userName" name="userName" th:field="${user.userName}" />
3.2 Thymeleaf中的URL寫法
Thymeleaf是通過語法@{...}來處理URL的,需要使用“th:href”和“th:src”等屬性,如以下代碼:
<a th:href="@{https://blog.csdn.net/pan_junbiao}">pan_junbiao的博客</a>
<a th:href="@{js/jquery-3.4.1.min.js}">默認訪問static目錄下的js文件夾</a>
3.3 用Thymeleaf進行條件求值
Thymeleaf通過“th:if”和“th:unless”屬性進行條件判斷。在下面的例子中,<a>標籤只有在“th:if”中的條件成立時才顯示。
<a th:href="@{/login}" th:if="${session.user == null}">登錄</a>
“th:unless”與“th:if”恰好相反——只有當表達式中的條件不成立時才顯示其內容。在下方代碼中,如果用戶session爲空,則不顯示登陸連接。
<a th:href="@{/login}" th:unless="${session.user == null}">登錄</a>
3.4 Switch
Thymeleaf支持Switch結構,如以下代碼:
<div th:switch="${user.role}">
<p th:case="admin">管理員</p>
<p th:case="vip">vip會員</p>
<p th:case="*">普通會員</p>
</div>
在Switch結構中,“*”表示默認情況。
3.5 Thymeleaf中的字符串替代
有時需要對字符串中的某一處地方進行替換,可以通過字符串拼接操作完成,如下代碼:
<span th:text="'您好,歡迎訪問'+${user.userName} + '!'"></span>
或:
<span th:text="|您好,歡迎訪問${user.userName}!|"></span>
上面的第2種形式限制比較多,|...|中只能包括變量表達式${...},不能包含其他常量、條件表達式等。
3.6 Thymeleaf的運算符
(1)算數運算符
如果要在模板中進行算數運算,則可以用下面的寫法。
<span th:text="1+3"></span><br/>
<span th:text="9%2"></span><br/>
(2)條件運算符 th:if
下方代碼演示了if判斷。
<div th:if="${user.role} eq admin">
<span>歡迎您,管理員</span>
</div>
<div th:if="${user.role} eq vip">
<span>歡迎您,vip會員</span>
</div>
eq是判斷表達式,代表等於。其他的判斷表達式如下:
- gt:大於。
- ge:大於或等於。
- eq:等於。
- lt:小於。
- le:小於或等於。
- ne:不等於。
4、處理循環遍歷
4.1 遍歷對象(Object)
在開發過程中,經常會遇到遍歷對象的情況,可以通過“tth:each="user:${user}"”標籤來處理。以下代碼是遍歷從控制器中傳來的用戶對象。
<div th:each="user:${user}">
用戶編號:<span th:text="${user.id}"></span><br/>
用戶姓名:<span th:text="${user.userName}"></span><br/>
博客地址:<span th:text="${user.blogUrl}"></span><br/>
博客信息:<span th:text="${user.blogInfo}"></span><br/>
</div>
4.2 遍歷列表(List)
要處理List,也使用“th:each="item:${userList}"”。
<div th:each="item:${userList}">
用戶編號:<span th:text="${item.id}"></span><br/>
用戶姓名:<span th:text="${item.userName}"></span><br/>
博客地址:<span th:text="${item.blogUrl}"></span><br/>
博客信息:<span th:text="${item.blogInfo}"></span><br/>
</div>
4.3 遍歷數組(Array)
使用“th:each="item:${userArray}"”標籤來遍歷數組。
<div th:each="item:${userArray}">
<li th:text="${item}"></li>
</div>
4.4 遍歷集合(Map)
集合通過“th:text="${item.key}”顯示集合的key,通過“th:text="${item.value}”顯示集合的值。
<!--遍歷key-->
<div th:each="item:${userMap}">
<li th:text="${item.key}"></li>
</div>
<!--遍歷value-->
<div th:each="item:${userMap}">
<li th:text="${item.value}"></li>
</div>
<!--遍歷key-value-->
<div th:each="item:${userMap}">
<li th:text="${item}"></li>
</div>
5、處理公共代碼塊
一個網頁的結構基本可以分爲上(header)、中(body)、下(footer)三個部分。在一般情況下,header和footer的信息在各個頁面都會重複顯示,如果每個頁面都複製一份代碼則太麻煩了。
Thymeleaf模板引擎提供了th:fragment、th:replace、th:include標籤用來處理重複的代碼塊。
1、使用th:fragment標記重複的代碼塊
創建common.html頁面,在該頁面中使用th:fragment標記重複的代碼塊,代碼如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<div class="header" th:fragment="header">
公共 header
</div>
<div class="footer" th:fragment="footer">
公共 footer
</div>
</body>
</html>
2、調用重複代碼塊
在需要調用的地方,使用th:replace或th:include標籤根據th:fragment標記的值來調用,如以下代碼:
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首頁</title>
<meta name="author" content="pan_junbiao的博客">
</head>
<body>
<div>replace調用方式:</div>
<div th:replace="~{common :: header}"></div>
<div>
<p>您好,歡迎訪問 pan_junbiao的博客</p>
<p>https://blog.csdn.net/pan_junbiao</p>
</div>
<div>include調用方式:</div>
<div th:include="~{common :: footer}"></div>
</body>
</html>
執行結果:
th:replace和th:include標籤都可以調用公共代碼。它們的區別如下:
th:replace標籤:替換當前標籤爲模板中的標籤。比如上面用th:replace標籤,則代碼替換爲:
<div class="header">
公共 header
</div>
th:include標籤:只加載模板的內容。比如上面用th:include標籤,則代碼替換爲:
<div>
公共 footer
</div>
6、解決IDEA中使用Thymeleaf頁面變量報錯問題
IDEA在使用Thymeleaf頁面編寫變量,如${user.id}會出現紅色波浪下劃線錯誤,提示:Validates unresolved references and invalid expressions.
解決方法:
菜單:File → Settings → Editor → Inspections,將Thymeleaf的檢測關閉。