Java – Display message after session timeout

javasession

I am setting the session timeout in web.xml of application as

<session-config>
    <session-timeout> 1 </session-timeout>
</session-config> 

So now after the session expires if user tries to do some operation I want to show a message saying “session expired relogin”. How to do so in Java?

Best Answer

I found a number of solutions to this problem by entering the following in to Google:

"Java session expired message"

Here's one solution copied from the web:

Create a SessionTimeout.java filter and assign the filter a /app/*.jsp pattern in the web.xml file. This will cause my filter to be called on every request (ie When the user hits the button after 30 minutes). Exclude the main page (login/login.jsp) from this filter so a new session can be established. The code for the filter is very simple:

public class SessionTimeout implements Filter{
   RequestDispatcher rd = null;

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
   throws IOException, ServletException{
      HttpServletRequest req = (HttpServletRequest)request;
      HttpSession session = req.getSession();

   // New Session so forward to login.jsp
   if (session.isNew()){
     requestDispatcher = request.getRequestDispatcher("/login/login.jsp");
     requestDispatcher.forward(request, response);
  }

  // Not a new session so continue to the requested resource
   else{
      filterChain.doFilter(request, response);
  }
}

public void init(filterConfig arg) throws ServletException{}
public void destroy(){}

}