《Spring Boot框架入门到实践》(17)spring boot使用Thymeleaf

Thymeleaf字面量

文本字面量

用单引号' '包围的字符串为文本变量,比如:

<a th:href="@{'api/getUser?id=' + ${user.id}}">修改</a>

数字字面量

	<p>今年是<span th:text="2017">1949</span></p>
 	<p>20年后是,<span th:text="2017+20">1969</span></p>

在这里插入图片描述

Boolean字面量

true和false

	<p th:if="${isFlag == true}">
 		执行操作。。。。
 	</p>

null字面量

	<p th:if="${userlist==null}">userlist为空</p>
	<p th:if="${userlist!=null}">userlist不为空</p>

Thymeleaf字符串拼接

一种是字面量拼接:
使用' '
<span th:text="'当前是第'+${sex}+'页,共'+${sex}+'页'"></span>
另一种是更优雅的方式,使用|减少了字符串的拼接:
<span th:text="|当前是第${sex}页,共${sex}页|"></span>

Thymeleaf三元运算判断

<span th:text="${sex == '1'}?'男':'女'">未知</span>
一定要注意:字符串要加''单引号

Thymeleaf运算和关系判断

算术运算:+,-,*,/,%
关系比较:>,<,>=,<= —(gt,lt,ge,le)
相等判断:==,!= —(eq,ne)

Thymeleaf表达式基本对象

1.模板引擎提供了一组内置对象,这些内置对象可以直接在模板中使用,这些对象由#号开始引用
2.官方手册

#request

相当于HttpServletRequest对象,3.x版本使用#request,若是2.x版本使用#httpServletRequest;
需要先在Controller后台设置与一个HttpServletRequest对象。
在这里插入图片描述

<p th:text="${#request.getAttribute('name')}">name</p>

在这里插入图片描述

#session

相当于HttpSession对象,3.x版本使用#session,若是2.x版本使用#httpSession;
需要先在Controller后台设置与一个HttpSession对象。
在这里插入图片描述

<p th:text="${#session.getAttribute('user')}"></p>

在这里插入图片描述

Thymeleaf表达式功能对象

  1. 模板引擎提供的一组功能性内置对象,可以在模板中直接使用这些对象提供的功能方法。
  2. 工作中常使用的数据类型,如集合,时间,数值,可以使用Thymeleaf提供的功能性对象来处理他们。
  3. 内置功能对象前都要加#号,内置对象一般以s结尾。
  4. 官方文档
  • #dates:java.util.Date对象的实用方法,<p th:text="${#dates.format(date,'yyyy-MM-dd HH:mm:ss')}"></p>
    可以输出时间,但是要先在Controller后台中加入Date。
    model.addAttribute("date", new Date());
  • #calendars: 和dates类型,但是是java.util.Calendar对象
  • #numbers: 格式化数字对象的实用方法
  • #strings: 字符串对象的使用方法
  • #objects: 对objects操作的实用方法
  • #bools: 对布尔值求值的使用方法
  • #arrays: 数组的实用方法
  • #lists: list的实用方法
  • #sets: set的实用方法
  • maps: map的实用方法
  • #aggregates: 对数组或集合创建聚合的实用方法
    具体实用方法和其他的表达式功能对象参考上边的官方文档。
发布了50 篇原创文章 · 获赞 13 · 访问量 1871

猜你喜欢

转载自blog.csdn.net/qq_43581078/article/details/103671898
今日推荐