I have 2 filters in my application. Based on some condition, I want to choose whether to execute the second filter or not. Is there a way to do this?
I did some googling with no success. I want the request to continue without executing the second filter. Is that possible?
Any help will be appreciated.
In addition to Colin's answer, there's another way: just don't call FilterChain#doFilter() , but RequestDispatcher#forward() . But this will skip all filters from current on, expect of the ones which are listening on <dispatcher>FORWARD</dispatcher> . Good solution.
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.
A FilterChain is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource.
Filters and interceptors can be used on both sides, on the client and the server side. Filters can modify inbound and outbound requests and responses including modification of headers, entity and other request/response parameters. Interceptors are used primarily for modification of entity input and output streams.
In addition to Colin's answer, there's another way: just don't call FilterChain#doFilter()
, but RequestDispatcher#forward()
.
if (condition) { request.getRequestDispatcher(((HttpServletRequest) request).getServletPath()).forward(request, response); } else { chain.doFilter(request, response); }
But this will skip all filters from current on, expect of the ones which are listening on <dispatcher>FORWARD</dispatcher>
.
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