我正在做一个类似于网上商店的小型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);
}