0

我正在做一个类似于网上商店的小型JEE5应用程序,我需要展示商店产品,在代码中可以更清楚地看到:

<c:forEach var="product" items="${productsBean.products}">
  <div class ="product">
   <table>
    <td>
     <c:out value="${product.id}"/>
    </td>
    <td>
     <c:out value="${product.name}"/>
    </td>
    <td>
     <c:out value="${product.price}"/>
    </td>
    <td>
     <c:out value="${product.description}"/> 
    </td>
    <td>
    <form method="post" action="/servlets-war/AddToCart">
     <input type="hidden" name="id" value="${product.id}"></input>
     <input type="submit" value="add to cart"/>    
    </form>
   </td>
  </table>
 </div>
</c:forEach>

问题是表单中的隐藏输入值在提交表单时返回 null 而不是 ${product.id}。

相关的 servlet 代码如下:

protected void processRequest(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

    ShoppingCart shoppingCart = (ShoppingCart)request.getSession()
            .getAttribute("shoppingCart");

    if(shoppingCart == null){
    shoppingCart = new ShoppingCart();
    }

    ProductsBean store =(ProductsBean) request
            .getSession().getAttribute("productsBean");

    int id = Integer.parseInt((String)request.getAttribute("id"));

    Product temp = store.getProduct(id);

    shoppingCart.getProducts().add(temp);

    request.getSession().setAttribute("shoppingCart", shoppingCart);

    this.getServletContext().getRequestDispatcher("/shop.jsp")
            .forward(request, response);
}
4

1 回答 1

0

您正在检索id作为请求属性。

int id = Integer.parseInt((String)request.getAttribute("id"));

表单输入作为请求参数发送到 servlet。适当地更改您的代码:

int id = Integer.parseInt((String)request.getParameter("id"));
于 2013-06-16T02:11:41.143 回答