一、前言

开发传统 Java WEB 工程时,我们可以使用 JSP 页面模板语言,但是在 SpringBoot 中已经不推荐使用了。SpringBoot 支持如下页面模板语言等

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • JSP

其中 Thymeleaf 是 SpringBoot 官方所推荐使用的

二、Thymeleaf 介绍

在应用开发中,可以使用 Thymeleaf 来完全代替 JSP

模板:将一些重复内容写好,其中某些可能发生变化的内容,采用占位符方式动态加载(JSP)

模板引擎技术:可以基于写好的模板,动态给写好的模板加载数据。

Thymeleaf:Thymeleaf 是一个模板引擎工具,主要用于页面渲染操作(页面数据填充操作),可以取代之前的 jsp 操作

三、Springboot 整合

使用 springboot 来集成使用 Thymeleaf 可以大大减少单纯使用 thymleaf 的代码量,接下来使用 springboot 集成使用 thymeleaf.

创建一个Springboot 工程 springboot-thymeleaf

1、添加 pom 依赖

1
2
3
4
5
6
7
8
9
10
11
<!-- 添加thymeleaf的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--热部署插件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

2、创建 html

resources\templates 目录下创建 demo.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="zh">
<!--这句声明使用thymeleaf标签-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Thymeleaf入门</title>
</head>
<body>
<!-- 输出helloOutput数据
th:text="${变量名}" :表示使用thymeleaf获取文本数据,类似于EL表达式。
thymeleaf:都是作用于HTML标签之上 -->
<p th:text="${helloOutput}"></p>
</body>
</html>
</html>

3、修改 application.yml 配置

IDEA 创建 Springboot 工程每次出来的都是 application.properties 文件

将此文件后缀名改为 yml

Thymeleaf 默认会开启页面缓存,提高页面并发能力,但会导致我们修改页面不会立即被展现,所以关闭缓存会更快显示

thymeleaf 的缓存设置为 false

1
2
3
spring:
thymeleaf:
cache: false

4、创建 Controller

创建 TestController,用于测试后台,设置数据到 model 中

1
2
3
4
5
6
7
8
9
@Controller
public class TestController {

@RequestMapping("/get")
public String hello(Model model) {
model.addAttribute("helloOutput", "Hello Thymeleaf");
return "demo";
}
}

5、测试

运行主程序SpringbootThymeleafApplication

浏览器访问:http://localhost:8080/get

6、关于 model.addattribute()

model.addattribute()的作用:往前台传数据,可以传对象,可以传 List

通过 el 表达式 ${}或者使用 thymeleaf 获取文本数据