Thymeleaf是用来开发Web和独立环境项目的现代服务器端Java模板引擎,既适用于 web 环境,也适用于独立环境,比较适合当前的人员分工问题。其能够处理HTML、XML、JavaScript、CSS 甚至纯文本。提供了一种优雅且高度可维护的模板创建方法,可以直接在浏览器中正确显示,也可以作为静态原型方便开发团队协作。
Thymeleaf特点:
-
动静结合: Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。
Thymeleaf支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
-
开箱即用: Thymeleaf提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
-
多方言支持: Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
-
与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。
使用Spring Initializr快速创建一个工程:
勾选web和Thymeleaf的依赖:
项目结构:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ly</groupId>
<artifactId>thymeleaf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>thymeleaf</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致我们修改页面不会立即被展现,因此我们关闭缓存。
# 关闭Thymeleaf的缓存
spring:
thymeleaf:
cache:
false
另外,修改完毕页面,需要使用快捷键:Ctrl + Shift + F9
来刷新工程。
我们准备一个controller,控制视图跳转:
@Controller
public class HelloController {
@GetMapping("hello")
public String show1(Model model){
model.addAttribute("msg", "Hello, Thymeleaf!");
return "index";
}
}
新建一个html模板:
语法说明:
Thymeleaf通过${}
来获取model中的变量,注意这不是el表达式,而是ognl表达式,但是语法非常像。不过区别在于,我们的表达式写在一个名为:th:text
的标签属性中,这个叫做指令
<!DOCTYPE html>
<!--把html 的名称空间,改成:xmlns:th="http://www.thymeleaf.org" 会有语法提示-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1 th:text="${msg}">大家好</h1>
</body>
</html>
启动项目,访问页面:
动静结合:
Thymeleaf崇尚自然模板
,意思就是模板是纯正的html代码,脱离模板引擎,在纯静态环境也可以直接运行。现在如果我们直接在html中编写 ${}
这样的表达式,显然在静态环境下就会出错,这不符合Thymeleaf的理念。
Thymeleaf中所有的表达式都需要写在指令
中,指令是HTML5中的自定义属性,在Thymeleaf中所有指令都是以th:
开头。因为表达式${user.name}
是写在自定义属性中,因此在静态环境下,表达式的内容会被当做是普通字符串,浏览器会自动忽略这些指令,这样就不会报错了!
| 标签 | 作用 | 样例 |
| — | — | — |
| th:id | 替换id | <input th:id="${user.id}"/>
|
| th:text | 文本替换 | <p text:="${user.name}">name</p>
|
| th:utext | 支持html的文本替换 | <p utext:="${htmlcontent}">content</p>
|
| th:object | 替换对象 | <div th:object="${user}"></div>
|
| th:value | 属性赋值 | <input th:value="${user.name}" >
|
| th:with | 变量赋值运算 | <div th:with="isEven=${user.age}%2==0"></div>
|
| th:style | 设置样式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
|
| th:src | 替换资源 | <script type="text/javascript" th:src="@{index.js}"></script>
|
| th:onclick | 点击事件 | th:onclick="'getCollect()'"
|
| th:href | 替换超链接 | <a th:href="@{index.html}">url</a>
|
| th:each | 迭代 | <tr th:each="student:${user}" >
|
| th:if | 判断条件 | <a th:if="${userId == collect.userId}" >
|
| th:unless | 和th:if判断相反 | <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
|
| th:switch | 多路选择,配合th:case 使用 | <div th:switch="${user.role}">
|
| th:case | th:switch的一个分支 | <p th:case="'admin'">User is an administrator</p>
|
| th:fragment | 布局标签,定义一个代码片段,方便其它地方引用 | <div th:fragment="alert">
|
| th:include | 布局标签,替换内容到引入的文件 | <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
|
| th:replace | 布局标签,替换整个标签到引入的文件 | <div th:replace="fragments/header :: title"></div>
|
| th:selected | selected选择框 选中 | th:selected="(${xxx.id} == ${configObj.dd})"
|
| th:inline | 定义js脚本可以使用变量 | <script type="text/javascript" th:inline="javascript">
|
| th:action | 表单提交的地址 | <form action="subscribe.html" th:action="@{/subscribe}">
|
| th:remove | 删除某个属性 | <tr th:remove="all">
all:删除所有的孩子、body:删除其所有的孩子,不包含标签、tag:删除标签、all-but-first:删除除第一个以外的所有、none:什么也不做
|
新建一个实体类:User
public class User {
private String name;
private int age;
private boolean sex;
private String role;
//Get、Set
}
然后在模型中添加数据
@GetMapping("add")
public String addUser(Model model){
User user = new User();
user.setAge(21);
user.setName("<font color='red'>小明</font>");
model.addAttribute("user", user);
return "user";
}
th:text
指令出于安全考虑,会把表达式读取到的值进行处理,防止html的注入。例如,<p>你好</p>
将会被格式化输出为$lt;p$gt;你好$lt;/p$lt;
。如果想要不进行格式化输出,而是要输出原始内容,则使用th:utext
来代替.
示例:我们在页面获取user数据:
<h1>
欢迎您:<span th:utext="${user.name}">---</span>
</h1>
效果:
ognl表达式的语法糖:
刚才获取变量值,我们使用的是经典的对象.属性名
方式。但有些情况下,我们的属性名可能本身也是变量,怎么办?ognl提供了类似js的语法方式:
例如:${user.name}
可以写作${user['name']}
看下面的案例:
<h2>
<p>Name: <span th:text="${user.name}">Jack</span>.</p>
<p>Age: <span th:text="${user.age}">21</span>.</p>
</h2>
我们获取用户的所有信息,分别展示。当数据量比较多的时候,频繁的写user.
就会非常麻烦。因此,Thymeleaf提供了自定义变量来解决:
<h2 th:object="${user}">
<p>Name: <span th:text="*{name}">Jack</span>.</p>
<p>Age: <span th:text="*{age}">21</span>.</p>
</h2>
-
首先在
h2
上 用th:object="${user}"
获取user的值,并且保存 -
然后,在
h2
内部的任意元素上,可以通过*{属性名}
的方式,来获取user中的属性,这样就省去了大量的user.
前缀了
ognl表达式本身就支持方法调用,例如:
<h2 th:object="${user}">
<p>FirstName: <span th:text="*{name.split(' ')[0]}">first</span>.</p>
<p>LastName: <span th:text="*{name.split(' ')[1]}">last</span>.</p>
</h2>
这里我们调用了name(是一个字符串)的split方法。
Thymeleaf内置对象
Thymeleaf中提供了一些内置对象,并且在这些对象中提供了一些方法,方便我们来调用。获取这些对象,需要使用#对象名
来引用。
环境相关对象:
| 对象 | 作用 |
| :-: | :-- |
| #ctx
| 获取Thymeleaf自己的Context对象 |
| #requset
| 如果是web程序,可以获取HttpServletRequest对象 |
| #response
| 如果是web程序,可以获取HttpServletReponse对象 |
| #session
| 如果是web程序,可以获取HttpSession对象 |
| #servletContext
| 如果是web程序,可以获取HttpServletContext对象 |
Thymeleaf提供的全局对象:
| 对象 | 作用 |
| :-: | :-- |
| #dates
| 处理java.util.date的工具对象 |
| #calendars
| 处理java.util.calendar的工具对象 |
| #numbers
| 用来对数字格式化的方法 |
| #strings
| 用来处理字符串的方法 |
| #bools
| 用来判断布尔值的方法 |
| #arrays
| 用来护理数组的方法 |
| #lists
| 用来处理List集合的方法 |
| #sets
| 用来处理set集合的方法 |
| #maps
| 用来处理map集合的方法 |
- 举例
我们在环境变量中添加日期类型对象
@GetMapping("date")
public String date(Model model){
model.addAttribute("today", new Date());
return "date";
}
在页面中处理
<p>
今天是: <span th:text="${#dates.format(today,'yyyy-MM-dd')}">2020-03-30</span>
</p>
效果:
有的时候,我们需要在指令中填写基本类型如:字符串、数值、布尔等,并不希望被Thymeleaf解析为变量,这个时候称为字面值。
字符串字面值:
使用一对'
引用的内容就是字符串字面值了:
<h1 th:text="'${msg}'">大家好</h1>
th:text
中的${msg}
并不会被认为是变量,而是一个字符串:
数字字面值:
数字不需要任何特殊语法, 写的什么就是什么,而且可以直接进行算术运算
<p>今年是 <span th:text="2021">1999</span>.</p>
<p>两年后将会是 <span th:text="2021 + 2">2001</span>.</p>
布尔字面值:
布尔类型的字面值是true或false:
<div th:if="true">
你填的是true
</div>
这里引用了一个th:if
指令,跟vue中的v-if
类似
我们经常会用到普通字符串与表达式拼接的情况:
<span th:text="'欢迎您:' + ${user.name} + '!'"></span>
字符串字面值需要用''
,拼接起来非常麻烦,Thymeleaf对此进行了简化,使用一对|
即可:
<span th:utext="|欢迎您:${user.name}!|"></span>
与上面是完全等效的,这样就省去了字符串字面值的书写。
需要注意:${}
内部的是通过OGNL表达式引擎解析的,外部的才是通过Thymeleaf的引擎解析,因此运算符尽量放在${}
外进行,例如: <span th:text="${user.age}+2"></span>
。
算术运算:
支持的算术运算符:+ - * / %
比较运算:
支持的比较运算:>
, <
, >=
, <=
,但是>
, <
不能直接使用,因为xml会解析为标签,要使用别名。
注意 ==
and !=
不仅可以比较数值,类似于equals的功能。
可以使用的别名:gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=).
三元运算:
<span th:text="${user.sex} ? '男':'女'"></span>
三元运算符的三个部分:conditon ? then : else
-
condition:条件
-
then:条件成立的结果
-
else:不成立的结果
其中的每一个部分都可以是Thymeleaf中的任意表达式。有的时候,我们取一个值可能为空,这个时候需要做非空判断,可以使用 表达式 ?: 默认值
简写: <span th:text="${user.name} ?: '小红' "></span>
,当前面的表达式值为null时,就会使用后面的默认值。 注意:?:
之间没有空格。
循环也是非常频繁使用的需求,我们使用th:each
指令来完成:
假如有用户的集合:users在Context中。
<tr th:each="user : ${users}">
<td th:text="${user.name}">name</td>
<td th:text="${user.age}">age</td>
</tr>
-
${users}
是要遍历的集合,可以是以下类型:-
Iterable,实现了Iterable接口的类
-
Enumeration,枚举
-
Interator,迭代器
-
Map,遍历得到的是Map.Entry
-
Array,数组及其它一切符合数组结果的对象
-
在迭代的同时,我们也可以获取迭代的状态对象:
<tr th:each="user,stat : ${users}">
<td th:text="${user.name}">name</td>
<td th:text="${user.age}">age</td>
</tr>
stat对象包含以下属性:
-
index,从0开始的角标
-
count,元素的个数,从1开始
-
size,总元素个数
最后
面试题文档来啦,内容很多,485页!
由于笔记的内容太多,没办法全部展示出来,下面只截取部分内容展示。
1111道Java工程师必问面试题
MyBatis 27题 + ZooKeeper 25题 + Dubbo 30题:
Elasticsearch 24 题 +Memcached + Redis 40题:
Spring 26 题+ 微服务 27题+ Linux 45题:
Java面试题合集:
器
* Map,遍历得到的是Map.Entry
* Array,数组及其它一切符合数组结果的对象
在迭代的同时,我们也可以获取迭代的状态对象:
<tr th:each="user,stat : ${users}">
<td th:text="${user.name}">name</td>
<td th:text="${user.age}">age</td>
</tr>
stat对象包含以下属性:
-
index,从0开始的角标
-
count,元素的个数,从1开始
-
size,总元素个数
最后
面试题文档来啦,内容很多,485页!
由于笔记的内容太多,没办法全部展示出来,下面只截取部分内容展示。
1111道Java工程师必问面试题
[外链图片转存中…(img-tdmQ03sm-1630844336397)]
MyBatis 27题 + ZooKeeper 25题 + Dubbo 30题:
[外链图片转存中…(img-8VhyPDgx-1630844336398)]
Elasticsearch 24 题 +Memcached + Redis 40题:
[外链图片转存中…(img-1bYGbOLX-1630844336400)]
Spring 26 题+ 微服务 27题+ Linux 45题:
[外链图片转存中…(img-0DC3qWSH-1630844336401)]
Java面试题合集: