23-springboot集成thymeleaf
Spring Boot 官方推荐前端不使用JSP,推荐使用thymeleaf来替代JSP技术;
Thymeleaf是一种模板技术,该模板技术也采用Java语言开发的;
但是thymeleaf是另外一家公司开源做的,并不属于springboot,springboot只是很好地集成这种模板技术,作为前端页面的数据展示;
Thymeleaf的官方网站:http://www.thymeleaf.org
Spring boot 集成 Thymeleaf
1、第一步:在Maven中引入Thymeleaf的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、第二步:在Spring boot核心配置文件application.properties中对Thymeleaf进行配置:
#开发阶段,建议关闭thymeleaf的缓存
spring.thymeleaf.cache=false
3、第三步:写一个Controller去跳转到模板页面(和SpringMVC基本一致):
@RequestMapping("/index")
public String index (Model model) {
model.addAttribute("data", "恭喜,Spring boot集成 Thymeleaf成功!");
//return 中就是你页面的名字(不带.html后缀)
return "index";
}
4、第四步:在src/main/resources 的 templates下新建一个index.html页面用于展示数据:
HTML页面的<html>元素中加入以下属性:
<html xmlns:th="http://www.thymeleaf.org">
使用 th: 开头的属性去展示数据;
Springboot使用thymeleaf作为视图展示,约定将模板文件放置在src/main/resource/templates目录下,静态资源放置在src/main/resource/static目录下
index.html页面的内容如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
thymeleaf展示数据:<br/>
<span>[[${data}]]</span>
</body>
</html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix