简体   繁体   English

更改对象时Java会话如何工作

[英]How does Java session work when I change the object

Recently, I am trying to write shopping cart with Java session. 最近,我试图用Java会话编写购物车。 I use List object to store products and then store in the session. 我使用List对象存储产品,然后存储在会话中。 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? 但是当我在jsp中检索会话时,存储在会话中的对象被更改了,它是如何工作的?

You can think of an HttpSession as a kind of per-user Map that the servlet container maintains for you across requests. 您可以将HttpSession视为一种每个用户的Map ,该Servlet容器会在整个请求中为您维护。 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. 启动会话后,容器会生成一个唯一的sessionid cookie,并在响应中进行设置,并为您提供一个实例,您可以将其与会话数据相关联。 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. 对于后续请求,容器负责标识sessionid cookie,并为您提供HttpSession实例以及该会话特定的数据。 You don't need to call setAttribute just like if you had 您不需要像调用setAttribute一样调用setAttribute

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. 现在,您已经更改了obj仍在地图中的状态。 You do not need to call map.put again. 您无需再次调用map.put。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM