JSP Automatic Redirect After Session Expire/Timeout

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)


You can of course do such a thing in JavaScript by implementing a document-wide keyboard and / or mouse listener and a periodical method with a timeout.

var timeOut = 1000 * 60 * 30; // 30 minutes
var lastActivity = new Date().getTime();
var checkTimeout;
checkTimeOut = function(){
    if(new Date().getTime() > lastActivity + timeOut){
        // redirect to timeout page
    }else{
        window.setTimeout(checkTimeOut, 1000); // check once per second
    }
}

now your global listeners just have to set lastActivity to the current time on every action.

On re-reading the question, you want to use the actual session timeout from the application server. That's a tough one, because your when you send ajax requests to the server you will actually keep the session from expiring (unless there is a hard limit), so my answer might still be the best way to do it.