How to redirect to login page after HTTP session expired

In any application if the user is idle for some time which results logging out user from the application. This idle time is configurable and in java based application we will configure in web.xml as below.

<!-- Session Configuration -->

As per above configuration user session will be timed out if 20 mins there is no activity encountered. As soon as session is timed out we need to redirect to login page stating session is expired. We can use SessionListener to get to know when time out is happening. Session destroyed method is getting invoked by the container as soon as session expired. But the problem is that we cannot redirect from session Destroyed method since we don't have access to request object.

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionCounterListener implements HttpSessionListener {
  public void sessionCreated(HttpSessionEvent arg0) {
  public void sessionDestroyed(HttpSessionEvent arg0) {

Then how can we do the redirection after session is timed out.
 Possible Solutions:
1. We can use filter to redirect to login page after user session expired. This will be invoked after user session expired your trying to access some application url. Here there is a possibility of going to infinite loop when user click login page on first time and we may need to add certain condition to avoid this.
HttpSession session = request.getSession(false);
if(session != null && !session.isNew()) {
    chain.doFilter(request, response);
} else {
2. We can handle this from client side as well by adding meta tags in the header.This will wait till the max-time and then it will redirect to the URL we mentioned.In this approach we may end up in adding this code in all the pages.
<META HTTP-EQUIV="refresh" CONTENT="<%= session.getMaxInactiveInterval() %>; URL=redirect url" />
3. If we are using JSF we will get will ViewExpiredException and we can handle those exception and map corresponding pages that needs to be redirected in web.xml


Post a Comment

Powered by Blogger.