官网:Thymeleaf官网地址
Thymeleaf模板文件后缀名就是.html,我之前用过的freemarker,它的文件后缀名是.ftl
org.springframework.boot
spring-boot-starter-thymeleaf
引入这个启动类之后,我们可以找到ThymeleafAutoConfiguration这个配置类查看相关配置
@AutoConfiguration(
after = {WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class}
)
@EnableConfigurationProperties({ThymeleafProperties.class})
@ConditionalOnClass({TemplateMode.class, SpringTemplateEngine.class})
@Import({ReactiveTemplateEngineConfiguration.class, DefaultTemplateEngineConfiguration.class})
public class ThymeleafAutoConfiguration {
public ThymeleafAutoConfiguration() {
}
...
然后我们跟到ThymeleafProperties这个类,发现这个类配置了Thymeleaf模板文件的前缀和后缀
这就是为什么Thymeleaf模板文件都放在templates文件夹下,而且后缀为.html
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
...
我们先写一个controller层接口
package com.decade.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/test")
public class TestController {
@RequestMapping(value = "/testPage")
public String testPage(Model model) {
model.addAttribute("msg", "test OK
");
model.addAttribute("pageContent", "test OK
");
model.addAttribute("userList", Arrays.asList("decade", "十年"));
return "test";
}
}
然后在templates文件夹下编写一个html文件
DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试页面title>
head>
<body>
<div th:text="${msg}">div>
<div th:utext="${pageContent}">div>
<hr/>
<h2 th:each="user:${userList}" th:text="${user}">h2>
body>
html>
访问接口后我们可以发现,页面可以直接转到我们的html页面,而且也可以直接使用后端返回的变量
我们并不需要像之前Spring MVC中那样配置视图解析器,这是因为thymeleaf模板引擎帮我们做了

thymeleaf官网:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
在使用thymeleaf之前,我们需要在html中声明thymeleaf的命名空间,xmlns:th=“http://www.thymeleaf.org”
Thymeleaf 作为一种模板引擎,它拥有自己的语法规则,主要分为
${...},作用为获取对象的属性和方法,使用内置的基本对象,使用内置的工具对象*{...},选择变量表达式与变量表达式功能基本一致,只是在变量表达式的基础上增加了与 th:object 的配合使用,当使用 th:object 存储一个对象后,我们可以在其后代中使用选择变量表达式*{...} 获取该对象中的属性,其中,“*”即代表该对象@{...},不管是静态资源的引用,还是 form 表单的请求,凡是链接都可以用链接表达式,它会自动拼接上当前项目的访问路径#{...},一般用于国际化~{...},片段引用表达式用于在模板页面中引用其他的模板片段