您的位置:首页 > 其它

thymeleaf 专题

2017-06-19 19:55 549 查看

Thymeleaf之内置对象、定义变量、URL参数及标签自定义属性

如标题所述,这篇文章主要讲述Thymeleaf中的内置对象(list解析、日期格式化、数字格式化等)、定义变量、获取URL的参数和在页面标签中自定义属性的应用。

如果对Thymeleaf的基本使用、maven依赖等不清楚的可以先阅读我的另一篇文章《Thymeleaf之初步使用》。

Controller部份

@Controller
publicclassIndexController{

@GetMapping(value="index")
publicStringindex(Modelmodel,HttpServletRequestrequest){
List<String>datas=newArrayList<String>();
datas.add("知识林");
datas.add("http://www.zslin.com");
datas.add("393156105");
model.addAttribute("datas",datas);
model.addAttribute("curDate",newDate());

model.addAttribute("money",Math.random()*100);
return"index";
}
}

在这个控制器的Model中存放了这样几个数据:一个String类型的列表、一个日期对象和一个数值,这些东西在实际应用开发过程中应用非常广泛,下面具体看一下在Thymeleaf中是如何解析这些数据的。

日期格式化

<spanth:text="${#dates.format(curDate,'yyyy-MM-ddHH:mm:ss')}"></span>

说明:使用内置对象
dates
format
函数即可对日期进行格式化,在
format
函数中,第一个参数是日期对象,对二两个参数为日期格式(规则跟
SimpleDateFormat
一样)

需要注意的是:

·内置对象一般都以
s
结尾,如
dates
lists
numbers


·在使用内置对象是在对象名前都需要加
#
号。

数字格式化

<spanth:text="${#numbers.formatDecimal(money,0,2)}"></span>

说明:此示例表示保留两位小数位,整数位自动;

<spanth:text="${#numbers.formatDecimal(money,3,2)}"></span>

说明:此示例表示保留两位小数位,3位整数位(不够的前加0)

获取列表长度

<spanth:text="${#lists.size(datas)}"></span>

说明:使用
#lists.size
来获取List的长度。

获取URL参数值

<spanth:text="${#httpServletRequest.getParameter('page')}"></span>

说明:当访问
http://localhost:1105/index?page=5
时页面将会得到
page
对应的值:
5


定义变量

<divth:with="curPage=${#httpServletRequest.getParameter('page')}">
<h3>当前页码:<spanth:text="${curPage}"></span></h3>
</div>

说明:同样,当访问
http://localhost:1105/index?page=5
时,页面将显示:
当前页码:5
,说明用
th:with
来定义变量,多个用
,
号隔开,使用范围在当前标签内。

自定义标签属性

Thymeleaf中可以使用
th:
加上标签的任何属性进行赋值,但有些时候会遇到自定义的属性,再用
th:
加自定义的属性则会无效。比如:需要对
<span>
标签增加
objName
objId
这样的属性,在非Thymeleaf情况下是这样:

<spanobjId="1"objName="知识林"></span>

变量情况是:

<spanobjId="${obj.id}"objName="${obj.name}"></span>

Thymeleaf下则是:

<spanth:attr="myDate=${#dates.format(curDate,'yyyy-MM-dd')},myMoney=${money}"></span>

说明:在页面上查看源代码可以看到:
<spanmyMoney="91.6059494319957"myDate="2016-31-02"></span>
,说明自定义属性用:
th:attr
,多个属性用
,
隔开。

内置对象

上面简单描述了比较常用的
dates
lists
numbers
这几个内置对象,在Thymeleaf还有很多的内置对象,像
strings
也非常常用,用法跟
java.lang.String
类的用法一样。

Thymeleaf中的内置对象有:

#dates
:日期格式化内置对象,具体方法可以参照
java.util.Date


#calendars
:类似于
#dates
,但是是
java.util.Calendar
类的方法;

#numbers
:数字格式化;

#strings
:字符串格式化,具体方法可以参照
java.lang.String
,如
startsWith
contains
等;

#objects
:参照
java.lang.Object


#bools
:判断boolean类型的工具;

#arrays
:数组操作的工具;

#lists
:列表操作的工具,参照
java.util.List


#sets
:Set操作工具,参照
java.util.Set


#maps
:Map操作工具,参照
java.util.Map


#aggregates
:操作数组或集合的工具;

#messages
:操作消息的工具。

thymeleaf+bootstrap,onclick传参

