Spring Boot添加用户后JSP<forEach>迭代报错:无法遍历items求解
问题描述
我想要实现向数据库表中添加一条用户记录,然后在JSP页面展示该新增记录的功能。运行代码后,用户记录已成功添加,但无法在JSP页面展示,反而出现错误:javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>。
Controller代码
@Controller public class UserController { @Autowired UserRepository userRepo; @RequestMapping("/adduser") public String userform(Model m){ m.addAttribute("command", new Users()); return "adduser"; } @RequestMapping("/saveuser") public String save(@ModelAttribute("user") Users user,Model model){ userRepo.save(user); model.addAttribute("user", user); return "forward:/user"; } @RequestMapping("/user") public String user(Model model) { return "user"; } }
JSP页面代码
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" /> <c:url value="/css/main.css" var="jstlCss" /> <link href="${jstlCss}" rel="stylesheet" /> </head> <body> <div class="container"> <div class="starter-template"> <h1>Product List</h1> <table class="table table-striped table-hover table-condensed table-bordered"> <tr> <th>Id</th> <th>Color</th> <th>Gender</th> <th>Category</th> </tr> <c:forEach var="u" items="${user}"> <tr> <td>${u.userid}</td> <td>${u.username}</td> <td>${u.userphone}</td> <td>${u.useremail}</td> </tr> </c:forEach> </table> </div> </div> <script type="text/javascript" src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script> </body> </html>
解决方法
错误核心原因:<c:forEach>标签要求items属性必须是可迭代的集合类型(如List、Set、数组等),但当前传入Model的是单个Users对象,不属于可迭代类型,因此JSP无法执行循环操作。
提供两种针对性解决方式:
方式一:直接展示单个用户记录(无需循环)
如果仅需展示刚新增的单条记录,删除<c:forEach>标签,直接读取单个对象的属性即可:
修改JSP表格部分:
<tr> <td>${user.userid}</td> <td>${user.username}</td> <td>${user.userphone}</td> <td>${user.useremail}</td> </tr>
同时建议同步修改表头文字,使其与用户属性匹配:
<tr> <th>Id</th> <th>用户名</th> <th>手机号</th> <th>邮箱</th> </tr>
方式二:传入集合类型(支持多条记录展示)
如果后续需要展示多个用户,将单个用户包装成集合后传入Model:
- 修改Controller的
save方法:
@RequestMapping("/saveuser") public String save(@ModelAttribute("user") Users user,Model model){ userRepo.save(user); // 将单个用户放入List集合 List<Users> userList = new ArrayList<>(); userList.add(user); model.addAttribute("userList", userList); return "forward:/user"; }
- 可选优化:修改
/user接口,使其访问时能展示所有用户记录:
@RequestMapping("/user") public String user(Model model) { // 查询数据库中所有用户 List<Users> userList = userRepo.findAll(); model.addAttribute("userList", userList); return "user"; }
- 修改JSP的循环标签,指向集合对象:
<c:forEach var="u" items="${userList}"> <tr> <td>${u.userid}</td> <td>${u.username}</td> <td>${u.userphone}</td> <td>${u.useremail}</td> </tr> </c:forEach>
内容的提问来源于stack exchange,提问作者Salahuddin Shayan
相关产品推荐
相关产品推荐

