Spring Boot - Thymeleaf模板简介以及集成
文章目錄
- Spring Boot - Thymeleaf模板簡介以及集成
- 1.什么是Thymeleaf?
- 2.標準表達式
- 2.1 變量表達式
- 2.2 選擇表達式/星號表達式
- 2.3 URL表達式
- 2.4 消息表達式/資源表達式
- messages.properties
- messages_zh_CN.properties
- messages_en_US.properties
- application.properties
- 3.常用標簽屬性
- 3.1 常用標簽屬性使用
- ThymeleafController.java
- th:each遍歷
- th:switch/th:case 多路開關
- 3.2 常用標簽屬性優先級
- 4.表達式支持語法
- 4.1 字面量(literals)
- 4.2 文本操作(Text operations)
- 4.3 算術運算(Arithmetic operations)
- 4.4 布爾操作(Boolean operations)
- 4.5 條件運算符(Conditional operators)
- 4.6 表達式上下文內置對象
- 4.7 表達式功能內置對象
- 5.集成Thymeleaf
- 5.1 添加pom依賴
- pom.xml
- 5.2 配置文件
- application
- 5.3 使用
- ThymeleafController.java
- index.html
Spring Boot - Thymeleaf模板簡介以及集成
?正所謂工欲善其事必先利其器,這里我們就來先大概了解一下Thymeleaf的一些特性和使用。
1.什么是Thymeleaf?
Thymeleaf官網
Thymeleaf使用官方文檔
Spring+Thymeleaf
?Thymeleaf是一個流行的模板引擎,該模板引擎采用Java語言開發。模板引擎只是一個技術名詞,是跨領域跨平臺的概念,在Java語言體系下有模板引擎,在C#、PHP等語言體系下也有各自的模板引擎。Thymeleaf是一個和Freemarker、Velocity、Beetl類似的模板引擎,在過去的Java Web開發中,我們往往會選擇使用Jsp去完成頁面的動態渲染,但是Thymeleaf的出現使它完全替代了JSP。新版的Spring中更推薦使用Thymeleaf去用作前端模版引擎,并且Spring Boot對Thymeleaf也提供了很好的集成。
?既然官方也更加推薦使用Thymeleaf作為模板引擎,那必然是存在與其他模板引擎相比較的優點:
2.標準表達式
?每種模板引擎都有自己的表達式,Thymeleaf標準表達式主要有四種:
?下面先來介紹這些標準表達式,里面會涉及一些Thymeleaf的常用標簽屬性,后面會介紹。
2.1 變量表達式
?語法:${...}
?變量表達式即OGNL表達式或Spring EL表達式,變量表達式用于訪問容器(例如:tomcat)上下環境中的變量,功能與JSTL中${}相同,Thymeleaf中的變量表達式用${變量名}方式獲取數據。例如:${user.name}
2.2 選擇表達式/星號表達式
?語法:*{...}
?選擇表達式也叫星號表達式,可使用th:object屬性綁定對象之后使用,實際綁定一個選擇的對象代替上下文變量容器。選擇表達式操作的是選定的對象,而不是整個環境變量映射。
?選擇表達式可以和變量表達式可以混合使用,并且只要沒有選定對象,選擇表達式*{}與變量表達式${}的語法作用是完全一樣的。`
<!-- 標準變量表達式和選擇表達式可以混用--> <p th:object="${user}"><span th:text="${user.name}">Jack</span><span th:text="*{age}">18</span> </p> <!--不使用th:object綁定對象,也可直接使用*{}獲取屬性--> <p><span th:text="*{user.name}">Jack</span><span th:text="*{user.age}">18</span> </p>2.3 URL表達式
?語法:@{...}
?URL表達式可用于<script src="..."> <link href="..."> <a href="...">等,URL表達式指的是把上下文信息添加到URL中,這個過程通常稱為URL重寫。
這里我們可以通過很多種方式去設置參數,例如下面示例:
?第一種方式和以前使用JSP的時候可能更加接近,這里第二種和第三種更加增強了動態URL的可讀性并且減少了拼接的復雜度,并且這里也可以指定相對路徑或者絕對路徑。
<!-- http://localhost:8080/user?name=jackson$age=20 --><a href="https://blog.csdn.net" th:href="@{'http://localhost:8080/user?name='+${user.name}+'$age='+${user.age}}">點擊一下</a><a href="https://blog.csdn.net" th:href="@{'http://localhost:8080/user(name=${user.name},age=${user.age})'}">點擊一下</a><!-- http://localhost:8080/user?name=jackson$age=20 --><a href="https://blog.csdn.ne" th:href="@{|http://localhost:8080/user?name=${user.name}$age=${user.age}|}">點擊一下</a><!-- user?name=jackson$age=20 --><a href="https://blog.csdn.ne" th:href="@{'user?name='+${user.name}+'$age='+${user.age}}">點擊一下(相對頁面)</a><!-- /springboot-thymeleaf/user?name=jackson$age=20 --><a href="https://blog.csdn.ne" th:href="@{'/user?name='+${user.name}+'$age='+${user.age}}">點擊一下(相對項目)</a>2.4 消息表達式/資源表達式
?語法:#{...}
?消息表達式也叫資源表達式,通常用于顯示頁面靜態文本,可以將靜態文本維護在properties配置文件用Key索引Value方便維護,做國際化等功能。
?若使用消息表達式做國際化功能,我們首先需要不同的配置文件,這里我們在statics/messages下建三個配置文件
messages.properties
main.msg=默認消息 second.msg=獨有信息messages_zh_CN.properties
main.msg=消息表達式messages_en_US.properties
main.msg=msg expression?由于我們項目是Spring Boot構建項目,所以需要在application配置文件中配置掃描國際化配置文件路徑
application.properties
#國際化配置文件 spring.messages.basename=statics/messages/messages?接下來我們就可以使用#{}去獲取數據
<!-- 信息表達式 --> <p><span th:text="#{main.msg}">example</span><span th:text="#{second.msg}">example</span> </p>?很簡單我們就可以實現國家化的功能,這里大家需要注意的是關于國際化的配置文件存在優先級別的,假如存在以下三個配置文件,那么下面文件會從上往下為高至低的優先級去匹配。
?messages_zh_CN.properties
?messages_zh.properties
?messages.properties
3.常用標簽屬性
?在之前的介紹中,我們已經接觸到了一些Thymeleaf的常見標簽屬性,那么我們來看看Thymeleaf還給我們提供了哪些功能的標簽屬性。
| th:id | id聲明,替換id | <input th:id="'user' + ${user.id}"/> | |
| th:text | 文本替換 | <p th:text="${msg}">description</p> | <td th:text="7+8">2019</td> |
| th:utext | 支持html文本替換 | <p th:utext="${htmlcontent}">html</p> | |
| th:object | 替換對象,用于數據對象綁定 | <div th:object="${user}"> | |
| th:value | 屬性賦值 | <input th:value="${user.name}" /> | |
| th:with | 變量賦值運算 | <div th:with="flag=${user.count}%2==0"></div> | |
| th:style | 設置樣式 | <div th:style="'display:none;'">style</div> | |
| th:onclick | 點擊事件 | th:onclick="'myOnclick()'" | |
| th:if | 判斷條件 | <span th:if="${display} eq true" th:text="${display}">true</span> | <div th:if="${user} != null and ${check} != null">show</div> |
| th:unless | 與th:if判斷相反 | <span th:unless="${display} eq true" th:text="${display}">false</span> | |
| th:each | 對象遍歷,功能類似jstl中的<c:forEach>標簽 | <p th:each="user,iterStat:${userList}"> | |
| th:href | 超鏈接,類似<a>標簽的href 屬性 | <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> /> | |
| th:switch | 多路選擇,配合th:case使用 | <div th:switch="${user.sex}"> | |
| th:case | th:switch的分支 | <span th:case="1">男</span><span th:case="2">女</span><span th:case="*">未知</span> | |
| th:fragment | 布局標簽,聲明該屬性的div為模板片段,常用與頭文件、頁尾文件的引入。常與th:include,th:replace組合使用。 | <div th: fragment="copy" >fragment</div> | <div th: include=" /templates/footer : : copy" ></div> |
| th:include | 布局標簽,替換內容到引入的文件 | <head th:include="layout :: htmlhead" th:with="title='include'"></head> /> | |
| th:replace | 布局標簽,替換整個標簽到引入的文件 | <div th:replace="fragments/header :: title"></div> | |
| th:selected | 選擇框選中 | th:selected="(${user.id} == ${target.id})" | |
| th:src | 用于外部資源引入,類似于<script>標簽的src屬性 | <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" /> | |
| th:inline | 內聯文本、內聯腳本 | <div th:inline="text"> [[${user.name}]]</div> | <script th:inline="javascript" type="text/javascript">console.log([[${user.name}]]);</script> |
| th:action | 定義后臺控制器路徑,類似<form>標簽的action屬性 | <form action="subscribe.html" th:action="@{/subscribe}"> | |
| th:remove | 刪除某個屬性 1.all:刪除包含標簽和所有的孩子。2.body:不包含標記刪除,但刪除其所有的孩子。3.tag:包含標記的刪除,但不刪除它的孩子。4.all-but-first:刪除所有包含標簽的孩子,除了第一個。5.none:什么也不做。這個值是有用的動態評估。 | <tr th:remove="all"> | |
| th:attr | 設置標簽屬性,多個屬性可以用逗號分隔 | <span th:text="${user.name}" th:attr="age=${user.age},sex=${user.sex}"> |
3.1 常用標簽屬性使用
ThymeleafController.java
@RequestMapping(value = "/index")public String index(Model model){model.addAttribute("msg","thymeleaf controller...");model.addAttribute("user",new User("jackson",20));ArrayList<User> users = new ArrayList<>();HashMap<Integer, Object> userMap = new HashMap<>();for (int i = 0;i < 10;i ++){User user = new User("jackson" + i, (int) (Math.random() * 10) + i);users.add(user);userMap.put(i,user);}model.addAttribute("userList",users);model.addAttribute("userMap",userMap);model.addAttribute("display",true);model.addAttribute("sex",1);return "index";}?在我們使用Thymeleaf模板時,遍歷是我們開發中經常遇見的,在以前使用JSP時,我們使用c:foreach標簽可以輕松完成數組集合的遍歷,這里也一樣,Thymeleaf提供了th:each標簽屬性很方便地也能達到遍歷的效果。
th:each遍歷
?對于array以及list數組,Thymeleaf提供了很多遍歷幫助變量:
注意:循環體信息iterStat若不定義,則默認采用迭代變量+Stat,這里為userStat(若iterStat未定義)
th:switch/th:case 多路開關
<span th:switch="${user.sex}"><span th:case="1">男</span><span th:case="2">女</span><span th:case="*">未知</span></span>3.2 常用標簽屬性優先級
?由于一個標簽中可以添加多個屬性,那么當然會有一個優先級的問題,這里我們可以看到官方文檔給我們列舉出了各個標簽屬性的優先級,大家組合使用的時候需要注意
4.表達式支持語法
?為了更好地使用Thymeleaf模板,我們對其支持的語法進行了解可以更加提升我們開發的效率,所有以下特征都可以被組合嵌套使用,這里我們看一下支持的語法有哪些。
4.1 字面量(literals)
?文本字面量:用單引號’ '包圍的字符串為文本字面量 例: 'api/user', 'hello world'
?數字字面量: 0, 88.8
?布爾字面量: true, false
?空字面量: null
4.2 文本操作(Text operations)
?字符串連接: 即字面量拼接,用 + 連接多個字面量 例:'當前在線用戶:'+${user.online}+'位'
?文本替換:使用 | 減少字符串拼接,更為優雅 例:|當前在線用戶${user.online}位|
4.3 算術運算(Arithmetic operations)
?二元運算符: +, -, *, /, %
?三元運算符:?: 例:<span th:if="${sex} eq 1?'男':'女'">未知</span>
?關系比較:>, <, >=, <= (gt, lt, ge, le)
?等值運算符: ==, != (eq, ne)
4.4 布爾操作(Boolean operations)
?一元運算符: !, not
?二元運算符: and, or
4.5 條件運算符(Conditional operators)
?If-then: (if) ? (then)
?If-then-else: (if) ? (then) : (else)
4.6 表達式上下文內置對象
?在使用Thymeleaf模板時我們仍能通過表達式去獲取某些上下文內置對象,保持更高的靈活性。
?#ctx:上下文對象。
?#vars: 上下文變量。
?#locale:上下文區域設置。
?#request: HttpServletRequest對象(`2.x版本使用#httpServletRequest)。
?#response: HttpServletResponse對象(2.x版本使用#httpServletResponse)。
?#session: HttpSession對象(2.x版本使用#httpSession)。
?#servletContext: ServletContext對象。
?以上內置對象我們可以在Thymeleaf引擎模板中直接使用:
4.7 表達式功能內置對象
?除了上面的上下文內置對象,Thymeleaf模板引擎也提供了一組功能性的內置對象,例如集合、時間、數值等處理都可以用這些對象輕松完成,也是通過#調用,這里我們簡單介紹幾個,完整的對象和使用各位可以查看官方文檔Thymeleaf官方文檔-表達式功能性內置對象
所有的這里不一一列出,各位可以通過上面連接去官方文檔里面查看,更加詳細
5.集成Thymeleaf
?首先對于Spring Boot的Web項目有幾點是需要我們知道的:
FreeMarker、Groovy、Thymeleaf、Mustache
5.1 添加pom依賴
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.1.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.springboot</groupId><artifactId>springboot-thymeleaf</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-thymeleaf</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><!-- springboot web起步依賴--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- spring boot 整合thymeleaf起步依賴--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!-- 取消標簽嚴格驗證 設置spring.thymeleaf.mode=LEGAYHTML5需要引入以下依賴--><!-- <dependency><groupId>net.sourceforge.nekohtml</groupId><artifactId>nekohtml</artifactId></dependency><dependency><groupId>org.unbescape</groupId><artifactId>unbescape</artifactId><version>1.1.5.RELEASE</version></dependency>--></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><resource><directory>src/main/resources</directory><includes><include>**/*.*</include></includes></resource><resource><directory>src/main/webapp</directory><targetPath>META-INF/resources</targetPath><includes><include>**/*.*</include></includes></resource></resources></build></project>5.2 配置文件
?這里我們不需要配置什么過多的屬性就可以直接去使用Thymeleaf模板引擎,特別方便
application
# 開發階段,建議關閉thymeleaf緩存 spring.thymeleaf.cache=false # 使用遺留的html5 去除html標簽嚴格驗證 # spring.thymeleaf.mode=LEGACYHTML5server.servlet.context-path=/springboot-thymeleaf5.3 使用
ThymeleafController.java
package com.springboot.controller;import com.springboot.repository.entity.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping;import java.util.ArrayList; import java.util.HashMap;/*** @author hzk* @date 2018/12/27*/ @Controller public class ThymeleafController {@RequestMapping(value = "/index")public String index(Model model){model.addAttribute("msg","thymeleaf controller...");model.addAttribute("user",new User("jackson",20));ArrayList<User> users = new ArrayList<>();HashMap<Integer, Object> userMap = new HashMap<>();for (int i = 0;i < 10;i ++){User user = new User("jackson" + i, (int) (Math.random() * 10) + i);users.add(user);userMap.put(i,user);}model.addAttribute("userList",users);model.addAttribute("userMap",userMap);model.addAttribute("display",true);model.addAttribute("sex",1);return "index";}}?我們可以通過上面controller填充好數據然后轉發到index.html模板頁面,所以我們需要在templates目錄下放置index.html文件,這里只需要將<html lang="en" xmlns:th="http://www.thymeleaf.org">加上即可使用Thymeleaf。
index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>index</title> </head> <body> <!-- 標準變量表達式 --> <p th:text="${msg}">index.... </p> <p><span th:text="${user.name}">杰克遜</span><span th:text="${user.age}">18</span> </p> <!-- 選擇變量表達式:先使用th:object綁定對象 后用*可直接獲取對象屬性--> <p th:object="${user}"><span th:text="*{name}">杰克遜a</span><span th:text="*{age}">18a</span> </p><!-- 標準變量表達式和選擇變量表達式可以混用--><p th:object="${user}"><span th:text="${user.name}">杰克遜b</span><span th:text="*{age}">18b</span></p><!--不使用th:object綁定對象,也可直接使用*{}獲取屬性--><p><span th:text="*{user.name}">杰克遜c</span><span th:text="*{user.age}">18c</span></p> <!-- 信息表達式 --> <p><span th:text="#{main.msg}">example</span><span th:text="#{second.msg}">example</span> </p> <!-- url表達式 --> <p><!-- http://localhost:8080/user?name=jackson$age=20 --><a href="http://www.baidu.com" th:href="@{'http://localhost:8080/user?name='+${user.name}+'$age='+${user.age}}">點擊一下</a><a href="http://www.baidu.com" th:href="@{'http://localhost:8080/user(name=${user.name},age=${user.age})'}">點擊一下(設置參數)</a><!-- http://localhost:8080/user?name=jackson$age=20 --><a href="http://www.baidu.com" th:href="@{|http://localhost:8080/user?name=${user.name}$age=${user.age}|}">點擊一下</a><!-- user?name=jackson$age=20 --><a href="http://www.baidu.com" th:href="@{'user?name='+${user.name}+'$age='+${user.age}}">點擊一下(相對頁面)</a><!-- /springboot-thymeleaf/user?name=jackson$age=20 --><a href="http://www.baidu.com" th:href="@{'/user?name='+${user.name}+'$age='+${user.age}}">點擊一下(相對項目)</a> </p> <!-- list/數組 th:each 遍歷屬性index:當前迭代對象index(0開始)count:當前迭代對象個數(1開始)size:被迭代對象大小current:當前迭代變量even/odd:布爾值,當前循環是否奇數/偶數first:布爾值,當前循環是否第一個last:布爾值,當前循環是否最后一個注意:循環體信息iterStat若不定義,則默認采用迭代變量+Stat,這里為userStat--> <p th:each="user,iterStat:${userList}"><span th:text="${user.name}">杰克遜</span><span th:text="${user.age}">18</span><span th:text="${iterStat.index}"></span><span th:text="${iterStat.size}"></span><span th:text="${iterStat.first}"></span> </p> <!-- Map類型遍歷 --> <p th:each="map:${userMap}"><span th:text="${map.key}">key</span><span th:text="${map.value}">value</span><span th:text="${map.value.name}">杰克遜</span><span th:text="${map.value.age}">18</span> </p> <!-- 條件判斷 == / eq 字符串需要''th:unless 與之相反 --> <p><span th:if="${display} eq true" th:text="${display}">th:if</span><span th:unless="${display} eq true" th:text="${display}">th:unless</span><span th:switch="${sex}"><span th:case="1">1</span><span th:case="2">2</span><span th:case="*">未知</span></span> </p> <!-- th:attr 設置標簽屬性 --> <p><span th:text="${user.name}" th:attr="age=${user.age},sex=${user.sex}"></span> </p> <!-- th:style設置樣式 --> <div th:style="'display:none;'">ttt </div> <!-- 內聯文本 用內聯表達式可以獲取屬性 <div th:text="${user.name}">jack </div> 與此效果一致--> <div th:inline="text">[[${user.name}]] </div> <!-- 內斂腳本 th:inline="javascript" --> <script th:inline="javascript" type="text/javascript">var user = [[${user.name}]];console.log(user); </script> <script th:src="@{/js/index.js}"></script> <!-- 字面量 --> <p><span th:text="'a'+'b'">文本字面量 ''</span><span th:text="2018+1">數字字面量</span><span th:if="${users == null}">null字面量</span> </p> <!-- 字符串拼接 --> <p><span th:text="'第一種拼接方式'+${user.name}">第一種</span><span th:text="|第二種拼接方式${user.name}|">第二種</span> </p> <!--<p><span th:if="${sex} eq 1?'男':'女'">不清楚</span> </p>--> <!-- 運算關系判斷算數運算: + - * / %關系比較: > < >= <= (gt lt ge le)相等判斷: == != (eq ne)--> <!-- #request(相當于HttpServletRequest 2.x使用#httpServletRequest)#session(相當于HttpSession 2.x使用#httpSession) ...表達式基本內置對象--> <p><span th:text="${#request.getContextPath()}"></span> </p> <!-- 功能內置對象 #dates #strings #object #lists .....模板引擎提供一組功能性內置對象,可以在模板中直接使用這些功能對象提供的功能方法,以#開頭引用--> <p><span th:text="${#dates.format('2018/12/28','yyyy-MM-dd HH:mm:ss')}">時間功能對象</span></p> </body> </html>?我們可以感受到Spring Boot集成Thymeleaf沒有很多繁瑣的操作,甚至很簡單就可以去使用該模板引擎。更多的是我們對Thymeleaf特性的了解和功能的使用需要花一些時間,官方文檔上面還是很齊全的,所以大家可以有時間多看一看官方文檔提供的信息。
總結
以上是生活随笔為你收集整理的Spring Boot - Thymeleaf模板简介以及集成的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA软件海豚_海豚调度系统Apach
- 下一篇: Spring Boot进阶(09):集成