rosenthal rosenthal - 3 years ago 172
reST (reStructuredText) Question

Spring REST post process all HTTP requests

What I'm Trying to accomplish

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. E.g. 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.

I want to be able to modify the HttpEntity response that is crafted from this return result. In particular, I want to do all HATEOAS work in this post-processor and wrap it in my parent object.

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. This was simple to do with Jersey OR CXF.

Is there a notion of ContainerResponseFilter in Spring REST?

Answer Source

I think, what you need is 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.

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.

Your other concern about OutputStream will be resolved and body will directly be available ,

@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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download