Thymeleaf知识点总结

一、语法详解
首先,创建HTML页面,在html页面中定义xmlns属性

<html lang="en" xmlns:th="http://www.thymeleaf.org">

th:text
最简单的一种,替换标签中的文本内容

<span th:text="Hello"></span>

<span th:text="${msg}">aaaaaaaaaaa</span>

th:value
与th:text类似,它是用来替换表单中的值。

<p>
  <
input type="text" th:value="${msg}"/>
</p>

th:href(th:src)
表达式以@开头:@{ 访问路径 }

<!-- thymeleaf URL表达式 -->
<div>
  <a th:href="@{/user/showInfo}">link</a>
</div>

条件判断
  1. th:if

<p>
  <span th:if="${sex==1}">
    男
  </span>
  <span th:if="${sex==0}">
    女
  </span>
</p>

  2.th:switch

<p>
  <div th:switch="${sex}">
    <span th:case="1"></span>
    <span th:case="0"></span>
  </div>
</p>

th:each
迭代遍历,a代表每个集合中便利到的对象,s代表对象的状态,:之后是要遍历的集合。

<div>
  <div th:each="a,s : ${list}">
    <span th:text="${a}"></span>,
    <span th:text="${#strings.concat('index--',s.index)}"></span>,
    <span th:text="${#strings.concat('count--',s.count)}"></span>,
    <span th:text="${#strings.concat('first--',s.first)}"></span>,
    <span th:text="${#strings.concat('last--',s.last)}"></span>,
    <span th:text="${#strings.concat('current--',s.current)}"></span>,
    <span th:text="${#strings.concat('odd--',s.odd)}"></span>,
    <span th:text="${#strings.concat('size--',s.size)}"></span>,
  </div>
</div>

二、Thymeleaf内置对象
Thymeleaf内置对象的语法${# }内部必须以 # 开头

strings
判断字符串是否为空,strings.isEmpty()

<p>
  <span th:text="${#strings.isEmpty(msg)}"></span>
</p>

判断是否包含某个字符串,strings.contains(msg,‘Th’)

<p>
  <span th:text="${#strings.contains(msg,'Th')}"></span>
</p>

判断是否字符串是否以指定字符串开头/结尾的 区分大小写

<p>
  <span th:text="${#strings.startsWith(msg,'Hello')}"></span>
  <span th:text="${#strings.endsWith(msg,'Hello')}"></span>
</p>

截取字符串,substring()

<p>
  <span th:text="${#strings.substring(msg,1)}"></span>
</p>
<p>
  <span th:text="${#strings.substring(msg,6,9)}"></span>
</p>

dates

  1.格式化日期

<p>
  <span th:text="${#dates.format(date,'yyyy-MM-dd HH:mm:ss')}"></span>
</p>

  2.获取年月日

<p>
  <span th:text="${#dates.year(date)}"></span>
</p>
<p>
  <span th:text="${#dates.month(date)}"></span>
</p>
<p>
  <span th:text="${#dates.day(date)}"></span>
</p>

Web作用域对象
  1.request

<span th:text="${#httpServletRequest.getAttribute('request')}"></span><br/>

  2.session

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

   3.application

<span th:text="${#servletContext.getAttribute('application')}"></span>

Thymeleaf 在 javascript 中的使用
我们可以在js代码内部直接获取返回的值

<script th:inline="javascript">
var request = [[${#servletContext.getAttribute('application')}]];
alert(request);
</script>
原文地址:https://www.cnblogs.com/chenglaoshi/p/13391942.html