How can I decorate a REST answer in Spring (Boot)?

I have a Spring boot application that returns various objects that are encoded as JSON responses, and I would like to process them and add information to some superclasses.

Is there a way to filter, intercept, etc. object responses from my REST endpoints before they are JSON encoded with Jackson.

The filter will not work, since it works at the level HttpServlet{Request,Response}.

+4
source share
1 answer

I think ResponseBodyAdviceyour friend. Mainly:

@ResponseBody ResponseEntity, HttpMessageConverter. RequestMappingHandlerAdapter ExceptionHandlerExceptionResolver , @ControllerAdvice, .

String :

@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();
    }
}
+7

Source: https://habr.com/ru/post/1625757/


All Articles