开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。SpringBoot支持如下页面模板语言
Thymeleaf
FreeMarker
Velocity
Groovy
JSP
其中 Thymeleaf的官方link,中文版可参见link
配置
pom中导入thymeleaf依赖
<!--模板引擎 thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<!-- 版本后由SpringBoot进行管理-->
</dependency>
application.properties中关闭缓存
# 开发过程建议关闭缓存
spring.thymeleaf.cache=false
html加入声明
<!DOCTYPE html>
<!--使用thymeleaf中必须声明加上该行代码-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
为了让每次页面更改后不用重启项目,配置热启动,更改完页面ctrl+shift+f9
<!--导入热启动-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
</dependency>
基本语法
# 使用简单的字符串,而不是变量,就使用 '' 包裹
<a th:text="${'hello=' + name}"><a>
# thymeleaf 提供的简便操作
th:href="|http://item.gulimall.com/${item.skuId}.html|"
# 字符串加表达式快速写法;使用 || 包裹内容
<a th:href="|http://item.gulimall.com/${product.skuId}.html|">
# 行内表达式,thymeleaf默认只能使用在标签上。
<a>[[ ${param.size()} ]]</a>
# th:utext 不转义
<a href="/static/search/#" th:utext="${product.skuTitle}"></a>
# 遍历
<li th:each="catalog:${result.catalogs}">
# 声明变量,多个变量可以使用,分割
<div th:replace="::frag" th:with="onevar=${value1},twovar=${value2}">
# 三段式
<a> [[ ${!#strings.isEmpty(p) ? '↓' : '↑' } ]] </a>
# 声明属性,多个属性使用, 分割
<img src="../../images/gtvglogo.jpg" th:attr="src=@{/images/gtvglogo.jpg},title=#{logo},alt=#{logo}" />
# 获取请求参数(url的参数);查看thymeleaf 附录
${param.foo}
${param.size()}
${param.isEmpty()}
${param.containsKey('foo')}
# 字符串工具类;查看thymeleaf 附录
${#strings.isEmpty(name)}
${#strings.startsWith(name,'Don')} // also array*, list* and set*
${#strings.endsWith(name,endingFragment)} // also array*, list* and set*
# 集合工具类;查看thymeleaf 附录
${#lists.contains(list, element)}
# 复杂的字符串拼接
<a href="/static/search/#"
th:href="${'javascript:searchProducts("attrs","' + attr.attrId + '_' + attrValue + '")'}"
th:text="${attrValue}">5.56英寸及以上</a>
# 属性优先级 Attribute Precedence
each > if > attr > value > href > src > text > utext >
<!--if判断、取内容为text-->
<li th:if="${session.loginUser} !=null">
<a>欢迎,[[${session.loginUser.nickname}]]</a>
</li>
<!--迭代、自定义属性-->
<li th:each="category : ${categorys}">
<a href="/" class="header_main_left_a" th:attr="ctg-data=${category.getCatId()}" th:text="${category.getName()}"><b>图书、音像、电子书刊</b></a>
</li>
<a th:href="'http://order.gulimall.com/payOrder?orderSn=' + ${submitOrderResp.orderEntity.orderSn}">支付宝</a>
<!--合并行操作-->
<table class="table" th:each="order:${orders.page.list}">
<tr>
<td th:if="${itemStat.index==0}" th:rowspan="${itemStat.size}">
<button>确认收货</button>
<p style="margin:4px 0; ">取消订单</p>
<p>催单</p>
</td>
</tr>
</table>
<!--${}可以有逻辑操作-->
[[${#numbers.formatDecimal(item.price,1,2)}]]
[[${orderConfirmData.stocks[item.skuId]?"有货":"无货"}]]