1. 添加thymeleaf的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
注意:在maven repo里面搜索的话第一个thymeleaf是thymeleaf官方的往下面的spring-boot-starter-thymeleaf这个才是springboot整合需要的
2. 配置thymeleaf视图解析
这里采用yml方式
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: utf-8
- 一般来说resources文件夹下的templates文件夹放置html页面,static文件夹下放置css、js等静态资源
- 如果需要直接访问html资源,可以直接将html放到static文件夹下,即可直接访问。
3. 在HTML中添加thymeleaf标签
后台的controller使用model向前端返回数据
@GetMapping("/index")
public String index(Model model){
List<User> list = userService.getUserList();
model.addAttribute("userlist",list);
return "index";
}
前端HTML使用标签获取数据
我这里是在表格中使用 th:each 标签遍历上面我controller中返回的List集合
<tbody>
<tr th:each = "user,status:${userlist}">
<td th:text="${status.index}"></td>
<td th:text="${status.count}"></td>
<td th:text="${user.getUId()}"></td>
<td th:text="${user.UName}"></td>
<td th:text="${user.UPsw}"></td>
<td th:text="${user.USex} == 1?'男':'女'"></td>
<td th:text="${user.UCollege}"></td>
<td th:text="${user.UMajor}"></td>
<td th:text="${user.UGrade}"></td>
</tr>
</tbody>
th:each = “use,status:${userlist}”:user是给遍历到的集合取别名,status是为了给集合中的每条数据进行排序,index从0开始,count从1开始
thymeleaf常见标签
- th:text :是用来获取数据:如上述
- th:each:进行遍历:如上述
- th:if & th:unless:条件判断
<p th:if="${flag == true}" th:text="if判断成立执行"></p>
<p th:unless="${flag != true}" th:text="unless判断不成立执行"></p>
- th:style:给当前元素添加样式
- 三元运算
<td th:text="${user.USex} == 1?'男':'女'"></td>
- 时间格式化:这里的time是LocalDateTime
<p th:text="${#temporals.format(time,'yyyy-MM-dd HH:mm:ss')}"></p>