Thymeleaf的意思是模板引擎,适用于Web和独立环境,能够处理HTML,XML,JavaScript,CSS甚至纯文本,类似于Velocity,FreeMaker等传统的java模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型.
它既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。
事实上, Thymeleaf 除了展示基本的 HTML ,进行页面渲染之外,也可以作为一个 HTML 片段进行渲染,例如我们在做邮件发送时,可以使用 Thymeleaf 作为邮件发送模板。
另外,由于 Thymeleaf 模板后缀为 .html,可以直接被浏览器打开,因此,预览时非常方便。
首先进行创建项目

SpringBoot整合Thymeleaf非常容易,只需要在创建项目时加入Thymeleaf即可
创建完成后,它的pom文件如下:

当然,Thymeleaf不仅可以在SpringBoot当中使用,还可以用到其他地方,只是SpringBoot对于Thymeleaf提供了一整套的自动化配置方案, 这一套配置类的属性在org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties中,源码如下:
- package com.example.config;
-
- import org.springframework.boot.context.properties.ConfigurationProperties;
-
- import java.nio.charset.Charset;
- import java.nio.charset.StandardCharsets;
-
- @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;
- }
首先通过@ConfigurationProperties注解,将application.properties前缀为spring.thymeleaf的配置和这个类中的属性进行绑定
前三个static变量定义的是:默认编码格式;视图解析器前缀;后缀;
从前三行的配置中可以看出,Thymeleaf模板的默认位置是在resources/templates的目录下,默认的后缀是.html
这些配置如果自己提供,则在application.properties中以spring.thymeleaf为前缀开始进行相关配置,如果不自己提供,则使用默认的
我们刚才提到的SpringBoot为Thymeleaf提供了自动化配置类,则是org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,源码如下:
- package com.example.config;
-
- import org.springframework.boot.autoconfigure.AutoConfigureAfter;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
- import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
- import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
- import org.springframework.boot.context.properties.EnableConfigurationProperties;
- import org.springframework.context.annotation.Configuration;
- import org.thymeleaf.spring5.SpringTemplateEngine;
- import org.thymeleaf.templatemode.TemplateMode;
-
- @Configuration
- @EnableConfigurationProperties(ThymeleafProperties.class)
- @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
- @AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
- public class ThymeleafAutoConfiguration {
- }
我们可以看到在这个自动化配置类中,首先导入的是ThymeleafProperties,然后@ConditionalOnClass注解表示当前系统中存在TemplateMode和springTemplateEngine类时,当前的自动化配置类才会生效,所以只要引入了Thymeleaf相关的依赖,这个配置就会生效
这些默认的配置我们几乎不需要做任何更改就可以直接进行使用,如果开发者有特殊需求,则可以在application.properties中配置以spring.thymeleaf为前缀的属性
接下来我们创建Controller,实际上在我们引入了Thymeleaf的依赖之后,我们可以不用做任何的配置了,新建的IndexController如下:
- package com.example.controller;
-
- import com.example.pojo.User;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.GetMapping;
-
- import java.util.ArrayList;
- import java.util.List;
-
- @Controller
- public class IndexController {
- @GetMapping("/index")
- public String index(Model model) {
- List<User> users = new ArrayList<>();
- for (int i = 0; i < 10; i++) {
- User u = new User();
- u.setId((long) i);
- u.setName("大黄:" + i);
- u.setAddress("济南:" + i);
- users.add(u);
- }
- model.addAttribute("users", users);
- return "index";
-
- }
- }
-
- @Data
- @Accessors(chain = true)
- public class User {
- private Long id;
- private String name;
- private String address;
- }
在IndexController中返回逻辑视图名和数据,逻辑视图名为index,意思是我们需要在resources/templates目录下创建一个index.html的Thyleaf模板文件
创建Thymeleaf
- <!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 th:each="user : ${users}">
- <td th:text="${user.id}"></td>
- <td th:text="${user.name}"></td>
- <td th:text="${user.address}"></td>
- </tr>
- </table>
- </body>
- </html>
在Thymeleaf中,通过th:each指令来遍历一个集合,数据的展示通过th:text的指令来实现
注意index.html最上面要引入thymeleaf名称文件
配置完成后,就可以启动项目了,访问/index接口,就能看到集合中的数据了
另外Thymeleaf支持js中直接获取Model中的变量,例如在IndexController中有一个变量username:
- @Controller
- public class IndexController {
- @GetMapping("/index")
- public String index(Model model) {
- model.addAttribute("username", "李四");
- return "index";
- }
- }
通过页面模板,可以直接在js中获取到这个变量
- <script th:inline="javascript">
- var username = [[${username}]];
- console.log(username)
- </script>
上面我们说返回一个Thymeleaf模板,我们也可以手动渲染Thymeleaf模板,一般在发送邮件时使用,例如我们在resources/templates目录下新建一个邮件模板mail.html,如下:
- <!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模板渲染成一个String字符串,再把这个字符串通过邮件的方式发送出去,那么该如何进行手动渲染呢?
- package com.example;
-
- import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.thymeleaf.TemplateEngine;
- import org.thymeleaf.context.Context;
-
- @SpringBootTest
- class mail {
- @Autowired
- TemplateEngine templateEngine;
- @Test
- void test1(){
- Context context = new Context();
- context.setVariable("username", "javaboy");
- context.setVariable("position", "Java工程师");
- context.setVariable("salary", 99999);
- String mail = templateEngine.process("mail", context);
-
- System.out.println(mail);
- }
- }
在渲染时,我们需要首先注入一个TemplateEngine对象,这个对象在Thymeleaf的自动化配置类中配置的(即当我们引入Thymeleaf这个依赖之后,这个实例就有了)
然后构造一个Context对象用来存放变量
调用process方法进行渲染,该方法的返回值就是渲染之后的HTML字符串,然后我们将这个字符串发送回去
以上内容就是Spring Boot整合Thymeleaf的几个关键点,希望能够帮助到大家