【原创】SpringBoot快速整合Thymeleaf模板引擎

前言
Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:
- Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外 的属性来达到模板 + 数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
- Thymeleaf 开箱即用的特性。它提供标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式效果,避免每天套模板、改 JSTL、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
- Thymeleaf 提供 Spring 标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
Thymeleaf简述
Thymeleaf 是 Java 模板引擎,Spring 官方推荐使用,也是 Spring Boot 默认的模板引擎;前后端分离之前就是thymeleaf这类引擎模板的地盘;其支持HTML5的视图模板,能够无缝衔接springboot;主要用途能进行web开发和非web开发,比如页面渲染,代码生成,文档生成等等,做些日常的小工具是个很好的选择。
开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。SpringBoot支持如下页面模板语言:
- Thymeleaf
- FreeMarker
- Velocity
示例代码
在templates目录下创建hello.html,内容
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot thymeleaf 模版渲染</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
<p th:text="'用户ID:' + ${pwd}"/></p>
<p th:text="'用户名称:' + ${name}"/></p>
</body>
</html>
controller
@Controller
@RequestMapping()
public class ThymeleafController {
@RequestMapping(value = "hello", method = RequestMethod.GET)
public String show(Model model){
model.addAttribute("pwd","123456");
model.addAttribute("name","Java后端技术全栈");
return "hello";
}
}
启动,访问http://localhost:8080/hello
OK,自此Spring Boot 集成Thymeleaf入门搞定。
参考资料
如果想深入的了解Thmeleaf相关的,请关注官网:
Thymeleaf的demo案例(集成Spring 、Spring Security 3.x and 4.x)