Spring Boot中不使用JSTL在JSP遍历列表报错的解决方法
问题解决:Spring Boot不使用JSTL遍历列表时的作用域错误
错误原因
报错bean allShoes not found within scope的核心问题是:你在Controller中仅创建了allShoes列表,但未将它存入request作用域,导致JSP无法定位到该对象。
解决步骤
1. 修改Controller,将列表存入request作用域
有两种常用实现方式:
方式一:通过HttpServletRequest存入
@RequestMapping(value="/getallitem", method=RequestMethod.GET) public String getAllItem(HttpServletRequest request) { List<ShoeData> allShoes = resource.getAllShoes(); // 将列表存入request作用域,key与JSP中引用的id一致 request.setAttribute("allShoes", allShoes); return "warehouse"; }
方式二:通过Model存入(推荐)
Model中的属性会自动同步到request作用域,写法更简洁:
@RequestMapping(value="/getallitem", method=RequestMethod.GET) public String getAllItem(Model model) { List<ShoeData> allShoes = resource.getAllShoes(); model.addAttribute("allShoes", allShoes); return "warehouse"; }
2. 调整JSP代码(可选优化)
原JSP的<jsp:useBean>写法可保留,但更推荐直接从request作用域获取列表,避免标签的潜在问题:
<% // 从request作用域取出列表并做非空判断 List<ShoeData> allShoes = (List<ShoeData>) request.getAttribute("allShoes"); if (allShoes != null && !allShoes.isEmpty()) { for (ShoeData shoe : allShoes) { %> <%= shoe.getId() %> <%= shoe.getColor() %> <% } } %>
完成上述修改后,JSP即可正确获取Controller传递的列表并完成遍历渲染。
内容的提问来源于stack exchange,提问作者Vishnu Gautam
相关产品推荐
相关产品推荐

