Ok, so I'm trying to add products to cart by introducing them in an ArrayList in servlet but the jstl "forEach" does not know how to iterate over it so im guessing im not doing a good job (I'm new to jsp-servlet)
I can add products but the previous ones are overwritten, so now I'm tryin to store them into an ArrayList which i store in a session variable from where i access it when i need to add another product.( i dont actually know if that's a good way to do it, but it seemed ok to me). Also this is the first question that i post so I'm sorry if i did a bad job.
@WebServlet(name = "mycart")
public class mycart extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
Product product = new Product();
ShoppingCart items = new ShoppingCart();
items.copyItems((ArrayList<Product>) session.getAttribute("sessionProducts"));
session.removeAttribute("sessionProducts");
String code = request.getParameter("code");
if(items.equals(null)){
items.addProduct(product.productById(code));
request.setAttribute("listofproducts", items.getCart());
session.setAttribute("sessionProducts", items.getCart());
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
else{
session.setAttribute("sessionProducts", product.productById(code));
request.setAttribute("listofproducts", product.productById(code));
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
<table border="1px solid">
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Code</th>
<th>Price</th>
</tr>
<tr>
<c:forEach items="${listofproducts}" var="list">
<tr>
<td>${list.name}</td>
<td>${list.quantity}</td>
<td>${list.code}</td>
<td>${list.price}</td>
</tr>
</c:forEach>
</tr>
</table>
public class ShoppingCart {
public ArrayList<Product> items = new ArrayList<>();
public void addProduct(Product product){
this.items.add(product);
}
public ArrayList<Product> getCart(){
return this.items;
}
public void copyItems(ArrayList<Product> items){
this.items = items;
}
}
All products have a "Add to cart" button, so i just want that when i click that button every product to be added to cart.