SpringBoot 整合Validator统一参数校验

1. JSP303定义的校验类型

复制代码
空检查

@Null       验证对象是否为null

@NotNull    验证对象是否不为null, 无法查检长度为0的字符串

@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.

@NotEmpty 检查约束元素是否为NULL或者是EMPTY.

 
Booelan检查

@AssertTrue     验证 Boolean 对象是否为 true  

@AssertFalse    验证 Boolean 对象是否为 false  

 
长度检查

@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  

@Length(min=, max=) Validates that the annotated string is between min and max included.

 
日期检查

@Past           验证 Date 和 Calendar 对象是否在当前时间之前  

@Future     验证 Date 和 Calendar 对象是否在当前时间之后  

@Pattern    验证 String 对象是否符合正则表达式的规则
 

数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null

@Min            验证 Number 和 String 对象是否大等于指定的值  

@Max            验证 Number 和 String 对象是否小等于指定的值  

@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度

@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度

@Digits     验证 Number 和 String 的构成是否合法  

@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。

@Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.

@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;

@Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)

@CreditCardNumber信用卡验证

@Email  验证是否是邮件地址,如果为null,不进行验证,算通过验证。

@ScriptAssert(lang= ,script=, alias=)

@URL(protocol=,host=, port=,regexp=, flags=)
复制代码

 

2. @RequestParam参数校验

  A. 方法所在的控制层Controller上加@Validated注解;

  B. 请求方法Method上加上需要校验的注解,比如:@Size等,最好重写message属性;

  C. 捕捉校验失败异常信息:ConstraintViolationException异常

  例如:

复制代码
package com.ruhuanxingyun.controller;

import com.ruhuanxingyun.controller.response.JsonResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ErrorHandlerController {
    
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JsonResult handleBindException(BindException e) {
        // 得到第一个字段的错误信息
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        
        return JsonResult.error(msg);
    }

}
复制代码

 

3. 实体对象参数校验

  A. 实体类字段上加需要校验的注解;

       B. 请求方法上实体前加@Valid或@Validated注解,对入参实体进行嵌套验证必须在响应字段上加@Valid,而不是@Validated;

  C. 捕捉校验失败异常信息:BindException异常,或者在实体后使用BindingResult类,然后进行处理;

  D. 分组校验,还可以排序,例如:新增和修改,参数ID有无的问题。

  例如:

复制代码
package com.ruhuanxingyun.controller;

import com.ruhuanxingyun.controller.response.JsonResult;import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

@ControllerAdvice
public class ErrorHandlerController {
   
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public JsonResult handleValidationException(ConstraintViolationException e) {
        // 得到第一个字段的错误信息
        String msg = e.getConstraintViolations().iterator().next().getMessage();

        return JsonResult.error(msg);
    }

}
复制代码

 

4. 检测第一个失败就抛出异常,配置如下:

复制代码
@Configuration
public class WebConfig {
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                //failFast的意思只要出现校验失败的情况,就立即结束校验,不再进行后续的校验。
                .failFast(true)
                .buildValidatorFactory();

        return validatorFactory.getValidator();
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }
}
复制代码

 

可参考:springboot使用hibernate validator校验

posted @   如幻行云  阅读(946)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示