[英]How does session work in java?
如果我把地圖放在會話中。 然后,如果我從地圖中刪除一個對象。 這會改變會話中的地圖還是我必須再次將地圖放入會話中?
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");
是的它會在會話中更新地圖......
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);
產量
{3=3, 2=2, 4=4}
會話保留對您放入的對象的引用。如果更改了地圖的內容,則地圖對象引用不會更改。 它仍然是相同的地圖,因此會話中的信息也會發生變化。
像這樣:
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.
您的地圖仍保留在會話中。 但是,在這種情況下使用WeakHashMap可能是更好的做法。 請參閱以下鏈接
是的,它會更新。
這背后的原因是Java中的所有對象都是通過引用傳遞的,除非訪問者返回對象的副本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.