Thymeleaf

来自版块 问答
250
2
一、Thymeleaf简介


  • Thymeleaf是用来开辟Web和独立情况项目标服务器端的Java模版引擎
  • Spring官方支持的服务的渲染模板中,并不包罗jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与SpringMVC的视图技能,及SpringBoot的主动化设置集成非常完善,险些没有任何本钱,你只用关注Thymeleaf的语法即可。
二、Thymeleaf的特点


  • 动静联合:Thymeleaf 在有网络和无网络的情况下皆可运行,即它可以让美工在欣赏器检察页面的静态结果,也可以让步伐员在服务器检察带数据的动态页面结果。这是由于它支持 html 原型,然后在 html 标签里增长额外的属性来到达模板+数据的展示方式。欣赏器表明 html 时会忽略未界说的标签属性,以是 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地更换掉静态内容,使页面动态表现。
  • 开箱即用:它提供尺度和spring尺度两种方言,可以直接套用模板实现JSTL、 OGNL表达式结果,制止天天套模板、该jstl、改标签的困扰。同时开辟职员也可以扩展和创建自界说的方言。
  • 多方言支持:Thymeleaf 提供spring尺度方言和一个与 SpringMVC 完善集成的可选模块,可以快速地实现表单绑定、属性编辑器、国际化等功能。
  • 与SpringBoot完善整合,SpringBoot提供了Thymeleaf的默认设置,而且为Thymeleaf设置了视图剖析器,昨们可以像从前操纵jsp一样来操纵Thymeleaf。代码险些没有任何区别,就是在模板语法上有区别。
三.ssm中添加thymeleaf

1.导入jar包

<dependency>  <groupId>org.thymeleaf</groupId>  <artifactId>thymeleaf</artifactId>  <version>3.0.9.RELEASE</version></dependency><dependency>  <groupId>org.thymeleaf</groupId>  <artifactId>thymeleaf-spring4</artifactId>  <version>3.0.9.RELEASE</version></dependency>2.在springmvc.xml文件中设置视图剖析器为thymeleaf剖析


<!-- 利用thymeleaf剖析 --><bean id=&quot;templateResolver&quot;      class=&quot;org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver&quot;>    <property name=&quot;prefix&quot; value=&quot;/WEB-INF/views/&quot; />    <property name=&quot;suffix&quot; value=&quot;.html&quot; />    <property name=&quot;templateMode&quot; value=&quot;HTML&quot; />    <property name=&quot;cacheable&quot; value=&quot;false&quot; />    <property name=&quot;characterEncoding&quot; value=&quot;UTF-8&quot;/><!--不加会乱码--></bean><bean id=&quot;templateEngine&quot;      class=&quot;org.thymeleaf.spring4.SpringTemplateEngine&quot;>    <property name=&quot;templateResolver&quot; ref=&quot;templateResolver&quot; /></bean><bean class=&quot;org.thymeleaf.spring4.view.ThymeleafViewResolver&quot;>    <property name=&quot;templateEngine&quot; ref=&quot;templateEngine&quot; />    <!--办理中文乱码-->    <property name=&quot;characterEncoding&quot; value=&quot;UTF-8&quot;/></bean>3.删除之前视图剖析器为jsp的设置信息,假如两个都设置,谁在前面,用谁

<!-- 设置视图剖析器 --><!--<bean class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;>-->    <!--<property name=&quot;prefix&quot; value=&quot;/WEB-INF/&quot; />-->    <!--<property name=&quot;suffix&quot; value=&quot;.jsp&quot; />--><!--</bean>-->4.设置web.xml文件中thymeleaf部门

   <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext-ioc.xml</param-value>  </context-param>    <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <servlet>  <servlet-name>springMVC</servlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  <!--SpringMVC设置文件的名字  <servlet-name>-servlet.xml      默认位置:src / resources    假如放在了 src/resources(maven)          contextConfigLocation:classpath:文件名即可!          Web-INF/xx.xml          contextConfigLocation:/WEB-INF/xx.xml  -->  <init-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:springmvc.xml</param-value>  </init-param>  <load-on-startup>1</load-on-startup></servlet><!-- 访问DispatcherServlet对应的路径 --><servlet-mapping>  <servlet-name>springMVC</servlet-name>  <url-pattern>/</url-pattern> <!--/不外滤jsp防止死循环--></servlet-mapping><!--设置thymeleaf  --><servlet-mapping>  <servlet-name>springMVC</servlet-name>  <url-pattern>*.html</url-pattern></servlet-mapping>5.创建控制器

