SpringBoot-Thymeleaf语法详解
-字符串日期转换
-条件判断
-迭代遍历
-获取作用域对象中的数据
-URL表达式
Thymeleaf语法详解-字符串操作
th:text的作用是什么?
答:在页面中输出值
th:value的作用是什么?
答:将一个值放到input标签的value中
什么是Thymeleaf的内置对象?
Thymeleaf的内置对象是指在Thymeleaf页面系统中已经默认内置的Java对象,
这些对象不需要开发人员显式声明即可使用。
在Thymeleaf页面中,可以通过存取Thylemeaf内置对象实现与Thymeleaf页面和Servlet环境的相互访问。
每个内部对象均有对应所属的ServletAPI类型。
内置对象的语法是什么?
${#内置对象.方法名(key)}
注意:1.内置对象一定要使用#
2.大部分的内置对象都是以s结尾
Thymeleaf语法详解-日期转换操作
在Thymeleaf中使用哪个内置对象转换日期?
答:Thymeleaf中使用#dates内置对象转换日期
常见的处理日期函数有哪些?
以当前浏览器为标准格式输出当前时间
<span th:text="${#dates.format(date)}"></span>
指定格式输出当前时间
<span th:text="${#dates.format(date,'yyyy/MM/dd')}"></span>
<span th:text="${#dates.year(date)}"></span>
<span th:text="${#dates.month(date)}"></span>
<span th:text="${#dates.day(date)}"></span>
Thymeleaf语法详解-条件判断
th:if的作用是什么?
答:th:if用于条件判断,作用与jdk中if..else..if相同
<span th:if="${sex} == '男'">
性别:男
</span>
<span th:if="${sex} == '女'">
性别:女
</span>
th:switch的作用是什么?
答:th:swith用于多条件判断,作用与jdk中switch..case相同
<div th:switch="${id}">
<span th:case="1">1</span>
<span th:case="2">2</span>
<span th:case="3">3</span>
</div>
Thymeleaf语法详解-迭代遍历
th:each的作用是什么?
答:th:each作用是迭代遍历,与jdk中foreach作用类似。
<table border="1" align="center" width="50%">
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</tr>
<tr th:each="u,var : ${list}">
<th th:text="${u.id}"></th>
<th th:text="${u.name}"></th>
<th th:text="${u.age}"></th>
</tr>
</table>
@RequestMapping("/show3")
public String showInfo3(Model model){
List<User> list = new ArrayList<>();
list.add(new User(1,"张三",12));
list.add(new User(2,"李四",22));
list.add(new User(3,"王五",32));
model.addAttribute("list",list);
return "index3";
}
th:each中可以获取哪些状态变量
index:当前迭代器索引,从0开始
count:当前迭代器计数,从1开始
size:被迭代对象的长度
even/odd:布尔值,当前循环是否是奇数/偶数,从0开始
first/last:,布尔值,当前循环是否是第一条/最后一条
<tr th:each="u,var : ${list}">
<th th:text="${u.id}"></th>
<th th:text="${u.name}"></th>
<th th:text="${u.age}"></th>
<!--当前迭代器索引,从0开始-->
<th th:text="${var.index}"></th>
<!--当前迭代器计数。从1开始-->
<th th:text="${var.count}"></th>
<!--被迭代对象的长度-->
<th th:text="${var.size}"></th>
<th th:text="${var.even}"></th>
<th th:text="${var.odd}"></th>
<!--是否是第一条-->
<th th:text="${var.first}"></th>
<th th:text="${var.last}"></th>
</tr>
Thymeleaf语法详解-获取作用域对象中的数据
在Thymeleaf中如何获取HttpServletRequest对象中的值?
Request:<span th:text="${#httpServletRequest.getAttribute('req')}">
在Thymeleaf中如何获取HttpSession中的值?
Session:<span th:text="${session.session}">
在Thymeleaf中如何获取ServletContext中的值?
Application:<span th:text="${application.app}"></span>
Thymeleaf语法详解-URL表达式
URL表达式的语法是什么?
基本语法:@{}
在URL表达式中可以给定几种URL格式?
在URL表达式中可以给顶两种URL格式,一种是绝对路径,一种是相对路径,相对路径又可以分为相对于当前项目的根和当前服务器的根两种情况。
绝对路径
<a th:href="@{http://www.baidu.com}">绝对路径</a>
相对路径1(当前项目的根)
<a th:href="@{/show}">相对路径<a>
相对路径2(当前服务器)
<a th:href="@{~/project/rsourcesname}">相对于服务器的根<a/>
如何在URL表达式中传递参数?
直接在请求后面使用括号,将参数放到括号里面进行传输,如果有多个参数,可以使用逗号进行分割
<a th:href="@{/show(id=1,name='张三')}">相对路径--传参<a>
如何在URL表达式中通过RESTful风格传递参数?
<a th:href="@{/path/{id}/show(id=1,name='张三')}">相对路径--传参--restful<a>