a.l.
a.l.

Reputation: 1135

How to convert response to another type before it handled by MessageConverter in Spring MVC

For example, here's a method which returns a User:

@RequestMapping(method = GET, value = "/user")
public User getUser() {
    return new Users();
}

For some reasons, the client expect an other type

class CommonResponse<T> {
  int code;
  T data;
}

So I need to convert all return value from T(User for this e.g.) to CommonResponse<T> before it handled by the MessageConverter.

Cause there're many request hanlders should be modified, is there any way to write the convert data just once?

Upvotes: 3

Views: 2346

Answers (2)

a.l.
a.l.

Reputation: 1135

Finally I find ResponseBodyAdvice to do such work.

Here the sample code:

@RestControllerAdvice
public class CommonAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getDeclaringClass().getPackage().getName().startsWith("foo.bar.demo");
        // you can change here to your logic
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return new CommonResponse<Object>().setCode(200).setData(body);
    }
}

Upvotes: 2

kuhajeyan
kuhajeyan

Reputation: 11027

you need to add/configure your custom converter. so that your custom converter is executed before others

@EnableWebMvc
@Configuration
@ComponentScan({ "org.app.web" })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(
      List<HttpMessageConverter<?>> converters) {

        messageConverters.add(createCustomConverter());
        super.configureMessageConverters(converters);
    }
    private HttpMessageConverter<Object> createCustomConverter() {
        ....
    }
}

Upvotes: 1

Related Questions