第一小节:主要是在html遍历出来controller层的List,这里类似于foreach.
controller层里面新建List集合的对象。这里注意实体类。
model.addAttribute("list",list); key-value的键值对。
html层
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<!--这里的u是用户自定义的,这个自己取值-->
<tr th:each="u:${list}">
<td th:text="${u.userid}"></td>
<td th:text="${u.username}"></td>
<td th:text="${u.userage}"></td>
</tr>
</table>
</body>
</html>
Controller层
@RequestMapping("show3")
public String showInfo3(Model model){
List<Users> list=new ArrayList<>();
list.add(new Users(1,"张三",20));
list.add(new Users(2,"李四",22));
list.add(new Users(3,"王五",24));
model.addAttribute("list",list);
return "index3";
}
实体类
结果:
第二小节:
each迭代 状态变量var
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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="u,var :${list}">
<td th:text="${u.userid}"></td>
<td th:text="${u.username}"></td>
<td th:text="${u.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>
controller层和第一小节一样。
结果
index当前迭代器的索引 从0开始
count 当前迭代对象的计数 从1开始
size 迭代对象的长度
even/odd 布尔值 当前循环是否为偶数/奇数 从0开始
first/last 布尔值 当前循环是否是第一条/对后一条,如果是返回true 否则 false
第三小节:通过th:each迭代Map
首先:html网页
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="maps:${map}">
<td th:text="${maps}"></td>
</tr>
</table>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<!--两次迭代-->
<tr th:each="maps:${map}">
<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>
</tr>
</table>
</body>
</html>
然后 controller层
@RequestMapping("show4")
public String showInfo4(Model model){
Map<String,Users> map=new HashMap<>();
map.put("u1",new Users(1,"张三",20));
map.put("u2",new Users(2,"李四",22));
map.put("u3",new Users(3,"王五",24));
model.addAttribute("map",map);
return "index4";
}
结果: