SpringBoot整合Thymeleaf模板
一、前言
开发传统 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 | <!-- 添加thymeleaf的起步依赖 --> |
2、创建 html
在 resources\templates
目录下创建 demo.html
1 |
|
3、修改 application.yml 配置
IDEA 创建 Springboot 工程每次出来的都是 application.properties 文件
将此文件后缀名改为 yml
Thymeleaf 默认会开启页面缓存,提高页面并发能力,但会导致我们修改页面不会立即被展现,所以关闭缓存会更快显示
将thymeleaf
的缓存设置为 false
1 | spring: |
4、创建 Controller
创建 TestController
,用于测试后台,设置数据到 model 中
1 | @Controller |
5、测试
运行主程序SpringbootThymeleafApplication
浏览器访问:http://localhost:8080/get
6、关于 model.addattribute()
model.addattribute()的作用:往前台传数据,可以传对象,可以传 List
通过 el 表达式 ${}或者使用 thymeleaf 获取文本数据