将后台从数据库中查询到的数据填到静态模板中的占位符的位置
将Thymeleaf依赖添加到pom.xml文件中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
另有一说:引入Thymeleaf的依赖为:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.1.0.RC1</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
在application.propertiers进行配置:
#排除静态文件夹
spring.devtools.restart.exclude=static/**,public/**
#关闭 Thymeleaf 缓存开发过程中无须重启
spring.thymeleaf.cache = false
#设置thymeleaf页面的编码
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#设置thymeleaf页面的后缀为.html
spring.thymeleaf.suffix=.html
#设置thymeleaf页面的存储路径
spring.thymeleaf.prefix=classpath:/templates/
在Controller包中建立一个UserController类,在里面写一个addUser()方法:
@Controller
public class UserController
{
@GetMapping("/addUser")
public String addUser(Model model)
{
model.addAttribute("title","I miss CC very much");
return "user/addUser";
//自动跳转到resources/templates/user/addUser.html,也就是说会自动将字符串拼接到resources/templates后面
}
}
在resources/templates下新建一个user目录,然后再新建一个addUser.html文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
标题是:
<p th:text="${title}">hello</p>
</body>
</html>
当在浏览器中输入/addUser时,会调用这里的addUser方法,会跳转到resources文件夹下面的templates目录下的user目录下的addUser.html页面(同时设置数据title为i miss CC very much)
在浏览器中访问localhost:8080/addUser