lv0gun9
lv0gun9

Reputation: 621

Tomcat session expired handling

I have a question about session in Tomcat.

When Tomcat default session expired time is 30 min I know.

I want to show session expired message page to users.

How can I handle it?

If session expired error code is exists, please guide to me.

I googled about session expired error code, but I couldn't found it.

please teach me your way.

Upvotes: 1

Views: 4769

Answers (2)

Usman Mutawakil
Usman Mutawakil

Reputation: 5259

When your session expires the session object will return null from the request object.

if(request.getSession(false)==null){
     //Session expired or never existed
} else{
   //session is still good.
}

It is better practice to leave such testing up to a filter that can check each request but you could do it inside a JSP or inside a servlet. Putting redirection code inside a JSP tends to make it more complicated and takes your focus away from the UI. I would recommend using a filter, if not then in the servlet that routes requests to your JSP ( Your controller). If your not using a controller...

JSP Version (Not Recommended) - Inside your JSP use the following

<%
         if(request.getSession(false)==null){
            //session has expired
            response.sendRedirect("/ExpiredPage");
         } else{
           //Do what you normally would               
        }
%>

Servlet Version (Better) - Inside the servlet that calls your JSP use the following

public void doGet(HttpServletRequest request,HttpServletResponse){    
     if(request.getSession(false)==null){
        //session has expired
        response.sendRedirect("/ExpiredPage");
     } else{
       //Do what you normally would
    }
}

Filter Version (Best Choice) - Inside your filter that calls your servlet that calls your JSP use the following

public void doFilter(ServletRequest request,ServletResponse, FilterChain chain){    
     if((HttpServletRequest)request.getSession(false)==null){
        //session has expired
        ((HttpServletResponse)response).sendRedirect("/ExpiredPage");
     } else{
       //Do what you normally would
       chain.doFilter(request,response);
    }
}

Upvotes: 6

rickz
rickz

Reputation: 4464

If you are using a Servlet, then you will throw java.lang.IllegalStateException. When you try to use your session.
If you are using a JSP, then you will throw NullPointerException. When you try to access a session attribute that was lost with the old session.

Upvotes: 0

Related Questions