Response Handling in Spring with ResponseBodyAdvice
--
When building web applications with the Spring Framework, it’s common to need to modify the response sent back to the client. Spring provides an elegant way to do this through a feature called ResponseBodyAdvice. In this article, we’ll explore what ResponseBodyAdvice is, how it works, and how to use it in Java code.
What is ResponseBodyAdvice?
ResponseBodyAdvice is an interface provided by Spring that allows you to modify the response returned by a controller method before it is sent back to the client. It’s essentially an interceptor that can be used to add, remove, or modify the content of the response. It’s particularly useful for handling cross-cutting concerns such as adding custom headers, logging, or modifying the response payload.
How ResponseBodyAdvice works
The ResponseBodyAdvice interface has three methods:
- supports
- beforeBodyWrite
- afterCompletion
The supports method is used to specify the type of the response object that this advice applies to. The beforeBodyWrite method is called before the response is written to the output stream, and allows you to modify the response object. The afterCompletion method is called after the response has been written to the output stream.
Here’s an example of how ResponseBodyAdvice can be used to modify the response object:
@ControllerAdvice
public class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
// modify the response body here
// for example, add a custom header
response.getHeaders().add("Custom-Header", "Hello World");
return body;
}
@Override
public void afterCompletion(NativeWebRequest request, ModelMap model, Exception ex) throws Exception {
// do nothing
}
}
In this example, we’ve created a custom ResponseBodyAdvice class that applies to all response objects (specified by returning true in the supports…