A filter is loaded before servlets. And you can do something on the request and the response(If you put the statements after the invokation of filterChain.dofilter).
The filter machenism is much like the servlet, and the configuration in web.xml is also similar.
Now, thinking about the question of more than one filter. What's the order of the filter chain?
Here is a simple example to show the order:
Filter one: (Named Basic Filter)
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { arg1.getWriter().println("Basic Filter!"); arg2.doFilter(arg0, arg1); }
Filter two: (Named First Filter)
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { arg1.getWriter().println("First Filter!"); arg2.doFilter(arg0, arg1); }
The configuration:
<!--1--> <filter> <filter-name>FirstFilter</filter-name> <filter-class>filters.FirstFilter</filter-class> </filter> <!--2--> <filter> <filter-name>BasicFilter</filter-name> <filter-class>filters.BasicFilter</filter-class> </filter> <!--3--> <filter-mapping> <filter-name>BasicFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--4--> <filter-mapping> <filter-name>FirstFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
The output is like this:
First Filter! Basic Filter!
And then, if I change the section 1 and section 2, the output is the same. However, if I change the section 3 and section 4, The output is become:
Basic Filter!First Filter!
Hence, the order of filter chain is determined by the order of the filter-mapping declared in web.xml.