Servlet Filter - Redirect Session Timeout

Use the following to code to override the doFilter method, which redirects to login page on session timeout. The web.xml should be configured to use this filter.

        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
                        ServletException
        {
               
               
                String ipAddress = request.getRemoteAddr();
               
                System.out.println("IP " + ipAddress + ", Time " + new Date().toString());

                boolean authorized = false;
                String username = null;
                String role = null;
                if (request instanceof HttpServletRequest)
                {
                        HttpSession session = ((HttpServletRequest) request).getSession(false);
                        if (session != null)
                        {
                                username = (String) session.getAttribute("username");
                                role = (String) session.getAttribute("role");
                                if (username != null && role != null)
                                        authorized = true;
                        }else{
                               
                                ((HttpServletResponse)response).sendRedirect("showlogin");
                        //or response.sendError(..) etc.
                        return ;
                   }
                }

                       
                                                       
                 

Technology: 

Search