![](/img/trans.png)
[英]How to change the session ID without invalidating the current session in JAVA
[英]Destroy all session variables without invalidating session java
我试图删除所有会话属性而不使会话无效,因为我需要一些会话变量,例如:
session.setAttribute("fatal", "fatal error");
session.setAttribute("sgadded", "Added");
session.setAttribute("sgverified", "Something");
session.setAttribute("sgmodified", false);
session.setAttribute("glexists", false);
session.setAttribute("fatal", false);
session.setAttribute("gladded", false);
Enumeration em = session.getAttributeNames();
while(em.hasMoreElements()){
if((String)em.nextElement() != "uname"){
session.removeAttribute((String)em.nextElement());
}
}
但我收到一个错误:
java.util.NoSuchElementException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:925)
at java.util.HashMap$KeyIterator.next(HashMap.java:956)
at java.util.Collections$2.nextElement(Collections.java:3665)
有没有一种更好的方法可以一次删除所有会话变量而不使会话无效。 我现在不想调用session.invalidate()
。
确实,您收到了此消息。 您检查枚举是否至少包含一个元素,然后获取并比较一个元素,然后删除另一个元素。 最重要的是,“ ==”比较引用,而不是值。 至少你的循环身体应该看起来像
String temp=(String)em.nextElement();
if (!temp.equals("uname")) {
session.removeAttribute(temp);
}
这段代码中发生了一些奇怪的事情。
em.nextElement()
,而第二次调用em.nextElement()
并不能确保实际上存在另一个元素。 ==
或!=
,这些运算符将检查引用相等性,而您想要的是值相等性,因此您需要使用.equals
方法。 您的情况是!"uname".equals((String)em.nextElement())
。 并快速注意一下,在此字符串相等性中我们如何首先使用字符串文字。 这是在Java中执行此操作的首选方式,因此,如果em.nextElement()
恰好为null,则此代码不会引发讨厌的NullPointerException
(因为.equals方法检查null,并且如果参数为null,它返回false) 因此,您的代码最终看起来像:
while (em.hasMoreElements()) {
String element = (String)em.nextElement();
if (!"uname".equals(element))
session.removeAttribute(element);
}
也可以
Collections.list(session.getAttributeNames())
.stream()
.filter(s -> !s.equals("uname"))
.forEach(session::removeAttribute);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.