Saturday, May 11, 2013

How to redirect to the login/index page after the session timeout in JSP

Hi Guys, as the title says...how do you manage your session timeout effectively and redirecting the user to the login page back in a JSP..?
I have seen many examples, work-a-rounds over the Google and I thought of sharing a good technique where you can achieve the goal in a few steps !


Step 1

specify the session timeout interval (in minutes) in the web.xml as follows:

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

 Step 2

Next step is to call the session timeout and the URL or the page that you need to redirect once the timeout occurred in your JSP file. 
ex:
<%
int timeout = session.getMaxInactiveInterval();
response.setHeader("Refresh", timeout + "; URL=index.jsperr=2");
%>
In the above example, when the timeout happens, I am redirecting to the "index.jsp" file with the error code as "2" which I handled inside the application. Therefore you can specify your URL instead of that.
Likewise, you can apply the same code segment every where that you need to specify a session timeout functionality in your application.

That's all folks. Hope it will help you get an idea on "how to handle session timeout and redirect to the login/index page".