Spring validation for RequestBody parameters bound to collections in Controller methods

后端 未结 3 612
遇见更好的自我
遇见更好的自我 2020-12-10 16:32

I have

An Entity:

package org.ibp.soq;

public class MyEntity {

    private String field1;
    private String field2;

    //..get         


        
3条回答
  •  长情又很酷
    2020-12-10 17:05

    Actually, this can be achieved using Spring Validation and JSR303.

    • Expose a MethodValidationPostProcessor bean.
    • Annotate your controller class with @Validated (org.springframework.validation.annotation.Validated)
    • Use the JSR303 validation annotations on your MyEntity fields/methods.
    • Annotate your RequestBody argument with @Valid (you've already done this in your example).
    • Add an @ExceptionHandler method to handle MethodArgumentNotValidException. This can be done in the controller or in a @ControllerAdvice class.

提交回复
热议问题