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>

 

posted on   companion  阅读(76)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示