简体   繁体   English

会话如何在java中工作?

[英]How does session work in java?

If I put a map in session. 如果我把地图放在会话中。 Then if I remove an object from map. 然后,如果我从地图中删除一个对象。 Will this also change the map in session or do I have to put the map in session again? 这会改变会话中的地图还是我必须再次将地图放入会话中?

            Map map = new HashMap();

        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");

        Session session = getSession();

        session.setAttribute("myMap", map);

        map.remove("1");

Yes it will update map in the session...... 是的它会在会话中更新地图......

 Map map = new HashMap();
        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");
        session.setAttribute("myMap", map);

        map.remove("1");
        Object mapw = session.getAttribute("myMap");  
        out.println(mapw);

Output 产量

{3=3, 2=2, 4=4}

The session keeps a reference to the object that you put in. If you change the content of the map, the map object reference doesn't change. 会话保留对您放入的对象的引用。如果更改了地图的内容,则地图对象引用不会更改。 It's still the same map, so the info you have in the session will also change. 它仍然是相同的地图,因此会话中的信息也会发生变化。

Like so: 像这样:

Map original_map = new HashMap();
session.setAttribute("myMap", original_map);

// Now put something into original_map...
// The _content_ of the map changes

// Later:
Map retrieved_map = session.getAttribute("myMap");

// you'll find that retreived_map == original_map.
// They're the same object, the same Map reference.
// So the retrieved_map contains all that you put into the original_map.

Your map still remains in the session. 您的地图仍保留在会话中。 However, could be a better practice to use a WeakHashMap in this case. 但是,在这种情况下使用WeakHashMap可能是更好的做法。 See the below link 请参阅以下链接

Weak Hash Map Discussion 弱哈希地图讨论

Yes, it will update. 是的,它会更新。

The reason behind this is all objects in Java are passed by reference unless of course the accessor returns a copy of the object. 这背后的原因是Java中的所有对象都是通过引用传递的,除非访问者返回对象的副本。

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

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