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

Servlet传递ProductType列表至JSP为空问题求助

问题分析与解决方案

核心问题

你遇到的问题根源在于Servlet中提前向响应输出内容,导致请求转发失效,进而使得request属性无法传递到JSP。另外JSP中存在一段多余且错误的脚本代码,也可能干扰结果。

具体修复步骤

1. 修正Servlet代码

移除Servlet中向响应输出内容的行:

// 删掉这行!它会触发HTTP响应提交,导致后续转发失效
response.getWriter().append("Served at: ").append(request.getContextPath());

一旦调用response.getWriter()并输出内容,HTTP响应的头信息就会被提交给客户端,此时服务器无法再执行请求转发操作,Servlet设置的productTypeList属性也就无法传递到JSP。

修正后的Servlet代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<ProductType> productTypes = facade.getAllProducts();
    
    // 设置请求属性
    request.setAttribute("productTypeList", productTypes);

    // 转发到JSP
    RequestDispatcher dispatcher = request.getRequestDispatcher("homePage.jsp");
    dispatcher.forward(request, response);
}

2. 清理JSP中的冗余代码

删掉JSP中这段多余的脚本:

<%
 List<ProductType> productList = (List<ProductType>)session.getAttribute("productTypeList");
 request.setAttribute("productList", productList);
%>

这段代码试图从session中获取不存在的属性(你是把列表存在request里的),得到的是null,完全没必要保留,还可能混淆属性来源。

3. 确认JSTL标签库正确引入

确保JSP页面顶部引入了JSTL核心标签库,否则<c:forEach>和<c:out>标签无法生效:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

4. 验证ProductType的getter方法

确保ProductType类中存在getProductName()方法,EL表达式${product.productName}(或${product.getProductName()})依赖这个方法获取属性值。

修正后的JSP代码示例

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<p>
    Our products    
</p>

<c:forEach items="${productTypeList}" var="product">
    <p><c:out value="${product.productName}"/></p>
</c:forEach>

原理说明

请求转发(forward)是服务器内部的操作,整个过程共享同一个HttpServletRequest对象,所以Servlet设置的request属性可以直接在JSP中访问。但如果在转发前向响应输出内容,会导致HTTP响应提前提交,转发操作失效,JSP自然无法接收到传递的列表。

内容的提问来源于stack exchange,提问作者jacob040

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:27:29