The javax.servlet.Filter object can be used both for authentication (where the Filter needs to catch the request before any servlet work needs to be done) and for XSLT translation (where the servlet needs to be completely finished generating content). When does it actually get executed?
I know this is implementation dependent (on the web container), but this seems to be problem that needs to be solved by all of them.
Maybe there is a configuration option set somewhere for each Filter registration with the web container?
Additional:
Also, what governs the order of Filter execution? Why would FooFilter get executed before BarFilter?
The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.
Every filter must implement the three methods in the Filter interface: init(), doFilter(), and destroy(). First there's init() When the Container decides to instantiate a filter, the init() method is your chance to do any set-up tasks before the filter is called.
doFilter. Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.
How does Servlet Filter work? When a request is made, it reaches the Web Container and checks if the filter contains any URL pattern, which is similar to the pattern of the URL requested. The Web Container locates the very first filter which matches the request URL, and then that filter code is executed.
The filter chain in essence wraps the servlet invocation. The chain will process all links until it hits the "bottom", then allow the servlet to run, and then return up the chain in reverse. For example, if you have a new "example filter", your doFilter() method may look like this:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // do pre-servlet work here chain.doFilter(request, response); // do post servlet work here }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With