I have an interceptor that logs the outcome of Spring MVC responses. All my responses return ResponseEntity objects that have JSON body contents.
I would like to grab both the response body and the http status from the ResponseEntity.
How can I get access to the ResponseEntity from the postHandle method attributes?
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) {}
The modelAndView attribute is null for my invocations.
Thanks, Jason
By the time you wrote your question I think it was not possible but now it is. From their docs http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-handlermapping-intercepto
"Note that the postHandle method of HandlerInterceptor is not always ideally suited for use with @ResponseBody and ResponseEntity methods. In such cases an HttpMessageConverter writes to and commits the response before postHandle is called which makes it impossible to change the response, for example to add a header. Instead an application can implement ResponseBodyAdvice and either declare it as an @ControllerAdvice bean or configure it directly on RequestMappingHandlerAdapter"
@ControllerAdvice
public class ResponseDTOFilterAdvice 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 ResponseDTO<?>) {
ResponseDTO<?> responseDTO = (ResponseDTO<?>) body;
responseDTO.setHostname(request.getLocalAddress().getHostName());
}
return body;
}
}
Source: Post processing of a Json response in spring MVC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With