Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发
模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎,甚至在JavaScript中也会用到模板引擎技术,Java生态下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等。
Thymeleaf 对网络环境不存在严格的要求,既能用于Web环境下,也能用于非Web环境下。在非Web环境下,他能直接显示模板上的静态数据;在Web环境下,它能像Jsp一样从后台接收数据并替换掉模板上的静态数据。它是基于HTML的,以HTML标签为载体,Thymeleaf要寄托在HTML标签下实现。
Spring Boot 集成了Thymeleaf模板技术,并且Spring Boot官方也推荐使用Thymeleaf来替代JSP技术,Thymeleaf是另外的一种模板技术,它本身并不属于Spring Boot,Spring Boot只是很好地集成这种模板技术,作为前端页面的数据展示,在过去的Java Web开发中,我们往往会选择使用Jsp去完成页面的动态渲染,但是jsp需要翻译编译运行,效率低
Thymeleaf的官方网站:
Thymeleaf
http://www.thymeleaf.org
Thymeleaf官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html




- server.port=9012
- server.servlet.context-path=/012-springboot-thymeleaf
在com.suke.springboot.web包下创建ThymeleafController类
- @Controller
- public class ThymeleafController {
-
- /*
- * http://localhost:9012/012-springboot-thymeleaf/springboot/thymeleaf/index
- * */
- @RequestMapping(value = "/springboot/thymeleaf/index")
- public String index(HttpServletRequest request, Model model) {
-
- model.addAttribute("data", "恭喜您,SpringBoot集成Thymeleaf成功");
-
- return "index";
- }
- }
注意:Springboot使用thymeleaf作为视图展示,约定将模板文件放置在src/main/resource/templates目录下,静态资源放置在src/main/resource/static目录下
HTML页面的<html>元素中加入以下属性:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>SpringBoot集成Thymeleaf</title>
- </head>
- <body>
- <!--Thymeleaf前端框架以Html为载体-->
-
- <span th:text="${data}"></span>
- <span th:text="${data}"></span>
- <p th:text="${data}"></p>
- <div th:text="${data}"></div>
- </body>
- </html>
问题:data 爆红
解决办法一:通过Alt+Enter进行自动生成的注释,补全IDEA;如果不加,IDEA将会报错cannot reslove
解决办法二:通过Alt+Enter选择Edit inspection profile setting修改
可以将error改成Warning,或者将√取消掉


