遍历map:
@GetMapping("/en") public String en(ModelMap map) { HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("aa", 2); hashMap.put("a", 1); hashMap.put("aaa", 3); hashMap.put("aaaa", 4); map.addAttribute("words",hashMap); <table border="1" cellspacing="0"> <tr> <th>单词</th> <th>频率</th> </tr> <tr th:each="item:${words}"> <td th:text="${item.key}"></td> <td th:text="${item.value}"></td> </tr> </table>
遍历list:
@RequestMapping("/list") public String list(ModelMap map) { List<User> list=new ArrayList<User>(); User user1=new User("⼤大⽜牛",12,"123456"); User user2=new User("⼩小⽜牛",6,"123563"); list.add(user1); list.add(user2); map.addAttribute("users", list); return "list"; } <table> <tr th:each="user,iterStat : ${users}"> <td th:text="${user.name}">neo</td> <td th:text="${user.age}">6</td> <td th:text="${user.pass}">213</td> <td th:text="${iterStat.index}">index</td> </tr> </table>
iterStat 称作状态变量量,属性有:
index,当前迭代对象的 index(从 0 开始计算); count,当前迭代对象的 index(从 1 开始计算); size,被迭代对象的⼤大⼩小; current,当前迭代变量量; even/odd,布尔值,当前循环是否是偶数/奇数(从 0 开始计算); first,布尔值,当前循环是否是第⼀一个; last,布尔值,当前循环是否是最后⼀一个。
特别注意的是在使用each属性时候
<tr th:each="user: ${users}">
如果没有指定状态变量,那么状态变量是隐式的,可以直接使用
状态变量的名称是遍历变量+Stat,上面默认名称即:userStat