SpringBoot整合Thymeleaf
搭建springboot环境
1.创建maven项目
加入依赖
我用的springboot2.7.7版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
dependencies依赖, commons-lang3和lombok看自己编码习惯, 非必须.
<dependencies>
<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>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
thymeleaf依赖如果用springboot对应的版本会报错, 所以根据众多网友的经验, 降低版本能解决问题, 所以须重新定义thymeleaf版本,覆盖掉它默认的版本
<properties>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
3.编写配置文件
资源目录创建:application.properties
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
表示不实用缓存, 因为测试的时候会因为缓存达不到测试的效果, 我们在项目上线时才考虑打开
spring.thymeleaf.prefix=classpath:/templates/
表示静态页面都从/templates 目录去找, 配置后我们在java代码里就不用写前后缀了
这也是springboot的默认配置
4.创建静态页面
创建页面: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<p>学习Thymeleaf首页</p>
<a href="/hello">1.第一个Springboot的Thymeleaf</a>
</body>
</html>
由于a标签会请求"/hello", 所以我们创建Java类HelloController
@Controller
public class HelloController {
/**
* 参数:Model可以存放数据,放入request域
* 返回值:String表示视图
*/
@RequestMapping(value = "/hello")
public String hello(Model model) {
model.addAttribute("name", "李思");
return "hello";
}
}
当请求"/hello"时, 就跳转到"hello.html", 所以创建页面"hello.html"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>第一个SpringBoot的Thymeleaf</title>
</head>
<body>
<p th:text="${name}"></p>
</body>
</html>
HelloController通过model参数, 将数据name传递给模板, 通过模板引擎解析后, 渲染到页面,
启动项目, 访问:localhost:8080/index.html
点击后跳转访问hello.html页面
即模板引擎已经正确回显了后台传递的数据.