I\'m working through the Java EE servlet tutorial and tried the mood example. I noticed the doFilter is getting called twice, once the servlet call is in the chain and the secon
The Filter.doFilter
method is called once per request. You can execute some code before other filters in the chain are called and also afterwards (in the order specified in the filter chain, as per the web.xml filter-mapping
order),
something like the following example:
public MyFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
codeToExecuteBeforeOtherFiltersInTheChain(request, response);
chain.doFilter(request, response);
codeToExecuteAfterOtherFiltersInTheChain(request, response);
}
}
If your filter is configured to dispatch REQUEST
and FORWARD
requests, then the MyFilter.doFilter
method will be called once for the original request and once if the request has been forwarded:
Configure filter mapping using web.xml
file:
...
MyFilter
/*
REQUEST
FORWARD
...
Configure filter mapping using @WebFilter annotation:
@WebFilter(urlPatterns = "/*", dispatcherTypes = {
DispatcherType.REQUEST, DispatcherType.FORWARD
}) public MyFilter implements Filter {
...
}
To be able to check if the request has been forwarded, you can use the request attribute described here: How to know when the request is forwarded in a RequestWrapper object
For details about filters see: https://docs.oracle.com/cd/B32110_01/web.1013/b28959/filters.htm