目录:

  • 引言
  • 1.Spring Boot 引入 Thymeleaf
    • 1.1 修改 Thymeleaf 版本
    • 1.2 修改 Thymeleaf Layout Dialect 版本
  • 2.Thymeleaf 语法介绍
    • 2.1 Thymeleaf 模板存放路径介绍   默认路径:classpath:/templates/
    • 2.2 Thymeleaf 引入工程
      • 1.导入 thymeleaf 的名称空间
      • 2.使用 thymeleaf 语法
    • 2.3 Thymeleaf 标签
    • 2.4 Thymeleaf 表达式介绍
      • 1.${...} 表达式 获取变量值;底层实现是OGNL
      • 2.*{...} 表达式 和${...}在功能上是一样;唯一一点不同如下↓↓↓
      • 3.#{...} 表达式 该表达式称之为消息表达式,消息表达式主要用于从消息源中提取消息内容实现国际化。
      • 4.@{...}表达式 该表达式称之为URL表达式
      • 5.~{...}表达式 该表达式称之为片段表达式
    • 2.5 Thymeleaf 其他基本使用介绍
      • 1.字面量
      • 2.文本操作
      • 3.数学运算
      • 4.布尔运算
      • 5.比较运算
      • 6.条件运算
      • 7.条件运算
  • 3.文末附Thymeleaf pdf 版使用手册一份

引言

Spring Boot 推荐我们使用模板引擎 Thymeleaf 来开发页面,因为它语法简单,功能强大。作为模板引擎,Thymeleaf 和市面上主流其他的 Java 模板引擎:JSPVelocityFreemarker,原理都是类似的。

  1. 模板引擎的作用:将模板(我们开发的页面)和 数据进行整合,然后输出内容显示的过程。
  2. 模板引擎的区别:不同的模板都有它们自己不同的语法。

1.Spring Boot 引入 Thymeleaf

Thymeleaf 官网:我是官网链接,Thymeleaf 已经将代码托管在了 Github 上:我是Github地址。Spring Boot 如何引入 Thymeleaf 模板,我们只需要在 pom.xml 中添加如下 Maven 依赖即可。

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

1.1 修改 Thymeleaf 版本

因为 Spring Boot 的自动配置,它已经为我们 Spring Boot 的每个版本都指定了各个组件的版本。如果你还在使用 Spring Boot 1.x 版本,它为我们自动指定的Thymeleaf 版本为 2.x 版本。在项目开发中,2.x 的 Thymeleaf 版本有点低,建议您升级到 Thymeleaf 3.x 版本。Spring Boot 官方有介绍我们该如何使用 Thymeleaf 3.x 版本。官网地址。我们只需要修改 Maven 依赖的 Thymeleaf 版本即可。

<properties><thymeleaf.version>3.0.11.RELEASE</thymeleaf.version><thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
</properties>

1.2 修改 Thymeleaf Layout Dialect 版本

修改 Thymeleaf 的同时,必须同时修改 Thymeleaf Layout Dialect 布局组件的版本。Thymeleaf Layout Dialect 布局组件从 2.0.0 版本开始支持 Thymeleaf 3 。 Thymeleaf Layout dialect 2.0.0 rewritten to support Thymeleaf 3 。官网有提及:我是官网说明。所以此处均使用目前最新版本,Thymeleaf:3.1.11.RELEASE,Thymeleaf Layout Dialect:2.4.1

2.Thymeleaf 语法介绍

Thymeleaf 的语法使用文档,官方为我们有提供 PDF 介绍,此处附官方文档:官方PDF文档,此处就来简单介绍一下基本的语法。

2.1 Thymeleaf 模板存放路径介绍   默认路径:classpath:/templates/

Spring Boot 关于 Thymeleaf 的所有配置信息,都在 ThymeleafProperties类下。部分代码如下:通过代码我可以知道→→(重要:)只要我们把(HTML)页面放在 classpath:/templates/这个目录下,后缀名为.html,thymeleaf 就能帮我们自动渲染!!!

