程序员社区

Spring Boot 引入 Thymeleaf 及入门使用

引言

        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 , false
      Null literal: null
      Literal 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 , or
    Boolean 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♪(・ω・)ノ

赞(0) 打赏
未经允许不得转载:IDEA激活码 » Spring Boot 引入 Thymeleaf 及入门使用

一个分享Java & Python知识的社区