目录
Thymeleaf 是一个流行的模板引擎,该模板引擎采用 Java 语言开发。
模板引擎是一个技术名词,是跨领域跨平台的概念,在 Java 语言体系下有模板引擎, 在 C#、PHP 语言体系下也有模板引擎,甚至在 JavaScript 中也会用到模板引擎技术,Java 生 态下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等。
Thymeleaf 对网络环境不存在严格的要求,既能用于 Web 环境下,也能用于非 Web 环 境下。在非 Web 环境下,他能直接显示模板上的静态数据;在 Web 环境下,它能像 Jsp 一 样从后台接收数据并替换掉模板上的静态数据。它是基于 HTML 的,以 HTML 标签为载体, Thymeleaf 要寄托在 HTML 标签下实现。
SpringBoot 集成了 Thymeleaf 模板技术,并且 Spring Boot 官方也推荐使用 Thymeleaf 来 替代 JSP 技术,Thymeleaf 是另外的一种模板技术,它本身并不属于 Spring Boot,Spring Boot 只是很好地集成这种模板技术,作为前端页面的数据展示,在过去的 Java Web 开发中,我 们往往会选择使用 Jsp 去完成页面的动态渲染,但是 jsp 需要翻译编译运行,效率低。
简单Thymeleaf案例
这个主要熟悉,springboot 使用 Thymeleaf 时,需要配置什么
创建一个springboot项目
在项目pom.xml文件中添加依赖
SpringBoot框架web项目起步依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
SpringBoot框架集成Thymeleaf的起步依赖,这是一定要有的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如果需要测试类,可以加测试依赖,如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
在resources/templates文件夹中添加 thymeleaf,thymeleaf 是基于html的
显示页面,名为 msg.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2 th:text="${date}">显示要显示的内容</h2>
</body>
</html>
【注意】:
需要在HTMl根标签中添加
<html lang="en" xmlns:th="http://www.thymeleaf.org">
thymeleaf 模板引擎的页面必须得通过中央调度器,${date}的内容会替换 “显示要显示的内容"。
在controller层,写一个控制层,用来映射到模板页面
package com.km.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
@RequestMapping(value = "/msg")
public String userDetail(Model model){
model.addAttribute("date","SpringBoot集成Thymeleaf模板引擎");
return "msg";
}
}
启动springboot,在url上输入 http://localhost:8080/msg,显示输出,如下
在 Spring boot 的核心配置文件 application.properties 中对 Thymeleaf 进行配置
#设置thymeleaf模板引擎的缓存,设置为false关闭,默认为true开启
spring.thymeleaf.cache=false
#设置thymeleaf模板引擎的前/后缀,默认的,可以不写
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
一般在开发的过程中,thymeleaf模板缓存是要关闭的,不方便调试。如果开启的话,改动一次,就需要重新启动服务器。
【注意】Springboot 使 用 thymeleaf 作 为 视 图 展 示 , 约 定 将 模 板 文 件 放 置 在 src/main/resource/templates 目录下,静态资源放置在 src/main/resource/static 目录下。
thymeleaf 表达式
创建一个User类,方便下面的测试
public class User {
private Integer id;
private String username;
private Integer age;
// set get方法
}
标准变量表达式
语法 ${...}
说明:标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和 EL 中的 ${} 相 同。
@Controller
public class UserController {
@RequestMapping(value = "/user/detail")
public ModelAndView userDetail(){
ModelAndView mv = new ModelAndView();
User user = new User();
user.setId(1001);
user.setUsername("lisi");
user.setAge(12);
mv.addObject("user",user);
mv.setViewName("userDetail");
return mv;
}
}
创建 src\main\resources\templates 下,创建显示页面userDetail.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>标准变量表达式:${}</h1>
用户编号:<span th:text="${user.id}"></span><br/>
用户姓名:<span th:text="${user.username}"></span><br/>
用户年龄:<span th:text="${user.age}"></span><br/>
<hr/>
</body>
</html>
【注意】:th:text="" 是 Thymeleaf 的一个属性,用于文本的显示。
选择变量表达式
语法:*{...}
说明:选择变量表达式,也叫星号变量表达式,使用 th:object 属性来绑定对象 选择表达式首先使用 th:object 来绑定后台传来的 User 对象,然后使用 * 来代表这个对 象,后面 {} 中的值是此对象中的属性。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>选择变量表达式(星号表达式):*{}</h1>
<div th:object="${user}">
用户编号:<span th:text="*{id}"></span><br/>
用户姓名:<span th:text="*{username}"></span><br/>
用户年龄:<span th:text="*{age}"></span><br/>
</div>
<hr/>
</body>
</html>
解析:*{}必须使用 th:object 属性来绑定这个对象,在div字标签中使用 * 来代替绑定的对象 ${user}
标准变量表达式和选择变量表达式混合使用
说明:标准变量和选择变量表达式可以混合使用,也可以不混合使用,使用 th:object 进行对 象的选择,也可以直接使用 *{...} 获取数据。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>标签变量表达式和选择变量表达式的混合使用</h1>
用户编号:<span th:text="*{user.id}"></span><br/>
用户姓名:<span th:text="*{user.username}"></span><br/>
用户年龄:<span th:text="*{user.age}"></span><br/>
<hr/>
</body>
</html>
URL 表达式
语法 @{...}
说明:主要用于链接、地址的展示,可以 在 URL 路径中动态获取数据。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a th:href="@{http://www.hao123.com}">路径表示式:跳转到hao123</a>
<br/>
</body>
</html>
路径可以是绝对路径,也可以是相对路径,路径可以带参数或者不带
绝对路径[可选带 参数]
<a th:href="@{http://www.hao123.com}">路径表示式:跳转到hao123</a><br/>
相对路径[可选带 参数]
<a th:href="@{/user/detail}">跳转到/user/detail</a><br/>
带参数
<a th:href="@{http://localhost:8080/test?username=zhangsan}">/test,并带参数username</a><br/>
还可以使用请求路径为RESTful风格
<a th:href="@{'/test3/'+${id} + '/' + ${username}}">请求路径为RESTful风格</a>
RESTful风格,controller层请求接收
@RequestMapping("/test3/{id}/{username}")
public @ResponseBody String test3(@PathVariable("id") Integer id,
@PathVariable("username") String username) {
return "ID =" + id + ",username=" + username;
}
文件中引用静态资源
<script type="text/javascript" th:src="@{/js/jquery-3.4.1.min.js}"></script>
一般静态资源会放到resources/static文件夹下
Thymeleaf 的常见属性
大部分属性和 html 的一样,只不过前面加了一个 th 前缀
只说一些需要注意的
th:action
th:action 定义后台控制器的路径,类似标签的 action 属性,主要结合 URL 表达式,获 取动态变量。
<form th:action="@{'/user/login?id='+${user.id}}"></form>
下面这两种方式是不正确的
<form action="'/user/login?id='+${user.id}"></form>
<form action="/user/login"+${user.id}></form>
解析:请求路径需要动态的获取变量的时候,必须在添加 th 前缀,否则无法获取动态属性。
原因: Thymeleaf 是以 html 为载体的,所以 html 不会认识${}语法。 我们请求的流程是,发送请求给服务器,服务器接收请求后,处理请求,跳转到指定的静 态 html 页面,在服务器端,Thymeleaf 模板引擎会按照它的语法,对动态数据进行处理, 所以如果要是 th 开头,模板引擎能够识别,会在服务器端进行处理,获取数据;如果没有 以 th 开头,那么 Thymeleaf 模板引擎不会处理,直接返回给客户端了。
th:method
<form th:action="@{/user/login}" th:method="post"></form>
th:href
定义超链接,主要结合 URL 表达式,获取动态变量
<a th:href="'http://www.baidu.com?id=' + ${user.id}">th:href 链接</a>
th:src
用于外部资源引入
<script type="text/javascript" th:src="@{/js/jquery-3.4.1.min.js}"></script>
【注意】在 SpringBoot 项目的静态资源都放到 resources 的 static 目录下。 放到 static 路径下的内容,写路径时不需要写上 static。
th:value
类似 html 标签中的 value 属性,能对某元素的 value 属性进行赋值
<input type="hidden" id="userId" name="userId" th:value="${userId}">
th:attr
该属性也是用于给 HTML 中某元素的某属性赋值,好处是可以给 html 中没有定义的属性动 态的赋值。
<span zhangsan="${user.name}"></span>
<!--通过 th:attr 对自定义的属性赋值-->
<span th:attr="zhangsan=${user.name}"></span>
th:text
用于文本的显示,该属性显示的文本在标签体中,如果是文本框,数据会在文本框外显示, 要想显示在文本框内,使用 th:value
<input type="text" id="userName" name="userName" th:text="${userName}">
th:onclick
<a th:onclick="'show('+${user.id}+')'">点击:显示学生编号</a>
<script type="text/javascript">
function show(id) {
alert("用户编号为:" + id);
}
</script>
Thymeleaf 运算符
三元运算:表达式?”正确结果”:”错误结果”
<div th:text="${sex eq 1 ? '男':'女'}"></div>
算术运算:+ , - , * , / , %
20+5=<span th:text="20+5"></span><br/>
关系比较::> , < , >= , <= ( gt , lt , ge , le )
5>2<span th:if="5 gt 2">真</span><br/>
相等判断:== , != ( eq , ne )
<span th:if="${sex eq 1}">男</span>
<span th:unless="${sex ne 1}">女</span>
条件判断
th:if
后端传过来的数据 sex 为 1
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>条件判断</title>
</head>
<body>
<div th:if="${sex eq 1}">
男
</div>
<div th:if="${sex eq 0}">
女
</div>
</body>
</html>
解析:如果满足条件执行
th:unless
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>条件判断</title>
</head>
<body>
<div th:unless="${sex ne 1}">
女
</div>
</body>
</html>
解析:与 th:if 用法相反,即条件判断取反。
th:switch/th:case
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>条件判断</title>
</head>
<body>
<h1>th:switch/th:case用法</h1>
<div th:switch="${productType}">
<span th:case="0">产品0</span>
<span th:case="1">产品1</span>
<span th:case="*">无此产品</span>
</div>
</body>
</html>
解析:一旦某个 case 判断值为 true,剩余的 case 默认不执行,“*”表示默 认的 case,前面的 case 都不匹配时候,执行默认的 case。
th:each 遍历集合
这个属性非常常用,比如从后台传来一个对象集合那么就可以使用此属性遍历输出,它与 JSTL 中的类似,此属性既可以循环遍历集合,也可以循环遍历数组及 Map.
遍历List集合(Array数组方式一样)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div th:each="user,userStat:${userList}">
<span th:text="${userStat.index}"></span>
<span th:text="${user.id}"></span>
<span th:text="${user.name}"></span>
</div>
</body>
</html>
解析:
user:当前对象的变量名
userStat:当前对象的状态变量名,可以不写,默认就是对象变量名称+Start
${userList}:循环遍历的集合
遍历Map集合
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div th:each="userMap,userMapStat:${userMaps}">
<span th:text="${userMapStat.count}"></span>
<span th:text="${userMap.key}"></span>
<span th:text="${userMap.value}"></span>
<span th:text="${userMap.value.id}"></span>
<span th:text="${userMap.value.name}"></span>
</div>
</body>
</html>
解析:
userMap:变量接收每次遍历的结果,封装 为一个键值对
userMapStat:状态,可以不写,默认就是对象变量名称+Start
userMap.key:获取当前键值对中的 key
userMap.value:获取当前键值对中的 value
遍历复杂集合
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>循环遍历复杂的集合</title>
</head>
<body>
<h1>循环遍历复杂集合:list -> Map -> List -> User</h1>
<div th:each="myListMap:${myList}">
<div th:each="myListMapObj:${myListMap}">
Map 集合的 key:<span th:text="${myListMapObj.key}"></span>
<div th:each="myListMapObjList:${myListMapObj.value}">
<span th:text="${myListMapObjList.id}"></span>
<span th:text="${myListMapObjList.name}"></span>
<span th:text="${myListMapObjList.phone}"></span>
<span th:text="${myListMapObjList.address}"></span>
</div>
</div>
</div>
</body>
</html>
上面案例,只起到语法的介绍,实际内容,自行脑补。
th:inline 内敛表达式
th:inline 有三个取值类型 (text, javascript 和 none),值为 none 什么都不做,没有效果。
内敛文本
th:inline = “text”
内敛文本表达式不依赖于 html 标签,直接使用内敛表达式[[表达式]]即可获取动态数据,但 必须要求在父级标签上加 th:inline = “text”属性
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>内敛表达式</title>
</head>
<body>
<div th:inline="text">
用户编号:<div>[[${user.id}]]</div><br/>
用户姓名:[[${user.name}]]<br/>
</div>
</body>
</html>
【注意】:一般我们将 th:inline="text" 放到<body>标签中。
<body th:inline="text">
内敛脚本
th:inline=”javascript”
在 js 代码中获取后台的动态数据
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>内敛表达式</title>
</head>
<body>
<h1>内敛脚本 th:javascript</h1>
<script type="text/javascript" th:inline="javascript">
function showData() {
alert([[${data}]]);
}
</script>
<button th:onclick="showData()">展示数据</button>
</body>
</html>
上面案例,只起到语法的介绍,实际内容,自行脑补。
表达式内置基本对象
#request
#request 相 当 于 httpServletRequest 对 象 , 这 是 3.x 版 本 , 若 是 2.x 版 本 使 用 #httpServletRequest,在页面获取应用的上下文根,一般在 js 中请求路径中加上可以避免 404
下面获取当前地址url
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" th:inline="javascript">
// 获取协议名称
var scheme = [[${#request.getScheme()}]];
// 获取服务器名称
var serverName = [[${#request.getServerName()}]];
// 获取服务器端口号
var serverPort = [[${#request.getServerPort()}]];
// 获取上下文根
var contextPath = [[${#request.getContextPath()}]];
var allPath = scheme + "://" + serverName + ":" + serverPort + contextPath;
alert(allPath);
// 获取当前地址URL
var requestURL = [[${#httpServletRequest.requestURL}]];
// 获取参数
var queryString = [[${#httpServletRequest.queryString}]];
alert("requestURL==" + requestURL);
alert("queryString==" + queryString);
var requestAddress = requestURL + "?" + queryString;
alert(requestAddress);
</script>
</body>
</html>
#session
#session相当于 HttpSession 对象,这是 3.x 版本,若是 2.x 版本使用#httpSession
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>从SESSION中获取值</h1>
<span th:text="${#session.getAttribute('data')}"></span><br/>
<span th:text="${#httpSession.getAttribute('data')}"></span><br/>
<span th:text="${session.data}"></span><br/>
</body>
</html>
表达式内置功能对象
简单列举一些,可以去官网查看
#dates: java.util.Date 对象的实用方法:
<div th:text="${#dates.format(time,'yyyy-MM-dd HH:mm:ss')}"></div>
#strings: 字符串对象的实用方法: contains, startsWith, prepending/appending 等;
<div th:text="${#strings.substring(data,0,10)}"></div>
#calendars: 和 dates 类似;
#number:格式化数字对象的实用方法;
#objects: 对 objects 操作的实用方法;
#bools: 对布尔值求值的实用方法;
#arrays: 数组的实用方法;
#lists: list 的实用方法,比如
#sets: set 的实用方法;
#map:: map 的实用方法;
#aggregates: 对数组或集合创建聚合的实用方法;
拼接字符串比较好的方式
|要拼接的字符串内容|
<span th:text="|共${totalRows}条${totalPage}页,当前第${currentPage}页,首页, 上一页 下一页 尾页|"></span>