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.

public class LoginFilter implements Filter {

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

    UserAccountProducer userAccountProducer;

    public void destroy() {
        // NOOP

    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);

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



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s