Spring MVC 中 Json 响应的后处理 [英] Post processing of a Json response in spring MVC
问题描述
我有几个控制器使用@ResponseBody 注释返回相同的通用响应对象,如下所示:
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()
在返回响应后,我需要对每个控制器执行操作.此操作将使用新数据丰富 Response 对象.
I need to perform an operation on every controller, after the Response is returned. This operation will enrich the Response object with new data.
我不想重复代码,所以我需要单点干预.但是,根据文档 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor 这不适用于@ResponseBody:
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:
请注意,HandlerInterceptor 的 postHandle 方法并不总是非常适合与 @ResponseBody 和 ResponseEntity 方法一起使用.在这种情况下,HttpMessageConverter 在调用 postHandle 之前写入并提交响应,这使得无法更改响应,例如添加标头.相反,应用程序可以实现 ResponseBodyAdvice 并将其声明为 @ControllerAdvice bean 或直接在 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.
推荐答案
最后我是这样实现 ResponseBodyAdvice 的:
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;
}
}
所以比预期的要容易.
这篇关于Spring MVC 中 Json 响应的后处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!