Chaining two or more filters means that a filter will be invoked as soon as the invocation of an other filter finishes and in this tutorial we will see how filter chains are used.

A few tutorials ago we saw how to redirect users to login page when session expires using servlet filters.Suppose now that we need to further process the request again using some filter -logging the request etc-.

The class for the redirect filter will be:

public class RedirectFilter implements Filter{

    public void init(FilterConfig filterConfig) throws ServletException {
       
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
//check if "role" attribute is null
        if(req.getSession().getAttribute("role")==null){
//forward request to login.jsp
            req.getRequestDispatcher("/login.jsp").forward(request, response);
        }else{
        chain.doFilter(request, response);
        }
    }

    public void destroy() {
        
    }  
}


The second filter class will be similar to the RedirectFilter.For example :

public class SecondFilter implements Filter{

    public void init(FilterConfig filterConfig) throws ServletException {
       
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //processing goes here
    }

    public void destroy() {
        
    }  
}

The actual declaration of the filter chain will be in the web.xml where the invocation order of the servlet filters will be defined.For example in case we need SecondFilter to be invoked prior the RedirectFilter,we will declare the filters at the web xml as in the below snippet:

<filter>
        <filter-name>SecondFilter</filter-name>
        <filter-class>com.javaonly.filters.RedirectFilter</filter-class>
</filter>
<filter-mapping>
       <filter-name>SecondFilter</filter-name>
       <url-pattern>/somepage.jsp</url-pattern>
</filter-mapping>

<filter>
        <filter-name>RedirectFilter</filter-name>
        <filter-class>com.javaonly.filters.RedirectFilter</filter-class>
</filter>
<filter-mapping>
       <filter-name>RedirectFilter</filter-name>
       <url-pattern>/somepage.jsp</url-pattern>
</filter-mapping>