package com.test.action;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping(&quot;thymeleaf&quot;)public class ThymeleafAction {    @RequestMapping(&quot;/testThymeleaf&quot;)    public String testThymeleaf(Model model)    {        model.addAttribute(&quot;uname&quot;,&quot;zhangsan&quot;);        return &quot;testThymeleaf&quot;;// WEB-INF/views/testThymeleaf.html    }}6.创建html页面

根据之前设置的前缀
在web-inf/views/文件夹下创建html文件
访问通报过来的数据,留意声明Thymeleaf定名空间
<!DOCTYPE html><html lang=&quot;en&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;       xmlns:th=&quot;http://www.thymeleaf.org&quot;><head>    <meta charset=&quot;UTF-8&quot;>    <title>Title</title></head><body><h1 th:text=&quot;${uname}&quot;>aaaa</h1></body></html>7.测试

​ http://localhost:8080/testssm/thymeleaf/testThymeleaf
​ 乐成

张三

四.常用th属性解读

html有的属性,Thymeleaf根本都有,而常用的属性大概有七八个。此中th属性实行的优先级从1~8,数字越低优先级越高。
一、th:text :设置当前元素的文本内容,雷同功能的另有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7
二、th:value:设置当前元素的value值,雷同修改指定属性的另有th:srcth:href。优先级不高:order=6
三、th:each:遍历循环元素,和th:text或th:value一起利用。留意该属性修饰的标签位置,具体今后看。优先级很高:order=2
四、th:if:条件判定,雷同的另有th:unlessth:switchth:case。优先级较高:order=3
五、th:insert:代码块引入,雷同的另有th:replaceth:include,三者的区别较大,若利用不适当会粉碎html布局,常用于公共代码块提取的场景。优先级最高:order=1
六、th:fragment:界说代码块,方便被th:insert引用。优先级最低:order=8
七、th:object:声明变量,一样平常和*{}一起共同利用,到达偷懒的结果。优先级一样平常:order=4
八、th:attr:修改恣意属性,现实开辟中用得较少,由于有丰富的其他th属性帮助,雷同的另有th:attrappend,th:attrprepend。优先级一样平常:order=5
五.底子利用语法

1.创建HTML

由上文也可以知道必要在html中添加:
<html xmlns:th=&quot;http://www.thymeleaf.org&quot;>如许,下文才气精确利用th:*情势的标签!
2.获取变量值${…}

通过**${…}举行取值,这点和ONGL表达式语法同等!**
  <h1 th:text=&quot;${uname}&quot;></h1>  <input type=&quot;text&quot; th:value=&quot;${uname}&quot; />  选择变量表达式*{…}


<div th:object=&quot;${items}&quot;>    <p th:text=&quot;*{name}&quot; >产物名</p>    <p th:text=&quot;*{detail}&quot; >产物名</p></div>

至于p内里的原有的值只是为了给前端开辟时做展示用的.如许的话很好地做到了前后端分离。
这也是Thymeleaf非常好的一个特性:在无网络的环境下也能运行,也就是完全可从前端先写出页面,模仿数据显现结果,后端职员再拿此模板修改即可!
3.链接表达式: @{…}

用来共同link src href利用的语法,雷同的标签有:th:hrefth:src
链接表达式布局

无参:@{/xxx}
有参:@{/xxx(k1=v1,k2=v2)} 对应url布局:xxx?k1=v1&k2=v2
引入当地资源:@{/项目当地的资源路径}
引入外部资源:@{/webjars/资源在jar包中的路径}
枚举:第三部门的实战引用会具体利用该表达式
<link th:href=&quot;@{/webjars/bootstrap/4.0.0/css/bootstrap.css}&quot; rel=&quot;stylesheet&quot;><link th:href=&quot;@{/main/css/itdragon.css}&quot; rel=&quot;stylesheet&quot;><form class=&quot;form-login&quot; th:action=&quot;@{/user/login}&quot; th:method=&quot;post&quot; ><a class=&quot;btn btn-sm&quot; th:href=&quot;@{/login.html(l='zh_CN')}&quot;>中文</a><a class=&quot;btn btn-sm&quot; th:href=&quot;@{/login.html(l='en_US')}&quot;>English</a><a href=&quot;details.html&quot; th:href=&quot;@{/thymeleaf/showItemsById(id=${items.id})}&quot;>view</a>    4.${…}变量表达式

变量表达式有丰富的内置方法,使其更强盛,更方便。
变量表达式功能

一、可以获取对象的属性和方法
二、可以利用ctx,vars,locale,request,response,session,servletContext内置对象
三、可以利用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法(重点先容)
常用的内置对象

一、ctx :上下文对象。
二、vars :上下文变量。
三、locale:上下文的语言情况。
四、request:(仅在web上下文)的 HttpServletRequest 对象。
五、response:(仅在web上下文)的 HttpServletResponse 对象。
六、session:(仅在web上下文)的 HttpSession 对象。
七、servletContext:(仅在web上下文)的 ServletContext 对象
这里以常用的Session举例,用户登载乐成后,会把用户信息放在Session中,Thymeleaf通过内置对象将值从session中获取。
// java 代码将用户名放在session中session.setAttribute(&quot;userinfo&quot;,username);// Thymeleaf通过内置对象直接获取th:text=&quot;${session.userinfo}&quot;常用的内置方法

一、strings:字符串格式化方法,常用的Java方法它都有。好比:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
二、numbers:数值格式化方法,常用的方法有:formatDecimal等
三、bools:布尔方法,常用的方法有:isTrue,isFalse等
四、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
五、listssets:聚集方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
六、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等
文章底部提供了对应的官网链接
<!DOCTYPE html><html lang=&quot;en&quot; xmlns:th=&quot;http://www.thymeleaf.org&quot;><head>    <meta charset=&quot;UTF-8&quot;>    <title>ITDragon Thymeleaf 内置方法</title></head><body>    <h2>ITDragon Thymeleaf 内置方法</h2>    <h3>#strings </h3>    <div th:if=&quot;${not #strings.isEmpty(itdragonStr)}&quot; >        <p>Old Str : <span th:text=&quot;${itdragonStr}&quot;/></p>        <p>toUpperCase : <span th:text=&quot;${#strings.toUpperCase(itdragonStr)}&quot;/></p>        <p>toLowerCase : <span th:text=&quot;${#strings.toLowerCase(itdragonStr)}&quot;/></p>        <p>equals : <span th:text=&quot;${#strings.equals(itdragonStr, 'itdragonblog')}&quot;/></p>        <p>equalsIgnoreCase : <span th:text=&quot;${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}&quot;/></p>        <p>indexOf : <span th:text=&quot;${#strings.indexOf(itdragonStr, 'r')}&quot;/></p>        <p>substring : <span th:text=&quot;${#strings.substring(itdragonStr, 2, 8)}&quot;/></p>        <p>replace : <span th:text=&quot;${#strings.replace(itdragonStr, 'it', 'IT')}&quot;/></p>        <p>startsWith : <span th:text=&quot;${#strings.startsWith(itdragonStr, 'it')}&quot;/></p>        <p>contains : <span th:text=&quot;${#strings.contains(itdragonStr, 'IT')}&quot;/></p>    </div>    <h3>#numbers </h3>    <div>        <p>formatDecimal 整数部门随意,小数点后保存两位,四舍五入: <span th:text=&quot;${#numbers.formatDecimal(itdragonNum, 0, 2)}&quot;/></p>        <p>formatDecimal 整数部门保存五位数,小数点后保存两位,四舍五入: <span th:text=&quot;${#numbers.formatDecimal(itdragonNum, 5, 2)}&quot;/></p>    </div>    <h3>#bools </h3>    <div th:if=&quot;${#bools.isTrue(itdragonBool)}&quot;>        <p th:text=&quot;${itdragonBool}&quot;></p>    </div>    <h3>#arrays </h3>    <div th:if=&quot;${not #arrays.isEmpty(itdragonArray)}&quot;>        <p>length : <span th:text=&quot;${#arrays.length(itdragonArray)}&quot;/></p>        <p>contains : <span th:text=&quot;${#arrays.contains(itdragonArray, 5)}&quot;/></p>        <p>containsAll : <span th:text=&quot;${#arrays.containsAll(itdragonArray, itdragonArray)}&quot;/></p>    </div>    <h3>#lists </h3>    <div th:if=&quot;${not #lists.isEmpty(itdragonList)}&quot;>        <p>size : <span th:text=&quot;${#lists.size(itdragonList)}&quot;/></p>        <p>contains : <span th:text=&quot;${#lists.contains(itdragonList, 0)}&quot;/></p>        <p>sort : <span th:text=&quot;${#lists.sort(itdragonList)}&quot;/></p>    </div>    <h3>#maps </h3>    <div th:if=&quot;${not #maps.isEmpty(itdragonMap)}&quot;>        <p>size : <span th:text=&quot;${#maps.size(itdragonMap)}&quot;/></p>        <p>containsKey : <span th:text=&quot;${#maps.containsKey(itdragonMap, 'thName')}&quot;/></p>        <p>containsValue : <span th:text=&quot;${#maps.containsValue(itdragonMap, '#maps')}&quot;/></p>    </div>    <h3>#dates </h3>    <div>        <p>format : <span th:text=&quot;${#dates.format(itdragonDate)}&quot;/></p>        <p>custom format : <span th:text=&quot;${#dates.format(itdragonDate, 'yyyy-MM-dd HH:mm:ss')}&quot;/></p>        <p>day : <span th:text=&quot;${#dates.day(itdragonDate)}&quot;/></p>        <p>month : <span th:text=&quot;${#dates.month(itdragonDate)}&quot;/></p>        <p>monthName : <span th:text=&quot;${#dates.monthName(itdragonDate)}&quot;/></p>        <p>year : <span th:text=&quot;${#dates.year(itdragonDate)}&quot;/></p>        <p>dayOfWeekName : <span th:text=&quot;${#dates.dayOfWeekName(itdragonDate)}&quot;/></p>        <p>hour : <span th:text=&quot;${#dates.hour(itdragonDate)}&quot;/></p>        <p>minute : <span th:text=&quot;${#dates.minute(itdragonDate)}&quot;/></p>        <p>second : <span th:text=&quot;${#dates.second(itdragonDate)}&quot;/></p>        <p>createNow : <span th:text=&quot;${#dates.createNow()}&quot;/></p>    </div></body></html>背景给负责给变量赋值,和跳转页面。
@RequestMapping(&quot;varexpressions&quot;)public String varexpressions(ModelMap map) {  map.put(&quot;itdragonStr&quot;, &quot;itdragonBlog&quot;);  map.put(&quot;itdragonBool&quot;, true);  map.put(&quot;itdragonArray&quot;, new Integer[]{1,2,3,4});  map.put(&quot;itdragonList&quot;, Arrays.asList(1,3,2,4,0));  Map itdragonMap = new HashMap();  itdragonMap.put(&quot;thName&quot;, &quot;${#...}&quot;);  itdragonMap.put(&quot;desc&quot;, &quot;变量表达式内置方法&quot;);  map.put(&quot;itdragonMap&quot;, itdragonMap);  map.put(&quot;itdragonDate&quot;, new Date());  map.put(&quot;itdragonNum&quot;, 888.888D);  return &quot;grammar/varexpressions&quot;;}
5.运算符

数学运算

  • 二元操纵:+, - , * , / , %
  • 一元操纵: - (负)
逻辑运算

  • 一元 : and or
  • 二元 : !,not
比力运算(为制止转义尴尬,可以利用括号中的英文举行比力运算!)

  • 比力:> , < , >= , <= ( gt , lt , ge , le )
  • 即是:== , != ( eq , ne )
条件运算

  • If-then: (if) ? (then)
  • If-then-else: (if) ? (then) : (else)
  • Default: (value) ?: (defaultvalue)
6.选择

if/unless
利用th:if和th:unless属性举行条件判定,th:unless于th:if恰恰相反,只有表达式中的条件不建立,才会表现其内容。
<td ><span th:if=&quot;${items.price gt 1000}&quot; >佳构</span></td>  <td ><span th:unless=&quot;${items.price gt 1000}&quot; >次品</span></td>switch
<div th:switch=&quot;${items.name}&quot;>  <p th:case=&quot;'aa'&quot;>aaaaaaaaa</p>  <p th:case=&quot;'bb'&quot;>bbbbbbb</p>  <p th:case=&quot;'cc'&quot;>cccccccc</p></div>7.循环

th:each
thymeleaf的th:each常见用法一.th:eath迭代集适用法:<table border=&quot;1&quot; id=&quot;stuTable&quot;>    <tr>        <td>是否选中</td>        <td>编号</td>        <td>姓名</td>        <td>年事</td>    </tr>    <tr th:each=&quot;stu,userStat:${studentList}&quot; >        <td><input th:type=&quot;checkbox&quot; th:name=&quot;id&quot; th:value=&quot;${stu.id}&quot;></td>        <td th:text=&quot;${stu.id}&quot;>编号</td>        <td th:text=&quot;${stu.name}&quot;>姓名</td>        <td th:text=&quot;${stu.age}&quot;>年事</td>    </tr></table>二.迭代下标变量用法:状态变量界说在一个th:每个属性和包罗以下数据:1.当前迭代索引,从0开始。这是索引属性。index2.当前迭代索引,从1开始。这是统计属性。count3.元素的总量迭代变量。这是巨细属性。 size4.iter变量为每个迭代。这是现在的产业。 current5.是否当前迭代是奇数照旧偶数。这些even/odd的布尔属性。6.是否第一个当前迭代。这是first布尔属性。7.是否末了一个当前迭代。这是last布尔属性。用法实例:<table border=&quot;1&quot; id=&quot;stuTable&quot;>    <tr>        <td>是否选中</td>        <td>编号</td>        <td>姓名</td>        <td>年事</td>    </tr>    <tr th:each=&quot;stu,userStat:${studentList}&quot; th:class=&quot;${userStat.odd}?'odd':'even'&quot;>        <td th:text=&quot;${userStat.index}&quot;></td>        <td><input th:type=&quot;checkbox&quot; th:name=&quot;id&quot; th:value=&quot;${stu.id}&quot;></td>        <td th:text=&quot;${stu.id}&quot;>编号</td>        <td th:text=&quot;${stu.name}&quot;>姓名</td>        <td th:text=&quot;${stu.age}&quot;>年事</td>    </tr></table>控制器端代码:

package com.test.action;import com.test.pojo.Items;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import java.util.ArrayList;import java.util.Date;import java.util.List;@Controller@RequestMapping(&quot;thymeleaf&quot;)public class ThymeleafAction {    @RequestMapping(&quot;/testThymeleaf&quot;)    public String testThymeleaf(Model model)    {        model.addAttribute(&quot;uname&quot;,&quot;zhangsan&quot;);        Items items=new Items();        items.setId(1);        items.setName(&quot;iphone&quot;);        items.setDetail(&quot;9999&quot;);        items.setPrice(6000);        model.addAttribute(&quot;items&quot;,items);        List<Items> itemsList=new ArrayList<Items>();        itemsList.add(new Items(101,&quot;aa&quot;,1000,&quot;aaa&quot;,&quot;1.jpg&quot;,new Date()));        itemsList.add(new Items(102,&quot;bb&quot;,1000,&quot;aaa&quot;,&quot;1.jpg&quot;,new Date()));        itemsList.add(new Items(103,&quot;cc&quot;,1000,&quot;aaa&quot;,&quot;1.jpg&quot;,new Date()));        model.addAttribute(&quot;itemsList&quot;,itemsList);        return &quot;testThymeleaf&quot;;    }    @RequestMapping(&quot;/showItemsById&quot;)    public String showItemsById(Model model,int id)    {        model.addAttribute(&quot;id&quot;,id);         return &quot;showItemsById&quot;;    }}tems);
    List<Items> itemsList=new ArrayList<Items>();    itemsList.add(new Items(101,&quot;aa&quot;,1000,&quot;aaa&quot;,&quot;1.jpg&quot;,new Date()));    itemsList.add(new Items(102,&quot;bb&quot;,1000,&quot;aaa&quot;,&quot;1.jpg&quot;,new Date()));    itemsList.add(new Items(103,&quot;cc&quot;,1000,&quot;aaa&quot;,&quot;1.jpg&quot;,new Date()));    model.addAttribute(&quot;itemsList&quot;,itemsList);    return &quot;testThymeleaf&quot;;}@RequestMapping(&quot;/showItemsById&quot;)public String showItemsById(Model model,int id){    model.addAttribute(&quot;id&quot;,id);     return &quot;showItemsById&quot;;}}

使用道具 举报

全部评论 2

学习了
7 天前
评论·
·举报
转发了
7 天前

热文

所属版块

您需要登录后才可以回帖 立即登录
说说你的想法......
0
2
0
返回顶部