2

a question to validation of put calls to a REST endpoint using spring boot and javax.validation (not the spring validation).

You have the following method in the resource:

@PutMapping(...)
public Response getResult(@RequestBody @Valid myBody, @PathVariable @MyIdValidation long id) {

}

When I call the method, myBody gets validated and I get a MethodArgumentNotValidException in my exception handler. But parameter id gets not validated!

Only if myBody is valid, id gets validated as well.

The only solution I found is to not use @Valid, and implement the validation of the body myself.

Are there better solutions?

TIA Kibu

noname
  • 565
  • 6
  • 23
kibu Kuhn
  • 81
  • 5

2 Answers2

1

I don't think its doable by Spring MVC framework itself because framework handles @RequestBody and others like @RequestParam or @PathVariable differently by using different components. Also, both pieces need to be disconnected because you might not like to validate all arguments of a method.

@RequestBody is handled by org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor and validations are called from there & for params or path variable validations are done by org.springframework.validation.beanvalidation.MethodValidationInterceptor.

So in my opinion, method arguments of a controller method are handled one by one by framework & are disconnected in logic so these validations can't be clubbed together.

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
  • I think you're right. Because when I use a custom validation annotion for the body instead of @Valid, everything is validated in one step and I get a ValidationConstraintException. – kibu Kuhn Feb 06 '20 at 11:38
  • @kibuKuhn: if you are from Germany then I need a personal favor from you. Please share some way like email or skype etc thorough which I can reach you. Its regarding my relocation there. Please share if willing to provide some info kind of help. – Sabir Khan Feb 06 '20 at 11:48
0

I've put some effort into this issue and started a project on github

It's possible to validate in one stop, but you need a different approach. Check out the project and test it.

Kibu

kibu Kuhn
  • 81
  • 5