Redirecting page if not log in using Filter

Posted: February 13, 2013 in web

This assumes all pages you wanted to apply the filter should be under the “src/main/webapp/secure/” directory.

LoginFilter.java


@WebFilter("/secure/*")
public class LoginFilter implements Filter {

    private static final String LOGIN_URL = "/index.xhtml";

    @Inject
    UserAccountProducer userAccountProducer;

    @Override
    public void destroy() {
        // NOOP
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession(false);
        if (session != null && userAccountProducer.getUserAccount().getUser().isLoggedIn()) {
            chain.doFilter(req, res);
        } else {
            HttpServletResponse response = (HttpServletResponse) res;
            response.sendRedirect(request.getContextPath() + LOGIN_URL);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        // NOOP
    }

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s