1. 作用:
不需要 服务端的支持,就能够被以 html 的方式打开,方便前端人员独立设计与调试,
jsp 就不行了, 不启动服务器 jsp 都没法运行出结果来。
2.修改 pom.xml, 增加了对 thymeleaf 的支持。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.配置application.properties
#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#缓存设置为false, 这样修改之后马上生效,便于调试
spring.thymeleaf.cache=false
#上下文
server.context-path=/thymeleaf
4.视图
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
//将在控制器绑定的数据显示到视图中
<p th:text="${name}" >name</p>
<p th:text="|Hello! ${name}!|" >hello world</p>
</body>
</html>
5.热更新
thymeleaf 修改 html 之后不能立即看到效果,要重新启动 Application 才可以看到效果,所以有了热更新
- 前提是有了热部署
- 然后是 idea 设置。
- 项目自动编译
菜单 -> Other Settings -> Default Settings -> Builld, Execution, Deployment -> Compiler
勾选其中的 Build project automatically. 这个选项默认是没有被勾选的。 - automake 选项开启
菜单->File->Settings->搜索框里输入 Registry
增加一个快捷键 Alt+Shift+M
然后通过 Alt+Shift +M 快捷键打开 Registry 窗口,找到 如图所示的 comipler.automake.allow.when.app.running 勾上。
然后点 Close.
接着重启 idea, 这样修改 html 就可以马上看到效果了
6.包含
- 新建一个 include.html 文件
<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer1">
<p >All Rights Reserved</p>
</footer>
<footer th:fragment="footer2(start,now)">
<p th:text="|${start} - ${now} All Rights Reserved|"></p>
</footer>
</html>
- 再建test.html
<div class="showing">
<div th:replace="include::footer1" ></div>
<div th:replace="include::footer2(2015,2018)" ></div>
</div>
4.判断条件
<p th:if="${testBoolean}" >如果testBoolean 是 true ,本句话就会显示</p>
5.循环
<tr th:each="p: ${ps}">
<td th:text="${p.id}"></td>
<td th:text="${p.name}"></td>
<td th:text="${p.price}"></td>
</tr>
6.链接js.css文件
<link rel="stylesheet" type="text/css" media="all" href="../../webapp/static/css/style.css" th:href="@{/static/css/style.css}"/>
<script type="text/javascript" src="../../webapp/static/js/thymeleaf.js" th:src="@{/static/js/thymeleaf.js}"></script>