0

I have some @RestController endpoints and want to add a loggging-uuid to every response that is send back to the client. I'd like to write that id into the http header. Also for error responses like 404 etc.

Question: should I use a HandlerInterceptor, Filter, or ResponseBodyAdvice?

Probably all might work, but which is the correct one for my needs?

public class HeaderInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("uuid", 1234);
    }
}

public class Filter extends OncePerRequestFilter {
 @Override
 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    response.setHeader("uuid", 1234);
    filterChain.doFilter(request, response);
 }
}


@ControllerAdvice
public class HeaderAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(final MethodParameter returnType, final Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(final Object body, final MethodParameter returnType, final MediaType selectedContentType,
        final Class<? extends HttpMessageConverter<?>> selectedConverterType, final ServerHttpRequest request, final ServerHttpResponse response) {
        if (body instanceof ResponseEntity) {
            ResponseEntity responseEntity = (ResponseEntity) body;
            responseEntity.getHeaders().add("uuid", "1234");
        }
        return body;
    }
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • Sidenote to the duplicate: your linked answers also state different solutions. That's why I'm asking which implementation would be the correct one. – membersound Nov 18 '19 at 16:36
  • Unfortunately the question has been closed. I would like to add the solution: when using `spring-security`, it's best to use register a `HeaderWriterFilter`. Otherwise just use a `OncePerRequestFilter`. – membersound Nov 19 '19 at 08:56

0 Answers0