title: Java Servlet filter: I have to add headers before passing to the chain, documentation tells otherwise
body: <p>We're currently working on adding headers to each response from our application. To add these headers we're using the Servlet APIs <code>Filter</code>-interface.</p>
  
  <p>We've got the following filter in our application:</p>
  
  <pre><code>public class SecurityFilter implements Filter
  {
      @Override
      public void init(FilterConfig filterConfig) throws ServletException
      {
  
      }
  
      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
      {
          chain.doFilter(request, response);
  
          HttpServletResponse httpServletResponse = ((HttpServletResponse) response);
          httpServletResponse.addHeader("X-Frame-Options", "DENY");
          httpServletResponse.addHeader("X-Content-Type-Options", "nosniff");
      }
  
      @Override
      public void destroy()
      {
  
      }
  }
  </code></pre>
  
  <p>This (specifically the <code>doFilter</code>-method) is implemented correctly according to the documentation, which suggests the following order of work:</p>
  
  <blockquote>
    <ol>
    <li>Examine the request</li>
    <li>Optionally wrap the request object with a custom implementation to filter content or headers for input filtering</li>
    <li><p>Optionally wrap the response object with a custom implementation to filter content or headers for output filtering</p></li>
    <li><ul>
    <li>Either invoke the next entity in the chain using the FilterChain object (chain.doFilter()),</li>
    <li>or not pass on the request/response pair to the next entity in the filter chain to block the request processing</li>
    </ul></li>
    <li>Directly set headers on the response after invocation of the next entity in the filter chain.</li>
    </ol>
  </blockquote>
  
  <p>As far as we can see, the order of our <code>doFilter</code>-method is correct according to the documentation (pass the request to the chain first as stated under point 4, add custom headers afterwards as stated under point 5). However, the headers we add aren't visible in the responses. If we change to order to the following, everything seems to work just fine:</p>
  
  <pre><code>@Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
  {
      HttpServletResponse httpServletResponse = ((HttpServletResponse) response);
      httpServletResponse.addHeader("X-Frame-Options", "DENY");
      httpServletResponse.addHeader("X-Content-Type-Options", "nosniff");
  
      chain.doFilter(request, response);
  }
  </code></pre>
  
  <p>Can anyone explain this behavior?</p>