前言
spring-boot-starter-thymeleaf 的基础学习
使用Thymeleaf 三大理由:
- 简洁漂亮 容易理解
- 完美支持HTML5 使用浏览器直接打开页面
- 不新增标签 只需增强属性
- 五大基础语法+常用内置对象
一、maven标签
<!-- SpringBoot集成thymeleaf模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、基础语法
1、变量表达式 ${}
使用方法:直接使用th:xx = "${}"
获取对象属性 。例如
<form id="userForm">
<input id="id" name="id" th:value="${user.id}"/>
<input id="username" name="username" th:value="${user.username}"/>
<input id="password" name="password" th:value="${user.password}"/>
</form>
<div th:text="hello"></div>
<div th:text="${user.username}"></div>
2、选择变量表达式 *{}
使用方法:首先通过th:object
获取对象,然后使用th:xx = "*{}"
获取对象属性。
这种简写风格极为清爽,推荐大家在实际项目中使用。 例如:
<form id="userForm" th:object="${user}">
<input id="id" name="id" th:value="*{id}"/>
<input id="username" name="username" th:value="*{username}"/>
<input id="password" name="password" th:value="*{password}"/>
</form>
3、链接表达式 @{}
使用方法:通过链接表达式@{}
直接拿到应用路径,然后拼接静态资源路径。例如:
<script th:src="@{/webjars/jquery/jquery.js}"></script>
<link th:href="@{/webjars/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css">
4、片段表达式 ~{}
片段表达式是Thymeleaf的特色之一,细粒度可以达到标签级别,这是JSP无法做到的。
片段表达式拥有三种语法:
~{ viewName } 表示引入完整页面
~{ viewName ::selector} 表示在指定页面寻找片段 其中selector可为片段名、jquery选择器等
~{ ::selector} 表示在当前页寻找
使用方法:首先通过th:fragment
定制片段 ,然后通过th:replace
填写片段路径和片段名。例如:
<!-- /views/common/head.html-->
<head th:fragment="static">
<script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
</head>
<!-- /views/your.html -->
<div th:replace="~{common/head::static}"></div>
在实际使用中,我们往往使用更简洁的表达,去掉表达式外壳直接填写片段名。例如:
<!-- your.html common/head::static-->
<!-- static 表示 th:fragment="static" ;common/head 从template 后开始的路径,其中不包含template ,需要包含文件名 -->
<div th:replace="common/head::static"></div>
值得注意的是,使用替换路径th:replace
开头请勿添加斜杠,避免部署运行的时候出现路径报错。(因为默认拼接的路径为spring.thymeleaf.prefix = classpath:/templates/
)
消息表达式
即通常的国际化属性:#{msg}
用于获取国际化语言翻译值。例如:
<title th:text="#{user.title}"></title>
5、th
- th:text
th:text用于文本的显示,将业务的值显示到HTML的页面中 - th:if
th:if用于条件判断,对业务数据的判断,如果条件成立,则显示内容,否则不显示,具体的使用:
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymaleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:if="${score>=90}">优秀</p>
<p th:if="${score<90}">良好</p>
</body>
</html>
- th:unless
th:unless也用作条件判断,逻辑于if恰好相反,如果条件成立不显示,条件不成立显示
<!--unless-->
<p th:unless="${score>=90}">优秀</p>
<p th:unless="${score<90}">良好</p>
- th:switch th:case
- th:switch th:case两结合起来使用,用于多条件的等值判断,逻辑于java的switch case一致,当switch中的业务数据等于摸个case时,就显示该case对应的内容
<!-- java -->
@GetMapping("/switch")
public ModelAndView switchTest(){
ModelAndView modelAndView =new ModelAndView();
modelAndView.setViewName("test");
modelAndView.addObject("mess",1);
return modelAndView;
}
<!--switch-->
<div th:switch="${mess}">
<p th:case="1">优秀</p>
<p th:case="2">良好</p>
</div>
- th:action
用来指定请求的URL,相当于form表单的action属性
<form th:action="@{/hello/action}" method="get">
<input type="submit" value="提交">
</form>
- th;each
用来遍历集合
<!--each-->
<table>
<tr>
<th> 编号</th>
<th> 姓名</th>
</tr>
<tr th:each="user:${list}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
</tr>
</table>
- th:attr
给HTML的任意标签来赋值
<!--attr-->
<input th:attr="value=${attr}"><br>
<input th:value="${attr}">
- th:selected标签
给html设置选中的元素,条件成立选中,条件不成立不选中
<!--selected-->
<select>
<option
th:each="user:${list}"
th:value="${user.id}"
th:text="${user.name}"
th:selected="${user.name==name}"
></option>
</select>
- th:href
用来设置超链接的href
<!--href-->
<a th:href="${src}">百度</a>
- th:src
用来引入静态资源相当于HTML的原生的img。scrip的src标签
图片、css、js都必须放在resource下的static中
<!--value-->
<input type="text" th:value="${list}">
- th:value
用来给标签赋值
<!--value-->
<input type="text" th:value="${list}">
二、内置对象
官方文档: 附录A: Thymeleaf 3.0 基础对象 官方文档: 附录B: Thymeleaf 3.0 工具类
七大基础对象:
-
${#ctx}
上下文对象,可用于获取其它内置对象。 -
${#vars}
: 上下文变量。 -
${#locale}
:上下文区域设置。 -
${#request}
: HttpServletRequest对象。 -
${#response}
: HttpServletResponse对象。 -
${#session}
: HttpSession对象。 -
${#servletContext}
: ServletContext对象。
常用的工具类:
-
#strings
:字符串工具类 -
#lists
:List 工具类 -
#arrays
:数组工具类 -
#sets
:Set 工具类 -
#maps
:常用Map方法。 -
#objects
:一般对象类,通常用来判断非空 -
#bools
:常用的布尔方法。 -
#execInfo
:获取页面模板的处理信息。 -
#messages
:在变量表达式中获取外部消息的方法,与使用#{...}语法获取的方法相同。 -
#uris
:转义部分URL / URI的方法。 -
#conversions
:用于执行已配置的转换服务的方法。 -
#dates
:时间操作和时间格式化等。 -
#calendars
:用于更复杂时间的格式化。 -
#numbers
:格式化数字对象的方法。 -
#aggregates
:在数组或集合上创建聚合的方法。 -
#ids
:处理可能重复的id属性的方法。
三、迭代循环
想要遍历List
集合很简单,配合th:each
即可快速完成迭代。例如遍历用户列表:
<div th:each="user:${userList}">
账号:<input th:value="${user.username}"/>
密码:<input th:value="${user.password}"/>
</div>
在集合的迭代过程还可以获取状态变量,只需在变量后面指定状态变量名即可,状态变量可用于获取集合的下标/序号、总数、是否为单数/偶数行、是否为第一个/最后一个。例如:
<div th:each="user,stat:${userList}" th:class="${stat.even}?'even':'odd'">
下标:<input th:value="${stat.index}"/>
序号:<input th:value="${stat.count}"/>
账号:<input th:value="${user.username}"/>
密码:<input th:value="${user.password}"/>
</div>
如果缺省状态变量名,则迭代器会默认帮我们生成以变量名开头的状态变量xxStat
, 例如:
<div th:each="user:${userList}" th:class="${userStat.even}?'even':'odd'">
下标:<input th:value="${userStat.index}"/>
序号:<input th:value="${userStat.count}"/>
账号:<input th:value="${user.username}"/>
密码:<input th:value="${user.password}"/>
</div>
四、条件判断
条件判断通常用于动态页面的初始化,例如:
<div th:if="${userList}">
<div>的确存在..</div>
</div>
如果想取反则使用unless 例如:
<div th:unless="${userList}">
<div>不存在..</div>
</div>
五、日期格式化
使用默认的日期格式(toString方法) 并不是我们预期的格式:Mon Dec 03 23:16:50 CST 2018
<input type="text" th:value="${user.createTime}"/>
此时可以通过时间工具类#dates
来对日期进行格式化:2018-12-03 23:16:50
<input type="text" th:value="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"/>
六、内联写法
- (1)为什么要使用内联写法?·答:因为 JS无法获取服务端返回的变量。
- (2)如何使用内联表达式?答:标准格式为:
[[${xx}]]
,可以读取服务端变量,也可以调用内置对象的方法。例如获取用户变量和应用路径:
<script th:inline="javascript">
var user = [[${user}]];`
var APP_PATH = [[${#request.getContextPath()}]];
var LANG_COUNTRY = [[${#locale.getLanguage()+'_'+#locale.getCountry()}]];
</script>
七、国际化
需要了解更多关于国际化的精彩描述请前往 SpringBoot 快速实现国际化i18n 。
例如在国际化文件中编写了user.title这个键值,然后使用#{}
读取这个KEY即可获取翻译。
<title th:text="#{user.title}">用户登陆</title>
八、例
1.页面复用
创建对象
建立Controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/fizi")
public class fuZIController {
private String prefix = "system/demoChuan";
/**
*
*/
@GetMapping("/f")
public String f(ModelMap mmap)
{
sysFu fu = new sysFu();
fu.setA("AAAAAAAAAAAAA");
fu.setB("BBBBBBBBBBBBB");
fu.setC("CCCCCCCCCCCCC");
sysZI zi= new sysZI();
zi.setD("DDDDDDDDDD");
zi.setE("EEEEEEEEE");
zi.setF("FFFFFFFFFFF");
sysFuZi fuzi = new sysFuZi();
fuzi.setFu(fu);
fuzi.setZi(zi);
// mmap.put("fu",fu);
// mmap.put("zi",zi);
mmap.put("fuzi",fuzi);
return prefix+"/fu";
}
}
建立页面
fu.html
zi.html
总结
学海无涯