一整合list
- 创建Controller
package com.synda.Controller;
/**
* thymeleaf对集合的操作
*/
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.synda.entity.User;
@Controller
public class ListController {
@RequestMapping("/list")
public String getListInfo(Model model) {
List<User> list = new ArrayList<User>();
list.add(new User("1", "张三", "20"));
list.add(new User("2", "里斯", "23"));
list.add(new User("3", "王五", "28"));
model.addAttribute("list", list);
return "listIndex";
}
}
- 创建listIndex.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</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.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>
<table border="1">
<tr>
<th>index</th>
<th>count</th>
<th>even</th>
<th>odd</th>
<th>size</th>
<th>first</th>
<th>last</th>
</tr>
<!-- index为集合状态 -->
<tr th:each="user,index:${list}">
<!-- 当前迭代对象的索引,从零开始 -->
<td th:text="${index.index}"></td>
<!-- 当前迭代对象的数量 -->
<td th:text="${index.count}"></td>
<!-- 当前循环次数为基数还是偶数 -->
<td th:text="${index.even}"></td>
<td th:text="${index.odd}"></td>
<!-- 迭代对象的数量 -->
<td th:text="${index.size}"></td>
<!-- 当前是否为第一次循环 -->
<td th:text="${index.first}"></td>
<!-- 当前是否为第二次循环 -->
<td th:text="${index.last}"></td>
</tr>
</table>
</body>
</html>
- 执行结果
二、整合map
- 创建Controller
package com.synda.Controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.synda.entity.User;
@Controller
public class mapController {
@RequestMapping("/map")
public String getMapInfo( Model model) {
Map<String, User> map = new HashMap<String, User>();
map.put("u1", new User("1", "张三", "20"));
map.put("u2", new User("2", "里斯", "21"));
map.put("u3", new User("3", "王五", "22"));
model.addAttribute("map", map);
return "mapIndex";
}
}
- 创建mapIndex.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<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.id}"></td>
<td th:each="entry:${maps}" th:text="${entry.value.name}"></td>
<td th:each="entry:${maps}" th:text="${entry.value.age}"></td>
</tr>
</table>
</body>
</html>
3.执行结果
版权声明:本文为hzy3344520原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。