I have 2 filters and a servlet in my web app. I registered the filters programmatically using @WebFilter annotation. They have same URL Pattern. Now first filter is calling FilterChain.doFilter and second filter is invoking the RequestDispatcher.forward method to forward the request to the servlet.The code runs fine as First filter is invoking second one and second one is invoking the servlet. I wonder ,no entries of filters are there in web.xml, and container is invoking them in correct order. So its just a coincidence or we can have ordering here in annotation based configuration?
Please find the code below.
First Filter :
@WebFilter(urlPatterns={"/*"},displayName="FirstFilterInFilterChain")
public class FirstFilterInFilterChain implements Filter{
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("Calling the Second Filter");
chain.doFilter(req, res);
System.out.println("Returning from Filter 1");
}
@Override
public void destroy() {
System.out.println("Inside Destroy method of Filter no 1");
}
@Override
public void init(FilterConfig config) throws ServletException {
System.out.println("Inside Init method of Filter no 1");
}
}
Second Filter :
@WebFilter("/*")
public class SecondFilterInFilterChain implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/PostFilterServlet");
dispatcher.forward(request, response);
System.out.println("Returning from Filter 2");
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("Inside Init method of Filter no 2");
}
}
Servlet code:
@WebServlet("/PostFilterServlet")
public class PostFilterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside PostFilterServlet");
}
}
Console Output :
Calling the Second Filter
Calling the servlet
Inside PostFilterServlet
Returning from Filter 2
Returning from Filter 1