Stanley Mungai
Stanley Mungai

Reputation: 4150

Destroy all session variables without invalidating session java

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

Answers (3)

Daniel C.
Daniel C.

Reputation: 5758

It works too

Collections.list(session.getAttributeNames())
                .stream()
                .filter(s -> !s.equals("uname"))
                .forEach(session::removeAttribute);

Upvotes: 1

Matthew Meacham
Matthew Meacham

Reputation: 403

There's a few weird things going on in this code.

  • First off, you call em.nextElement() twice in the while loop, and that second call to em.nextElement() doesn't ensure that there is actually another element there.
  • Second, when doing string comparisons in Java you shouldn't use == 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

Vasyl Moskalov
Vasyl Moskalov

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

Related Questions