- 第一步:在Maven中引入Thymeleaf的依赖,加入以下依赖配置即可:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 第二步:在Spring boot的核心配置文件application.properties中对Thymeleaf进行配置:
#开发阶段,建议关闭thymeleaf的缓存
spring.thymeleaf.cache=false
#使用遗留的html5以去掉对html标签的校验
spring.thymeleaf.mode=LEGACYHTML5
在使用springboot的过程中,如果使用thymeleaf作为模板文件,则要求HTML格式必须为严格的html5格式,必须有结束标签,否则会报错;如果不想对标签进行严格的验证,使用spring.thymeleaf.mode=LEGACYHTML5去掉验证。去掉验证,则需要引入如下依赖,否则会报错(Springboot2.0+版本可不引入以下依赖):
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
</dependency>
<dependency>
<groupId>org.unbescape</groupId>
<artifactId>unbescape</artifactId>
<version>1.1.5RELEASE</version>
</dependency>
NekoHTML是一个Java语言的HTML扫描器和标签补全器,这个解析器能够扫描HTML文件并“修正”HTML文档中的常见错误。
NekoHTML能增补确实的父元素,自动用结束标签关闭相应的元素,修改不匹配的内嵌标签等;
3. 第三步:写一个Controller去映射到模板页面(和SpringMVC基本一致),比如:
@RequestMapping("/index")
public String index(Model model){
model.addAttribute("data","恭喜,Spring boot 集成Thymeleaf成功!");
//return 中就是页面的名字(不带html后缀)
return "index";
}
- 第四步:在src/main/resources的templates下新建一个index.html页面用于展示数据:
HTML页面的元素中加入以下属性:
<html xmlns:th="http://www.thymeleaf.org">
HTML页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Springboot集成Thymeleaf</title>
</head>
<body>
<p th:text="${data}">Springboot集成Thymeleaf</p>
</body>
</html>
- Springboot使用Thymeleaf作为视图展示,约定将模板文件放置在src/main/resource/templates目录下,静态资源放置在src/main/resource/static目录下