SpringBoot整合Thymeleaf1.简介2.整

「这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战」。

1.简介

Spring Boot 提供了大量模板引擎,包括: FreeMarker /Groovy /Mustache /Thymeleaf /Velocity/ Beetl

  • 为什么使用Thymeleaf?

Spring Boot 官方中推荐使用 Thymeleaf 作为模板引擎,主要原因Thymeleaf有以下三大特性:

  1. Thymeleaf 在有网络和无网络的环境下皆可运行。它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。对前后端分离不明确业务的很多公司,减轻了前端人员负担。

  2. Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板亦可以扩展和创建自定义的方言。

  3. Thymeleaf 提供了完美的 Spring MVC 支持,可以快速的实现表单绑定、属性编辑器、国际化等功能。

  • 怎么使用?

现在Thymeleaf已经更新到3.0版本,可以进入官网:www.thymeleaf.org/查看使用教程来学习,下面我来具体介绍一下SpringBoot该如何整合Thymeleaf!

image.png

2.整合

  • 在创建SpringBoot时,引擎中选择Thymeleaf

image.png

  • 添加依赖

pom.xml中增加spring-boot-starter-thymelea依赖 ,作用是自动配置 ;因为Thymeleaf可以让我们在html 标签里增加额外的属性,我们可能使用非严格的 HTML 语法,所以还需要加上一个nekohtml依赖,来解决这个问题。

        <!-- 支持非严格语法的neko -->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>
        
         <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

复制代码
  • yml文件中配置Thymeleaf

主要有两个配置:

cache: false #开发阶段建议关闭缓存

mode: LEGACYHTML5 #用非严格的HTML5 默认是HTML5

注意:使用spring.thymeleaf.mode=LEGCYHTML5去掉验证,是为了不想对标签进行严格的验证,这就是为什么要引入NekoHTML包的原因。

spring:
  thymeleaf:
    encoding: UTF-8  #编码规范 默认
    cache: false #开发阶段建议关闭缓存
    prefix: classpath:/templates/ 
    suffix: .html
    mode: LEGACYHTML5 #用非严格的HTML5 默认是HTML5
    servlet:
      content-type: text/html
复制代码
  • 创建html页面

在 templates 目录下创建 index.html 文件,

修改 html 标签用于引入 thymeleaf 引擎,这样才可以在其他标签里使用 th:* 语法,声明如下:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html  xmlns:th="http://www.thymeleaf.org">
复制代码

代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
    模版引擎主页的HTML页面
    <p th:text="${msg}">信息显示</p>
</body>
</html>
复制代码

这样springboot整合Thymeleaf就已经结束,接下来编写可通过编写控制层请求访问或者直接请求访问就不在这里描述了!

  • 附加知识点

SpringBoot使用thymeleaf作为视图展示,约定将模板文件放置在src/main/resource/templates目录下,即templates文件夹,是放置模板文件的,因此需要视图解析器来解析它。如果想直接访问html就把它放置在static目录下。