Search code examples
javalistsessionarraylistshopping-cart

How does Java session work when I change the object


Recently, I am trying to write shopping cart with Java session. I use List object to store products and then store in the session. When the user change the amount of the product is changed, I use the code below try to update the session. And it does work, cause when I refresh my page the number showing next to the cart icon is changed, but I really don't know how it works. Can anyone help me please ;/ ?
Here's the code when the user cancel a sprcific product, and I just remove from the list:

List<OrderProduct> orderProductList = (ArrayList<OrderProduct>)session.getAttribute("orderProductList");
for (int i = 0; i < orderProductList.size(); i ++) {
        if (orderProductList.get(i).getProduct().getId() == productID) {
            orderProductList.remove(i); 
        }
    }

My problem is I did not do this

    session.setAttribute(...)

but when I retrieve session in the jsp, the object stored in the session is changed, how does it works?


Solution

  • You can think of an HttpSession as a kind of per-user Map that the servlet container maintains for you across requests. Once you initiate a session, the container generates a unique sessionid cookie and sets it in the response and gives you an instance with which you can associate your session data. For subsequent requests, the container takes care of identifying the sessionid cookie and giving you an instance of HttpSession with the data specific to that session. You don't need to call setAttribute just like if you had

    SomeObj obj = new SomeObj();
    Map<String, SomeObj> map = HashMap();
    map.put("key", obj);
    SomeObj o2 = map.get("key");
    o2.setProperty("foo");
    

    Now you've changed the state of obj while it is still in your map. You do not need to call map.put again.