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

ShoppingServlet中HashMap值无法在JSP显示的技术求助

问题分析与解决方案

嘿,我来帮你搞定这个问题!你遇到的核心问题是ShoppingServlet没有将请求转发到Browse.jsp,导致直接访问Browse.jsp时,request域中根本没有存储产品信息的HashMap;另外还有个小细节可以调整,让JSTL遍历逻辑更严谨。下面一步步来解决:

1. 修复Servlet的请求转发逻辑

在ShoppingServlet的doGet方法末尾,必须添加请求转发代码,把包含产品数据的request对象传递给Browse.jsp。否则,当你直接访问Browse.jsp时,request里没有product属性,自然无法渲染产品列表。

修改后的ShoppingServlet代码:

package com.shopping;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ShoppingServlet
 */
@WebServlet("/ShoppingServlet")
public class ShoppingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		final Map<Integer,String> products= new HashMap<Integer,String>();
		products.put(1, "Motorola MotoX");
		products.put(2, "Google Pixel2");
		products.put(3, "Essential");
		products.put(4, "Iphone 6");
		request.setAttribute("product", products);
		// 关键:添加请求转发到Browse.jsp,把带数据的request传递过去
		request.getRequestDispatcher("/Browse.jsp").forward(request, response);
	}
}

2. 优化JSTL遍历Map的代码(可选但更规范)

虽然你当前的${pro.value}能正常获取值,但明确指定entry的value属性会让代码更易读;另外建议给页面设置更清晰的标题:

修改后的Browse.jsp代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>产品浏览页</title>
</head>
<body>
Click on the products to add to the Cart. <br/>
<!-- 遍历Map的entry对象,明确获取value属性 -->
<c:forEach items="${product}" var="proEntry">
    ${proEntry.value} <br/>
</c:forEach>
</body>
</html>

3. 正确的访问方式

现在你需要访问Servlet的路径(比如http://localhost:8080/你的项目名/ShoppingServlet),而不是直接访问Browse.jsp。Servlet会先处理请求、设置产品数据,再转发到Browse.jsp渲染页面,这样就能看到完整的产品列表了。

另外别忘了检查项目是否已经正确引入JSTL的jar包,如果缺失的话,JSTL标签会失效,也会导致产品列表无法显示。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:42:04