Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is doFilter() executed before or after the Servlet's work is done?

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?

like image 985
Jeremy Powell Avatar asked Aug 24 '09 15:08

Jeremy Powell


People also ask

What is the role of doFilter () method?

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.

What is the sequence of method execution in filter init doFilter destroy?

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.

What is the purpose of calling FilterChain doFilter request response method?

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?

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.


1 Answers

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  } 
like image 172
Rich Kroll Avatar answered Sep 28 '22 17:09

Rich Kroll