public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain){ try{ HttpSession session = ((HttpServletRequest)req).getSession(false); if(session!=null){ String userName = (String) session.getAttribute("userid"); if(userName==null || userName.equals("")){ //Invalid user. Redirect to login page String message= "You have been logged out of the application. Please log in again."; session.setAttribute("message", message); ((HttpServletResponse)resp).sendRedirect(((HttpServletRequest)req).getContextPath()+session.getServletContext().getInitParameter("initPage")); } else{ //If valid user, forward the request chain.doFilter(req, resp); } } else{ ((HttpServletResponse)resp).sendRedirect("errorPage.html"); } } catch(ServletException se){ System.out.println("In Servlet Exception"); try{ throw se.getRootCause(); } catch(Throwable e){ e.printStackTrace(); } se.printStackTrace(); } catch(IOException ioe){ System.out.println("In IO Exception"); ioe.printStackTrace(); } }