<spantitle="删除"
th:onclick="'javascript:delCfmModel(\'/user/'+${user.id}+'/delete\')'"
style="cursor:pointer"
class="glyphiconglyphicon-trash">
</span>


或使用字符串拼接的另外一种简洁写法:<spanth:text="|Welcometoourapplication,${user.name}!|">

<spantitle="删除"
th:onclick="|javascript:delCfmModel('/sys/user/${user.id}/delete')|"
style="cursor:pointer"
class="glyphiconglyphicon-trash">
</span>


如果参数是字符串,需要加引号,如上图所示。否则会报错:UncaughtSyntaxError:Invalidregularexpressiongflags



如果只传数字,可以不加引号,如下图所示:

<ahref="#editModal"
role="button"
data-toggle="modal"
th:onclick="'javascript:editUser('+${prod.id}+');'">
Edit
</a>
<script>
functioneditUser(id){
$.get("/projectName/user/edit",
{objectid:id},
function(data){
$("#frm_container1").html(data);
});
}
</script>

https://yq.aliyun.com/articles/60696
<!--信息删除确认-->
<divclass="modalfade"id="deleteModal">
<divclass="modal-dialog">
<divclass="modal-contentmessage_align">
<divclass="modal-header">
<buttontype="button"class="close"data-dismiss="modal"aria-label="Close">
<spanaria-hidden="true">×</span>
</button>
<h4class="modal-title">Delete</h4>
</div>
<divclass="modal-body"style="text-align:center">
<p>
<iclass="glyphiconglyphicon-alert"></i>
DoYouReallyWanttoDeleteThis?
</p>
</div>
<divclass="modal-footer">
<inputtype="hidden"id="modalUrl"/>
<buttontype="button"class="btnbtn-default"data-dismiss="modal">Cancel</button>
<aid="modalConfirmBtn"class="btnbtn-success"data-dismiss="modal">Delete</a>
</div>
</div><!--/.modal-content-->
</div><!--/.modal-dialog-->
</div><!--/.modal-->


<scripttype="text/javascript">

functiondelCfmModel(url){
$('#modalUrl').val(url);//给会话中的隐藏属性URL赋值
$('#deleteModal').modal();
}

$("#modalConfirmBtn").click(function(){
$.get($('#modalUrl').val(),function(){
window.location.reload();//重新加载页面
});
});
</script>


如果需要弹出的Modal窗口垂直居中,水平居中,可以添加以下css样式(这个样式是覆盖了bootstrap的。tips,这个css是为上面的Modaldiv深度定制的,如需更改,需确定上面的html是否同步更改)

.modal{
text-align:center;
}

@mediascreenand(min-width:768px){
.modal:before{
display:inline-block;
vertical-align:middle;
content:"";
height:100%;
}
}

.modal-dialog{
display:inline-block;
text-align:left;
vertical-align:middle;
}


StandardExpressionsyntax

MostThymeleafattributesallowtheirvaluestobesetasorcontainingexpressions,

whichwewillcallStandardExpressionsbecauseofthedialectstheyareusedin.Thesecanbeoffivetypes:

${...}:Variableexpressions.
*{...}:Selectionexpressions.
#{...}:Message(i18n)expressions.
@{...}:Link(URL)expressions.
~{...}:Fragmentexpressions.


2017-09-0623:06:20.026WARN9824---[nio-8081-exec-1]n.n.u.t.expressions.ExpressionProcessor:

Fragmentexpression"layout/default"isbeingwrappedasaThymeleaf3fragmentexpression(~{...})forbackwardscompatibilitypurposes."

Thiswrappingwillbedroppedinthenextmajorversionoftheexpressionprocessor,

sopleaserewriteasaThymeleaf3fragmentexpressiontofuture-proofyourcode.

Seehttps://github.com/thymeleaf/thymeleaf/issues/451formoreinformation.


消除掉上面的WARN日志,

use:

<htmllang="zh"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/default}">


replace

<htmllang="zh"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="layout/default">

http://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
Createacommonlayouttobeusedforseveralpages,definingextensionpointsinthebodywiththe
layout:fragment
/
data-layout-fragment
processors:

<!DOCTYPEhtml>
<html>
<head>
<title>Layoutpage</title>
<scriptsrc="common-script.js"></script>
</head>
<body>
<header>
<h1>Mywebsite</h1>
</header>
<sectionlayout:fragment="content">
<p>Pagecontentgoeshere</p>
</section>
<footer>
<p>Myfooter</p>
<playout:fragment="custom-footer">Customfooterhere</p>
</footer>
</body>
</html>


