Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I decorate the REST response in Spring (Boot)?

I've got a Spring Boot application that returns various objects that get encoded as JSON responses and I'd like to post-process them and add information to certain super classes.

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

A filter won't work since it operates at the HttpServlet{Request,Response} level.

like image 255
Lee Crawford Avatar asked Jan 24 '16 23:01

Lee Crawford


People also ask

What is @RestController in spring boot?

Spring RestController annotation is a convenience annotation that is itself annotated with @Controller and @ResponseBody . This annotation is applied to a class to mark it as a request handler. Spring RestController annotation is used to create RESTful web services using Spring MVC.

How do I use REST services in spring boot?

Create a simple Spring Boot web application and write a controller class files which is used to redirects into the HTML file to consumes the RESTful web services. We need to add the Spring Boot starter Thymeleaf and Web dependency in our build configuration file. For Maven users, add the below dependencies in your pom.


Video Answer


1 Answers

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 Strings 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();
    }
}
like image 102
Ali Dehghani Avatar answered Oct 24 '22 04:10

Ali Dehghani