Reputation: 4150
I am attempting to remove all my session attributes without invalidating the session since I need some session variables like this:
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());
}
}
But I am getting an error:
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)
Is there a better way of removing all the session variables at once without invalidating the session. I do not want to call session.invalidate()
at this point.
Upvotes: 0
Views: 2283
Reputation: 5758
It works too
Collections.list(session.getAttributeNames())
.stream()
.filter(s -> !s.equals("uname"))
.forEach(session::removeAttribute);
Upvotes: 1
Reputation: 403
There's a few weird things going on in this code.
em.nextElement()
twice in the while loop, and that second call to em.nextElement()
doesn't ensure that there is actually another element there. ==
or !=
, those operators check for reference equality, what you want is value equality so you need to use the .equals
method. In your case, !"uname".equals((String)em.nextElement())
. And as a quick note, notice how we used the string literal first in this string equality. This is the preferred way to do it in Java so that if the em.nextElement()
happened to be null, this code won't throw a nasty NullPointerException
(because the .equals method checks for null, and if the argument is null, it returns false)Thus your code would end up looking something like:
while (em.hasMoreElements()) {
String element = (String)em.nextElement();
if (!"uname".equals(element))
session.removeAttribute(element);
}
Upvotes: 2
Reputation: 4630
Indeed you got this message. You check if the enumeration has at least one element, then you fetchs and compares one element and remove another one. On top of that "==" compares references, not values. At least your loop body should looks like
String temp=(String)em.nextElement();
if (!temp.equals("uname")) {
session.removeAttribute(temp);
}
Upvotes: 1