SpringBoot整合thymeleaf
2020-03-08 本文已影响0人
CodePandaes
thymeleaf简介
Spring Boot提供了多种模板引擎的默认配置支持,但嵌入式容器JSP有限制,2010年后Velocity停止更新,所以这JSP与Velocity两个不建议使用。而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可。
Thymeleaf的特点
- 动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
- 开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
- 多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
- 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。
和SpringBoot整合
- 新建SpringBoot项目(可参考我的上一篇博客SpringBoot初体验),打开pom.xml,添加thymeleaf依赖
<dependencies>
<!--web容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--前端模板thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
- 打开配置文件application,yml(application.properties),关闭thymeleaf缓存
- 新建HelloWorldController类,返回hello页面
- templates目录下新建hello.html
5.打开SpringBootThymeleafApplication类启动项目
- 浏览器中输入localhost:8080/hello,访问成功