I guess ResponseBodyAdvice
is your friend. Basically it:
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.
Here i'm intercepting all the returned String
s and make them uppercase:
@ControllerAdvice
public class MyResponseBodyAdvisor implements ResponseBodyAdvice<String> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.getParameterType().equals(String.class);
}
@Override
public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
return body.toUpperCase();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…