Createacontentpagethatwillusethelayout,defininganyHTMLtousefortheextensionpointsinthelayout,andspecifiedbya
layout:decorate
/
data-layout-decorate
processorattherootelementofyourpage:

<htmllayout:decorate="~{layout.html}">
<head>
<title>Contentpage</title>
<scriptsrc="content-script.js"></script>
</head>
<body>
<sectionlayout:fragment="content">
<p>Thisisaparagraphfromthecontentpage</p>
</section>
<footer>
<playout:fragment="custom-footer">Thisissomefootercontentfromthecontentpage</p>
</footer>
</body>
</html>


GetThymeleaftoprocessyourcontentpage.Theresultwillbethelayouttemplatedecoratedbyyourcontentpage,meaningthatthecontentpagewillfilloutthelayout'sextensionpoints,replacetitles,andmerge
<head>
items:

<!DOCTYPEhtml>
<html>
<head>
<title>Contentpage</title>
<scriptsrc="common-script.js"></script>
<scriptsrc="content-script.js"></script>
</head>
<body>
<header>
<h1>Mywebsite</h1>
</header>
<section>
<p>Thisisaparagraphfromthecontentpage</p>
</section>
<footer>
<p>Myfooter</p>
<p>Thisissomefootercontentfromthecontentpage</p>
</footer>
</body>
</html>


Intrigued?Checkoutthedocumentationlinksnearthetopofthisreadmetolearnmore.
https://github.com/ultraq/thymeleaf-layout-dialecthttps://ultraq.github.io/thymeleaf-layout-dialect/
[PleasemakesuretoselectthebranchcorrespondingtotheversionofThymeleafyouareusing]

Status

Thisisathymeleafextrasmodule,notapartoftheThymeleafcore(andassuchfollowingitsownversioningschema),butfullysupportedbytheThymeleafteam.

Thisrepositorycontainstwoprojects:

thymeleaf-extras-springsecurity3forintegrationwithSpringSecurity3.x

thymeleaf-extras-springsecurity4forintegrationwithSpringSecurity4.x

Currentversions:

Version3.0.2.RELEASE-forThymeleaf3.0(requiresThymeleaf3.0.3+)

Version2.1.3.RELEASE-forThymeleaf2.1(requiresThymeleaf2.1.2+)

Features

Thismoduleprovidesanewdialectcalled
org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect
or
org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect
(dependingontheSpringSecurityversion),withdefaultprefix
sec
.Itincludes:

Newexpressionutilityobjects:

#authentication
representingtheSpringSecurityauthenticationobject(anobjectimplementingthe
org.springframework.security.core.Authentication
interface).

#authorization
:aexpressionutilityobjectwithmethodsforcheckingauthorizationbasedonexpressions,URLsandAccessControlLists.

Newattributes:

sec:authentication="prop"
outputsa
prop
propertyoftheauthenticationobject,similartotheSpringSecurity
<sec:authentication/>
JSPtag.

sec:authorize="expr"
or
sec:authorize-expr="expr"
renderstheelementchildren(tagcontent)iftheauthenticateduserisauthorizedtoseeitaccordingtothespecifiedSpringSecurityexpression.

sec:authorize-url="url"
renderstheelementchildren(tagcontent)iftheauthenticateduserisauthorizedtoseethespecifiedURL.

sec:authorize-acl="object::permissions"
renderstheelementchildren(tagcontent)iftheauthenticateduserhasthespecifiedpermissionsonthespecifieddomainobject,accordingtoSpringSource'sAccessControlListsystem.

Configuration

Inordertousethethymeleaf-extras-springsecurity3orthymeleaf-extras-springsecurity4modulesinourSpringMVCapplication,wewillfirstneedtoconfigureourapplicationintheusualwayforSpring+Thymeleafapplications(TemplateEnginebean,templateresolvers,etc.),andaddtheSpringSecuritydialecttoourTemplateEnginesothatwecanusethe
sec:*
attributesandspecialexpressionutilityobjects:

<beanid="templateEngine"class="org.thymeleaf.spring4.SpringTemplateEngine">
...
<propertyname="additionalDialects">
<set>
<!--Notethepackagewouldchangeto'springsecurity3'ifyouareusingthatversion-->
<beanclass="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/>
</set>
</property>
...
</bean>


Andthat'sall!

Usingtheexpressionutilityobjects

The
#authentication
objectcanbeeasilyused,likethis:

<div[b]th:text[/b]="${#authentication.name}">
Thevalueofthe"name"propertyoftheauthenticationobjectshouldappearhere.
</div>


