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

时间:2022-07-23
本文章向大家介绍【原创】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
  • Groovy
  • JSP

上面并没有列举所有SpringBoot支持的页面模板技术。其中Thymeleaf是SpringBoot官方所推荐使用的,下面来谈谈Thymeleaf一些常用的语法规则。

添加依赖包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Boot默认存放模板页面的路径在

src/main/resources/templates或者src/main/view/templates,但是index.html默认是在static目录下。

这个无论是使用什么模板语言都一样,当然默认路径是可以自定义的,不过一般不推荐这样做。另外Thymeleaf默认的页面文件后缀是.html

application.properties添加配置项

#开启thymeleaf视图解析
spring.thymeleaf.enabled=true
#编码为UTF-8
spring.thymeleaf.encoding=UTF-8
#是否使用缓存(开发环境建议使用false,线上使用true)
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#严格执行HTML语法格式
spring.thymeleaf.mode=HTML
#模式
spring.thymeleaf.servlet.content-type=text/html

在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 th:text="'用户名称:' + ${name}"/>
</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相关的,请关注官网

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

Thymeleaf的demo案例(集成Spring 、Spring Security 3.x and 4.x)

https://github.com/thymeleaf