1 th:each
@Controller
public class DemoController {
@RequestMapping("/showInfo3")
public String showInfo3(Model model) {
List<User> list = new ArrayList<>();
list.add(new User(1, "zhangsan", 20));
list.add(new User(2, "lisi", 22));
list.add(new User(3, "wangwu发", 25));
// 需要一个Model对象
model.addAttribute("list", list);
return "index3";
}
}
public class User {
private Integer userId;
private String username;
private Integer userAge;
public User() {
super();
}
public User(Integer userId, String username, Integer userAge) {
super();
this.userId = userId;
this.username = username;
this.userAge = userAge;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
}
index3.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Thymeleaf入门-迭代遍历</title>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="user:${list}">
<td th:text="${user.userId}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.userAge}"></td>
</tr>
</table>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>index</th>
<th>count</th>
<th>size</th>
<th>even</th>
<th>odd</th>
<th>first</th>
<th>last</th>
</tr>
<tr th:each="user,var : ${list}">
<td th:text="${user.userId}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.userAge}"></td>
<td th:text="${var.index}"></td>
<td th:text="${var.count}"></td>
<td th:text="${var.size}"></td>
<td th:text="${var.even}"></td>
<td th:text="${var.odd}"></td>
<td th:text="${var.first}"></td>
<td th:text="${var.last}"></td>
</tr>
</table>
</body>
</html>
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2 状态变量属性:
2.1 index
当前迭代器的索引,从0开始;
2.2 count
当前迭代对象的技术, 从1开始;
2.3 size
被迭代对象的大小
2.4 even/odd
表示当前循环是否是偶数或奇数
2.5 first/last
当前循环的是否是第一条/最后一条,如果是,则返回true,否则返回false。
3 th:each迭代遍历map
@Controller
public class DemoController {
@RequestMapping("/showInfo4")
public String showInfo4(Model model) {
Map<String, User> map = new HashMap<>();
map.put("u1",new User(1, "zhangsan", 20));
map.put("u2",new User(2, "lisi", 22));
map.put("u3",new User(3, "wangwu发", 25));
// 需要一个Model对象
model.addAttribute("map", map);
return "index4";
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Thymeleaf入门-迭代遍历(map)</title>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="maps:${map}">
<span th:each="entry:${maps}">
<td th:each="entry:${maps}" th:text="${entry.value.userId}"></td>
<td th:each="entry:${maps}" th:text="${entry.value.username}"></td>
<td th:each="entry:${maps}" th:text="${entry.value.userAge}"></td>
</span>
</tr>
</table>
</body>
</html>