Issue
Here is my piece of code for a filter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String path = ((HttpServletRequest) request).getRequestURI();
LOGGER.log(Level.INFO, "Current request path :: {0}", path);
if (ignorePath(path)) {
LOGGER.log(Level.INFO, "continuing to next filter");
chain.doFilter(request, response);
}
LOGGER.log(Level.INFO, "Should not come here");
}
logging is done just for debugging purposes. I am getting below logs on execution.
2020-07-18T12:02:30.805301+00:00 app[web.1]: Jul 18, 2020 12:02:30 PM security.filter.SecurityFilter doFilter
2020-07-18T12:02:30.805302+00:00 app[web.1]: INFO: continuing to next filter
2020-07-18T12:02:30.889518+00:00 app[web.1]: Jul 18, 2020 12:02:30 PM security.filter.SecurityFilter doFilter
2020-07-18T12:02:30.889520+00:00 app[web.1]: INFO: Should not come here
What is really going wrong here? The log Should not come here, shouldn't be printed(That is what I expect).
Solution
The doFilter()
is called each time when a request/response is passed through the chain. The FilterChain.doFilter()
method invokes the next filter in the chain and calls resource at the end of the chain if the filter is the last filter in the chain.
This is just a normal method and after it's execution the control will come to the next line. That's the reason you're getting the log after the if
condition.
If you want to ignore the execution of the next filter for certain URIs, I recommend you use the else
block.
if (ignorePath(path)) {
chain.doFilter(request, response);
LOGGER.log(Level.INFO, "Called doFilter for this URI");
} else {
LOGGER.log(Level.INFO, "doFilter is not called for this URI");
}
Answered By - Karthick Ram
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)