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
I came across the same issue when the doFilter
is called twice (or multiple times). The problem was that the filter handles every request including css, js, image and all other files while I expected one request for each page, so I solved the issue by adding the following code:
@WebFilter(filterName = "MyCustomFilter")
public class MyCustomFilter implements Filter {
public void doFilter(ServletRequest request,ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String accept = httpRequest.getHeader("accept");
// Since the filter handles every request
// we have to ensure that the request is asking for text/html
if (accept == null || !accept.toLowerCase().startsWith("text/html")) {
chain.doFilter(request, response);
return;
}
// your code goes here
Hope this will help people like me who googled this question .