注意:th:text="" 是Thymeleaf的一个属性,用于文本的显示
语法: ${...}
标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和EL中的 ${} 相同。Thymeleaf 中的变量表达式使用 ${变量名} 的方式获取Controller中model其中的数据${age}
在com.suke.springboot.model包下创建User实体类
- public class User implements Serializable {
-
- private Integer id;
-
- private String nick;
-
- private String phone;
-
- private String address;
-
- public User() {
- }
-
- public User(Integer id, String nick, String phone, String address) {
- this.id = id;
- this.nick = nick;
- this.phone = phone;
- this.address = address;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getNick() {
- return nick;
- }
-
- public void setNick(String nick) {
- this.nick = nick;
- }
-
- public String getPhone() {
- return phone;
- }
-
- public void setPhone(String phone) {
- this.phone = phone;
- }
-
- public String getAddress() {
- return address;
- }
-
- public void setAddress(String address) {
- this.address = address;
- }
- }
在ThymeleafController中添加user方法中,向model放入User对象
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/user
- * */
- @RequestMapping(value = "/thymeleaf/expression/user")
- public String user(Model model) {
- User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
- model.addAttribute("user", user);
- return "user";
- }
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>Thymeleaf标准变量表达式</title>
- </head>
- <body>
-
- <h2>Thymeleaf以HTML为载体展示数据</h2>
- <h2>展示用户信息:</h2>
- <span th:text="${user}"></span><br>
- <span th:text="${user.id}"></span><br>
- <span th:text="${user.nick}"></span><br>
- <span th:text="${user.getPhone()}"></span><br>
- <span th:text="${user.getAddress()}"></span><br>
-
- </body>
- </html>

语法:*{...}
- 选择变量表达式,也叫星号变量表达式,使用 th:object 属性来绑定对象
- 选择表达式首先使用th:object来绑定后台传来的User对象,然后使用 * 来代表这个对象,后面 {} 中的值是此对象中的属性。
- 选择变量表达式 *{...} 是另一种类似于标准变量表达式 ${...} 表示变量的方法
- 选择变量表达式在执行时是在选择的对象上求解,而${...}是在上下文的变量Model上求解,这种写法比标准变量表达式繁琐,只需要大家了解即可
- <h2>选择变量表达:又叫做*号表达式</h2>
- <h3 style="color: red">用户对象仅在div范围内有效</h3>
- <div th:object="${user}">
- <span th:text="*{id}"></span><br/>
- <span th:text="*{nick}"></span><br/>
- <span th:text="*{phone}"></span><br/>
- <span th:text="*{address}"></span><br/>
- </div>

标准变量表达式和选择变量表达式可以混合一起使用, 也可以不使用 th:object 进行对象的选择,而直接使用 *{...} 获取数据
- <h3 style="color: red">2.选择变量表达式其它用法展示数据</h3>
- <div>
- <span th:text="*{user.id}"></span><br/>
- <span th:text="*{user.nick}"></span><br/>
- <span th:text="*{user.phone}"></span><br/>
- <span th:text="*{user.address}"></span><br/>
- </div>

语法:@{...}
主要用于链接、地址的展示,可用于<script src="...">、<link href="...">、<a href="...">、<form action="...">、<img src="">等,可以在URL路径中动态获取数据
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/url
- * */
- @RequestMapping(value = "/thymeleaf/expression/url")
- public String url(Model model) {
- User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
- model.addAttribute("user", user);
- return "url";
- }
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>URL表达式</title>
- </head>
- <body>
- <!--
- 绝对路径:协议开头 盘符 /
- -->
- <a href="http://www.baidu.com">baidu</a>
- <a href="D:\IT\Java\IdeaProjects\Suke2\06-SpringBoot\012-springboot-thymeleaf\src\main\resources\templates">index1</a>
- <a href="/012-springboot-thymeleaf/springboot/thymeleaf/index">index2</a>
-
- <hr>
-
- <a th:href="@{/012-springboot-thymeleaf/thymeleaf/expression/user}">user1</a>
- <a th:href="@{/thymeleaf/expression/user}">user2</a>
- <a th:href="@{/thymeleaf/expression/user?name=zsf&age=120}">user3</a>
- <a th:href="@{'/thymeleaf/expression/user?name='+${user.nick}+'&age=120'}">user4</a>
- <a th:href="@{/thymeleaf/expression/user(name=${user.nick},age=110)}">user5</a>
-
- <hr>
-
- <!--
- 相对路径:相对当前资源所在目录 计算出来的路径
- ① http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/url
- ② http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/
- ③ http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/user
- ① http://localhost:9012/012-springboot-thymeleaf/springboot/thymeleaf/index
- ② ../../springboot/thymeleaf/index
- -->
- <a href="user">user6</a>
- <a href="./user">user7</a>
- <a href="../../springboot/thymeleaf/index">index3</a>
- <a th:href="@{./user}">user8</a>
- <a th:href="@{./user(name=${user.nick},age=130)}">user9</a>
- </body>
- </html>


定义后台控制器的路径,类似<form>标签的action属性,主要结合URL表达式,获取动态变量
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/action
- * */
- @RequestMapping(value = "/thymeleaf/expression/action")
- public String action(Model model) {
- User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
- model.addAttribute("user", user);
- return "action";
- }
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>action的使用</title>
- </head>
- <body>
- <h1>th:action的使用</h1>
-
- <div>当你需要动态获取变量数据的时候,就需要加th前缀</div>
- <form id="login" th:action="@{'/login/' + ${user.id}}"></form>
-
- <div>以下两种方式获取不到用户的id</div>
- <form id="login2" action="/login/${user.id}"></form>
- <form id="login3" action="/login"+${user.id}></form>
-
- </body>
- </html>

思考:为什么login3中${user.id} 获取不到数据?
因为我们Thymeleaf是以html为载体的,所以html不会认识${}语法。
我们请求的流程是,发送请求给服务器,服务器接收请求后,处理请求,跳转到指定的静态html页面,在服务器端,Thymeleaf模板引擎会按照它的语法,对动态数据进行处理,所以如果要是th开头,模板引擎能够识别,会在服务器端进行处理,获取数据;如果没有以th开头,那么Thymeleaf模板引擎不会处理,直接返回给客户端了。
在页面渲染之前,Thymeleaf模板引擎会作用(获得后台数据),把th开头的标签静态内容,换成动态数据,如果要是th开头,模板引擎不处理。
设置请求方法
<form id="login" th:action="@{/login}" th:method="post">......</form>
定义超链接,主要结合URL表达式,获取动态变量
用于外部资源引入,比如<script>标签的src属性,<img>标签的src属性,常与@{}表达式结合使用,在SpringBoot项目的静态资源都放到resources的static目录下
放到static路径下的内容,写路径时不需要写上static
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/src
- * */
- @RequestMapping(value = "/thymeleaf/expression/src")
- public String src(Model model) {
- User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
- model.addAttribute("user", user);
- return "src";
- }
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>src使用</title>
- </head>
- <body>
- <h1>th:src使用</h1>
-
- <script src="/static/js/jquery-1.7.2.min.js"></script>
- <script th:src="@{/js/jquery-1.7.2.min.js}"></script>
- <img th:src="@{/img/ls.jpg}">
-
- </body>
- </html>

这种方式比传统方式的好处是,在URL表达式前加/,会自动加上上下文根,避免404找不到资源的情况。
类似html标签中的id属性
<span th:id="${hello}">aaa</span>
设置名称
<input th:type="text" th:id="userName" th:name="userName">
类似html标签中的value属性,能对某元素的value属性进行赋值
<input type="hidden" id="userId" name="userId" th:value="${userId}">
该属性也是用于给HTML中某元素的某属性赋值,但该方式写法不够优雅
比如上面的例子可以写成如下形式
<input type="hidden" id="userId" name="userId" th:attr="value=${userId}" >
好处是可以给html中没有定义的属性动态的赋值
- <input type="text" id="userId" name="userId" th:value="${user.id}">
- <!--thymeleaf没有对应的th标签,所以${user.id}不能被识别-->
- <span zhangsan=${user.id}></span>
- <!--通过th:attr对自定义的属性赋值-->
- <span id="zs" th:attr="zhangsan=${user.id}"></span>
-
- <script>
- $(function () {
- alert("=====" + $("#zs").attr("zhangsan"));
- alert("=====" + document.getElementById("zs").zhangsan);
- });
- </script>
用于文本的显示,该属性显示的文本在标签体中,如果是文本框,数据会在文本框外显示,要想显示在文本框内,使用th:value
<input type="text" id="realName" name="reaName" th:text="${realName}">
用于数据对象绑定
通常用于选择变量表达式(星号表达式)
点击事件:th:οnclick="'getCollect()'"
js不能跨域(站点)访问 jsonp:跨域访问(利用script src标签的漏洞)
- <!--目前thymeleaf版本要求只能传递数字和布尔类型-->
- <a th:onclick="'fun1('+${user.id}+')'">点击我</a>
- <script type="text/javascript">
- function fun1(userId) {
- alert(userId);
- }
- </script>
设置样式
<a th:οnclick="'fun1('+${user.id}+')'" th:style="'color:red'">点击我</a>
这个属性非常常用,比如从后台传来一个对象集合那么就可以使用此属性遍历输出,它与JSTL中的<c: forEach>类似,此属性既可以循环遍历集合,也可以循环遍历数组及Map
(1)创建each.html对each(Array、List、Set、Map)集合进行遍历
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>each遍历的使用</title>
- </head>
- <body>
- <h1>th:each遍历Array数据集合</h1>
- <div th:each="array,arrayState:${userArray}">
- <span th:text="${arrayState.first}"></span>--
- <span th:text="${arrayState.last}"></span>--
- <span th:text="${arrayState.even}"></span>--
- <span th:text="${arrayState.odd}"></span>--
- <span th:text="${arrayState.index}"></span>--
- <span th:text="${arrayState.count}"></span>--
- <span th:text="${arrayState.current}"></span>-->
- <span th:text="${array.id}"></span>
- <span th:text="${array.phone}"></span>
- <span th:text="${array.nick}"></span>
- <span th:text="${array.address}"></span>
- </div>
-
- <h1>th:each遍历List集合 for each</h1>
- <div th:each="list,listState:${userList}">
- <span th:text="${listState.first}"></span>--
- <span th:text="${listState.last}"></span>--
- <span th:text="${listState.even}"></span>--
- <span th:text="${listState.odd}"></span>--
- <span th:text="${listState.index}"></span>--
- <span th:text="${listState.count}"></span>--
- <span th:text="${listState.current}"></span>-->
- <span th:text="${list.getId()}"></span>
- <span th:text="${list.getPhone()}"></span>
- <span th:text="${list.getNick()}"></span>
- <span th:text="${list.address}"></span>
- </div>
-
- <h1>th:each遍历Set集合 for each</h1>
- <div th:each="set,setState:${userSet}">
- <span th:text="${setState.index}"></span>--
- <span th:text="${setState.last}"></span>--
- <span th:text="${setState.even}"></span>--
- <span th:text="${setState.odd}"></span>--
- <span th:text="${setState.index}"></span>--
- <span th:text="${setState.count}"></span>--
- <span th:text="${setState.current}"></span>-->
- <span th:text="${set.getId()}"></span>
- <span th:text="${set.getPhone()}"></span>
- <span th:text="${set.getNick()}"></span>
- <span th:text="${set.address}"></span>
- </div>
-
- <h1>th:each遍历map集合 entrySet Map.Entry for each </h1>
- <h1>1+1=2, 2 </h1>
- <div th:each="map,mapState:${userMap}">
- <span th:text="${mapState.index}"></span>--
- <span th:text="${map.key}"></span>--
- <span th:text="${map.value}"></span>-->
- <span th:text="${map.value.getId()}"></span>
- <span th:text="${map.value.getPhone()}"></span>
- <span th:text="${map.value.getNick()}"></span>
- <span th:text="${map.value.address}"></span>
- </div>
-
- <h1>遍历复杂的集合:List -> Map -> List -> User</h1>
- <!--首先遍历List,获取Map-->
- <span th:each="myMap,listStat:${myList}">
- <!--再次遍历Map,获取List-->
- <span th:each="myKeyValue:${myMap}">
- <!--获取当前Map集合的Id-->
- <span th:text="${myKeyValue.key}"></span>--
- <span th:each="user,listSate:${myKeyValue.value}">-->
- <span th:text="${user.id}"></span>
- <span th:text="${user.phone}"></span>
- <span th:text="${user.nick}"></span>
- <span th:text="${user.address}"></span>
- <br/>
- </span>
- </span>
- </span>
-
- </body>
- </html>
(2)在ThymeleafController中添加eachArray方法,准备集合数据
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/array
- * */
- @RequestMapping(value = "thymeleaf/each/array")
- public String eachArray(Model model) {
- User[] userArray = new User[10];
- for (int i = 0; i < 10; i++) {
- User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
- userArray[i] = user;
- }
- model.addAttribute("userArray", userArray);
- return "each";
- }
(2)在ThymeleafController中添加eachList方法,准备集合数据
代码说明
① th:each="user, iterStat : ${userlist}"中的 ${userList} :是后台传过来的集合
② user:定义变量,去接收遍历${userList}集合中的一个数据
③ iterStat :${userList} 循环体的信息
④ 其中user及iterStat自己可以随便取名
⑤ interStat是循环体的信息,通过该变量可以获取如下信息
index: 当前迭代对象的index(从0开始计算)
count: 当前迭代对象的个数(从1开始计算)这两个用的较多
size: 被迭代对象的大小
current: 当前迭代变量
even/odd: 布尔值,当前循环是否是偶数/奇数(从0开始计算)
first: 布尔值,当前循环是否是第一个
last: 布尔值,当前循环是否是最后一个
注意:循环体信息interStat也可以不定义,则默认采用迭代变量加上Stat后缀,即userStat
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/list
- * */
- @RequestMapping("/thymeleaf/each/list")
- public String eachList(Model model) {
- List<User> userList = new ArrayList<User>();
- for (int i = 0; i < 10; i++) {
- User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
- userList.add(user);
- }
- model.addAttribute("userList", userList);
- return "each";
- }
(2)在ThymeleafController中添加eachSet方法,准备集合数据
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/set
- * */
- @RequestMapping("/thymeleaf/each/set")
- public String eachSet(Model model) {
- Set userSet = new HashSet();
- for (int i = 0; i < 10; i++) {
- User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
- userSet.add(user);
- }
- model.addAttribute("userSet", userSet);
- return "each";
- }
(2)在ThymeleafController中添加eachMap方法,准备集合数据
代码说明
① th:each="map:${userMap}" : 用map接收每次遍历的结果,封装为一个键值对
② map.key : 获取当前键值对中的key
③ map.value : 获取当前键值对中的value
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/map
- * */
- @RequestMapping(value = "/thymeleaf/each/map")
- public String eachMap(Model model) {
- Map<Integer, Object> userMap = new HashMap<Integer, Object>();
- for (int i = 0; i < 10; i++) {
- User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
- userMap.put(i, user);
- }
- model.addAttribute("userMap", userMap);
- return "each";
- }
(2)在ThymeleafController中添加eachAll方法,准备集合数据
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/all
- * */
- @RequestMapping(value = "/thymeleaf/each/all")
- public String eachAll(Model model) {
- //构造复杂的数据关系 List->Map->List->User
- List<Map<Integer, List<User>>> userAll = new ArrayList<Map<Integer, List<User>>>();
- for (int n = 0; n < 2; n++) {
- Map<Integer, List<User>> myMap = new HashMap<Integer, List<User>>();
- for (int m = 0; m < 2; m++) {
- List<User> myList = new ArrayList<User>();
- for (int i = 0; i < 3; i++) {
- User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
- myList.add(user);
- }
- myMap.put(m, myList);
- }
- userAll.add(myMap);
- }
- model.addAttribute("userAll", userAll);
- return "each";
- }
(1)创建condition.html页面进行条件判断
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>条件判断</title>
- </head>
- <body>
- <div style="color: red">th:if条件判断:如果满足条件,显示标签,如果不满足条件,标签就不显示</div>
- <!--th:if条件判断:如果满足条件,显示标签,如果不满足条件,标签就不显示-->
- <span th:if="${sex == 1}">
- 男:<input type="radio" name="sex" th:value="男"/>
- </span>
- <span th:if="${sex==2}">
- 女:<input type="radio" name="sex" th:value="女"/>
- </span>
- <hr>
- <span th:if="${sex == '1'}">
- 男:<input type="radio" name="sex" th:value="男"/>
- </span>
-
- <span th:unless="${sex==1}">
- 女:<input type="radio" name="sex" th:value="女"/>
- </span>
- <hr>
- <div th:switch="${sex}">
- <p th:case="1">性别:男</p>
- <p th:case="2">性别:女</p>
- <p th:case="*">性别:未知</p>
- </div>
- </body>
- </html>
注意:一旦某个case判断值为true,剩余的case则都当做false,“*”表示默认的case,前面的case都不匹配时候,执行默认的case 。
(2)在ThymeleafController中添加condition方法,通过model传递sex值为1
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/condition
- * */
- @RequestMapping(value = "/thymeleaf/condition")
- public String condition(Model model) {
- //model.addAttribute("sex",1);
- model.addAttribute("sex", "1");
- return "condition";
- }
th:inline 有三个取值类型 (text, javascript 和 none)
(1)在ThymeleafController中添加inline方法
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/inline
- * */
- @RequestMapping(value = "/thymeleaf/expression/inline")
- public String inline(Model model) {
- User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
- model.addAttribute("user", user);
- return "inline";
- }
可以让Thymeleaf表达式不依赖于html标签,直接使用内敛表达式[[表达式]]即可获取动态数据,要求在父级标签上加th:inline = “text”属性
(2)在inline.html页面上,加如下代码
- <!--内敛文本-->
-
- 标准变量表达式用户数据的展示:<br>
- <span th:text="${user.id}"></span>
- <span th:text="${user.nick}"></span>
- <span th:text="${user.phone}"></span>
- <span th:text="${user.address}"></span>
- <br>
- <!--以上代码可以使用内敛文本代替-->
- 内敛表达式 用户数据的展示:<br>
- <span th:inline="text">
- [[${user.id}]]
- [[${user.nick}]]
- [[${user.phone}]]
- [[${user.address}]]
- </span>
- <br>
注意:一般我们将<span th:inline="text">放到<body th:inline="text">标签中
在js代码中获取后台的动态数据
(2)在inline.html页面上,加如下代码
- <button type ="button" onclick="func()">抽奖</button>
-
- <script type="text/javascript" th:inline="javascript">
- function func(){
- alert("恭喜" + [[${user.nick}]] +"手机号为"+[[${user.phone}]]+"中奖!");
- }
- </script>
(3)启动程序,浏览器访问


int a=100; fun(a) fun(100)
变量:a
直接量:100
字面量:对应数据类型的合法取值,可以在html页面直接使用,不需要后台传递
(1)在ThymeleafController中添加literal方法
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/literal
- * */
- @RequestMapping(value = "/thymeleaf/expression/literal")
- public String literal(Model model) {
- User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
- model.addAttribute("user", user);
- model.addAttribute("sex", 1);
- model.addAttribute("cunPage", 8);
- model.addAttribute("totalPage", 41);
- return "literal";
- }
用单引号'...'包围的字符串为文本字面量
- <!--文本字面量-->
- <a th:href="@{'/user/' + ${user.id}}">修改用户</a>
- <!--数字字面量-->
- <p>今年是<span th:text="2017">1949</span>年</p>
- <p>20年后, 将是<span th:text="2017 + 20">1969</span>年</p>
true 和 false
- <!--boolean字面量-->
- <p th:if="${sex == true}">执行操作</p>
- <!--null字面量-->
- <p th:if="${user == null}">user为空</p>
- <p th:if="${user != null}">user不为空</p>
(2)在literal.html页面上,加如下代码
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>字面量的使用</title>
- </head>
- <body>
- <!--文本字面量-->
- <a th:href="@{'/user/' + ${user.id}}">修改用户</a>
-
- <!--数字字面量-->
- <p>今年是<span th:text="2017">1949</span>年</p>
- <p>20年后, 将是<span th:text="2017 + 20">1969</span>年</p>
-
- <!--boolean字面量-->
- <p th:if="${sex == true}">执行if操作</p>
- <p th:unless="${sex == true}">执行unless操作</p>
-
- <!--null字面量-->
- <p th:if="${user == null}">user为空</p>
- <p th:if="${user != null}">user不为空</p>
-
- <span th:text="${sex==1?'boy':'girl'}"></span>
- <span th:text="${sex eq 1?'boy':'girl'}"></span>
- <hr>
- <!--一种是字面量使用加号拼接-->
- <span th:text="'当前是第'+${cunPage}+'页,共'+${totalPage}+'页'"></span>
- <br>
- <span th:text="|当前是第${cunPage}页,共${totalPage}页|"></span>
-
- </body>
- </html>
- <!--一种是字面量使用加号拼接-->
- <span th:text="'当前是第'+${sex}+'页 ,共'+${sex}+'页'"></span>
-
- <!--另一种更优雅的方式,使用“|”减少了字符串的拼接的加号-->
- <span th:text="|当前是第${sex}页,共${sex}页|"></span>
三元运算: sex == 1? '男' : '女'
算术运算:+ , - , * , / , %
关系比较: > , < , >= , <= ( gt , lt , ge , le )
相等判断:== , != ( eq , ne )
- <span th:text="${sex == 1?'男':'女'}"></span>
- <span th:text="${sex eq 1?'男':'女'}"></span>
模板引擎提供了一组内置的对象,这些内置的对象可以直接在模板中使用,这些对象由#号开始引用,我们比较常用的内置对象
相当于httpServletRequest 对象,这是3.x版本,若是2.x版本使用 #httpServletRequest
相当于HttpSession 对象,这是3.x版本,若是2.x版本使用#httpSession
(1)在ThymeleafController中添加inlineObj方法
- /*
- * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/inlineObj
- * */
- @RequestMapping(value = "/thymeleaf/expression/inlineObj")
- public String inlineObj(Model model, HttpServletRequest request) {
- User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
- model.addAttribute("user", user);
- model.addAttribute("sex", 1);
- request.setAttribute("birthday", new Date());
- request.getSession().setAttribute("salary", 12500);
- return "inlineObj";
- }
(2)在inlineObj.html页面上,加如下代码
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>表达式基本对象的使用</title>
- </head>
- <body th:inline="text">
- <span th:text="${#request.getAttribute('birthday')}"></span>
- <span th:text="${#session.getAttribute('salary')}"></span>
- <hr>
- [[${#request.getAttribute('birthday')}]]--[[${#session.getAttribute('salary')}]]<br>
- [[${#request.getRequestURI()}]]--[[${#request.getContextPath()}]]
- <hr>
-
- <span th:text="${#strings.substring(user.getPhone(),1,8)}"></span>
- <span th:text="${#dates.format(#request.getAttribute('birthday'),'yyyy-MM-dd HH:mm:ss')}"></span>
- <br>
- <span th:text="${#numbers.formatDecimal(#session.getAttribute('salary'),10,10)}"></span>
- <br>
- <span th:text="${#numbers.formatDecimal(#session.getAttribute('salary'),2,3)}"></span>
-
- </body>
- </html>
模板引擎提供的一组功能性内置对象,可以在模板中直接使用这些对象提供的功能方法
工作中常使用的数据类型,如集合,时间,数值,可以使用Thymeleaf的提供的功能性对象来处理它们。
内置功能对象前都需要加#号,内置对象一般都以s结尾
官方手册:Tutorial: Using Thymeleaf
http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
#dates: java.util.Date对象的实用方法,<span th:text="${#dates.format(curDate, 'yyyy-MM-dd HH:mm:ss')}"></span>
#calendars: 和dates类似, 但是 java.util.Calendar 对象;
#numbers: 格式化数字对象的实用方法;
#strings: 字符串对象的实用方法: contains, startsWith, prepending/appending等;
#objects: 对objects操作的实用方法;
#bools: 对布尔值求值的实用方法;
#arrays: 数组的实用方法;
#lists: list的实用方法,比如<span th:text="${#lists.size(datas)}"></span>
#sets: set的实用方法;
#maps: map的实用方法;
#aggregates: 对数组或集合创建聚合的实用方法;