[英]Set object from JSP to servlet
I've found different solutions, even on stackOverflow, but they don't work for me. 即使在stackOverflow上,我也找到了不同的解决方案,但它们对我不起作用。
I have a JSP file that dinamically shows product
, a Java user-defined object, that has an unique ID. 我有一个JSP文件,可以动态显示product
,它是Java用户定义的对象,具有唯一的ID。 For every product, it should show all infos and a button that says "Add to cart". 对于每种产品,它应该显示所有信息以及一个显示“添加到购物车”的按钮。 How can I implement the Add to cart? 如何实施添加到购物车?
My code (JSP): 我的代码(JSP):
<% List<Product> queryResults = (ArrayList<Product>) request.getAttribute("queryResults");
for(Product product : queryResults) { %>
<table class = "qrtable">
.......
<% User currentUser = (User) session.getAttribute("currentSessionUser");
if (currentUser != null){%> <!-- user is logged -->
<tr><td colspan="2">
<form action="${pageContext.request.contextPath}/cart" method="post">
<input type="submit" value="Add to cart"/>
</form>
</td></tr>
<%}
else{
} %>
</table>
<% } %>
How do I add the product to the user cart? 如何将产品添加到用户购物车? How do I pass to the servlet the productID when the "Add to cart" button is pressed? 当按下“添加到购物车”按钮时,如何将productID传递给servlet?
I've found the solution. 我找到了解决方案。
In JSP: 在JSP中:
<% User currentUser = (User) session.getAttribute("currentSessionUser");
if (currentUser != null){%>
<tr>
<td colspan="2">
<form action="${pageContext.request.contextPath}/cart" method="POST">
<input type="hidden" name="productID" value="<%=product.getID()%>" />
<input type="submit" value="Add to cart"/>
</form>
</td>
</tr>
<%} else{%>
<tr>
<td colspan="2">Account required to buy.</td>
</tr>
<%} %>
In the servlet (method POST
): 在servlet中(方法POST
):
int productID = Integer.parseInt(request.getParameter("productID"));
HttpSession session = request.getSession(true);
User loggedUser = (User) session.getAttribute("currentSessionUser");
loggedUser.getShoppingCart().addToCart(ProductDAO.getFromDatabase(productID));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.