Search code examples
javasessionhttpsession

How to check if a session is invalid


How to check if a session is invalid or not? There is no method in the API.

Is it the same as isNew()? And what is the difference if not?


Solution

  • If you want to know whether it valid based on a request:

    request.isRequestedSessionIdValid()
    
      or
    
    HttpSession sess = request.getSession(false);
    if (sess != null) {
       // it's valid
    }
    

    If you have stored a reference to the session and need to validate I would

    try {
      long sd = session.getCreationTime();
    } catch (IllegalStateException ise) {
      // it's invalid
    }