Search code examples
javasessionhttpsession

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.


Solution

  • 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);
    }