You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 17:05:18