(一)Thymeleaf 是个什么?

简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:

1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

3. Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

(二)应用

1.简单的 Thymeleaf 应用

1)只需加入thymeleaf-2.1.4.RELEASE.jar(http://www.thymeleaf.org/download.html )包,若用maven,则加入如下配置

  1. <dependency>
  2.     <groupId>org.thymeleaf</groupId>
  3.     <artifactId>thymeleaf</artifactId>
  4.     <version>2.1.4</version>
  5. </dependency>

2)然后增加头文件(如下)

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml"
  3.       xmlns:th="http://www.thymeleaf.org">

3)就可以用th标签动态替换掉静态数据了。如下图,后台传出的message会将静态数据“Red Chair”替换掉,若访问静态页面,则显示数据“Red Chair”。

  1. <td th:text="${message}">Red Chair</td>

2.整合spring

1)加入thymeleaf-spring4-2.1.4.RELEASE.jar(http://www.thymeleaf.org/download.html )包,若用maven,则加入如下配置

  1. <dependency>
  2.     <groupId>org.thymeleaf</groupId>
  3.     <artifactId>thymeleaf-spring3</artifactId>
  4.     <version>2.1.4</version>
  5. </dependency>

2)在servlet配置文件中加入如下代码

  1. <!-- Scans the classpath of this application for @Components to deploy as beans -->
  2.        <context:component-scan base-package="com.test.thymeleaf.controller" />
  3.  
  4.        <!-- Configures the @Controller programming model -->
  5.        <mvc:annotation-driven />
  6.  
  7.         <!--Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
  8.         <!--springMVC+jsp的跳转页面配置-->
  9.        <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
  10.               <!--<property name="prefix" value="/WEB-INF/views/" />-->
  11.               <!--<property name="suffix" value=".jsp" />-->
  12.        <!--</bean>-->
  13.  
  14.        <!--springMVC+thymeleaf的跳转页面配置-->
  15.        <bean id="templateResolver"          class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
  16.          <property name="prefix" value="/WEB-INF/views/" />
  17.          <property name="suffix" value=".html" />
  18.          <property name="templateMode" value="HTML5" />
  19.        </bean>
  20.  
  21.        <bean id="templateEngine"           class="org.thymeleaf.spring4.SpringTemplateEngine">
  22.           <property name="templateResolver" ref="templateResolver" />
  23.        </bean>
  24.  
  25.        <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
  26.          <property name="templateEngine" ref="templateEngine" />
  27.        </bean>

3)将静态页面加到项目中,更改文件头,加入th标签即可。

3.th标签整理

1)简单表达式

--变量表达式  ${……}

  1. <input type="text" name="userName" value="James Carrot" th:value="${user.name}" />

上述代码为引用user对象的name属性值。

--选择/星号表达式 *{……}

  1. <div th:object="${session.user}">                                                                       
  2.      <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>    
  3. </div>

选择表达式一般跟在th:object后,直接取object中的属性。

--文字国际化表达式  #{……}

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

调用国际化的welcome语句,国际化资源文件如下

  1. resource_en_US.propertieshome.welcome=Welcome to hereresource_zh_CN.propertieshome.welcome=欢迎您的到来!
  1.  

-- URL表达式  @{……}

  1. <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

@{……}支持决定路径和相对路径。其中相对路径又支持跨上下文调用url和协议的引用(//code.jquery.com/jquery-2.0.3.min.js)。

当URL为后台传出的参数时,代码如下

  1. <img src="../../static/assets/images/qr-code.jpg" th:src="@{${path}}" alt="二维码" />

2)常用的th标签

--简单数据转换(数字,日期)

  1.    <dt>价格</dt>
  2.     <dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">180</dd>
  3.    <dt>进货日期</dt>
  4.    <dd th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</dd>

--字符串拼接

  1. <dd th:text="${'$'+product.price}">235</dd>

--转义和非转义文本

当后台传出的数据为“This is an &lt;em&gt;HTML&lt;/em&gt; text. &lt;b&gt;Enjoy yourself!&lt;/b&gt;”时,若页面代码如下则出现两种不同的结果

  1. <div th:text="${html}">
  1.   This is an &lt;em&gt;HTML&lt;/em&gt; text. &lt;b&gt;Enjoy yourself!&lt;/b&gt;
  1. </div> <div th:utext="${html}">
  1.   This is an <em>HTML</em> text. <b>Enjoy yourself!</b>
  1. </div>

--表单中

  1. <form th:action="@{/bb}" th:object="${user}" method="post" th:method="post">
  2.  
  3.     <input type="text" th:field="*{name}"/>
  4.     <input type="text" th:field="*{msg}"/>
  5.  
  6.     <input type="submit"/>
  7. </form>

