
1. 什么是 Thymeleaf ? 雖然我們目前擁有許多十分優(yōu)秀的前端框架,例如: Vue 、 React 等,非常適用于前后端分離的場景,前端可以獨(dú)立部署成為服務(wù),前后端從物理上完全進(jìn)行隔離,降低程序耦合度。但是 Spring Boot 官方依然為我們提供了模版引擎用于一些無需前后端分離的場景。 Thymeleaf 是新一代的模板引擎,在 Spring Boot 中,官方推薦使用 Thymeleaf 來做前端模版引擎。打開 https://start./ 可以看到,在當(dāng)前Spring Boot 的版本中( 2.1.8.RELEASE ), 官方提供的模版引擎有以下幾種: Thymeleaf FreeMarker Mustache Groovy
Spring Boot 建議使用這些模版引擎,而并不推薦我們繼續(xù)使用 JSP 。 Thymeleaf 具體特性如下:(了解源碼可+求求: 1791743380) Thymeleaf 在有網(wǎng)絡(luò)和無網(wǎng)絡(luò)的環(huán)境下皆可運(yùn)行,即它可以讓美工在瀏覽器查看頁面的靜態(tài)效果,也可以讓程序員在服務(wù)器查看帶數(shù)據(jù)的動態(tài)頁面效果。這是由于它支持 html 原型,然后在 html 標(biāo)簽里增加額外的屬性來達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋 html 時(shí)會忽略未定義的標(biāo)簽屬性,所以 Thymeleaf 的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁面時(shí),Thymeleaf 標(biāo)簽會動態(tài)地替換掉靜態(tài)內(nèi)容,使頁面動態(tài)顯示。 Thymeleaf 開箱即用的特性。它提供標(biāo)準(zhǔn)和 Spring 標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn) JSTL、 OGNL表達(dá)式效果,避免每天套模板、改 Jstl、改標(biāo)簽的困擾。同時(shí)開發(fā)人員也可以擴(kuò)展和創(chuàng)建自定義的方言。 Thymeleaf 提供 Spring 標(biāo)準(zhǔn)方言和一個(gè)與 SpringMVC 完美集成的可選模塊,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國際化等功能。
2. 快速入門這里我們先正常構(gòu)建一個(gè) Spring Boot 工程: spring-boot-thymeleaf ,在 pom.xml 文件中引入 Thymeleaf 的相關(guān)依賴,如下: <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId></dependency> COPY
工程的配置文件 application.yml 如下: server: port: 8080spring: application: name: spring-boot-thymleaf thymeleaf:
# 關(guān)閉thymeleaf緩存 開發(fā)時(shí)使用 否則沒有實(shí)時(shí)畫面 cache: false
# 檢查模板是否存在,然后再呈現(xiàn) check-template-location: true
# Content-Type value. servlet: content-type: text/html
# 啟用MVC Thymeleaf視圖分辨率 enabled: true
# Template encoding. encoding: UTF-8
# 關(guān)閉嚴(yán)格模式 mode: LEGACYHTML5
# Prefix that gets prepended to view names when building a URL. prefix: classpath:/templates/
# Suffix that gets appended to view names when building a URL. suffix: .html mvc:
# 指定靜態(tài)資源處理路徑 static-path-pattern: /static/** view: suffix: .html COPY
有關(guān) thymeleaf 都寫明了注釋,這里需要注意的有以下幾點(diǎn): spring.thymeleaf.mode :這里是配置當(dāng)前模版的解析模式的,默認(rèn)值為 HTML ,這時(shí)會開啟嚴(yán)格模式,所有的 HTML 必須有頭有尾,很多地方并不符合我們平時(shí)的書寫習(xí)慣,這里最好關(guān)閉嚴(yán)格模式。 spring.thymeleaf.cache :這里是 thymeleaf 的緩存,在平時(shí)的練習(xí)中最好關(guān)閉,否則頁面修改后刷新瀏覽器將會無效,而在生產(chǎn)環(huán)境中,視具體的業(yè)務(wù)場景而定。 spring.mvc.static-path-pattern :這里是配置我們靜態(tài)資源的路徑,一般默認(rèn)是配置 /static/** 路徑,這里用于存放我們的 js 、 css 、圖片等靜態(tài)資源。
配置通用 404 和 500 頁面,直接在 templates\error 創(chuàng)建對應(yīng)頁面即可,這里可以看一下 Spring Boot 錯(cuò)誤頁面轉(zhuǎn)發(fā)的源碼 org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver ,如下: @Overridepublic ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = resolve(String.valueOf(status.value()), model); if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
} return modelAndView;
}private ModelAndView resolve(String viewName, Map<String, Object> model) {
String errorViewName = "error/" + viewName;
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext); if (provider != null) { return new ModelAndView(errorViewName, model);
} return resolveResource(errorViewName, model);
} COPY
可以看到這里會根據(jù)當(dāng)前的狀態(tài)響應(yīng)碼轉(zhuǎn)發(fā)到對應(yīng)的頁面,路由為 error/** 。筆者這里簡單創(chuàng)建兩個(gè)錯(cuò)誤頁面,如圖:
創(chuàng)建測試 Controller ,如下: @Controllerpublic class HelloController { @GetMapping("/hello") public String hello(HttpServletRequest request) { // 構(gòu)建測試數(shù)據(jù)
Map<String, Object> map = new HashMap<>();
UserModel userModel = new UserModel();
userModel.setId(1L);
userModel.setName("Spring Boot");
userModel.setAge(18);
map.put("user", userModel);
List<CourseModel> list = new ArrayList<>(); for (int i = 0; i < 2; i++) {
CourseModel courseMode = new CourseModel();
courseMode.setId((long) i);
courseMode.setName("Spring Boot:" + i);
courseMode.setAddress("課程地點(diǎn):" + i);
list.add(courseMode);
}
map.put("list", list);
map.put("flag", true);
request.setAttribute("data", map); return "hello";
}
} COPY
在此注冊測試類中,進(jìn)行數(shù)據(jù)初始化并輸出至頁面。 Thymeleaf 模版文件如下: <!DOCTYPE html><html xmlns="http://www./1999/xhtml"
xmlns:th="http://www."><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello Spring Boot</title>
<link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}"></head><body><div class="container">
<div>用戶信息:</div>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">姓名</th>
<th scope="col">年齡</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row" th:text="${data.user.id}"></th>
<td th:text="${data.user.name}"></td>
<td th:text="${data.user.age}"></td>
</tr>
</tbody>
</table>
<div>課程信息:</div>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">課程名稱</th>
<th scope="col">課程地點(diǎn)</th>
</tr>
</thead>
<tbody>
<tr th:each="course, iterStat : ${data.list}">
<th scope="row" th:text="${course.id}"></th>
<td th:text="${course.name}"></td>
<td th:text="${course.address}"></td>
</tr>
</tbody>
</table>
<div th:if="${data.flag == true}">如果 flag 為 true 你將可以看到這行字:)</div></div></body></html> COPY
Thymeleaf 部分常用 th 標(biāo)簽如下: 關(guān)鍵字 | 功能介紹 | 案例 |
---|
th:id | 替換id | <input th:id="'xxx' + ${collect.id}"/> | th:text | 文本替換 | <p th:text="${collect.description}">description</p> | th:utext | 支持html的文本替換 | <p th:utext="${htmlcontent}">conten</p> | th:object | 替換對象 | <div th:object="${session.user}"> | th:value | 屬性賦值 | <input th:value="${user.name}" /> | th:with | 變量賦值運(yùn)算 | <div th:with="isEven=${prodStat.count}%2==0"></div> | th:style | 設(shè)置樣式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" | th:onclick | 點(diǎn)擊事件 | th:onclick="'getCollect()'" | th:each | 屬性賦值 | tr th:each="user,userStat:${users}"> | th:if | 判斷條件 | <a th:if="${userId == collect.userId}" > | th:unless | 和th:if判斷相反 | <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> | th:href | 鏈接地址 | <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> /> | th:switch | 多路選擇 配合th:case 使用 | <div th:switch="${user.role}"> | th:case | th:switch的一個(gè)分支 | <p th:case="'admin'">User is an administrator</p> | th:fragment | 布局標(biāo)簽,定義一個(gè)代碼片段,方便其它地方引用 | <div th:fragment="alert"> | th:include | 布局標(biāo)簽,替換內(nèi)容到引入的文件 | <head th:include="layout :: htmlhead" th:with="title='xx'"></head> /> | th:replace | 布局標(biāo)簽,替換整個(gè)標(biāo)簽到引入的文件 | <div th:replace="fragments/header :: title"></div> | th:selected | selected選擇框 選中 | th:selected="(${xxx.id} == ${configObj.dd})" | th:src | 圖片類地址引入 | <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" /> | th:inline | 定義js腳本可以使用變量 | <script type="text/javascript" th:inline="javascript"> | th:action | 表單提交的地址 | <form action="subscribe.html" th:action="@{/subscribe}"> | th:remove | 刪除某個(gè)屬性 | <tr th:remove="all"> 1.all:刪除包含標(biāo)簽和所有的孩子。2.body:不包含標(biāo)記刪除,但刪除其所有的孩子。3.tag:包含標(biāo)記的刪除,但不刪除它的孩子。4.all-but-first:刪除所有包含標(biāo)簽的孩子,除了第一個(gè)。5.none:什么也不做。這個(gè)值是有用的動態(tài)評估。 | th:attr | 設(shè)置標(biāo)簽屬性,多個(gè)屬性可以用逗號分隔 | 比如 th:attr="src=@{/image/aa.jpg},title=#{logo}" ,此標(biāo)簽不太優(yōu)雅,一般用的比較少。 |
3. 測試啟動當(dāng)前工程,打開瀏覽器訪問路徑: http://localhost:8080/hello ,結(jié)果如圖:

|