The
#authorization
objectcanbeusedinasimilarway,normallyin
th:if
or
th:unless
tags:

<divth:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">
ThiswillonlybedisplayedifauthenticateduserhasroleROLE_ADMIN.
</div>


The
#authorization
objectisaninstanceof
org.thymeleaf.extras.springsecurity[3|4].auth.Authorization
,seethisclassanditsdocumentationtounderstandallthemethodsoffered.

Usingtheattributes

Usingthe
sec:authentication
attributeisequivalenttousingthe
#authentication
object,butusingitsownattribute:

<divsec:authentication="name">
Thevalueofthe"name"propertyoftheauthenticationobjectshouldappearhere.
</div>


The
sec:authorize
and
sec:authorize-expr
attributesareexactlythesame.Theyworkequivalentlytoa
th:if
thatevaluatedan
#authorization.expression(...)
expression,byevaluatingaSpringSecurityExpression:

<divsec:authorize="hasRole('ROLE_ADMIN')">
ThiswillonlybedisplayedifauthenticateduserhasroleROLE_ADMIN.
</div>


TheseSpringSecurityExpressionsin
sec:authorize
attributesareinfactSpringELexpressionsevaluatedonaSpringSecurity-specificrootobjectcontainingmethodssuchas
hasRole(...)
,
getPrincipal()
,etc.

AswithnormalSpringELexpressions,Thymeleafallowsyoutoaccessaseriesofobjectsfromthemincludingthecontextvariablesmap(the
#vars
object).Infact,youareallowedtosurroundyouraccessexpressionwith
${...}
ifitmakesyoufeelmorecomfortable:

<divsec:authorize="${hasRole(#vars.expectedRole)}">
Thiswillonlybedisplayedifauthenticateduserhasarolecomputedbythecontroller.
</div>


RememberthatSpringSecuritysetsaspecialsecurity-orientedobjectasexpressionroot,whichiswhyyouwouldnotbeabletoaccessthe
expectedRole
variabledirectlyintheaboveexpression.

Anotherwayofcheckingauthorizationis
sec:authorize-url
,whichallowsyoutocheckwhetherauserisauthorizedtovisitaspecificURLornot:

<divsec:authorize-url="/admin">
Thiswillonlybedisplayedifauthenticatedusercancallthe"/admin"URL.
</div>


ForspecifyingaspecificHTTPmethod,do:

<divsec:authorize-url="POST/admin">
Thiswillonlybedisplayedifauthenticatedusercancallthe"/admin"URL
usingthePOSTHTTPmethod.
</div>


Finally,thereisanattributeforcheckingauthorizationusingSpringSecurity'sAccessControlLists,whichneedsthespecificationofadomainobjectandthepermissionsdefinedonitthatweareaskingfor.

<divsec:authorize-acl="${obj}::'1,3'">
Thiswillonlybedisplayedifauthenticateduserhaspermissions"1"and"3"
ondomainobjectreferencedbycontextvariable"obj".
</div>


Inthisattribute,bothdomainobjectandpermissionspecificationsareconsideredtobethymeleafStandardExpressions.

Namespace

ThenamespaceforbothSpring3and4versionsofthisdialectis
http://www.thymeleaf.org/extras/spring-security
.

<htmlxmlns:sec="http://www.thymeleaf.org/extras/spring-security">


Gettingthenamespaceincorrectwon'timpactprocessingofyourtemplate.ItmighthoweverimpactyourIDEwhenitcomestothingslikesuggestions/auto-completioninyourtemplates.
https://github.com/thymeleaf/thymeleaf-extras-springsecurityhttps://github.com/ultraq/thymeleaf-layout-dialecthttp://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#including-template-fragmentshttps://github.com/zsl131/thymeleaf-studyhttps://github.com/kolorobot/spring-boot-thymeleafhttp://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#howto-use-thymeleaf-3https://github.com/spring-projects/spring-boot/blob/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-web-thymeleaf3/src/main/resources/application.propertieshttp://blog.imyxiao.com/2016/11/26/Spring-Boot-thymeleaf-3/https://github.com/kolorobot/spring-boot-thymeleaf
在spring-boot1.4之后,支持thymeleaf3,可以更改版本号来进行修改支持.
3相比2极大的提高了效率,并且不需要标签闭合,类似的link,img等都有了很好的支持,按照如下配置即可

解决下面的问题的办法是升级到Thymeleaf3

74.9UseThymeleaf3