--显示页面的数据迭代

  1. //用 th:remove 移除除了第一个外的静态数据,用第一个tr标签进行循环迭代显示    <tbody th:remove="all-but-first">
  2.           //将后台传出的 productList 的集合进行迭代,用product参数接收,通过product访问属性值
  3.                <tr th:each="product:${productList}">            //用count进行统计,有顺序的显示
  4.             <td th:text="${productStat.count}">1</td>
  5.                    <td th:text="${product.description}">Red Chair</td>
  6.                    <td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$123</td>
  7.                    <td th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</td>
  8.                </tr>
  9.                <tr>
  10.                    <td>White table</td>
  11.                    <td>$200</td>
  12.                    <td>15-Jul-2013</td>
  13.                </tr>
  14.                <tr>
  15.                    <td>Reb table</td>
  16.                    <td>$200</td>
  17.                    <td>15-Jul-2013</td>
  18.                </tr>
  19.                <tr>
  20.                    <td>Blue table</td>
  21.                    <td>$200</td>
  22.                    <td>15-Jul-2013</td>
  23.                </tr>
  24.      </tbody>

--条件判断

  1. <span th:if="${product.price lt 100}" class="offer">Special offer!</span>

不能用"<”,">"等符号,要用"lt"等替代

  1. <!-- 当gender存在时,选择对应的选项;若gender不存在或为null时,取得customer对象的name-->
  2. <td th:switch="${customer.gender?.name()}">
  3.     <img th:case="'MALE'" src="../../../images/male.png" th:src="@{/images/male.png}" alt="Male" /> <!-- Use "/images/male.png" image -->
  4.     <img th:case="'FEMALE'" src="../../../images/female.png" th:src="@{/images/female.png}" alt="Female" /> <!-- Use "/images/female.png" image -->
  5.     <span th:case="*">Unknown</span>
  6. </td>

  1.    <!--除非resume对象的name属性值为null,否则就用name的值作为placeholder值-->
  2.  
  3.    <!--除非resume对象的name属性不为空,否则就定义一个field方便封装对象,并用placeholder提示-->

  1. <!-- 增加class="enhanced"当balance大雨10000 -->
  2. <td th:class="${customer.balance gt 10000} ? 'enhanced'" th:text="${customer.balance}">350</td>

--根据后台数据选中select的选项

按 Ctrl+C 复制代码

按 Ctrl+C 复制代码

因为gender是定义的Enum(枚举)类型,所以要用toString方法。用th:switch指定传出的变量,用th:case对变量的值进行匹配。!"请选择"放在第一项会出现永远选择的是这个选项。或者用th:if

  1. <div class='form-group col-lg-4'>
  2.           <select class='form-control' name="skill[4].proficiency">
  3.                 <option >掌握程度</option>
  4.                 <option th:if="${skill.level eq '一般'}" th:selected="selected">一般</option>
  5.                  <option th:if="${skill.level eq '熟练'}" th:selected="selected">熟练</option>
  6.                  <option th:if="${skill.level eq '精通'}" th:selected="selected">精通</option>
  7.            </select>
  8. </div>

--spring表达式语言

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3.     <head>
  4.         <title>Thymeleaf tutorial: exercise 10</title>
  5.         <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
  6.         <meta charset="utf-8" />
  7.     </head>
  8.     <body>
  9.         <h1>Thymeleaf tutorial - Solution for exercise 10: Spring Expression language</h1>
  10.   
  11.         <h2>Arithmetic expressions</h2>
  12.         <p class="label">Four multiplied by minus six multiplied by minus two module seven:</p>
  13.         <p class="answer" th:text="${4 * -6 * -2 % 7}">123</p>
  14.  
  15.         <h2>Object navigation</h2>
  16.         <p class="label">Description field of paymentMethod field of the third element of customerList bean:</p>
  17.         <p class="answer" th:text="${customerList[2].paymentMethod.description}">Credit card</p>
  18.  
  19.         <h2>Object instantiation</h2>
  20.         <p class="label">Current time milliseconds:</p>
  21.         <p class="answer" th:text="${new java.util.Date().getTime()}">22-Jun-2013</p>
  22.         
  23.         <h2>T operator</h2>
  24.         <p class="label">Random number:</p>
  25.         <p class="answer" th:text="${T(java.lang.Math).random()}">123456</p>
  26.     </body>
  27. </html>

