doFilter called twice, intended behaviour?

后端 未结 8 1597
孤街浪徒
孤街浪徒 2021-02-19 16:42

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

8条回答
  •  别跟我提以往
    2021-02-19 16:52

    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 .

提交回复
热议问题