Spring Boot 参数校验

一、背景介绍

开发过程当中,后台的参数校验是必不可少的,因此常常会看到相似下面这样的代码php

这样写并无什么错,还挺工整的,只是看起来不是很优雅而已。html

接下来,用Validation来改写这段java

二、Spring Boot文档中的Validation

在Spring Boot的官网中,关于Validation只是简单的提了一句,以下spring

其实,Spring ValidatorHibernate Validator是两套Validator,能够混着用,这里咱们用Hibernate Validatorapp

三、Hibernate Validator

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

四、Spring Validator

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

五、示例

5.一、引入spring-boot-starter-validation

5.二、定义一个对象

5.三、适用@Valid校验,并将校验结果放到BindingResult对象中

注意:.net

  • 默认状况下,若是校验失败会抛javax.validation.ConstraintViolationException异常,能够用统一异常处理去对这些异常作处理
  • An Errors/BindingResult argument is expected to be declared immediately after the model attribute

5.四、看效果

若是在校验的对象后面再加上Model对象的话,若是返回的是ModelAndView就能够将这个Model设置到其中,这样在页面就能够取到错误消息了hibernate

仅仅只是单字段校验的话未免也太不灵活了吧,若是字段之间有关联关系,那该如何校验呢?答案是自定义3d

5.五、自定义校验规则

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

这里,以优惠券建立为例来演示如何自定义校验规则

首先,优惠券表单以下(仅仅只是演示用):

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

为何要有分组这一说呢?由于,举个例子,添加的时候不须要校验id,而修改的时候id不能为空,有了分组之后,就能够添加的时候校验用组A,修改的时候校验用组B

下面重点看一下@CheckTimeInterval

第一步、定义一个注解叫CheckTimeInterval

第二步、定义Validator去校验它

顺便提一句,这里BeanWrapper去取对象的属性值,咱们稍微看一下BeanWrapper是作什么的

 

 

 言归正传

第三步、验证

 

 

 

 看,自定义的校验生效了

六、补充

6.一、校验模式

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

下面补充一点,关于校验模式

默认会校验完全部属性,而后将错误信息一块儿返回,但不少时候不须要这样,一个校验失败了,其它就没必要校验了

为此,须要这样设置

 6.二、单个参数校验

 

 若是是调整页面的时候参数校验失败的话,这时能够不作处理,让其调到错误页面。

若是是接口参数校验失败的话,能够在这里进行统一处理,并返回。例如:

 6.三、错误页面

 以刚才优惠券详情为例

http://localhost:8080/coupon/detail.html      400

http://localhost:8080/coupon/detail.html?id=    400

http://localhost:8080/coupon/detail.html?id=abc   400

http://localhost:8080/coupon/detail222.html?id=123  404

无权限  403

int a = 1 / 0;  500

 

 6.四、@Valid与@Validated

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

 

 参考

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

相关文章
相关标签/搜索