1、导入Thymeleaf依赖
<!--Thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在创建项目时,选择打钩Thymeleaf场景也可以
2、导入Thymeleaf在application的配置
#Thymeleaf配置
spring:
thymeleaf:
prefix: classpath:/templates/ #默认访问路径 url前缀
suffix: .html #后缀
mode: HTML5 #模板格式
encoding: UTF-8 #模板编码格式
servlet:
content-type: text/html #内容类型
cache: false #是否启用模板缓存,开发时不建议开启
3、编写测试使用Controller
public class Controller {
@GetMapping("name")
public String getName(Model model){
model.addAttribute("name","hello,thymeleaf!");
return "name";
}
}
返回值类型使用String类型或Model或ModelAndView都行
4、在resources下templates下,编写h5页面
记得导入模板连接在HTML标签中:xmlns:th=“http://www.thymeleaf.org”
<!DOCTYPE html>
<!--记得导入模板连接:xmlns:th="http://www.thymeleaf.org"-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<h1 th:text="${name}"></h1>
</div>
</body>
</html>
5、运行测试
![aaa](https://img-blog.csdnimg.cn/20210302173124595.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl81MDgzOTE4Nw==,size_16,color_FFFFFF,t_70)
小提示:使用Thymeleaf模板时,在templates下的页面跳转时,使用a标签进行页面跳转,自我感觉行不通,好像必须通过Controller来实现页面跳转。
简单的SpringBoot整合Thymeleaf,深入学习,官方文档:www.thymeleaf.org
点个赞吧!谢谢!