SpringBoot Validation

545 阅读1分钟

1、Hibernate Validator

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#preface

2、Spring Validator

https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/core.html#validation

3、Example

3.1、引入spring-boot-starter-validation

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

3.2、定义对象


3.3、使用@Valid校验,并将校验结果放到BindingResult对象中


注意:

  • 默认情况下,如果校验失败会抛javax.validation.ConstraintViolationException异常,可以用统一异常处理去对这些异常做处理

3.4、自定义校验规则

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-customconstraints


这里除了自定义了两条校验规则之外,还用到了分组。

为什么要有分组这一说呢?因为,举个例子,添加的时候不需要校验id,而修改的时候id不能为空,有了分组以后,就可以添加的时候校验用组A,修改的时候校验用组B

再看看如何自定义validator


最后使用自定义的校验器进行


4、Extension

4.1、校验模式

关于校验模式,默认会校验完所有属性,然后将错误信息一起返回,但很多时候不需要这样,一个校验失败了,其它就不必校验了

为此,需要这样设置


4.2、单个参数校验


5、Other

5.1、@valid和@validated

 https://blog.csdn.net/qq_27680317/article/details/79970590

5.2、参考

http://rensanning.iteye.com/blog/2357373

https://blog.csdn.net/kenight/article/details/77774465

https://www.cnblogs.com/mr-yang-localhost/p/7812038.html

https://www.phpsong.com/3567.html

https://www.cnblogs.com/mr-yang-localhost/p/7812038.html