Bydefault,
spring-boot-starter-thymeleaf
usesThymeleaf2.1.Ifyouareusingthe
spring-boot-starter-parent
,youcanuseThymeleaf3byoverridingthe
thymeleaf.version
and
thymeleaf-layout-dialect.version
properties,forexample:

<properties>
<thymeleaf.version>3.0.7.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
<thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
</properties>


Tips:

如果不同时更改thymeleaf-extras-springsecurity4的version,则thymeleafspringsecurity4相关的标签会不生效




ifyouaremanagingdependenciesyourself,lookat
spring-boot-dependencies
forthelistofartifactsthatarerelatedtothosetwoversions.

ToavoidawarningmessageabouttheHTML5templatemodebeingdeprecatedandtheHTMLtemplatemodebeingusedinstead,youmayalsowanttoexplicitlyconfigure
spring.thymeleaf.mode
tobe
HTML
,forexample:

spring.thymeleaf.mode:HTML

PleaserefertotheThymeleaf3sampletoseethisinaction.

Ifyouareusinganyoftheotherauto-configuredThymeleafExtras(SpringSecurity,DataAttribute,orJava8Time)youshouldalsooverrideeachoftheirversionstoonethatiscompatiblewithThymeleaf3.0.
http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#howto-use-thymeleaf-3
It'smuchsimpler,justreadthis:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-use-thymeleaf-3
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>


Youmightalsowanttoadd<thymeleaf-extras-java8time.version>3.0.0.RELEASE</thymeleaf‌​-extras-java8time.ve‌​rsion>–SamuelEUSTACHIJun6at9:42
https://stackoverflow.com/questions/37439369/spring-boot-and-thymeleaf-3-0-0-release-integrationhttp://blog.imyxiao.com/2016/11/26/Spring-Boot-thymeleaf-3/http://www.thymeleaf.org/doc/articles/thymeleaf3migration.htmlhttps://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-web-thymeleaf3
org.xml.sax.SAXParseException:元素类型"img"必须由匹配的结束标记"</img>"终止。

1、必须要有结束标签,这个很烦,不加就报错,像下面这样:

org.xml.sax.SAXParseException:元素类型"input"必须由匹配的结束标记"</input>"终止。

org.xml.sax.SAXParseException:元素类型"img"必须由匹配的结束标记"</img>"终止。

org.xml.sax.SAXParseException:元素类型"hr"必须由匹配的结束标记"</hr>"终止。

org.xml.sax.SAXParseException:元素类型"br"必须由匹配的结束标记"</br>"终止。

2、包含的模板,也必须有闭合标签。我要引入公共的头部和底部,头部还好说,外面有个<head>包着,底部必须得在外面套个div,引入js的代码也得包括在div里,不爽啊,像这样:

<divclass="container"th:fragment="footer">
<hr></hr>
<div>
<p>AntsClub2013-2015</p>
</div>
<scriptth:src="@{bootstrap334/js/jquery.min.js}"></script>
<scriptth:src="@{bootstrap334/js/bootstrap.min.js}"></script>
</div>

3、引入个css文件,js文件也得用thymeleaf的标签,就像上面的例子

如果你的代码使用了HTML5的标准,而Thymeleaf版本来停留在2.x,那么如果没有把
<input>
闭合,如下:

<form>
Firstname:<br>
<inputtype="text"name="firstname">
<br>
Lastname:<br>
<inputtype="text"name="lastname">
</form>


就会抛出如下错误。

org.xml.sax.SAXParseException:元素类型"input"必须由匹配的结束标记"</input>"终止。


解决方案

1.沿用Thymeleaf老版本

如果你的Thymeleaf不能变更,那么你的HTML标准也只能停留在老版本了。你必须严格遵守XML定义,在
<input>
加上结束标记
</input>
。这显然,对于HTML5不友好。

2.升级至Thymeleaf3新版本

是时候尝试下使用Thymeleaf3了。Thymeleaf3使用了新的解析系统。

Thymeleaf3不再是基于XML结构的。由于引入新的解析引擎,模板的内容格式不再需要严格遵守XML规范。即不在要求标签闭合,属性加引号等等。当然,出于易读性考虑,还是推荐你按找XML的标准去编写模板。

Thymeleaf3使用一个名为AttoParser2的新解析器。一个新的、基于事件(不符合SAX标准)的解析器,AttoParser由Thymeleaf的作者开发,符合Thymeleaf的风格。

AttoParser提供Thymeleaf3两个重要功能:

完全支持XML和HTML5(非XML化)标记,从而不再需要外部标记平衡操作。

无损解析,以便在处理的输出的标记类似于具有最高精度的原始模板。

所以下面的格式在Thymeleaf3里面是合法的:

<div><imgalt=logoth:src='@{/images/logo.png}'>


Thymeleaf3其他方面的解析改进

1.启用验证的解析

在Thymeleaf2.1提供了两种
VALID*
模板模式,名为
VALIDXHTML
VALIDXML
,在而Thymeleaf3中将不再存在。新的解析基础结构不提供HTML或XML验证,即在解析期间无法验证模板标记是否符合指定的DTD或XML模式定义。

2.不再需要
<![CDATA[...]]>

Thymeleaf2.1要求将
<script>
标记的内容封装在CDATA中,以便所使用的任何
<
>
符号不会干扰基于XML的解析:

<script>
/*<![CDATA[*/
varuser=...
if(user.signupYear<1990){
alert('You\'vebeenhereforalongtime!');
}
/*]]>*/
</script>


而在Thymeleaf3中则不需要这样做,代码立马变得简洁干净:

<script>
varuser=...
if(user.signupYear<1990){
alert('You\'vebeenhereforalongtime!');
}
</script>


参考文献

https://github.com/thymeleaf/thymeleaf/issues/390
https://waylau.com/thymeleaf-3-adopts-a-new-parsing-system/

THYMELEAF3-GETSTARTEDQUICKLYWITHTHYMELEAF3ANDSPRINGMVC

Thymeleaf3releasearrived.ThenewversionbringsplentyofnewfeatureslikeHTML5supportaswellasTexttemplatessupportwithnomarkup-
[#th:utext="${thymeleaf.version}"/]
,improvedinlinecapabilities-
<p>Thymeleaf[[${thymeleaf.version}]]isgreat!</p>
,performenceimprovementsandmuchmore.

TheeasiestwaythegetstarterwithThymeleaf3andSpringMVCisbyusingSpringMVC4QuickstartMavenArchetype.ThearchetypewasupdatedtosupportThymeleaf3.Thechangesthataremadetothearchetypearedescribedbelow.

Dependencies

TheprojectusesSpringPlatformBOMfordependenciesmanagement,butitdoesnotyet(astimeofwritingthispost)declaredependencyonThymeleaf3,soIneededtodeclaretheversionsmanually.

Thymeleaf:

<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>


ThymeleafSpring4:

<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>


ThymeleafSpringSecurity4:

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>

TheapplicationgeneratedwiththearchetypeusesJava8TimeDialectandsinceThymeleafAPIchanged,thedialectdependencymustbeupdatedtoo.BeforeitisavailableinMavenCentral,wemustaddsnapshotrepositorytoPOM:

<repository>
<id>sonatype-nexus-snapshots</id>
<name>SonatypeNexusSnapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>

Andthendeclarethedependency:

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>

Configurationchanges

Templateresolver

Templateresolverbefore:

@Bean
publicTemplateResolvertemplateResolver(){
TemplateResolverresolver=newServletContextTemplateResolver();
resolver.setPrefix(VIEWS);
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setCacheable(false);
returnresolver;
}

Templateresolverafter:

@Bean
publicITemplateResolvertemplateResolver(){
SpringResourceTemplateResolverresolver=newSpringResourceTemplateResolver();
resolver.setPrefix(VIEWS);
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(false);
returnresolver;
}


TemplateEngine

@Bean
publicSpringTemplateEnginetemplateEngine(){
SpringTemplateEnginetemplateEngine=newSpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(newSpringSecurityDialect());
templateEngine.addDialect(newJava8TimeDialect());
returntemplateEngine;
}


ViewResolver:

@Bean
publicViewResolverviewResolver(){
ThymeleafViewResolverthymeleafViewResolver=newThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(templateEngine());
thymeleafViewResolver.setCharacterEncoding("UTF-8");
returnthymeleafViewResolver;
}

Templates

Thetemplatesdidnotchangeinthisproject.Butifyouaremigratingarealproject,youmaybeinterestedinreadingmigrationguide.

References

Thymeleaf3releaseinfo

Thymeleaf3Migrationguide

SpringMVC4QuickstartMavenArchetype

Youmaybealsointerestedin

SpringBootandThymeleafwithMaven

SpringMVCandThymeleaf:howtoacessdatafromtemplates

ThymeleafPageLayouts
http://blog.codeleak.pl/2016/05/thymeleaf-3-get-started-quickly-with.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: