JSP Automatic Redirect After Session Expire/Timeout

user473445 picture user473445 · Oct 12, 2010 · Viewed 33.3k times · Source

Is there any way to detect session timeout without (user interaction)*, and redirect it to some page; i.e. if there is no activity on page @ specific duration; server detects it and redirect it automatically on some other.

By user user interaction I mean; there is a way to detect session timeout when user clicks on something, then some request goes to server and then server checks if current user session is expired or not.

What I need here is that we don't inform server anything (or we don't perform any action), but when session expires server detects it automatically and perform required action.

Thanks, Raza

Answer

Jimmy Leo picture Jimmy Leo · Sep 17, 2011

If the requirement is to just redirect to the login page (or any other page) after the session timed out, this is how I've tried to implement it:

Include the following scriptlet to ALL pages that requires login

<%
int timeout = session.getMaxInactiveInterval();
response.setHeader("Refresh", timeout + "; URL = login.jsp");
%>

This way any page that requires login will refresh/redirect to login.jsp (change it your desired url) after the session timed out

OR (to avoid missing any pages)

You can actually write it in a separate file (timedoutRedirect.jsp) and include it as a header to all pages that requires login using "JSP property group" (in web.xml)

<jsp-property-group>
        <display-name>all jsp</display-name>
        <url-pattern>/users/*</url-pattern>
        <include-prelude>/timedoutRedirect.jsp</include-prelude>           
</jsp-property-group>

(you may have to adjust the prelude url to your project specifications)