Question

I have set Tomcat to dispose of sessions after 15 minutes of inactivity. Something like this

<session-config>
    <session-timeout>15</session-timeout>
</session-config>

Whenever a user accesses a restricted page (one that requires a user to be logged in) I check the session to see if the login process has been completed. If it has then access is granted if it hasn't then the user is redirected to the login page where he/she is prompted with a valid ID and a password. If a session times out then the user is required to log in again. And this is fine, but I would like to let the user know that he/she has to logi in again because the session has timed out.

How do I go about doing this? I found the HttpSessionListener interface and thought it might help but the sessionDestroyed method is called right before the session is invalidated so setting a parameter there is no good, as expected.

Was it helpful?

Solution

On login, set a long living cookie (1 day?) which you remove (set age to 0) during a normal logout. If you land at the login page again while the user is not logged in and the cookie is still present, then it means that the session has been expired.

<c:if test="${empty user && not empty cookie.user}">
    You were logged out because the session was expired.
</c:if>

OTHER TIPS

When you redirect the user to the login form, set a request parameter, url parameter, or cookie that indicates that the session has expired (erase the cookie once you've displayed the login form if you use a cookie). Then, when displaying the form, check for the session expired indicator and show an appropriate message.

You can check if the session has expired and/or timed out with:

if (request.getRequestedSessionId() != null
        && !request.isRequestedSessionIdValid()) {
    // Session is expired
}

Use getRequestedSessionId to distinguish between new and existing (valid/expired) sessions, and use isRequestedSessionIdValid to distinguish betwheen valid and new/expired sessions.

You can put this code in a Filter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top