除此之外,我们也可以在全局配置文件中,通过spring.thymeleaf.prefix 的方式来修改这个路径。 其他配置信息的修改,通过spring.thymeleaf.属性名即可。

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");//默认前缀public static final String DEFAULT_PREFIX = "classpath:/templates/";//默认后缀public static final String DEFAULT_SUFFIX = ".html";/*** Check that the template exists before rendering it (Thymeleaf 3+).*/private boolean checkTemplate = true;/*** Check that the templates location exists.*/private boolean checkTemplateLocation = true;/*** Prefix that gets prepended to view names when building a URL.*/private String prefix = DEFAULT_PREFIX;/*** Suffix that gets appended to view names when building a URL.*/private String suffix = DEFAULT_SUFFIX;
}

2.2 Thymeleaf 引入工程

1.导入 thymeleaf 的名称空间

导入 thymeleaf 的名称空间,只是为了语法提示,你也可以不导入的。

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2.使用 thymeleaf 语法

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><!--th:text 将div里面的文本内容设置为 --><div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>

2.3 Thymeleaf 标签

这类属性很多,每个属性都针对特定的HTML5属性,以下属性内容摘抄自官方 pdf 文档,标签有缺失。在这些所有属性中,我们常用到的也就那么几个,用的时候查一查就好了。

th:abbr                 th:accept                th:accept-charset
th:accesskey            th:action               th:align
th:alt                  th:archive              th:audio
th:autocomplete         th:axis                 th:background
th:bgcolor              th:border               th:cellpadding
th:cellspacing          th:challenge            th:charset
th:cite                 th:class                th:classid
th:codebase             th:codetype             th:cols
th:colspan              th:compact              th:content
th:contenteditable      th:contextmenu          th:data
th:datetime             th:dir                  th:draggable
th:dropzone             th:enctype              th:for
th:form                 th:formaction           th:formenctype
th:formmethod           th:formtarget           th:fragment
th:frame                th:frameborder          th:headers
th:height               th:high                 th:href
th:hreflang             th:hspace               th:http-equiv
th:icon                 th:id                   th:inline
th:keytype              th:kind                 th:label
th:lang                 th:list                 th:longdesc
th:low                  th:manifest             th:marginheight
th:marginwidth          th:max                  th:maxlength
th:media                th:method               th:min
th:name                 th:onabort              th:onafterprint
th:onbeforeprint        th:onbeforeunload       th:onblur
th:oncanplay            th:oncanplaythrough     th:onchange
th:onclick              th:oncontextmenu        th:ondblclick
th:ondrag               th:ondragend            th:ondragenter
th:ondragleave          th:ondragover           th:ondragstart
th:ondrop               th:ondurationchange     th:onemptied
th:onended              th:onerror              th:onfocus
th:onformchange         th:onforminput          th:onhashchange
th:oninput              th:oninvalid            th:onkeydown
th:onkeypress           th:onkeyup              th:onload
th:onloadeddata         th:onloadedmetadata     th:onloadstart
th:onmessage            th:onmousedown          th:onmousemove
th:onmouseout           th:onmouseover          th:onmouseup
th:onmousewheel         th:onoffline            th:ononline
th:onpause              th:onplay               th:onplaying
th:onpopstate           th:onprogress           th:onratechange
th:onreadystatechange   th:onredo               th:onreset
th:onresize             th:onscroll             th:onseeked
th:onseeking            th:onselect             th:onshow
th:onstalled            th:onstorage            th:onsubmit
th:onsuspend            th:ontimeupdate         th:onundo
th:onunload             th:onvolumechange       th:onwaiting
th:optimum              th:pattern              th:placeholder
th:poster               th:preload              th:radiogroup
th:rel                  th:rev                  th:rows
th:rowspan              th:rules                th:sandbox
th:scheme               th:scope                th:scrolling
th:size                 th:sizes                th:span
th:spellcheck           th:src                  th:srclang
th:standby              th:start                th:step
th:style                th:summary              th:tabindex
th:target               th:text                 th:title
th:type                 th:usemap               th:value
th:valuetype            th:vspace               th:width
th:wrap                 th:xmlbase              th:xmllang
th:xmlspace

