• Spring Boot Thymeleaf(十一)


    一、Thymeleaf 简介

            Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。它与 JSP,Velocity,FreeMaker 等模板引擎类似,也可以轻易地与 Spring MVC 等 Web 框架集成。与其它模板引擎相比,Thymeleaf 最大的特点是,即使不启动 Web 应用,也可以直接在浏览器中打开并正确显示模板页面 。

            Thymeleaf 是新一代 Java 模板引擎,与 Velocity、FreeMarker 等传统 Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。

            Thymeleaf 通过在 html 标签中,增加额外属性来达到“模板+数据”的展示方式,示例代码如下:

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. head>
    7. <body>
    8. <h1 th:text="迎您来到Thymeleaf">欢迎您访问静态页面 HTMLh1>
    9. body>
    10. html>

    当直接使用浏览器打开时,浏览器展示结果如下:


    当通过 Web 应用程序访问时,浏览器展示结果如下: 

     项目参考:五—3.1

    Thymeleaf 模板引擎具有以下特点:

    • 动静结合:Thymeleaf 既可以直接使用浏览器打开,查看页面的静态效果,也可以通过 Web 应用程序进行访问,查看动态页面效果。
    • 开箱即用:Thymeleaf 提供了 Spring 标准方言以及一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
    • 多方言支持:它提供了 Thymeleaf 标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式;必要时,开发人员也可以扩展和创建自定义的方言。
    • 与 SpringBoot 完美整合:SpringBoot 为 Thymeleaf 提供了的默认配置,并且还为 Thymeleaf 设置了视图解析器,因此 Thymeleaf 可以与 Spring Boot 完美整合。

    二、Thymeleaf 语法规则

            在使用 Thymeleaf 之前,首先要在页面的 html 标签中声明名称空间,示例代码如下:

    xmlns:th="http://www.thymeleaf.org"

    在 html 标签中声明此名称空间,可避免编辑器出现 html 验证错误,但这一步并非必须进行的,即使我们不声明该命名空间,也不影响 Thymeleaf 的使用。

    Thymeleaf 作为一种模板引擎,它拥有自己的语法规则。Thymeleaf 语法分为以下 2 类:

    • 标准表达式语法
    • th 属性

    1.标准表达式语法

    Thymeleaf 模板引擎支持多种表达式:

    • 变量表达式:${...}
    • 选择变量表达式:*{...}
    • 链接表达式:@{...}
    • 国际化表达式:#{...}
    • 片段引用表达式:~{...}

    1.1 变量表达式

    使用 ${} 包裹的表达式被称为变量表达式,该表达式具有以下功能:

    • 获取对象的属性和方法
    • 使用内置的基本对象
    • 使用内置的工具对象


    1.1.1 获取对象的属性和方法
            使用变量表达式可以获取对象的属性和方法,例如,获取 person 对象的 lastName 属性,表达式形式如下:

    ${person.name}

    1.1.2 使用内置的基本对象
            使用变量表达式还可以使用内置基本对象,获取内置对象的属性,调用内置对象的方法。 Thymeleaf 中常用的内置基本对象如下:

    • #ctx :上下文对象;
    • #vars :上下文变量;
    • #locale:上下文的语言环境;
    • #request:HttpServletRequest 对象(仅在 Web 应用中可用);
    • #response:HttpServletResponse 对象(仅在 Web 应用中可用);
    • #session:HttpSession 对象(仅在 Web 应用中可用);
    • #servletContext:ServletContext 对象(仅在 Web 应用中可用)。

    例如,我们通过以下 2 种形式,都可以获取到 session 对象中的 map 属性:

    1. ${#session.getAttribute('map')}
    2. ${session.map}

    1.1.3 使用内置的工具对象
            除了能使用内置的基本对象外,变量表达式还可以使用一些内置的工具对象。

    • strings:字符串工具对象,常用方法有:equals、equalsIgnoreCase、length、trim、toUpperCase、toLowerCase、indexOf、substring、replace、startsWith、endsWith,contains 和 containsIgnoreCase 等;
    • numbers:数字工具对象,常用的方法有:formatDecimal 等;
    • bools:布尔工具对象,常用的方法有:isTrue 和 isFalse 等;
    • arrays:数组工具对象,常用的方法有:toArray、length、isEmpty、contains 和 containsAll 等;
    • lists/sets:List/Set 集合工具对象,常用的方法有:toList、size、isEmpty、contains、containsAll 和 sort 等;
    • maps:Map 集合工具对象,常用的方法有:size、isEmpty、containsKey 和 containsValue 等;
    • dates:日期工具对象,常用的方法有:format、year、month、hour 和 createNow 等。

    例如,我们可以使用内置工具对象 strings 的 equals 方法,来判断字符串与对象的某个属性是否相等,代码如下:

    ${#strings.equals('晓杰杰',name)}

    1.2 选择变量表达式

            选择变量表达式与变量表达式功能基本一致,只是在变量表达式的基础上增加了与 th:object 的配合使用。当使用 th:object 存储一个对象后,我们可以在其后代中使用选择变量表达式(*{...})获取该对象中的属性,其中,“*”即代表该对象:

    1. <div th:object="${person}">
    2. 姓名:<span th:text="*{name}">span>br>
    3. 年龄:<span th:text="*{age}">span>br>
    4. 宠物:<span th:text="*{pets}">span>br>
    5. 食物:<span th:text="*{food}">span>br>
    6. div>

    th:object 用于存储一个临时变量,该变量只在该标签及其后代中有效,在后面的内容“th 属性”中我详细介绍。

    1.3 链接表达式

            不管是静态资源的引用,还是 form 表单的请求,凡是链接都可以用链接表达式 (@{...})。
    链接表达式的形式结构如下:

    • 无参请求:@{/xxx}
    • 有参请求:@{/xxx(k1=v1,k2=v2)}

    例如使用链接表达式引入 css 样式表,代码如下:

    <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">

    1.4 国际化表达式

            消息表达式一般用于国际化的场景。结构如下:

    th:text="#{msg}"

    1.5 片段引用表达式

            片段引用表达式用于在模板页面中引用其他的模板片段,该表达式支持以下 2  中语法结构:

    • 推荐:~{templatename::fragmentname}
    • 支持:~{templatename::#id}

            以上语法结构说明如下:

    • templatename:模版名,Thymeleaf 会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
    • fragmentname:片段名,Thymeleaf 通过 th:fragment 声明定义代码块,即:th:fragment="fragmentname"
    • id:HTML 的 id 选择器,使用时要在前面加上 # 号,不支持 class 选择器。

     项目参考:五—3.2 

    2. th 属性

            Thymeleaf 还提供了大量的 th 属性,这些属性可以直接在 HTML 标签中使用,其中常用 th 属性及其示例如下表:

    属性描述示例
    th:id替换 HTML 的 id 属性
     
        
    t文本替换,转义特殊字符
     
        
    • hello

    th:utext文本替换,不转义特殊字符
     
        
    • 欢迎你
    th:object在父标签选择对象,子标签使用 *{…} 选择表达式选取值。
    没有选择对象,那子标签使用选择表达式和 ${…} 变量表达式是一样的效果。
    同时即使选择了对象,子标签仍然可以使用变量表达式。
     
        
    • firstname

    th:value替换 value 属性
     
        
    th:with局部变量赋值运算
     
        
    th:style设置样式
     
        
    • 编程帮 www.biancheng.net
    th:onclick点击事件
     
        
    th:each遍历,支持 Iterable、Map、数组等。
     
     
        
    th:if根据条件判断是否需要展示此标签
     
        
    th:unless和 th:if 判断相反,满足条件时不显示
     
        
    th:switch与 Java 的 switch case语句类似
    通常与 th:case 配合使用,根据不同的条件展示不同的内容
     
        
    • 编程帮
    • www.biancheng.net
    th:fragment模板布局,类似 JSP 的 tag,用来定义一段被引用或包含的模板片段
     
        
    • 插入的内容
    th:insert布局标签;
    将使用 th:fragment 属性指定的模板片段(包含标签)插入到当前标签中。
     
        
    th:replace布局标签;
    使用 th:fragment 属性指定的模板片段(包含标签)替换当前整个标签。
     
        
    th:selectedselect 选择框选中
     
        
    th:src替换 HTML 中的 src 属性 
     
        
    th:inline内联属性;
    该属性有 text、none、javascript 三种取值,
    th:action替换表单提交地址
     
        

    三、Thymeleaf 公共页面抽取

            在 Web 项目中,通常会存在一些公共页面片段(重复代码),例如头部导航栏、侧边菜单栏和公共的 js css 等。我们一般会把这些公共页面片段抽取出来,存放在一个独立的页面中,然后再由其他页面根据需要进行引用,这样可以消除代码重复,使页面更加简洁。

    1.抽取公共页面

            Thymeleaf 作为一种优雅且高度可维护的模板引擎,同样支持公共页面的抽取和引用。我们可以将公共页面片段抽取出来,存放到一个独立的页面中,并使用 Thymeleaf 提供的 th:fragment 属性为这些抽取出来的公共页面片段命名。

    示例 1

    将公共页面片段抽取出来,存放在 commons.html 中,代码如下:

    1. <div th:fragment="fragment-name" id="fragment-id">
    2. <span>公共页面片段span>
    3. div>

    2.引用公共页面

    在 Thymeleaf 中,我们可以使用以下 3 个属性,将公共页面片段引入到当前页面中。

    • th:insert:将代码块片段整个插入到使用了 th:insert 属性的 HTML 标签中;
    • th:replace:将代码块片段整个替换使用了 th:replace 属性的 HTML 标签中;
    • th:include:将代码块片段包含的内容插入到使用了 th:include 属性的 HTML 标签中。


    使用上 3 个属性引入页面片段,都可以通过以下 2 种方式实现。

    • ~{templatename::selector}:模板名::选择器
    • ~{templatename::fragmentname}:模板名::片段名

    通常情况下,~{} 可以省略,其行内写法为 [[~{...}]] 或 [(~{...})],其中  [[~{...}]] 会转义特殊字符,[(~{...})] 则不会转义特殊字符。

    示例 2

    (1). 在页面thymeleaf2.html 中引入 commons.html 中声明的页面片段,可以通过以下方式实现:

    1. <div th:insert="commons::fragment-name">div>
    2. <div th:insert="commons::#fragment-id">div>
    3. ------------------------------------------------
    4. <div th:replace="commons::fragment-name">div>
    5. <div th:replace="commons::#fragment-id">div>
    6. ------------------------------------------------
    7. <div th:include="commons::fragment-name">div>
    8. <div th:include="commons::#fragment-id">div>

    (2). 启动 Spring Boot,使用浏览器访问 fragment.html,查看源码,结果如下:

    1. <div>
    2. <div id="fragment-id">
    3. <span>公共页面片段span>
    4. div>
    5. div>
    6. <div>
    7. <div id="fragment-id">
    8. <span>公共页面片段span>
    9. div>
    10. div>
    11. ------------------------------------------------
    12. <div id="fragment-id">
    13. <span>公共页面片段span>
    14. div>
    15. <div id="fragment-id">
    16. <span>公共页面片段span>
    17. div>
    18. ------------------------------------------------
    19. <div>
    20. <span>公共页面片段span>
    21. div>
    22. <div>
    23. <span>公共页面片段span>
    24. div>

     项目参考:五—3.3 

    3. 传递参数

    Thymeleaf 在抽取和引入公共页面片段时,还可以进行参数传递,大致步骤如下:

    (1)传入参数;

    (2)使用参数。

    3.1 传入参数

    引用公共页面片段时,我们可以通过以下 2 种方式,将参数传入到被引用的页面片段中:

    • 模板名::选择器名或片段名(参数1=参数值1,参数2=参数值2)
    • 模板名::选择器名或片段名(参数值1,参数值2)

    注:

    • 若传入参数较少时,一般采用第二种方式,直接将参数值传入页面片段中;
    • 若参数较多时,建议使用第一种方式,明确指定参数名和参数值,。

    示例代码如下:

    1. <div th:insert="commons::fragment-name(var1='insert-name',var2='insert-name2')">div>
    2. <div th:insert="commons::#fragment-id(var1='insert-id',var2='insert-id2')">div>
    3. ------------------------------------------------
    4. <div th:replace="commons::fragment-name(var1='replace-name',var2='replace-name2')">div>
    5. <div th:replace="commons::#fragment-id(var1='replace-id',var2='replace-id2')">div>
    6. ------------------------------------------------
    7. <div th:include="commons::fragment-name(var1='include-name',var2='include-name2')">div>
    8. <div th:include="commons::#fragment-id(var1='include-id',var2='include-id2')">div>

    3.2 使用参数

    在声明页面片段时,我们可以在片段中声明并使用这些参数,例如: 

    1. <div th:fragment="fragment-name(var1,var2)" id="fragment-id">
    2. <p th:text="'参数1:'+${var1} + '-------------------参数2:' + ${var2}">...p>
    3. div>

     启动 Spring Boot,使用浏览器访问 fragment.html,结果如下图:

     项目参考:五—3.4 

    四、Spring Boot整合Thymeleaf 

            Spring Boot 推荐使用 Thymeleaf 作为其模板引擎。SpringBoot 为 Thymeleaf 提供了一系列默认配置,项目中一但导入了 Thymeleaf 的依赖,相对应的自动配置 (ThymeleafAutoConfiguration) 就会自动生效,因此 Thymeleaf 可以与 Spring Boot 完美整合 。
            Spring Boot 整合 Thymeleaf 模板引擎,需要以下步骤:

    • 引入 Starter 依赖
    • 创建模板文件,并放在在指定目录下

     1.引入依赖

            Spring Boot 整合 Thymeleaf 的第一步,就是在项目的 pom.xml 中添加 Thymeleaf 的 Starter 依赖,代码如下:

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-thymeleafartifactId>
    4. dependency>

    2.创建模板文件

            Spring Boot 通过 ThymeleafAutoConfiguration 自动配置类对 Thymeleaf 提供了一整套的自动化配置方案,该自动配置类的部分源码如下: 

    1. @Configuration(
    2. proxyBeanMethods = false
    3. )
    4. @EnableConfigurationProperties({ThymeleafProperties.class})
    5. @ConditionalOnClass({TemplateMode.class, SpringTemplateEngine.class})
    6. @AutoConfigureAfter({WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class})
    7. public class ThymeleafAutoConfiguration {
    8. }

             ThymeleafAutoConfiguration 使用 @EnableConfigurationProperties 注解导入了 ThymeleafProperties 类,该类包含了与 Thymeleaf 相关的自动配置属性,其部分源码如下:

    1. @ConfigurationProperties(
    2. prefix = "spring.thymeleaf"
    3. )
    4. public class ThymeleafProperties {
    5. private static final Charset DEFAULT_ENCODING;
    6. public static final String DEFAULT_PREFIX = "classpath:/templates/";
    7. public static final String DEFAULT_SUFFIX = ".html";
    8. private boolean checkTemplate = true;
    9. private boolean checkTemplateLocation = true;
    10. private String prefix = "classpath:/templates/";
    11. private String suffix = ".html";
    12. private String mode = "HTML";
    13. private Charset encoding;
    14. private boolean cache;
    15. ...
    16. }

            ThymeleafProperties 通过 @ConfigurationProperties 注解将配置文件(application.properties/yml) 中前缀为 spring.thymeleaf 的配置和这个类中的属性绑定,比如:

    1. # 启用缓存:建议生产开启
    2. spring.thymeleaf.cache=false
    3. # 建议模版是否存在
    4. spring.thymeleaf.check-template-location=true
    5. # Content-Type 值
    6. spring.thymeleaf.content-type=text/html
    7. # 是否启用
    8. spring.thymeleaf.enabled=true
    9. # 模版编码
    10. spring.thymeleaf.encoding=UTF-8
    11. # 应该从解析中排除的视图名称列表(用逗号分隔)
    12. spring.thymeleaf.excluded-view-names=
    13. # 模版模式
    14. spring.thymeleaf.mode=HTML5
    15. # 模版存放路径
    16. spring.thymeleaf.prefix=classpath:/templates/
    17. # 模版后缀
    18. spring.thymeleaf.suffix=.html

     在 ThymeleafProperties 中还提供了以下静态变量:

    • DEFAULT_ENCODING:默认编码格式
    • DEFAULT_PREFIX:视图解析器的前缀
    • DEFAULT_SUFFIX:视图解析器的后缀

            根据以上配置属性可知,Thymeleaf 模板的默认位置在 resources/templates 目录下,默认的后缀是 html,即只要将 HTML 页面放在“classpath:/templates/”下,Thymeleaf 就能自动进行渲染。

    与 Spring Boot 其他自定义配置一样,我们可以在 application.properties/yml 中修改以 spring.thymeleaf 开始的属性,以实现修改 Spring Boot 对 Thymeleaf 的自动配置的目的。 

    五、项目举例

    1.项目架构

    2.项目代码实现

    MainApplication.java:

    1. package com.xj.main;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.context.annotation.ComponentScan;
    5. /**
    6. * @Author : xjfu
    7. * @Description :Spring Boot 启动类
    8. */
    9. @ComponentScan("com.xj")
    10. @SpringBootApplication
    11. public class MainApplication {
    12. public static void main(String[] args) {
    13. SpringApplication.run(MainApplication.class, args);
    14. }
    15. }

    PersonThree.java:

    1. package com.xj.entity;
    2. import org.springframework.boot.context.properties.ConfigurationProperties;
    3. import org.springframework.context.annotation.PropertySource;
    4. import org.springframework.stereotype.Component;
    5. import java.util.List;
    6. /**
    7. * @Author : xjfu
    8. * @Description :
    9. */
    10. @PropertySource(value = {"classpath:person.properties"}, encoding = "UTF-8")
    11. @Component
    12. @ConfigurationProperties(value = "personthree")
    13. public class PersonThree {
    14. private String name;
    15. private Integer age;
    16. private List pets;
    17. private List food;
    18. private Child child;
    19. public String getName() {
    20. return name;
    21. }
    22. public void setName(String name) {
    23. this.name = name;
    24. }
    25. public Integer getAge() {
    26. return age;
    27. }
    28. public void setAge(Integer age) {
    29. this.age = age;
    30. }
    31. public List getPets() {
    32. return pets;
    33. }
    34. public void setPets(List pets) {
    35. this.pets = pets;
    36. }
    37. public List getFood() {
    38. return food;
    39. }
    40. public void setFood(List food) {
    41. this.food = food;
    42. }
    43. public Child getChild() {
    44. return child;
    45. }
    46. public void setChild(Child child) {
    47. this.child = child;
    48. }
    49. }

    Child.java:

    1. package com.xj.entity;
    2. /**
    3. * @Author : xjfu
    4. * @Description :
    5. */
    6. public class Child {
    7. private String name;
    8. private Integer age;
    9. private String gender;
    10. public String getName() {
    11. return name;
    12. }
    13. public void setName(String name) {
    14. this.name = name;
    15. }
    16. public Integer getAge() {
    17. return age;
    18. }
    19. public void setAge(Integer age) {
    20. this.age = age;
    21. }
    22. public String getGender() {
    23. return gender;
    24. }
    25. public void setGender(String gender) {
    26. this.gender = gender;
    27. }
    28. }

    ThymeleafController.java:

    1. package com.xj.controller;
    2. import com.xj.entity.PersonThree;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.stereotype.Controller;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.servlet.ModelAndView;
    7. /**
    8. * @Author : xjfu
    9. * @Description : Thymeleaf控制类
    10. */
    11. @Controller
    12. @RequestMapping(value = "/thymeleaf")
    13. public class ThymeleafController {
    14. @Autowired
    15. private PersonThree personThree;
    16. @RequestMapping(value = "/hello")
    17. public String sayHello(){
    18. //启动thymeleafHello.html页面
    19. return "thymeleafHello";
    20. }
    21. @RequestMapping(value = "/person")
    22. public ModelAndView getPerson(){
    23. ModelAndView modelAndView = new ModelAndView();
    24. //对象名为person
    25. modelAndView.addObject("person",personThree);
    26. //启动thymeleafPerson.html页面
    27. modelAndView.setViewName("thymeleafPerson");
    28. return modelAndView;
    29. }
    30. @RequestMapping(value = "/common")
    31. public String getCommon(){
    32. //启动thymeleaf1.html页面
    33. return "thymeleaf1";
    34. }
    35. @RequestMapping(value = "/common2")
    36. public String getCommon2(){
    37. //启动thymeleaf2.html页面
    38. return "thymeleaf2";
    39. }
    40. }

    application.yml:

    1. #默认配置
    2. server:
    3. port: 8080
    4. #切换配置
    5. spring:
    6. profiles:
    7. active: dev #指定使用哪个profile
    8. ---
    9. #开发环境
    10. server:
    11. port: 8081
    12. spring:
    13. config:
    14. activate:
    15. on-profile: dev
    16. ---
    17. #测试环境
    18. server:
    19. port: 8082
    20. spring:
    21. config:
    22. activate:
    23. on-profile: test
    24. ---
    25. #生产环境
    26. server:
    27. port: 8083
    28. spring:
    29. config:
    30. activate:
    31. on-profile: prod
    32. logging:
    33. config: classpath:logback-spring.xml #指定使用哪个日志配置文件

    person.properties:

    1. personthree.name = dave3
    2. personthree.age = 88
    3. personthree.pets = pig3,dog3,cat3
    4. personthree.food = HuiMian3,YouPoMian3,HeLuo3
    5. personthree.child.name = ss3
    6. personthree.child.age = ${random.int}
    7. personthree.child.gender = female

    pom.xml:

    1. <project xmlns="http://maven.apache.org/POM/4.0.0"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>com.xj.studygroupId>
    6. <artifactId>spring-boot-study-projectartifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <parent>
    9. <groupId>org.springframework.bootgroupId>
    10. <artifactId>spring-boot-starter-parentartifactId>
    11. <version>2.4.5version>
    12. <relativePath/>
    13. parent>
    14. <dependencies>
    15. <dependency>
    16. <groupId>org.springframework.bootgroupId>
    17. <artifactId>spring-boot-starter-webartifactId>
    18. dependency>
    19. <dependency>
    20. <groupId>org.springframework.bootgroupId>
    21. <artifactId>spring-boot-starter-testartifactId>
    22. <scope>testscope>
    23. dependency>
    24. <dependency>
    25. <groupId>org.springframework.bootgroupId>
    26. <artifactId>spring-boot-configuration-processorartifactId>
    27. <optional>trueoptional>
    28. dependency>
    29. <dependency>
    30. <groupId>org.webjarsgroupId>
    31. <artifactId>jqueryartifactId>
    32. <version>3.6.0version>
    33. dependency>
    34. <dependency>
    35. <groupId>org.springframework.bootgroupId>
    36. <artifactId>spring-boot-starter-thymeleafartifactId>
    37. dependency>
    38. dependencies>
    39. <build>
    40. <plugins>
    41. <plugin>
    42. <groupId>org.springframework.bootgroupId>
    43. <artifactId>spring-boot-maven-pluginartifactId>
    44. <executions>
    45. <execution>
    46. <goals>
    47. <goal>repackagegoal>
    48. goals>
    49. execution>
    50. executions>
    51. plugin>
    52. plugins>
    53. build>
    54. project>

    2-1. Thymeleaf支持Html原型模板

    thymeleafHello.html:

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>thymeleaf学习title>
    6. head>
    7. <body>
    8. <h1 th:text="迎您来到Thymeleaf">欢迎您访问静态页面 HTMLh1>
    9. body>
    10. html>

    2-2. 变量表达式和选择变量表达式模板

    thymeleafPerson.html:

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>thymeleaf学习title>
    6. head>
    7. <body>
    8. <h1 th:text="迎您来到Thymeleaf">欢迎您访问静态页面 HTMLh1>
    9. <h2>变量表达式:${}h2>
    10. 姓名:<span th:text="${person.name}">span>br>
    11. 年龄:<span th:text="${person.age}">span>br>
    12. 宠物:<span th:text="${person.pets}">span>br>
    13. 食物:<span th:text="${person.food}">span>br>
    14. 孩子姓名:<span th:text="${person.child.name}">span>br>
    15. 孩子年龄:<span th:text="${person.child.age}">span>br>
    16. 孩子性别:<span th:text="${person.child.gender}">span>br>
    17. <h2>选择变量表达式:*{}h2>
    18. <div th:object="${person}">
    19. 姓名:<span th:text="*{name}">span>br>
    20. 年龄:<span th:text="*{age}">span>br>
    21. 宠物:<span th:text="*{pets}">span>br>
    22. 食物:<span th:text="*{food}">span>br>
    23. 孩子姓名:<span th:text="*{child.name}">span>br>
    24. 孩子年龄:<span th:text="*{child.age}">span>br>
    25. 孩子性别:<span th:text="*{child.gender}">span>br>
    26. div>
    27. body>
    28. html>

    2-3. 引用公共页面

    公共页面commons.html:

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>公共页面title>
    6. head>
    7. <body>
    8. <div th:fragment="comName" id="comId">
    9. <span>公共页面片段span>
    10. div>
    11. body>
    12. html>

    thymeleaf1.html:

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>thymeleaf学习title>
    6. head>
    7. <body>
    8. <h1 th:text="引用公共页面">静态页面:引用公共页面h1>
    9. <div th:insert="commons::comName">div>
    10. <div th:insert="commons::#comId">div>
    11. ------------------------------------------------
    12. <div th:replace="commons::comName">div>
    13. <div th:replace="commons::#comId">div>
    14. ------------------------------------------------
    15. <div th:include="commons::comName">div>
    16. <div th:include="commons::#comId">div>
    17. body>
    18. html>

    2-4. 引用公共页面—参数传递

    公共页面commons2.html:

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>公共页面2title>
    6. head>
    7. <body>
    8. <div th:fragment="comName(var1,var2)" id="comId">
    9. <p th:text="'参数1:'+ ${var1} + '-------------------参数2:' + ${var2}">...p>
    10. div>
    11. body>
    12. html>

    thymeleaf2.html:

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>thymeleaf学习title>
    6. head>
    7. <body>
    8. <h1 th:text="引用公共页面">静态页面:引用公共页面h1>
    9. <div th:insert="commons2::comName(var1='高', var2='冯')"/>
    10. <div th:insert="commons2::#comId(var1='高', var2='冯')"/>
    11. ------------------------------------------------
    12. <div th:replace="commons2::comName(var1='高', var2='冯')"/>
    13. <div th:replace="commons2::#comId(var1='高', var2='冯')"/>
    14. ------------------------------------------------
    15. <div th:include="commons2::comName(var1='高', var2='冯')"/>
    16. <div th:include="commons2::#comId(var1='高', var2='冯')"/>
    17. body>
    18. html>

    3.运行结果

     3.1 Thymeleaf支持Html原型模板

    当直接使用浏览器打开时:

     当通过 Web 应用程序访问时:

    3.2 变量表达式和选择变量表达式模板

    3.3 引用公共页面

    3.4 引用公共页面—参数传递

    六、参考

    1.Thymeleaf教程(10分钟入门)

    2.Spring Boot整合Thymeleaf 

    3.Thymeleaf介绍和基操(附截图和代码)_小威要向诸佬学习呀的博客-CSDN博客_thymeleaf 

    4.SpringBoot | 第十六章:web应用开发 | oKong | 趔趄的猿 

  • 相关阅读:
    马上消费金融CIO蒋宁:拨云见日,金融行业大模型落地三大真核技术
    Redis 分布式锁 @Klock 注解详解及使用教程
    2022-2028年全球与中国工业分析软件市场现状及未来发展趋势分析报告
    路径分析—QGIS+PostgreSQL+PostGIS+pgRouting(一)
    使用PyQt5界面设计
    CSS补充
    VulnHub 兰皮昂 1 Lampiao
    前端在项目中添加自己的功能页面
    Linux 压缩和解压指令
    数字孪生技术在智慧工厂中的应用,你知道多少?
  • 原文地址:https://blog.csdn.net/qq_21370419/article/details/125592916