Post processing of a Json response in spring MVC

北城以北 提交于 2019-11-27 01:08:00

问题


I have several controllers that return the same generic Response object with @ResponseBody annotation, like this:

@RequestMapping(value = "/status", method = RequestMethod.GET)
    @Transactional(readOnly = true)
    public @ResponseBody Response<StatusVM> status()

I need to perform an operation on every controller, after the Response is returned. This operation will enrich the Response object with new data.

I don't want to duplicate code, so I need a single point of intervention. I thought I could do this with Interceptors, however, according to the docs http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor this does not work well with @ResponseBody:

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.

I haven't been able to find an example of this tecnique, could anybody help me?

As an alternative I could work with aspects, but then I'd need to annotate every controller, which is something I'd like to avoid.


回答1:


In the end I implemented ResponseBodyAdvice like this:

@ControllerAdvice
public class StatusAdvice implements ResponseBodyAdvice<Response<?>> {


    @Override
    public boolean supports(MethodParameter returnType,
            Class<? extends HttpMessageConverter<?>> converterType) {

        if (returnTypeIsReponseVM(returnType)&&responseConverterIsJackson2(converterType)){
            return true;
        }

        return false;
    }

....

    @Override
    public Response<?> beforeBodyWrite(Response<?> body, MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request, ServerHttpResponse response) {

        ....

        return body;
    }

}

So it was easier then expected.



来源:https://stackoverflow.com/questions/26756811/post-processing-of-a-json-response-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!