Thymeleaf 视图集成
SpringBoot 支持多种视图技术集成,并且 SpringBoot 官网推荐使用 Thymeleaf 作为前端视图页面,这里实现Thymeleaf 视图集成,借助入门项目引入 Thymeleaf 环境配置。
starter坐标引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
添加 Thymeleaf 配置信息
Thymeleaf 默认默认视图路径 resources/templates 目录(由自动化配置类 ThymeleafProperties 类决定),该目录可以进行在 application.yml 中进行修改。
## 环境选择配置
spring:
# thymeleaf配置
thymeleaf:
# 前缀(资源存放的路径)
prefix: classpath:/html/
# 关闭 thymeleaf 页面缓存
cache: false
编写 IndexController 控制器转发视图
@Controller
public class IndexController {
@RequestMapping("index")
public String index(Model model) {
// 设置请求域的值
model.addAttribute("msg", "Hello SpringBoot");
return "index";
}
}
html 目录下添加 index.html 视图
修改 Thymeleaf 模板默认存放路径 (在 resources 目录下创建 html 文件夹)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf视图</title></head>
<body>
<!-- 获取请求域的值 -->
<h2 th:text="${msg}"></h2>
</body>
</html>