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