2.4 Thymeleaf 表达式介绍

Thymeleaf 内置了 5 种表达式:

1.${…} 表达式 获取变量值;底层实现是OGNL

①获取对象的属性、调用方法

此部分的具体使用,参考:pdf 这部分→4.2 Variables

/*
* Access to properties using the point (.). Equivalent to calling property getters.
*/
${person.father.name}
/*
* Access to properties can also be made by using brackets ([]) and writing
* the name of the property as a variable or between single quotes.
*/
${person['father']['name']}
/*
* If the object is a map, both dot and bracket syntax will be equivalent to
* executing a call on its get(...) method.
*/
${countriesByCode.ES}
${personsByName['Stephen Zucchini'].age}
/*
* Indexed access to arrays or collections is also performed with brackets,
* writing the index without quotes.
*/
${personsArray[0].name}
/*
* Methods can be called, even with arguments.
*/
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}

②还可以使用 Thymeleaf 内置的基本对象:(使用#号)

#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.

此部分的介绍,请参考 pdf 这部分→Expression Basic Objects。详细使用介绍,请参见考:pdf 这部分→18 Appendix A: Expression Basic Objects

③Thymeleaf 还内置了一些工具对象:

#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

此部分的介绍,请参考 pdf 这部分→Expression Utility Objects。详细使用介绍,请参考:pdf 这部分→18 Appendix A: Expression Basic Objects

2.*{…} 表达式 和${…}在功能上是一样;唯一一点不同如下↓↓↓

使用*{…}方式:

<div th:object="${session.user}"><p>Name: <span th:text="*{firstName}">Sebastian</span>.</p><p>Surname: <span th:text="*{lastName}">Pepper</span>.</p><p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>

使用${…}方式:

<div th:object="${session.user}"><p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p><p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p><p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

区别在于:针对对象遍历来说,使用*{…} 比 ${…} 简洁点。这两种表达式,也可以混合在一起使用,不过没人会这么用吧,哈哈。

此部分的介绍,请参见 pdf 这部分→4.3 Expressions on selections (asterisk syntax)。详细使用介绍也参考:pdf 这部分→4.3 Expressions on selections (asterisk syntax)

3.#{…} 表达式 该表达式称之为消息表达式,消息表达式主要用于从消息源中提取消息内容实现国际化。

举个例子:

<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>

消息属性可以是传统的静态值

home.welcome=¡Bienvenido a nuestra tienda de comestibles!

也可以带有参数声明,参数声明格式符合java.text.MessageFormat标准

home.welcome=¡Bienvenido a nuestra tienda de comestibles, {0}!

通过在消息名称后边加括号声明参数的方式#{messageKey(param=value)}实现参数赋值

<p th:utext="#{home.welcome(${session.user.name})}">Welcome to our grocery store, Sebastian Pepper!
</p>

多个参数用","分割

#{messageKey(param1=value1,param2=value2)}

messageKey 本身可以是一个变量表达式

<p th:utext="#{${welcomeMsgKey}(${session.user.name})}">Welcome to our grocery store, Sebastian Pepper!
</p>

消息源介绍:

大多数情况下,消息源是 .properties文件,同时你可以自定义其他消息源,比如数据库。消息源通过org.thymeleaf.messageresolver.IMessageResolver 获取,如果在初始化模板引擎时没有自定义的IMessageResolver 被提供,那么一个默认的实现org.thymeleaf.messageresolver.StandardMessageResolver会被自动提供。

StandardMessageResolver查找和模板文件位于同级目录,且具有和模板文件相同名字的*.properties*文件。

模板/WEB-INF/templates/home.html在渲染时,会根据 local 设置,使用下面的消息源文件

  • /WEB-INF/templates/home_en.properties for English texts.
  • /WEB-INF/templates/home_es.properties for Spanish language texts.
  • /WEB-INF/templates/home_pt_BR.properties for Portuguese (Brazil) language texts.
  • /WEB-INF/templates/home.properties for default texts (if the locale is not matched).

此部分的介绍,主要应用于国际化,请参见 pdf 这部分→4.1 Messages。详细使用介绍请参考:pdf 这部分→Using th:text and externalizing text

4.@{…}表达式 该表达式称之为URL表达式

@{…}表达式,用来定义URL。我在此处扔个例子就走人了→→→

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

此部分的介绍,主要应用于国际化,请参见 pdf 这部分→4.4 Link URLs。详细使用介绍也参考:pdf 这部分→4.4 Link URLs

5.~{…}表达式 该表达式称之为片段表达式

片段表达式的使用,你可以参考博主的这篇文章→→→Thymeleaf 公共组件的抽取

片段表达式表示标记片段,并将其在模板中"移动"的简便方法。 这允许我们复制它们,将它们作为参数传递给其他模板,依此类推。最常见的用途是使用 th:insertth:replace进行片段插入。

<div th:insert="~{commons :: main}">...</div>

但是它们可以在任何地方使用,就像其他任何变量一样:

<div th:with="frag=~{footer :: #main/text()}"><p th:insert="${frag}">
</div>

此部分的介绍,请参见 pdf 这部分→4.5 Fragments。详细使用介绍也参考:pdf 这部分→8 Template Layout。此部分建议你去看一下详细介绍,就类似于模板使用一样:一处编写,到处使用

2.5 Thymeleaf 其他基本使用介绍

Thymeleaf 对 字面量、文本操作、数学运算、布尔运算、比较运算、条件运算、特殊无操作运算,都做了一些基本的介绍。如下所示:

1.字面量

Literals(字面量)Text literals: 'one text' , 'Another one!' ,…Number literals: 0 , 34 , 3.0 , 12.3 ,…Boolean literals: true , falseNull literal: nullLiteral tokens: one , sometext , main ,…

2.文本操作

Text operations:(文本操作)String concatenation: +Literal substitutions: |The name is ${name}|

3.数学运算

Arithmetic operations:(数学运算)Binary operators: + , - , * , / , %Minus sign (unary operator): -

4.布尔运算

Boolean operations:(布尔运算)Binary operators: and , orBoolean negation (unary operator): ! , not

5.比较运算

Comparisons and equality:(比较运算)Comparators: > , < , >= , <= ( gt , lt , ge , le )Equality operators: == , != ( eq , ne )

6.条件运算

Conditional operators:条件运算(三目运算符)If-then: (if) ? (then)If-then-else: (if) ? (then) : (else)Default: (value) ?: (defaultvalue)

7.条件运算

Special tokens:(特殊操作)No-Operation: _        举例:可以这么使用 if(1=1)?'yes':_  (否则啥也不干)

3.文末附Thymeleaf pdf 版使用手册一份

附 Thymeleaf 开发参考手册一份:参考手册链接


博主写作不易,来个关注呗

求关注、求点赞,加个关注不迷路 ヾ(◍°∇°◍)ノ゙

博主不能保证写的所有知识点都正确,但是能保证纯手敲,错误也请指出,望轻喷 Thanks♪(・ω・)ノ

Spring Boot 引入 Thymeleaf 及入门使用相关推荐

  1. Spring Boot集成Thymeleaf模板引擎

    一.Thymeleaf 模板介绍 Spring Boot 推荐使用Thymeleaf 来代替传统开发中的JSP,那么什么是Thymeleaf 模板引擎呢?下面就来简单的介绍一下. Thymeleaf ...

  2. java 模板引擎_极简 Spring Boot 整合 Thymeleaf 页面模板

    点击"牧码小子"关注,和众多大牛一起成长! 关注后,后台回复 java ,领取松哥为你精心准备的技术干货! 虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在 ...

  3. Spring Boot 使用Thymeleaf

    2019独角兽企业重金招聘Python工程师标准>>> 1.引入thymeleaf: <dependency> <groupId>org.springfram ...

  4. Spring Boot整合Thymeleaf模板引擎

    转载自 Spring Boot整合Thymeleaf模板引擎 什么是Thymeleaf Thymeleaf是一款用于渲染XML.XHTML.HTML5内容的模板引擎.类似Velocity,FreeMa ...

  5. Spring Boot (16)---优雅的入门篇

    Spring Boot (16)---优雅的入门篇 Spring一直是很火的一个开源框架,在过去的一段时间里,Spring Boot在社区中热度一直很高,所以决定花时间来了解和学习,为自己做技术储备. ...

  6. 项目监控之Spring Boot 监控端点 Actuator 入门

    1. 概述 应用在部署在生产环境下,我们还需要考虑应用的管理与监控.例如说,应用是否健康存活.应用的 JVM 监控信息.服务器的监控信息(CPU.内存.磁盘等等). 如果我们为应用的管理与监控做相应的 ...

  7. 没有找到 html 模板,Spring Boot and Thymeleaf:找不到HTML模板

    我正在嘗試用Thymeleaf創建一個基於Spring Boot的應用程序.我使用PetClinic樣本作爲起點. 我的應用程序找不到一些模板.Spring Boot and Thymeleaf:找不 ...

  8. Spring Boot 消息队列 RocketMQ 入门

    转载自  芋道 Spring Boot 消息队列 RocketMQ 入门 摘要: 原创出处 http://www.iocoder.cn/Spring-Boot/RocketMQ/ 「芋道源码」欢迎转载 ...

  9. Spring Boot和Thymeleaf:重新加载模板和静态资源,而无需重新启动应用程序

    Thymeleaf是围绕自然模板的概念设计的,该模板允许进行静态原型制作:模板逻辑不会影响用作原型的模板. 尽管这是一项很棒的技术,但您可能还希望在运行的Spring Boot应用程序中查看结果,而不 ...

最新文章

  1. java数组长度怎么看,威力加强版
  2. python数据挖掘Hello World
  3. 无法升级_Windows 10出现升级BUG:无法保留用户个人数据
  4. Shell Here Document 免交互命令和Expect
  5. 如何让文字溢出自动变成省略号
  6. maven 连接sqlserver
  7. Gradle 插件 + ASM 实战 - 监控图片加载告警
  8. 正睿(比赛--Day10)
  9. Servlet开发验证码
  10. 你为什么错过优质信息?
  11. CMD查看Win10注册码
  12. 【学习OpenCV4】图像金字塔总结
  13. 【索引分类】位图索引
  14. 大时代势不可挡_使IT项目经理势不可挡的12种软技能
  15. 爬取近千张女神赫本的美照,做成网站并给其中的黑白照片上色,好玩!
  16. HDU 1236 排名(Microsoft_zzt)
  17. 2013---平静的心态迎接新的开始
  18. Chinfa DRA480-24A
  19. 知识管理软件之二 卡拉OK读小说 藏书库系列
  20. 【数据挖掘之关联规则实战】关联规则智能推荐算法

热门文章

  1. 自然语言处理基础技术工具篇之Flair
  2. 马!马上看~ 推荐给学绘画的人的电影
  3. verilog设计简易正弦波信号发生器_采用集成运放和分立元件相结合的方式,利用迟滞比较器电路产生方波信号,以及充分利用差分电路进行电路转...
  4. 大连东软信息学院计算机专业19分数线,大连东软信息学院历年分数线 2021大连东软信息学院录取分数线...
  5. python实验报告内容实现购物车系统_Python 实践--购物车功能简单实现
  6. 服务器光口自协商协议,千兆光口自协商过程
  7. 特征值、特征向量和奇异值
  8. 07-wtm用户管理
  9. vue中excel导出功能
  10. 如何看懂设计师给到的设计图?