1

Currently I use the following filter to redirect user to index page after session is expired.

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession httpSession = httpRequest.getSession(false);
        if (httpSession != null && !httpSession.isNew()) {
            chain.doFilter(request, response);
        } else {
            httpResponse.sendRedirect(request.getServletContext().getContextPath() + PathManager.getPagePath("index"));
        }
    }

But can the session be expired when executing code in doPost/doGet methods? So on entering the filter the session is ok, but the session expires inside the servlet's doPost/doGet method.

If such a scenario can happen, what is the solution to redirect the user to the login page?

Joeblade
  • 1,735
  • 14
  • 22
StasKolodyuk
  • 4,256
  • 2
  • 32
  • 41
  • Take a look at [here](http://stackoverflow.com/questions/3201991/auto-log-off-once-the-session-expires/3203250#3203250) – Sas Dec 17 '14 at 17:02

1 Answers1

0

You can throw an exception/message to the client when session has expired and then have the client redirect the user to the login Page.

To detect if session has been expired you will need to get the session from the ServletRequest and if it is null then it is expired.

//false parameter is used to return the existing session. if expired then null is returned.
final HttpSession session  = request.getSession(false);
Rami Del Toro
  • 1,130
  • 9
  • 24
  • The problem is that I can't detect the session timeout. Of course, I can implement a SessionListener and throw some kind of RuntimeException, but it looks like a work around – StasKolodyuk Dec 17 '14 at 15:22
  • No need for a SessionListener. A session filter is sufficent to solve this issue. Note to have your session filter, to filter all incoming requests to the server. You might want to leave out the login page, as the user will not have a valid session at that point. – Rami Del Toro Dec 17 '14 at 16:34