In my home page, I have the following code:
<h2>Item 1</h2>
<p>100.00</p>
<form action= "addtoCart" method="POST">
<input type="hidden" name="item1" value="1"/>
<button value="add">Add this to cart</button>
</form>
<h2>Item 2</h2>
<p>50.00</p>
<form action= "addtoCart" method="POST">
<input type="hidden" name="item2" value="2"/>
<button type="submit" value="add">Add this to cart</button>
</form>
For my servlet, I have the following:
HttpSession session = request.getSession();
ArrayList<Product> cart = new ArrayList<Product>();
session.setAttribute("InCart", cart);
Product a = new Product("Item 1", 200);
Product b = new Product("Item 2", 50);
if ((request.getParameter("item1")) != null) {
cart.add(a);
out.println(cart.toString());
} else if ((request.getParameter("item2")) != null) {
cart.add(b);
out.print(cart.toString());
}
In my code, if I click the Add to Cart button for item 1, I get redirected to my servlet and it successfully displays the list (which currently has product a). Now if I go back to my home page and click the Add to Cart button for item 2, the servlet does not maintain the contents, it only ends up printing the list which only has product b.
My desired outcome would be that the list prints out product a product b (since I clicked the button for item 1 and item 2). I am almost sure that it has to do with properly handling my sessions, but I can't figure out what I am doing wrong.
CodePudding user response:
Welcome to stackoverflow.
HttpSession session = request.getSession();
ArrayList<Product> cart = new ArrayList<Product>();
session.setAttribute("InCart", cart);
You are always creating a new cart object and adding it to your HttpSession. Overwriting any existing ArrayList that was created on previous requests.
It might be better to check to see if the ArrayList called "InCart" exists in the session first and if not, then create it and add it to the HttpSession.
HttpSession session = request.getSession();
List<Product> cart = session.getAttribute("InCart");
if (cart == null) {
cart = new ArrayList<Product>();
session.setAttribute("InCart", cart);
}