Saturday, 3 March 2018

How to create a Controller advice to manipulate the response from every controller ?


Define Controller advice by providing @ControllerAdvice, implement ResponseBodyAdvice and implement all the required methods.

Below example Controller advice will be called after each controller, and add the headers.

EXAMPLE
@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public Object beforeBodyWrite(Object arg0, MethodParameter arg1, MediaType arg2,
            Class<? extends HttpMessageConverter<?>> arg3, ServerHttpRequest arg4, ServerHttpResponse response) {
        System.out.println("Inside ResponseHandler : Contoller advice manipulating response... Adding headers !");
        response.getHeaders().add("MyHead", "Shaan");
        return response;
    }

    // Check the content type and return true, if matches

    @Override
    public boolean supports(MethodParameter arg0, Class<? extends HttpMessageConverter<?>> arg1) {
        return true;
    }
}


No comments:

Post a Comment

Note: only a member of this blog may post a comment.