1.概述
在上篇笔记中我们学习了如何通过JPA对数据库进行操作,那接下来就是如何将数据显示到前台了,Spring Boot框架默认不支持JSP,这使得我们要使用HTML页面,为了完成页面动态化,Spring Boot很好的支持了模板引擎Thymeleaf。
2.目标
通过本次学习,能够完成在Spring Boot框架下Thymeleaf的配置与使用。
3.详细步骤
(1)配置
在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在application.properties文件中添加配置项
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
(2)使用
要在HTML上使用Thymeleaf首先需要引入
<html xmlns:th="http://www.thymeleaf.org">
语法
1.变量
${} 其作用是获取后台返回的变量值
th:text的作用是设置标签文本值
<p th:text="${user.name}"></p>
2.URL
@{} 其作用是用来获取URL对应的资源
th:href 用来设置资源地址
<link rel="stylesheet" th:href="@{css/bootstrap.css}"/>
3.字符串替换
这个基本上与变量一致不做过多赘述
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
这种是拼接字符串的形式,还有另一个更简单的形式
<span th:text="|Welcome to our application, ${user.name}!|">
4.运算符
在表达式中可以使用各类算术运算符,例如+, -, *, /, %,以及各种逻辑运算符>, <, <=,>=,==,!=,其中<,>要是用html转义符
th:if="${count} < 1"
th:if="${count} > 1"
5.for循环
th:each的使用
<div th:each="user:${list}" class="col-sm-6 col-sm-offset-2" style="margin-bottom: 10px">
<span th:text="${user.name}"></span>
</div>
6.if/unless
th:if的标签表达式结果为真就显示这部分标签,否则不显示;th:unless与th;if相反结果为真就不显示,结果为假就显示
<div class="col-md-2" th:title="${url.description}" th:if="${lstat.index}%4 == 0" >
<strong th:text="${url.link_name}">这个冬天不太冷</strong>
</div>
<div class="col-md-2 col-md-offset-1" th:title="${url.description}" th:unless="${lstat.index}%4==0">
<strong th:text="${url.link_name}">这个冬天不太冷</strong>
</div>
7.switch
th:switch与th:case搭配使用,*代表default,其使用基本与java语言使用无异
<div th:switch="${role}">
<p th:case="'admin'">admin</p>
<p th:case="'manager'">manager</p>
<p th:case="*">default</p>
</div>
8.th:onclick
其作用是当触发点击事件时,运行表达式
<li id="more" style="width: 100%;display: inline-table" th:onclick="showMoreAttented(page++)" >
<a style="width: 100%;display: inline-table">更多关注</a>
</li>
9.session
可以通过session对象,直接访问session中的attribution获取值
<p class="text-center" th:text="${session.user.name}"></p>
10.fragment与include
可以通过fragment与include完成前端页面模板的引用
定义模板
<div th:fragment="nav" xmlns:th="http://www.w3.org/1999/xhtml">
•••此处省略
</div>
使用模板
<div th:include="nav :: nav"></div>