[英]Spring REST post process all HTTP requests
I want to be able to process the results of a HTTP request to a Spring RestController after a particular endpoints method has returned it's value.在特定端点方法返回它的值之后,我希望能够处理对 Spring RestController 的 HTTP 请求的结果。 Eg I have:
例如我有:
GET /customer/{id}
This normally just returns a custom resource.这通常只返回一个自定义资源。 It's endpoint I define in my
RestController
just returns a customer object.我在
RestController
中定义的端点只是返回一个客户对象。
I want to be able to modify the HttpEntity
response that is crafted from this return result.我希望能够修改根据此返回结果制作的
HttpEntity
响应。 In particular, I want to do all HATEOAS work in this post-processor and wrap it in my parent object.特别是,我想在这个后处理器中完成所有 HATEOAS 工作,并将其包装在我的父对象中。
What would be the best way to accomplish this?实现这一目标的最佳方法是什么? I would include what I've tried, but I can't think of any way this could be done cleanly.
我会包括我尝试过的东西,但我想不出任何可以干净地完成的方法。
In frameworks that implement JAX-RS, all you would need to do is implement the ContainerResponseFilter
interface and you could add it to your REST server.在实现 JAX-RS 的框架中,您需要做的就是实现
ContainerResponseFilter
接口,然后您可以将它添加到您的 REST 服务器。 This was simple to do with Jersey OR CXF.使用 Jersey OR CXF 很容易做到这一点。
Is there a notion of ContainerResponseFilter
in Spring REST? Spring REST 中有
ContainerResponseFilter
的概念吗?
I think, what you need is ResponseBodyAdvice .我认为,您需要的是ResponseBodyAdvice 。
As per documentation ,根据文档,
Allows customizing the response after the execution of an @ResponseBody or a ResponseEntity controller method but before the body is written with an HttpMessageConverter.
允许在执行 @ResponseBody 或 ResponseEntity 控制器方法之后但在使用 HttpMessageConverter 编写正文之前自定义响应。
Implementations may be may be registered directly with RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver or more likely annotated with @ControllerAdvice in which case they will be auto-detected by both.
实现可以直接使用 RequestMappingHandlerAdapter 和 ExceptionHandlerExceptionResolver 进行注册,或者更可能使用 @ControllerAdvice 进行注释,在这种情况下它们将被两者自动检测到。
Your other concern about OutputStream
will be resolved and body will directly be available ,您对
OutputStream
的其他担忧将得到解决,正文将直接可用,
@ControllerAdvice
public class CustomerResponseFilter implements ResponseBodyAdvice<ResponseEntity<Customer>> {
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
// TODO Auto-generated method stub
return false;
}
@Override
public ResponseEntity<Customer> beforeBodyWrite(ResponseEntity<Customer> body,
MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
//..do your manipulations
return body;
}
}
Since it is annotated with @ControllerAdvice
, it will be automatically detected for your controllers.由于它带有
@ControllerAdvice
注释,因此会自动检测到您的控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.