1.entity包中建立一个对象 ---------User
package com.cc.springboot.entity;
public class User {
private String username;
// 1:女 2:男
private Integer gender;
public User() {
}
public User(String username, Integer gender) {
this.username = username;
this.gender = gender;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
}
2.controller中创建几个对象并将对象添加到map
package com.cc.springboot.controller;
import com.cc.springboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/success")
public String hello(){
return "hello cc";
}
@RequestMapping("/study")
public String study(Map<String, Object> map){
List<User> userList=new ArrayList<>();
userList.add(new User("小梦",1));
userList.add(new User("小里",2));
userList.add(new User("小岚",1));
map.put("userList",userList);
return "study";
}
}
3.模块中实现
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1px">
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>总记录数</th>
<th>偶数/奇数</th>
<th>第一个元素</th>
<th>最后一个元素</th>
</tr>
<!--
user : 第1个值,代表每次迭代出对象,名字任意取
iterStat : 第2个值,代表每次迭代器内置对象, 名字任意取, 并有如下属性:
index : 当前迭代下标 0 开始
count : 当前迭代下标 1 开始
size : 获取总记录数
current : 当前迭代出的对象
even/odd : 当前迭代是偶数还是奇数 (1开始算,返回布尔值)
first : 当前是否为第一个元素
last : 当前是否为最后一个元素
-->
<tr th:each="user,iterStat: ${userList}">
<td th:text="${iterStat.count}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.gender == 1 ? '女':'男'}"></td>
<td th:text="${iterStat.size}"></td>
<td th:text="${iterStat.even? '偶数':'奇数'}"></td>
<td th:text="${iterStat.first}"></td>
<td th:text="${iterStat.last}"></td>
</tr>
</table>
<hr/>
//迭代什么用什么
<ul>
<li th:each="user: ${userList}"th:text="${user.username}"></li>
</ul>
</body>
</html>
user : 第1个值,代表每次迭代出对象,名字任意取
iterStat : 第2个值,代表每次迭代器内置对象, 名字任意取, 并有如下属性:
index : 当前迭代下标 0 开始
count : 当前迭代下标 1 开始
size : 获取总记录数
current : 当前迭代出的对象
even/odd : 当前迭代是偶数还是奇数 (1开始算,返回布尔值)
first : 当前是否为第一个元素
last : 当前是否为最后一个元素