When a JSP login session timeout occurs due to user’s inactivity, it is a common practice to redirect the user to a different URL, which informs the user that his JSP session has expired and he should login again to start a new session. This activity is a fundamental requirement in web programming regardless of which platform or language you are using to develop your website.
While working on a Java Server Pages (JSP) website, I googled a bit to find out an easy and straightforward way to do this session timeout redirection. And I found that are actually many ways to perform this task. But the easiest method I found involves the use of <META> tag.
So, let’s see how to redirect when a JSP session expires. Let’s learn it by example:
<META HTTP-EQUIV="refresh" CONTENT="<%= session.getMaxInactiveInterval() %>; URL=redirect url" />
Use the above given little piece of code in the header of your JSP page. The META tag will get the timeout value from the getMaxInactiveInterval() method of the session object. If the user stays on the current page for more than the timeout value without any activity, the above code will automatically redirect him to the URL specified by you.
Note 1: getMaxInactiveInterval() returns time-out value in seconds while in web.xml this value is specified in minutes. However, it does not matter!
Note 2: Also don’t forget to write the code to invalidate session on the page you are redirecting the user to. Although the session has already expired but it is still important to explicitly invalidate it to remove all traces of the previous session.
I hope this tiny tip was useful for you. Please feel free to ask in case you’ve have any doubts. Your suggestions are also, as always, welcome. Thank you for using TechWelkin!