springboot整合thymeleaf

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常见标签

  1. th:text :是用来获取数据:如上述
  2. th:each:进行遍历:如上述
  3. th:if & th:unless:条件判断
<p th:if="${flag == true}" th:text="if判断成立执行"></p>
<p th:unless="${flag != true}" th:text="unless判断不成立执行"></p>
  1. th:style:给当前元素添加样式
  2. 三元运算
<td th:text="${user.USex} == 1?'男':'女'"></td>
  1. 时间格式化:这里的time是LocalDateTime
<p th:text="${#temporals.format(time,'yyyy-MM-dd HH:mm:ss')}"></p>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值