Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring mvc interceptor: access to ResponseEntity in postHandle

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

like image 707
jason Avatar asked Apr 04 '12 20:04

jason


Video Answer


2 Answers

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"

like image 137
Jordi Llach Avatar answered Sep 20 '22 13:09

Jordi Llach


@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

like image 27
Lucas Avatar answered Sep 19 '22 13:09

Lucas