1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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(); } } |
Thursday, September 20, 2012
Using filters in Java
Subscribe to:
Post Comments
(
Atom
)