1、简介
Thymeleaf是一个流行的模板引擎,该模板引擎采用 Java 语言开发。
Java 中常见的模板引擎有 Velocity、Freemaker、Thymeleaf 等。不同的模板引擎都会具有自己的特定的标签体系,而 Thymeleaf 以 HTML 标签为载体,在 HTML 的标签下实现对数据的展示。
Thymeleaf 本身与 SpringBoot 是没有关系的,但 SpringBoot 官方推荐使用 Thymeleaf 作为前端页面的数据展示技术。同时,SpringBoot 很好地集成了这种模板技术。
关于Thymeleaf 的详情可访问其官网: http://www.thymeleaf.org
2、Spring Boot集成Thymeleaf
2.1、添加依赖
- 方法1:通过创建工程添加依赖
SpringBoot学习笔记15 - Thymeleaf1、简介2、Spring Boot集成Thymeleaf3、Thymeleaf标准表达式4、Thymeleaf常见属性5、运算基础6、内置对象 - 方法2:通过pom.xml添加配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.2、在开发阶段关闭thymeleaf缓存
打开application.yml文件并添加如下属性:
spring:
...
thymeleaf:
cache: false
生产环境建议开启(即默认)
2.3、编写Controller类并传参
将需要传递的参数传递到Model对象中:
@Controller
public class ThymeleafController {
@RequestMapping("/demo")
public String thymeleafHandler(Model model) {
model.addAttribute("welcome", "hello thymeleaf");
// 返回 resources/templates 目录下指定html页面,无需添加后缀
return "index";
}
}
2.4、添加index.html页面并测试
在 resources/templates 目录下创建index.html页面,编写界面,并从model对象中读取参数值:
<!DOCTYPE html>
<!-- 添加thymeleaf命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<p th:text="${welcome}">这里将要显示数据,但这些文字不显示。</p>
</body>
</html>
启动并测试:
3、Thymeleaf标准表达式
3.1、变量表达式 ${}
${}
获取从Model或Request对象中设置的参数.。
- 创建实体类
package com.blairscott.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Teacher { private Integer id; private String name; private int age; }
- Controller传递参数
@Controller public class ThymeleafController { @RequestMapping("/demo") public String thymeleafHandler(Model model) { model.addAttribute("teacher", new Teacher(1, "zhangsan", 18)); return "index"; } }
- 创建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="${teacher}">这里将要显示数据,但这些文字不显示。</p> <p th:text="${teacher.id}">这里将要显示数据,但这些文字不显示。</p> <p th:text="${teacher.name}">这里将要显示数据,但这些文字不显示。</p> <p th:text="${teacher.age}">这里将要显示数据,但这些文字不显示。</p> </body> </html>
- 启动服务并测试
SpringBoot学习笔记15 - Thymeleaf1、简介2、Spring Boot集成Thymeleaf3、Thymeleaf标准表达式4、Thymeleaf常见属性5、运算基础6、内置对象
3.2、选择表达式 *{}
*{}
先通过
th:object="${teacher}"
选择了对象,再通过
th:text="*{id}"
等选择属性
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<div th:object="${teacher}">
<p th:text="*{id}">这里将要显示数据,但这些文字不显示。</p>
<p th:text="*{name}">这里将要显示数据,但这些文字不显示。</p>
<p th:text="*{age}">这里将要显示数据,但这些文字不显示。</p>
</div>
</body>
</html>
启动并测试:
3.3、URL表达式 @{}
@{}
在3.1的基础上:
- 新增Controller
@RestController public class FindController { @GetMapping("/find/{name}") public String find(@PathVariable("name") String name) { return "查询指定的老师:" + name; } }
- 修改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="${teacher.name}">这里将要显示数据,但这些文字不显示。</p> <a th:href="@{|http://localhost:8081/devpath/find/${teacher.name}|}">查询</a> </body> </html>
- 启动服务并测试
SpringBoot学习笔记15 - Thymeleaf1、简介2、Spring Boot集成Thymeleaf3、Thymeleaf标准表达式4、Thymeleaf常见属性5、运算基础6、内置对象
4、Thymeleaf常见属性
4.1、逻辑运算相关属性
4.1.1、判断标签
th:if
<p th:if="${gender} == 'male'">男</p>
<p th:if="${gender} == 'female'">女</p>
4.1.2、选择标签
th:switch
<!-- 里面是OGNL表达式 -->
<div th:switch="${teacher.age/10}">
<p th:case="0">幼年</p>
<p th:case="1">少年</p>
<p th:case="2">青年</p>
<p th:case="3">中年</p>
<p th:case="4">中年</p>
<p th:case="5">中年</p>
<p th:case="*">老年</p> <!-- 相当于 default -->
</div>
4.1.3、选择标签
th:each
- 遍历List集合 / 数组
<div th:each="stu : ${students}"> <span th:text="${stu.id}"></span> <span th:text="${stu.name}"></span> <span th:text="${stu.age}"></span> </div>
<!-- 写法1 --> <div th:each="stu, ite : ${students}"> <!-- 显示当前遍历对象的序号(从1开始计数) --> <span th:text="${ite.count}"></span> <!-- 显示当前遍历对象的索引(从0开始计数) --> <span th:text="${ite.index}"></span> <!-- 返回布尔值,判断当前遍历对象是否是第一个 --> <span th:text="${ite.first}"></span> <!-- 返回布尔值,判断当前遍历对象是否是最后一个 --> <span th:text="${ite.last}"></span> <!-- 返回布尔值,判断当前遍历对象的序号是否奇数 --> <span th:text="${ite.odd}"></span> <!-- 返回布尔值,判断当前遍历对象的序号是否偶数 --> <span th:text="${ite.even}"></span> </div> <!-- 写法2(参数后拼接Stat) --> <div th:each="stu : ${students}"> <!-- 显示当前遍历对象的序号(从1开始计数) --> <span th:text="${stuStat.count}"></span> <!-- 显示当前遍历对象的索引(从0开始计数) --> <span th:text="${stuStat.index}"></span> <!-- 返回布尔值,判断当前遍历对象是否是第一个 --> <span th:text="${stuStat.first}"></span> <!-- 返回布尔值,判断当前遍历对象是否是最后一个 --> <span th:text="${stuStat.last}"></span> <!-- 返回布尔值,判断当前遍历对象的序号是否奇数 --> <span th:text="${stuStat.odd}"></span> <!-- 返回布尔值,判断当前遍历对象的序号是否偶数 --> <span th:text="${stuStat.even}"></span> </div>
- 遍历Map集合
<div th:each="entry : ${map}"> <p th:text="${entryStat.count}"></p> <p th:text="${entry.key}"></p> <p th:text="${entry.value}"></p> <p th:text="${entry.value.id}"></p> <p th:text="${entry.value.name}"></p> <p th:text="${entry.value.age}"></p> </div>
4.2、Html、js、CSS中的属性
- 文本原样输出
th:text
- H5格式输出
th:utext
- input标签中的name与value
、th:name
th:value
- img标签中的src
th:src
其他Html标签中的属性也都可以通过这种方式动态获取数据。
同理,css中的样式属性、js中的事件等也可以通过这种方式动态获取数据。
4.3、内联属性与万能属性
th:inline
,它可以存在以下4种属性值:
-
text
内嵌文本,表示标签体中需要嵌入动态文本。(默认值)
<p th:inline="text">姓名:[[${name}]]</p> <p>姓名:[[${name}]]</p>
-
javascritp
内嵌脚本,表示js中需要嵌入动态内容。
<script th:inline="javascript" type="text/javascript"> alert([[${teacher.name}]]); </script>
-
css
内嵌样式,表示css中需要嵌入文本。
<style> #[[${styleBean.id}]] { width: [[${styleBean.width}]]; height: [[${styleBean.height}]]; background-color: [[${styleBean.color}]]; } </style>
-
non
不解析内嵌动态内容
4.4、万能属性
th:attr
-
设置单一属性
官方文档中提到:
Enter then the
attribute, and its ability to change the value of attributes of the tags it is set in:th:attr
<form action="subscribe.html" th:attr="action=@{/subscribe}"> <fieldset> <input type="text" name="email" /> <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/> </fieldset> </form>
-
同时设置多属性
官方文档中提到:
But what if we wanted to set more than one attribute at a time? XML rules do not allow you to set an attribute twice in a tag, so
will take a comma-separated list of assignments, like:th:attr
<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
5、运算基础
5.1、字面常量
Thymeleaf包含四种字面常量:文本、数字、布尔值、NULL
5.1.1、文本
5.1.2、数字
5.1.3、布尔值
Thymeleaf中的布尔常量为true与false,对大小写不敏感。
<span th:if="${boolVal} == true">布尔值为TRUE</span>
<span th:if="${boolVal == false}">布尔值为FALSE</span>
假设存在以下Controller:
@GetMapping("/boolJdg/{bool}")
public String boolJdg(@PathVariable("bool") String bool, Model model) {
model.addAttribute("boolVal", Boolean.valueOf(bool));
return "index";
}
5.1.4、NULL值
关于NULL值需要注意:
- 若对象未定义,则其值为NULL。
- 若对象定义了,但其值被指定为NULL,则其值为NULL。
- 若集合已定义,但其长度为0,此时的集合不为NULL。
5.2、运算符
5.2.1、字符串拼接运算符
可以使用加号(+)进行字符串拼接,也可以将文本字面量与动态数据直接写入由双竖线括起来的字符串内,此时无需使用加号进行连接。
<span th:text="'Hello ' + ${language}"></span>
<span th:text="|Hello ${language}|"></span>
5.2.2、算术运算符
- 支持:
、+
、-
、*
、/
%
- 不支持:
、++
--
5.2.3、关系运算符
- 符号:
、>
、<
、>=
、<=
、==
!=
- 表达式:
、gt
、lt
、ge
、le
、eq
ne
5.2.4、逻辑运算符
- 与:
and
- 或:
or
- 非:
、not
!
5.2.5、条件运行符
? :
6、内置对象
6.1、ServletAPI对象
通过
#request
、
#session
、
servletContext
可以获取到
HttpServletRequest
、
HttpSession
和
ServletContext
对象,然后可以调用其相应的方法。
在Controller中我们定义:
@Controller
public class ThymeleafController {
@GetMapping("/servletApi")
public String servletApi(HttpServletRequest request, HttpSession session) {
request.setAttribute("req", "reqValue");
session.setAttribute("ses", "sesValue");
session.getServletContext().setAttribute("app", "appValue");
return "index";
}
}
在index.html中我们定义:
...
req = <span th:text="${#request.getAttribute('req')}"></span><br>
res = <span th:text="${#session.getAttribute('ses')}"></span><br>
app = <span th:text="${#servletContext.getAttribute('app')}"></span><br>
<!-- 获取上下文根 -->
contextPath = <span th:text="${#request.getContextPath()}"></span><br>
<!-- 获取指定参数值 -->
paramValue = <span th:text="${#request.getParameter('param')}"></span><br>
...
启动程序,结果如下:
6.2、表达式实用对象
这些实用对象都是以#开头,由于是对象,所以首字母是小写,且一般都是复数形式,即一般都是以 s 结尾:
属性 | 说明 |
---|---|
#executionInfo | 获取当前 Thymeleaf 模板对象的执行信息。 |
#messages | 获取外部信息。 |
#uris / #urls | URI / URL 处理工具。 |
#conversions | 类型转换工具。 |
#dates | 日期处理工具。 |
#calendars | 日历处理工具。 |
#numbers | 数字处理工具。 |
#strings | 字符串处理工具。 |
#Objects | 对象处理工具。 |
#booleans | 布尔值处理工具。 |
#arrays | 数组处理工具 |
#lists | List处理工具 |
#sets | Set处理工具。 |
#maps | Map处理工具。 |
#aggregates | 聚合处理工具,例如,对数组、集合进行求和、平均值等。 |
#ids | th:id 属性处理工具。 |
举例说明:假设我们要为Controller传递的一个数组求和,聚合处理工具
#aggregates
中有个
sum()
方法,可以帮我们实现:
@GetMapping("/arraySum")
public String arraySum(Model model) {
int[] arr = new int[]{1, 2, 3, 4, 5};
model.addAttribute("arr", arr);
return "index";
}
...
list求和:<span th:text="${#aggregates.sum(arr)}"></span>
...
更多内容请点击标题进入官网。