0

I have a component that should be able to access the @RequestBody object that is sent within a request and check if it’s of a certain type.

Is there a way to do this, without deserializing the object again and without manually saving the @RequestBody somewhere when the controller method (where the @RequestBody parameter is declared) is called?

I’d like a solution that works independently of the rest controller and without modifying it’s methods.

Thanks!

regisxp
  • 956
  • 2
  • 10
  • 31

1 Answers1

0

Using a class that extends RequestBodyAdviceAdapter, as explained here, solves the problem.

@ControllerAdvice
public class CustomRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
    }

}

The method supports should return true if the Class should be able to handle the request. And inside afterBodyRead you can access the object and process it.

regisxp
  • 956
  • 2
  • 10
  • 31