1

I am adding a header to the response inside HandlerInterceptorAdapter. However it seems that the response header cannot be modified in the postHandle method.

public class CredentialInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
      return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView) {
            String value = "...";
            response.addHeader("header_name",value ); // doesn't work
    }
}

How to add a header to the response ?

Popular solution is to use OncePerRequestFilter ( Set response header in Spring Boot ). Isn't there any other way ?

Raymond Chenon
  • 11,482
  • 15
  • 77
  • 110
  • 3
    If the response has already (partially) been send you cannot change it, this is already very likely in the case of the `postHandle` method. You can do it in the `preHandle` as that is before the response has been send. Using a filter (and doing it after the call to `chain.doFilter`) would yield the same result. – M. Deinum Mar 09 '22 at 12:48
  • @M.Deinum , doing it in `preHandle` solved the problem. You comment is already the solution. – Raymond Chenon Mar 09 '22 at 21:15

1 Answers1

3

The problem with adding headers in the postHandle method is that the response may already be (partially) send. When that is the case you cannot add/change headers anymore. You need to set the headers before anything is sent to the client.

This you can do in the preHandle method or more generic a servlet filter before you call filterchain.doFilter. Doing it after the aforementioned call you might get the same issue that a response has already (partially) been sent.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224