本文参考自江南一点雨的Spring Boot+Vue系列视频教程第 3 章,详情参加【Spring Boot+Vue系列视频教程】
文章目录
springboot+Thymeleaf(详解)
现在开发虽然流行前后端分离,但是后端模板在一些关键地方还是非常有用的,例如邮件模板、代码模板等。当然也不排除一些老项目中依然使用动态模板。
一、Thymeleaf简介
Thymeleaf简介漂亮、容易理解,并且完美支持HTML5, 可以直接打开静态界面,同时不新增标签,只需要增强属性。Thymeleaf是新一代java模板引擎,它既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实的数据查看显示效果,同时,SpringBoot提供的Thymeleaf自动配置解决方案让开发更加方便。
事实上,Thymeleaf除了展示基本的HTML,进行页面渲染之外,也可以作为一个HTML片段进行渲染,例如我们在做邮件发送时,可以使用Thymeleaf作为右键发送模板。另外,由于thymeleaf模板后缀为html,可以直接被浏览器打开,因此,预览时非常方便。
二、整合springboot
1.基本用法
创建项目时,添加Thymeleaf
创建完成后,pom.xml中有以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
当然,thymeleaf不仅仅能在springboot中使用,也可以使用在其他地方。
springboot提供的配置类的属性源码在
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
部分源码如下:
//通过注解将application.properties前缀为spring.thymeleaf的配置和这个类中的属性绑定
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
//定义编码格式:
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
//定义视图解析器的前缀后缀
public static final String DEFAULT_PREFIX = "classpath:/templates/"; //默认位置
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = DEFAULT_PREFIX;
private String suffix = DEFAULT_SUFFIX;
private String mode = "HTML";
private Charset encoding = DEFAULT_ENCODING;
private boolean cache = true;
//...
}
springboot提供的自动化配置类源码分析:
@Configuration
//导入ThymeleafProperties
@EnableConfigurationProperties(ThymeleafProperties.class)
//当前系统中存在templateMode和SpringTemplateEngine才会生效
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}
总结:
# 一般情况下引入thymeleaf依赖之后,我们不需要做任何配置,除非你需要个性化配置!
2.演示
2.1 创建Controller
@Controller
public class IndexController {
@Autowired
private User user;
@GetMapping("index")
public String index(Model model){
user.setName("王泽");
user.setAge(20);
user.setHobby("美女");
model.addAttribute(user);
return "index";
}
@Data
@Component
public class User {
private String name;
private Integer age;
private String hobby;
}
2.2 创建index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>编号</td>
<td>用户名</td>
<td>地址</td>
</tr>
<tr>
<td th:text="${user.age}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.hobby}"></td>
</tr>
</table>
</body>
</html>
三、手动渲染
我们之前是返回一个thymeleaf模板,我们也可以手动渲染模板,这个一般在邮件发送的时候有用,例如我在templates目录下新建一个邮件模板:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>hello 欢迎 <span th:text="${username}"></span>加入 XXX 集团,您的入职信息如下:</p>
<table border="1">
<tr>
<td>职位</td>
<td th:text="${position}"></td>
</tr>
<tr>
<td>薪水</td>
<td th:text="${salary}"></td>
</tr>
</table>
<img src="http://www.javaboy.org/images/sb/javaboy.jpg" alt="">
</body>
</html>
这一个HTML模板中,有几个变量,我们哟啊将这个HTML模板渲染成一个string字符串,如何渲染呢?
@Autowired
TemplateEngine templateEngine;
@Test
public void test1() throws MessagingException {
Context context = new Context();
context.setVariable("username", "javaboy");
context.setVariable("position", "Java工程师");
context.setVariable("salary", 99999);
String mail = templateEngine.process("mail", context);
}
- 渲染时,我们需要首先注入一个 TemplateEngine 对象,这个对象就是在 Thymeleaf 的自动化配置类中配置的(即当我们引入 Thymeleaf 的依赖之后,这个实例就有了)。
- 然后构造一个 Context 对象用来存放变量。
- 调用 process 方法进行渲染,该方法的返回值就是渲染后的 HTML 字符串,然后我们将这个字符串发送出去。
四、Thymeleaf语法详解
1.标准表达式语法
1.1 简单表达式
直接使用 th:xx = "${...}" 获取对象属性
-
*{…}
可以像 ${....} 一样使用,也可以通过 th:object获取对象,然后使用 th:xx = "*{...}" 获取对象属性,这种风格很清爽,推荐大家使用! <table border="1" th:object="${user}"> <tr> <td>编号</td> <td>用户名</td> <td>地址</td> </tr> <tr> <td th:text="*{age}"></td> <td th:text="*{name}"></td> <td th:text="*{hobby}"></td> </tr> </table>
-
#{…}
通常国际化属性: #{...} 用户获取国际化语言翻译值。 1.在resource目录下新建两个文件: messages.properties 和messages_zh_CN.properties messages.properties: message = handsomeWang messages_zh_CN.properties: message = 王泽 2.在thymeleaf中引用message,系统会根据浏览器的语言环境显示不同的值: <div th:text="#{message}"></div>
-
@{…}
-
引用绝对Url
<script type="text/javascript" th:src="@{http://localhost:8080/hello.js}"></script> 等价于 <script type="text/javascript" src="http://localhost:8080/hello.js"></script>
-
上下文相爱难改观的URL
首先在 application.properties 中配置 Spring Boot 的上下文,以便于测试: server.servlet.context-path=/myapp
引用路径:
<script type="text/javascript" th:src="@{/hello.js}"></script> 等价于 <script type="text/javascript" src="/myapp/hello.js"></script>
-
相对URL
这个相对,指的是相对于服务器的URL
<script type="text/javascript" th:src="@{~/hello.js}"></script> 等价于 <script type="text/javascript" src="/hello.js"></script>
应用程序的上下文 /myapp 将被忽略。
-
协议相对URL
<script type="text/javascript" th:src="@{//localhost:8080/hello.js}"></script> 等价于 <script type="text/javascript" src="//localhost:8080/hello.js"></script>
-
带参数的URL
<script type="text/javascript" th:src="@{//localhost:8080/hello.js(name='javaboy',age=99)}"></script> 等价于 <script type="text/javascript" th:src="//localhost:8080/hello.js?name=javaboy&age=99"></script>
-
-
~{…}
片段表达式是Thymeleaf的特色之一,细粒度可以达到标签级别,这是jsp无法做到的,片段表达式拥有三种语法:
~{ viewName }:表示引入完整页面 ~{ viewName ::selector}:表示在指定页面寻找片段,其中 selector 可为片段名、jquery选择器等 ~{ ::selector}:表示在当前页寻找
例子:在resource/templates 目录下新建my_fragment.html
<div th:fragment="javaboy_link"><a href="http://www.javaboy.org">www.javaboy</a></div> <div th:fragment="itboyhub_link"><a href="http://www.itboyhub.com">www.itboyhub.com</a></div>
这里有两个 div,通过 th:fragment 来定义片段,两个 div 分别具有不同的名字。
然后在另外一个页面中引用该片段:
<table border="1" th:object="${user}" th:fragment="aaa"> <tr> <td>用户名</td> <td th:text="*{username}"></td> </tr> <tr> <td>地址</td> <td th:text="*{address}"></td> </tr> </table> <hr> <div th:replace="my_fragment.html"></div> <hr> <div th:replace="~{my_fragment.html::javaboy_link}"></div> <hr> <div th:replace="~{::aaa}"></div>
通过 th:replace 来引用片段。第一个表示引用完整的
my_fragment.html
页面;第二个表示引用
my_fragment.html
中的名为javaboy_link
的片段;第三个表示引用当前页面名为 aaa 的片段,也就是上面那个 table。
1.2.字面量
这些是一些可以直接写在表达式中的字符,主要有如下几种:
- 文本字面量:‘one text’, ‘Another one!’,…
- 数字字面量:0, 34, 3.0, 12.3,…
- 布尔字面量:true, false
- Null字面量:null
- 字面量标记:one, sometext, main,…
案例:
<div th:text="'这是 文本字面量(有空格)'"></div>
<div th:text="javaboy"></div>
<div th:text="99"></div>
<div th:text="true"></div>
如果文本是英文,并且不包含空格、逗号等字符,可以不用加单引号。
1.3 文本运算
文本可以使用 +
进行拼接。
<div th:text="'hello '+'javaboy'"></div>
<div th:text="'hello '+${user.username}"></div>
如果字符串中包含变量,也可以使用另一种简单的方式,叫做字面量置换,用 |
代替 '...' + '...'
,如下:
<div th:text="|hello ${user.username}|"></div>
<div th:text="'hello '+${user.username}+' '+|Go ${user.address}|"></div>
1.4 算数运算
算术运算有:+
, -
, *
, /
和 %
。
<div th:with="age=(99*99/99+99-1)">
<div th:text="${age}"></div>
</div>
th:with 定义了一个局部变量 age,在其所在的 div 中可以使用该局部变量。
1.5 布尔运算
- 二元运算符:and, or
- 布尔非(一元运算符):!, not
案例:
<div th:with="age=(99*99/99+99-1)">
<div th:text="9 eq 9 or 8 ne 8"></div>
<div th:text="!(9 eq 9 or 8 ne 8)"></div>
<div th:text="not(9 eq 9 or 8 ne 8)"></div>
</div>
1.6 比较和相等
表达式里的值可以使用 >
, <
, >=
和 <=
符号比较。==
和 !=
运算符用于检查相等(或者不相等)。注意 XML
规定 <
和 >
标签不能用于属性值,所以应当把它们转义为 <
和 >
。
如果不想转义,也可以使用别名:gt (>);lt (<);ge (>=);le (<=);not (!)。还有 eq (==), neq/ne (!=)。
举例:
<div th:with="age=(99*99/99+99-1)">
<div th:text="${age} eq 197"></div>
<div th:text="${age} ne 197"></div>
<div th:text="${age} ge 197"></div>
<div th:text="${age} gt 197"></div>
<div th:text="${age} le 197"></div>
<div th:text="${age} lt 197"></div>
</div>
1.7 条件运算符
类似于我们 Java 中的三目运算符。
<div th:with="age=(99*99/99+99-1)">
<div th:text="(${age} ne 197)?'yes':'no'"></div>
</div>
其中,: 后面的部分可以省略,如果省略了,又同时计算结果为 false 时,将返回 null。
1.8 内置对象
基本内置对象:
- #ctx:上下文对象。
- #vars: 上下文变量。
- #locale:上下文区域设置。
- #request:(仅在 Web 上下文中)HttpServletRequest 对象。
- #response:(仅在 Web 上下文中)HttpServletResponse 对象。
- #session:(仅在 Web 上下文中)HttpSession 对象。
- #servletContext:(仅在 Web 上下文中)ServletContext 对象。
在页面可以访问到上面这些内置对象,举个简单例子:
<div th:text='${#session.getAttribute("name")}'></div>
实用内置对象:
- #execInfo:有关正在处理的模板的信息。
- #messages:在变量表达式中获取外部化消息的方法,与使用#{…}语法获得的方式相同。
- #uris:转义URL / URI部分的方法
- #conversions:执行配置的转换服务(如果有)的方法。
- #dates:java.util.Date对象的方法:格式化,组件提取等
- #calendars:类似于#dates但是java.util.Calendar对象。
- #numbers:用于格式化数字对象的方法。
- #strings:String对象的方法:contains,startsWith,prepending / appending等
- #objects:一般对象的方法。
- #bools:布尔评估的方法。
- #arrays:数组方法。
- #lists:列表的方法。
- #sets:集合的方法。
- #maps:地图方法。
- #aggregates:在数组或集合上创建聚合的方法。
- #ids:处理可能重复的id属性的方法(例如,作为迭代的结果)。
这是一些内置对象以及工具方法,使用方式也都比较容易,如果使用的是 IntelliJ IDEA,都会自动提示对象中的方法,很方便。
举例:
<div th:text="${#execInfo.getProcessedTemplateName()}"></div>
<div th:text="${#arrays.length(#request.getAttribute('names'))}"></div>
2.设置属性值
这个是给 HTML 元素设置属性值。可以一次设置多个,多个之间用 ,
分隔开。
例如:
<img th:attr="src=@{/1.png},title=${user.username},alt=${user.username}">
会被渲染成:
<img src="/myapp/1.png" title="javaboy" alt="javaboy">
当然这种设置方法不太美观,可读性也不好。==Thymeleaf 还支持在每一个原生的 HTML 属性前加上 th: 前缀的方式来使用动态值,==像下面这样:
<img th:src="@{/1.png}" th:alt="${user.username}" th:title="${user.username}">
这种写法看起来更清晰一些,渲染效果和前面一致。
上面案例中的 alt 和 title 则是两个特殊的属性,可以一次性设置,像下面这样:
<img th:src="@{/1.png}" th:alt-title="${user.username}">
这个等价于前文的设置。
3.遍历
数组/集合/Map/Enumeration/Iterator 等的遍历也算是一个非常常见的需求,Thymeleaf 中通过 th:each 来实现遍历,像下面这样:
<table border="1">
<tr th:each="u : ${users}">
<td th:text="${u.username}"></td>
<td th:text="${u.address}"></td>
</tr>
</table>
users 是要遍历的集合/数组,u 则是集合中的单个元素。
遍历的时候,我们可能需要获取遍历的状态,Thymeleaf 也对此提供了支持:
- index:当前的遍历索引,从0开始。
- count:当前的遍历索引,从1开始。
- size:被遍历变量里的元素数量。
- current:每次遍历的遍历变量。
- even/odd:当前的遍历是偶数次还是奇数次。
- first:当前是否为首次遍历。
- last:当前是否为最后一次遍历。
u 后面的 state 表示遍历状态,通过遍历状态可以引用上面的属性。
<table border="1">
<tr th:each="u,state : ${users}">
<td th:text="${u.username}"></td>
<td th:text="${u.address}"></td>
<td th:text="${state.index}"></td>
<td th:text="${state.count}"></td>
<td th:text="${state.size}"></td>
<td th:text="${state.current}"></td>
<td th:text="${state.even}"></td>
<td th:text="${state.odd}"></td>
<td th:text="${state.first}"></td>
<td th:text="${state.last}"></td>
</tr>
</table>
4.分支语句
只显示奇数次的遍历,可以使用 th:if,如下:
<table border="1">
<tr th:each="u,state : ${users}" th:if="${state.odd}">
<td th:text="${u.username}"></td>
<td th:text="${u.address}"></td>
<td th:text="${state.index}"></td>
<td th:text="${state.count}"></td>
<td th:text="${state.size}"></td>
<td th:text="${state.current}"></td>
<td th:text="${state.even}"></td>
<td th:text="${state.odd}"></td>
<td th:text="${state.first}"></td>
<td th:text="${state.last}"></td>
</tr>
</table>
th:if 不仅仅只接受布尔值,也接受其他类型的值,例如如下值都会判定为 true:
- 如果值是布尔值,并且为 true。
- 如果值是数字,并且不为 0。
- 如果值是字符,并且不为 0。
- 如果值是字符串,并且不为 “false”, “off” 或者 “no”。
- 如果值不是布尔值,数字,字符或者字符串。
但是如果值为 null,th:if 会求值为 false。
th:unless 的判定条件则与 th:if 完全相反。
<table border="1">
<tr th:each="u,state : ${users}" th:unless="${state.odd}">
<td th:text="${u.username}"></td>
<td th:text="${u.address}"></td>
<td th:text="${state.index}"></td>
<td th:text="${state.count}"></td>
<td th:text="${state.size}"></td>
<td th:text="${state.current}"></td>
<td th:text="${state.even}"></td>
<td th:text="${state.odd}"></td>
<td th:text="${state.first}"></td>
<td th:text="${state.last}"></td>
</tr>
</table>
这个显示效果则与上面的完全相反。
当可能性比较多的时候,也可以使用 switch:
<table border="1">
<tr th:each="u,state : ${users}">
<td th:text="${u.username}"></td>
<td th:text="${u.address}"></td>
<td th:text="${state.index}"></td>
<td th:text="${state.count}"></td>
<td th:text="${state.size}"></td>
<td th:text="${state.current}"></td>
<td th:text="${state.even}"></td>
<td th:text="${state.odd}"></td>
<td th:text="${state.first}"></td>
<td th:text="${state.last}"></td>
<td th:switch="${state.odd}">
<span th:case="true">odd</span>
<span th:case="*">even</span>
</td>
</tr>
</table>
th:case="*"
则表示默认选项。
5.本地变量
使用 th:with 可以定义一个本地变量。
6.内联
我们可以使用属性将数据放入页面模版中,但是很多时候,内联的方式看起来更加直观一些,像下面这样:
<div>hello [[${user.username}]]</div>
用内联的方式去做拼接也显得更加自然。
[[...]]
对应于 th:text (结果会是转义的 HTML),[(...)]
对应于 th:utext,它不会执行任何的 HTML 转义。
像下面这样:
<div th:with="str='hello <strong>javaboy</strong>'">
<div>[[${str}]]</div>
<div>[(${str})]</div>
</div>
显示效果:
不过内联方式有一个问题。我们使用 Thymeleaf 的一大优势在于不用动态渲染就可以直接在浏览器中看到显示效果,当我们使用属性配置的时候确实是这样,但是如果我们使用内联的方式,各种表达式就会直接展示在静态网页中。
也可以在 js 或者 css 中使用内联,以 js 为例,使用方式如下:
<script th:inline="javascript">
var username=[[${user.username}]]
console.log(username)
</script>
js 中需要通过 th:inline="javascript"
开启内联。