Thymeleaf中循环变量集合使用th:each标签。th:each属性用于跌代循环,迭代对象可以是List、Map或数组等,语法如下:
th:each="obj,iterStat:${objList}"
【测试Thymeleaf循环取数据】
程序清单:/springboot2/src/main/java/com/dwx/hello/User.java
package com.dwx.hello;
public class User {
private String userName;
private String sex;
private Integer age;
public User() {}
public User(String userName,String sex,Integer age) {
this.userName=userName;
this.sex=sex;
this.age=age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
程序清单:/springboot2/src/main/java/com/dwx/hello/ThymeleafController.java
package com.dwx.hello;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
@Controller
public class ThymeleafController {
@RequestMapping("/eachTest")
public String eachTest(WebRequest request) {
User user1=new User("jack","男",22);
User user2=new User("tom","男",20);
User user3=new User("lucy","女",18);
List<User> users=new ArrayList<User>();
users.add(user1);
users.add(user2);
users.add(user3);
request.setAttribute("users", users, WebRequest.SCOPE_REQUEST);
return "success";
}
}
程序清单:/springboot2/src/main/resources/templates/success.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>thymeleaf循环</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}"/>
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">thymeleaf循环</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-6">
<table class="table table-bordered">
<thead>
<th>序号</th>
<th>用户名</th>
<th>性别</th>
<th>年龄</th>
</thead>
<tbody>
<tr th:each="user,userStat : ${users}">
<td th:text="${userStat.index+1}">序号</td>
<td th:text="${user.userName}">用户名</td>
<td th:text="${user.sex}">性别</td>
<td th:text="${user.age}">年龄</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
启动Spring Boot项目,访问如下地址:http://localhost:8080/eachTest