--内联

  1. <label for="body">Message body:</label>
  2. <textarea id="body" name="body" th:inline="text">Dear [[${customerName}]],
  3.  
  4. it is our sincere pleasure to congratulate your in your birthday:
  5.     Happy birthday [[${customerName}]]!!!See you soon, [[${customerName}]].
  6.  
  7. Regards,
  8.     The Thymeleaf team</textarea>

--内联JS <js起止加入如下代码,否则引号嵌套或者"<"">"等不能用>

  1. /*<![CDATA[*/……/*]]>*/

--js附加代码:

  1. /*[+
  2. var msg = 'This is a working application';
  3. +]*/

--js移除代码:

  1. /*[- */var msg = 'This is a non-working template';/* -]*/

4.不常用

--表达式

2)文字

a)文本文字                        'one text','Another one',……

b)数字文字                        0,34,3.0,12.3,……

c)布尔文字                        true,flase

d)空文字                            null

e)文字标记                         one,sometext,main,……

3)文本处理

a)字符串连接                       +

b)文字替换                           | The name id ${name} |

4)算术表达式

a)基本表达式                        +,-,*,/,%

b)减号(一元运算符)           -

5)布尔表达式

a)基本表达式                        and,or

b)布尔否定(一元运算符)    !,not

6)比较和相等

a)比较                                >,<,>=,<=(gt,lt,ge,le)

b)相等表达式                       ==,!=(eq,ne)

7)条件表达式

a)If-then                            (if) ? (then)

b)If-then-else                    (if) ? (then) : (else)

c)Default                           (value) ? : (defaltvalue)

所有这些标签能够结合和嵌套:

User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

--表达式基本对象

在上下文变量评估OGNL表达式时,一些对象表达式可获得更高的灵活性。这些对象将由#号开始引用。

- #ctx: 上下文对象.

- #vars: 上下文变量.

- #locale: 上下文语言环境.

- #httpServletRequest: (仅在web上文)HttpServletRequest 对象.

- #httpSession: (仅在web上文)  HttpSession 对象.

--表达式功能对象

- #dates:java.util.Date对象的实用方法。

- #calendars:和dates类似, 但是 java.util.Calendar 对象.

- #numbers: 格式化数字对象的实用方法。

- #strings: 字符创对象的实用方法: contains, startsWith, prepending/appending等.

- #objects: 对objects操作的实用方法。

- #bools: 对布尔值求值的实用方法。

- #arrays: 数组的实用方法。

- #lists: list的实用方法。

- #sets: set的实用方法。

- #maps: map的实用方法。

- #aggregates: 对数组或集合创建聚合的实用方法。

- #messages: 在表达式中获取外部信息的实用方法。

- #ids: 处理可能重复的id属性的实用方法 (比如:迭代的结果)。

--给特定的属性设值

下面是用th:action给action设值。

<form action="subscribe.html" th:action="@{/subscribe}">

还有很多这样的属性,它们每一个都针对一个特定的XHTML或者HTML5属性:

th:text="${data}"

将data的值替换该属性所在标签的body。字符常量要用引号,比如th:text="'hello world'",th:text="2011+3",th:text="'my name is '+${user.name}"
            th:utext

和th:text的区别是"unescaped text"。
            th:with

定义变量,th:with="isEven=${prodStat.count}%2==0",定义多个变量可以用逗号分隔。
            th:attr

设置标签属性,多个属性可以用逗号分隔,比如th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。
            th:[tagAttr]

设置标签的各个属性,比如th:value,th:action等。
                可以一次设置两个属性,比如:th:alt-title="#{logo}"
                   对属性增加前缀和后缀,用th:attrappend,th:attrprepend,比如:th:attrappend="class=${' '+cssStyle}"
                   对于属性是有些特定值的,比如checked属性,thymeleaf都采用bool值,比如th:checked=${user.isActive}
            th:each

循环,<tr th:each="user,userStat:${users}">,userStat是状态变量,有 index,count,size,current,even,odd,first,last等属性,如果没有显示设置状态变量,    thymeleaf会默 认给个“变量名+Stat"的状态变量。
            th:if or th:unless

条件判断,支持布尔值,数字(非零为true),字符,字符串等。
            th:switch,th:case

选择语句。 th:case="*"表示default case。

