23-springboot集成thymeleaf

发布时间 2023-04-03 15:28:51作者: companion

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>