Reputation: 2480
In my project i have multiple API's(implemented using Spring REST API). Now i have this requirement that i have to manipulate the response in specific way before it is sent to client and changing it in every API method does not seems to be a good option.
Only solution i can think of is using servlet.Filter (by extending filter class)
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
> chain.doFilter(req, res);
and write my logic after
chain.doFilter(req, res);
but i am struggling to convert ServletResponse or HTTPServletResponse into HttpEntity.
Please help me how can i achieve this ? and is there any better approach available ?
Thanks
UPDATE
@jny solution has helped me.
little code snippet to show how it works.
@ControllerAdvice(basePackages = { "com.test.controller" }) // package where it will look for the controllers.
public class ResponseFilter implements ResponseBodyAdvice<Object> {
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
//here you can manipulate the body the way you want.
return body;
}
important is that your controller should be annotated with @ResponseBody
Upvotes: 1
Views: 3172
Reputation: 8057
It depends on what exactly you need.
If you need to make changes of the body of the response,
if you use Spring 4.1
or higher, you can use ResponseBodyAdvice
to manipulate the body of the response.
If you need to filter certain fields, there are other options available. From documentation:
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.
Upvotes: 1
Reputation: 106
This may point you in the right direction: Spring MVC: How to modify json response sent from controller
It involves wrapping the ServletResponse before invoking doFilter and using a custom ServletOutputStream that allows the response data to be manipulated after it would normally have been closed. HttpEntity is not involved.
Upvotes: 0