Spring(十)--Spring校验

Spring校验使用场景

  • Spring常规校验
  • Spring数据绑定
  • SpringWeb参数绑定
  • SpringWebMVC/SpringWebFlux处理方法参数校验

Validator接口设计

  • 接口的职责: Spring内部校验器接口,通过编程的方式校验目标对象
  • 核心方法
supports(Class): 校验目标类能否校验
validate(Object, Errors): 校验目标对象,并将校验失败的内容输出至Errors对象
  • 配套组件
错误收集器: org.springframework.validation.Errors
Validator工具类: org.springframework.validation.ValidationUtils

Error接口设计

  • 接口职责:数据绑定和校验错误收集接口,与Java Bean和其属性有强关联性, Error的实现类会关联一个javabean,因为接口定义了能获取bean的指定属性
Errors errors = new BeanPropertyBindingResult(user, "user");
  • 核心方法
  1. reject方法:收集错误文案
/**
 * Register a global error for the entire target object,
 * using the given error description.
 * @param errorCode error code, interpretable as a message key
*/
void reject(String errorCode);
2.rejectValue方法(重载):收集对象字段中的错误文案
/**
	 * Register a field error for the specified field of the current object
	 * (respecting the current nested path, if any), using the given error
	 * description.
	 * <p>The field name may be {@code null} or empty String to indicate
	 * the current object itself rather than a field of it. This may result
	 * in a corresponding field error within the nested object graph or a
	 * global error if the current object is the top object.
	 * @param field the field name (may be {@code null} or empty String)
	 * @param errorCode error code, interpretable as a message key
	 * @see #getNestedPath()
	 */
void rejectValue(@Nullable String field, String errorCode);
  • 配套组件

1.Java Bean错误描述: org.springframework.validation.ObjectError
2.Java Bean属性错误描述: org.springframework.validation.FieldError

Errors文案来源

  • Errors文案生成步骤

1.选择Errors实现
2.调用reject或rejectValue方法
3.获取Errors对象中ObjectError或FieldError
4.将ObjectError或FieldError中的code和args,关联MessageSource实现(如:ResourceBundleMessageSource)

自定义Validator

  • 实现org.springframework.validation.Validator接口

1.实现supports方法
2.实现validate方法、

Validator的救赎

  • Bean Validation与Validator适配: Spring并没有对JSR-303进行实现,它要依赖于其他实现,比如hibernate Validator。
  • 核心组件: org.springframework.validation.beanvalidation.LocalValidatorFactoryBean
  • 依赖Bean Validation-JSR-303 或 JSR-349的实现
  • Bean方法参数校验-org.springframework.validation.beanvalidation.MethodValidationPostProcessor,这个类继承

AbstractBeanFactoryAwareAdvisingPostProcessor的,它会对类级别上使用@Validated标注的生成代理,从而使得方法调用能被校验。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值