views:

547

answers:

3

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?

+3  A: 

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

}
Rich Kroll
This may be a bit contrived, but what if I want to reject the response? In other words, I want to stop the response actually going out? Is this where a ServletException could be thrown?
Jeremy Powell
Throwing a ServletException would still return a "response" to the client, so it would depend what you meant by not returning a response. You could create a new response object, with only content you specify and return that if you so chose.
Rich Kroll
Ah good point. Absolutely no response isn't really ever desirable. Even when the doFilter() returns before calling chain.doFilter(), it still returns some other error page or default something or other.
Jeremy Powell
@Jeremy RE: filter order: The order of application of filters is defined by their order of definition in web.xml
Rich Kroll
A: 

@Rich:Is doFilter() executed before or after the Servlet’s work is done?

A filter is a program that runs on the server before the servlet or JSP page with which it is associated.

adatapost
Where is that quoted from?
Jeremy Powell
It looks to be quoted from "More Servlets and JavaServer Pages" by Marty Hall.
Zack Mulgrew
@adatapost since it wraps the invocation, it will be invoked prior to the servlet/jsp, but will regain control after it processes (if another filter did not interrupt processing)
Rich Kroll
A: 
Roman