介绍
教程
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
准备工作
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.yml
spring:
thymeleaf:
prefix: classpath:/templates/ #模版路径
suffix: .html #模版后缀
servlet:
content-type: text/html #设置 Content-type
encoding: UTF-8 #编码方式
mode: HTML5 #校验 H5 格式
cache: false #关闭缓存,在开发过程中可以立即看到页面修改的结果
页面
xxx.html
需要引⼊模版标签。
<html xmlns:th="http://www.thymeleaf.org">
2、通过特定的标签完成操作。
<p th:text="${name}">Hello World</p>
Thymeleaf 模版标签不同于 JSTL,Thymeleaf 模版标签是直接嵌⼊到 HTML 原⽣标签内部。
后端发送请求的方式
- 在URL的请求路径中增添参数
- 使用url+参数的方式完成数据的请求
- 使用ajax
- 使用form的方法
比较
我们对上面的几种方法进行比较
方法 | 形式 | 优势 |
---|---|---|
url路由带参数 | /student/{id} | 简单、便捷 |
url+参数 | @{href="{/student/(value=${object.x})}"} | 可以简单实现多参数的传递 |
ajax | $(‘ajax’){…} | 可以传递多种复杂的数据类型 |
form | <form action="{target}" type=""> …</form> | 可以直接将填写的数据发送 |
实现
url路由带参数
<a href="#" th:href="@{/admin/news/{id}/toUpdate(id=${news.id})}" class="ui mini teal basic button">编辑</a>
url+参数
<a href="#" th:href="@{/student/chooseClassLogic(studentId=${course.studentId},courseId=${course.courseId},startTime=${course.startTime},endTime=${course.endTime})}" class="ui positive button">添加</a>
ajax方式
$.ajax({
type : 'post',
url: "/student/changePassword",
data: {repassword, password},
success: function (res) {
alert(res.message)
$(location).attr('href', '/student/profile')
},
error: function (err) {
alert('更新用户失败')
}
})
form表单
<form action="/student/loginJudge" method="get">
<input type="text" value="" placeholder="用户名" name="name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'User name';}"/>
<input type="password" value="" placeholder="密码" name="password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'password';}"/>
<div class="remember">
<span class="checkbox1">
<label class="checkbox"><input type="checkbox" name="" checked=""><i> </i>记住我 </label>
</span>
<div class="forgot">
<h6><a href="#">忘记密码</a></h6>
</div>
<div class="clear"></div>
</div>
<input type="submit" value="Login">
</form>
常用标签
迭代
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
<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>
表单
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}"
隐藏的标签
<th:block></th:block>是Thymeleaf提供的唯一的一个Thymeleaf块级元素,其特殊性在于Thymeleaf模板引擎在处理<th:block>的时候会删掉它本身,标签本身不显示,而保留其内容
可以跟if 和foreach结合
th:text
th:text ⽤于⽂本的显示,将业务数据的值填充到 HTML 标签中。
th:if
th:if ⽤于条件判断,对业务数据的值进⾏判断,如果条件成⽴,则显示内容,否则不显示,具体的使⽤
如下所示。
@GetMapping("/if")
public ModelAndView ifTest(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test");
modelAndView.addObject("score",90);
return modelAndView;
}
<p th:if="${score>=90}">优秀</p>
<p th:if="${score<90}">良好</p>
th:unless
th:unless 也⽤作条件判断,逻辑与 th:if 恰好相反,如果条件不成⽴则显示,否则不显示。
<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 对应的内容。
<div th:switch="${studentId}">
<p th:case="1">张三</p>
<p th:case="2">李四</p>
<p th:case="3">王五</p>
</div>
th:action
⽤来指定请求的 URL,相当于 form 表单中的 action 属性
<form th:action="@{/hello/login}" method="post">
<input type="submit"/>
</form>
th:value
⽤来给标签赋值。
<input type="text" th:value="${value}"/>
th:src
⽤来引⼊静态资源,相当于 HTML 原⽣标签 img、script 的 src 属性。
图⽚,css,js,静态加载的 html 都需要放置在 resources/static ⽂件中
@GetMapping("/src")
public ModelAndView src(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test");
modelAndView.addObject("src","/1.png");
return modelAndView;
}
<img th:src="${src}"/>
如果 src 的值直接写在 HTML 中
<img th:src="@{/1.png}"/>
th:selected
⽤作给 HTML 元素设置选中,条件成⽴则选中,否则不选中。
@GetMapping("/select")
public ModelAndView select(){
List<User> list = Arrays.asList(
new User(1,"张三"),
new User(2,"李四"),
new User(3,"王五")
);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test");
modelAndView.addObject("list",list);
modelAndView.addObject("name","李四");
return modelAndView;
}
<select>
<option
th:each="user:${list}"
th:value="${user.id}"
th:text="${user.name}"
th:selected="${user.name == name}"
></option>
</select>
结合 th:each 来使⽤,⾸先遍历 list 集合动态创建 option 元素,根据每次遍历出的 user.name 与业务数据中的 name 是否相等来决定是否要选择。
设置属性
一个值
<form action="subscribe.html" th:attr="action=@{/subscribe}">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
</fieldset>
</form>
多个值
<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
@GetMapping("/attr")
public ModelAndView attr(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test");
modelAndView.addObject("attr","Spring Boot");
return modelAndView;
}
<input th:attr="value=${attr}"/><br/>
<input th:value="${attr}"/>
Thymeleaf 内置对象
dates
:⽇期格式化calendars
:⽇期操作numbers
:数字格式化strings
:字符串格式化bools
:booleanarrays
:数组内置对象lists
:List 集合内置对象sets
:Set 集合内置对象maps
:Map 集合内置对象
@GetMapping("/utility")
public ModelAndView utility(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test");
modelAndView.addObject("date",new Date());
Calendar calendar = Calendar.getInstance();
calendar.set(2020,1,1);
modelAndView.addObject("calendar",calendar);
modelAndView.addObject("number",0.06);
modelAndView.addObject("string","Spring Boot");
modelAndView.addObject("boolean",true);
modelAndView.addObject("array",Arrays.asList("张三","李四","王五"));
List<User> list = new ArrayList<>();
list.add(new User(1,"张三"));
list.add(new User(2,"李四"));
modelAndView.addObject("list",list);
Set<User> set = new HashSet<>();
set.add(new User(1,"张三"));
set.add(new User(2,"李四"));
modelAndView.addObject("set",set);
Map<Integer,User> map = new HashMap<>();
map.put(1,new User(1,"张三"));
map.put(2,new User(2,"李四"));
modelAndView.addObject("map",map);
return modelAndView;
}
date格式化:<span th:text="${#dates.format(date,'yyyy-MM-dd')}"></span><br/>
当前⽇期:<span th:text="${#dates.createToday()}"></span><br/>
当前时间:<span th:text="${#dates.createNow()}"></span><br/>
Calendar格式化:<span th:text="${#calendars.format(calendar,'yyyy-MM-dd')}">
</span><br/>
number百分⽐格式化:<span th:text="${#numbers.formatPercent(number,2,2)}"></span>
<br/>
name是否为空:<span th:text="${#strings.isEmpty(string)}"></span><br/>
name⻓度:<span th:text="${#strings.length(string)}"></span><br/>
name拼接:<span th:text="${#strings.concat('Good',string)}"></span><br/>
boolean是否为true:<span th:text="${#bools.isTrue(boolean)}"></span><br/>
arrays的⻓度:<span th:text="${#arrays.length(array)}"></span><br/>
arrays是否包含张三:<span th:text="${#arrays.contains(array,'张三')}"></span>
<br/>
List是否为空:<span th:text="${#lists.isEmpty(list)}"></span><br/>
List的⻓度:<span th:text="${#lists.size(list)}"></span><br/>