Thymeleaf模板引擎
Spring Boot 官方不推荐使用JSP,因为内嵌的 Tomcat 、Jetty 容器不支持以 jar 形式运行 JSP。Spring Boot 中提供了大量模板引擎,包含 Freemarker、Mastache、Thymeleaf 等。 而 Spring Boot 官方推荐使用 Thymeleaf 作为模板引擎, 因为 Thymeleaf 提供了完美的 SpringMVC 的支持。
目录
1.Thymeleaf使用
1.pom.xml文件加入Thymeleaf启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.编写控制类
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("name","你好!...");
return "success";
}
}
3.在resources/templates下创建success.html页面
为什么放在templates下?因为在spring-boot-autoconfigure.jar包下的ThymeleafProperties指定了读取路径
html文件引入Thymeleaf名称空间
<html xmlns:th="http://www.thymeleaf.org">
用th属性获取值
<p th:text="${name}">name</p>
4.启动SpringBoot测试
2.关闭Thymeleaf缓存
关闭thymeleaf缓存后,每次修改html文件后就不需要重启服务器了
1.修改application.properties文件,开发环境下关闭thymeleaf缓存,默认是开启的
spring.thymeleaf.cache=false
2.每次文件修改后,自动编译
- 在Eclipse开发工具,手动保存就会自动编译触发热部署
- 在IDEA开发工具,修改文件后都是自动保存不会自动编译,手动编译按CTRL+F9
3.Thymeleaf属性
常用属性
优先级 | 属性名 | 作用 |
---|---|---|
1 | th:insert th:replace | 引入片段,与th:fragment声明组合使用,注意:引入路径前不需要加'/',因为默认会在'/teamplates/'下查找,如果再加了'/'打成jar包发布到服务器上会出错 |
2 | th:each | 遍历 |
3 | th:if th:unless th:switch th:case | 条件判断 |
4 | th:object th:with | 声明遍历 |
5 | th:attr th:attrprepend th:attrappend | 修改任意属性, prepend前面追加, append后面追加 |
6 | th:value th:href th:src ... | 修改任意html原生属性值 |
7 | th:text th:utext | 修改标签体中的内容 th:text 转义特殊字符, 即 h1标签以文本显示出来 th:utext 是不转义特殊字符, 即 h1 标签展现出本来效果 |
8 | th:fragment | 声明片段 |
9 | th:remove | 移除片段 |
示例:
th:insert、th:replace、th:fragment
th:switch
<div th:switch="${sex}">
<p th:case="1">男</p>
<p th:case="0">女</p>
<P th:case="*">未知</P>
</div>
th:if
<p th:if="${#lists.isEmpty(userLsit)}">userList为空显示</p>
th:object
<!--th:object直接取出对象,*{属性名}直接获取对象属性-->
<div th:object="${session.user}">
<p th:text="*{name}"></p>
<p th:text="*{gender == 1 ? '男' : '女'}"></p>
</div>
th:each
<table border="1px">
<tr>
<th>姓名</th>
<th>性别</th>
<th>index</th>
</tr>
<!--
user:第1个值,代表每次迭代出的对象,名字任意
iter:第2个值,代表每次迭代器的内置对象,名字任意.有如下属性:
index(从0开始下标)、count(从1开始下标)、size、
even/odd(判断奇偶数返回boolean)、
first/last:是否 第一/最后 个元素
-->
<tr th:each="user, iter :${userList}">
<td th:text="${user.name}"></td>
<td th:text="${user.gender}"></td>
<td th:text="${iter.index}"></td>
</tr>
</table>
行内表达式
<!--[[${变量名}]]-->
<h3>[[${username}]]</h3>
@{ }:访问资源路径,前面会自动加上下文路径
<link rel="stylesheet" th:href="@{/css/style.css}" href="../css/style.css"/>
th:attr 绑定属性到标签上
<!--th:attr="变量名=xxx"-->
<a th:attr="test=123">超链接</a>