一.Thymeleaf简介
- Thymeleaf是用来开发web和独立环境的项目的服务器端的java模版引擎
- Spring官方支持的服务器的渲染模版中,并不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可
二.Thymeleaf的特点
- 动静结合:Thymeleaf在由网络和无网络的环境下皆可运行,既可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看数据的动态页面效果。这是由于它支持html原型,然后再html标签中增加额外的舒心来表达模块+数据的展示方式,浏览器解释html时会忽略未定义的标签属性,所以thymeleaf的模版可以以静态的运行;当浏览器返回到页面时,Thmeleaf标签会自动的替换掉静态内容,使页面动态显示。
- 开箱即可:它提供标准和spring标准两种方言,可以直接套用模版实现JSTL、OFNL表达式效果,避免每天套模版、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言
- 多方语言支持:Thymeleaf提供的Spring标准方言和Spring MVC完备的集成的可选模块,可以快速实现表单绑定、属性编辑器、国际化等功能。
- 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器。我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模版语法上有区别。
三.ssm中添加thymeleaf
-
导入jar包
<!-- thymeleaf --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.9.RELEASE</version> </dependency> <!--thymeleaf-spring5 --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.9.RELEASE</version> </dependency>
-
在springmvc.xml文件中设置视图解析器thyemleaf解析
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/p http://www.springframework.org/schema/p/spring-p.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--1 配置 扫描控制层在哪个包--> <context:component-scan base-package="com.zhj.controller"/> <!--2 jsp 视图解析解析器中的前缀和后缀--> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">--> <!-- <!– 设置前缀–>--> <!-- <property name="prefix" value="/WEB-INF/"/>--> <!-- <!– 设置后缀–>--> <!-- <property name="suffix" value=".jsp"/>--> <!-- </bean>--> <!--2 thymeleaf 视图解析--> <bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML" /> <property name="cacheable" value="false" /> <property name="characterEncoding" value="UTF-8" /> </bean> <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> </bean> <bean id="thymeleafViewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <property name="characterEncoding" value="UTF-8" /> </bean> <mvc:annotation-driven/> <!--3 设置静态文件--> <!-- <mvc:resources mapping="static/**" location="static/"/>--> <!--4 上传文件 配置 MultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSize" value="5242880"/> <!-- <property name="uploadTempDir" value="static/temp"/>--> <property name="resolveLazily" value="true"/> </bean> </beans>
-
删除之前的视图解析器为jsp的配置信息,如果两个都配置,谁在前用谁
<!--2 配置 jsp 视图解析解析器中的前缀和后缀--> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">--> <!-- <!– 设置前缀–>--> <!-- <property name="prefix" value="/WEB-INF/"/>--> <!-- <!– 设置后缀–>--> <!-- <property name="suffix" value=".jsp"/>--> <!-- </bean>-->
-
配置web.xml文件中的thymeleaf部分
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>SSM-DEMO</display-name> <!-- 1 监听器配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 2 前端过滤器 转换乱码 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <!-- 3 加入前端控制器 frontController --> <servlet-name>frontController</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--设置前端控制器参数--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <!--1 启动服务器时再加载--> <!--0 使用时再加载--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>frontController</servlet-name> <url-pattern>*.html</url-pattern><!--放行 .html 页面--> <!-- <url-pattern>/</url-pattern>--> </servlet-mapping> </web-app>
-
创建控制器
@Controller @RequestMapping("/thymeleaf") public class ThymeleafTest { @RequestMapping("testThymeleaf") public String testThymeleaf(Model model){ model.addAttribute("uname","zhangsan"); return "testThymeleaf"; // /WEB—INF/views/testThymeleaf } }
-
创建html页面
根据之前设置的前缀
在web-inf/views文件夹下创建html文件
访问传递过来的数据,注意声明thymeleaf的命名空间
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 th:text="${uname}">aaaa</h1> </body> </html>
7.测试
四.常用th属性解读
html的属性,Thymeleaf基本都有,其中th属性执行的优先级从1-8,数字越低优先级越高
-
th:text 设置当前元素的文本内容,相同的功能还有 th:utext ,两者的区别 前者不会转义html标签,后者会。优先级 :order=7
-
th:value 设置当前元素的value值,类似修改指定属性的还有 th:src th:href。优先级:order=6
-
th:each 遍历循环元素,和th:text 或 th:value一起使用。注意该属性修饰标签的位置。优先级:order=2
itemStat.index:当前从0开始的索引
itemStat.count:当前从1开始的长度
itemStat.size:总长度
itemStat.even/itemStat.odd:当前迭代是奇数还是偶数
-
th:if 条件判断 常与 th:unless 一起使用 类似 还有th:switch th:case 优先级:order=3
-
th:insert 代码块引入 ,类似于 th:replace th:include,三者区别较大,若使用不当会破坏html结构,常用于公共代码块提取场景。优先级最高:order=1
-
th:fragment 定义代码块,方法被th:insert 引用,优先级最低:order=8
-
th:object 声明变量,一般和*{} 一起配合使用,达到偷懒的效果。order=4
-
th:arr 修改任意属性 类似 有 th:class, order=5
五.测试
top.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:fragment="top">
头部信息
</div>
</body>
</html>
test.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:replace="top.html"></div>
<!--<h1 th:text="${uname}">aaaa</h1>-->
用户名:
<div th:text="${uname}">用户名</div>
密码:
<div th:text="${upassword}">密码</div>
用户名:<input type="text" th:value="${uname}" value="uname"/>
密码:<input type="text" th:value="${upassword}" value="upassword"/>
商品:
<div th:each="items,itemStat:${items}">
name:<span th:text="${items.key}">name</span>
index:<span th:text="${itemStat.index}"></span>
price:<span th:if="${items.value > 30}">此商品大于30</span>
price:<span th:unless="${items.value > 30}">此商品小于等于30</span>
</div>
<a th:href="@{success.html}" href="">跳转到 success.html</a>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
success
</body>
</html>
Controller
package com.zhj.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafTest {
@RequestMapping("test")
public ModelAndView testThymeleaf(){
ModelAndView modelAndView = new ModelAndView();
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("car",30);
hashMap.put("dog",40);
hashMap.put("mimi",50);
modelAndView.addObject("uname","zhangsan");
modelAndView.addObject("upassword","333");
modelAndView.addObject("items",hashMap);
modelAndView.setViewName("test");
return modelAndView; // /WEB—INF/views/testThymeleaf
}
@RequestMapping("success")
public String success(){
return "success";
}
}