Thymeleaf 学习笔记的更多相关文章

  1. Thymeleaf 学习笔记-实例demo(中文教程)

    项目demo     http://pan.baidu.com/s/1wg6PC 学习资料网址  http://www.blogjava.net/bjwulin/archive/2013/02/07/ ...

  2. thymeleaf学习笔记

    1.${@dict.hello().fatherName} 显示对象的属性2.${@dict.hello()[0].fatherName} 显示列表对象的属性3.<div th:object=& ...

  3. thymeleaf学习笔记:总结

    Thymeleaf定义:Thymeleaf is a modern server-side Java template engine for both web and standalone envir ...

  4. thymeleaf 学习笔记-基础篇(中文教程)

    (一)Thymeleaf 是个什么?      简单说, Thymeleaf 是一个跟 Velocity.FreeMarker 类似的模板引擎,它可以完全替代 JSP .相较与其他的模板引擎,它有如下 ...

  5. 004 Thymeleaf学习笔记

    1.Thymeleaf概述 SpringBoot并不推荐使用jsp,但是支持一些模板引擎技术:Freemarker.Thymeleaf.Mustache. 简单说, Thymeleaf 是一个跟 Ve ...

  6. thymeleaf 学习笔记(转)

    原文:http://blog.csdn.net/pdw2009/article/details/44410659 thymeleaf,我个人认为是个比较好的模板,性能也比一般的,比如freemaker ...

  7. spring学习笔记(一) Spring概述

    博主Spring学习笔记整理大部分内容来自Spring实战(第四版)这本书.  强烈建议新手购入或者需要电子书的留言. 在学习Spring之前,我们要了解这么几个问题:什么是Spring?Spring ...

  8. Spring实战第六章学习笔记————渲染Web视图

    Spring实战第六章学习笔记----渲染Web视图 理解视图解析 在之前所编写的控制器方法都没有直接产生浏览器所需的HTML.这些方法只是将一些数据传入到模型中然后再将模型传递给一个用来渲染的视图. ...

  9. SpringBoot学习笔记(2):引入Spring Security

    SpringBoot学习笔记(2):用Spring Security来保护你的应用 快速开始 本指南将引导您完成使用受Spring Security保护的资源创建简单Web应用程序的过程. 参考资料: ...

随机推荐

  1. 如何修改word文档中每行字符的最大默认值和每页最大行数默认值

    事情起因是这样的,小明在写论文的过程中,发现自己的文档的字与字的间距看起来比其他人的字符间距大,于是觉得奇怪,明明设置了一样的格式啊,设置每行38个字符,每页34行,为什么小明写的文档字符间距看着比较 ...

  2. React阻止事件冒泡的正确打开方式

    需求:点击导航list按钮出现侧弹框,点击空白处弹框消失 问题:绑定空白处的点击事件到document上,但是非空白处的点击也会触发这个点击事件,在react中如何阻止事件冒泡? 解决方法:e.sto ...

  3. Grafana3.0.1+Zabbix3.0.4监控系统平台搭建

    前言 本文的Zabbix部分知识只介绍它的基础安装,Zabbix的使用以及配置优化并不在本文的介绍范围之内. 本文只介绍在CentOS6系列下的安装和部署,其他发行版与其他版本号暂不涉及 本文默认使用 ...

  4. Moleskine智能笔+专用本:写完随时传到手机

    http://www.totiot.com/61805.html Moleskine公司生产的速写本和速写板一直是涂鸦爱好者和速记员们的首选.该公司还联合Adobe. Livescribe. Ever ...

  5. yarn的学习-2-从 npm 迁移到 yarn-包管理工具

    从npm处迁移过来多许多用户来说是一个相对简单的过程.yarn能想npm一样定制相同的package.json,并能够从npm仓库下载任意的包 如果你想要在已存在的npm项目中使用yarn,运行yar ...

  6. pyspider爬取数据存入es--2.测试数据库连通性

    写一个简单案例测试能否将数据写入es #!/usr/bin/env python # -*- encoding: utf-8 -*- # Created on 2017-10-27 08:35:57 ...

  7. Java安全通信:HTTPS与SSL

    转载地址:http://www.cnblogs.com/devinzhang/archive/2012/02/28/2371631.html Java安全通信:HTTPS与SSL 1. HTTPS概念 ...

  8. 【转】php容易犯错的10个地方

    原文地址: http://www.toptal.com/php/10-most-common-mistakes-php-programmers-make 译文地址:http://codecloud.n ...

  9. 手机视频编辑软件APP

    1. VUE    iOS/Android 2.Alive    iOS/Android 3.Splice  iOS 4. Plotagragh+   能让照片动起来的app 5.Cinepic  能 ...

  10. 20155308《网络对抗》Exp9 Web安全基础实践

    20155308<网络对抗>Exp9 Web安全基础实践 本实践的目标理解常用网络攻击技术的基本原理.Webgoat实践下相关实验. 基础问题回答 SQL注入攻击原理,如何防御? 原理:攻 ...