How to get new HttpSession after invalidating the current one in Spring controller?

When you invalidate your current session you can no longer perform actions on it, like adding attributes. What if you would like to add attributes to your session after you invalidated it? Of course in this case you will be adding the attributes to a new session, because the invalidated one is not longer accessible.

Because of this you could get an exception like this:

java.lang.IllegalStateException: setAttribute: Session [24420949034523442D2704B180E4342] 
has already been invalidated

To solve this, just call the request.getSession() method on your HttpServletRequest. This method will return the current session if there is one, otherwise it will create a new one, and returns that.

Here is a short example:

@RequestMapping(value = { "/doSomething"}, method = RequestMethod.POST)
public String doSomething(final HttpServletRequest request) {

    // ... some more code 

    HttpSession oldSession = request.getSession();

    // The session has been invalidated in the previous call so we need to get the new one.
    HttpSession newSession = request.getSession();
    newSession.setAttribute("attribute-name", "attribute-value");

    // ... some more code 

You can check the documentation for: getSession().