SpringBoot+JSR303

SpringBoot+JSR303

依赖引入
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
  • 框架自带校验

    • entity设置

      • @Data
        @Builder
        public class Employee implements Serializable {
            public interface Operation {}
            public interface Query extends Operation{}
            public interface Update extends Operation{}
            public interface Save extends Operation{}
            public interface Delete extends Operation{}
            //激活子父也会激活,激活父不会激活子
            @Range(min = 0L,max = 1000L,groups = {Operation.class})
            @NotNull(groups = {Query.class})
            private Integer id;
        }
        
    • controller设置

      •     @PostMapping("/employee")
            public String getEmployee(@RequestBody @Validated(Employee.Operation.class) Employee employee, BindingResult bindingResult) {
                if (bindingResult.hasErrors()){
                    List<FieldError> allErrors = bindingResult.getFieldErrors();
                    String error = "";
                    for (FieldError fieldError : allErrors) {
                        error += fieldError.getObjectName()+fieldError.getField()+fieldError.getDefaultMessage();
                    }
                    return error;
                }
                List<Employee> employees = employeeService.selectByExample(employee);
                return employees.toString();
            }
        
    • 通用校验异常

      • class A {}
        
  • 自定义校验类

    • @Documented
      //注解使用的校验器
      @Constraint(
              validatedBy = {AgeValidator.class}
      )
      @SupportedValidationTarget({ValidationTarget.ANNOTATED_ELEMENT})
      @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
      @Retention(RetentionPolicy.RUNTIME)
      @ReportAsSingleViolation
      public @interface Age {
      
          int min() default 0;
      
          int max() default 125;
      	//{max}用来获取参数值
          String message() default "年龄是非法的,最大不能超过{max}岁,最小不能小于{min}岁";
      
          Class<?>[] groups() default {};
      
          Class<? extends Payload>[] payload() default {};
      }
      
    • public class AgeValidator implements ConstraintValidator<Age,Integer> {
      
          private Integer max;
          private Integer min;
      
          @Override
          public void initialize(Age constraintAnnotation) {
             this.max = constraintAnnotation.max();
             this.min = constraintAnnotation.min();
          }
      
          @Override
          public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
              return integer != null && integer < max && min < integer;
          }
      }
      
  • 配置全局异常捕获参数校验错误

    • 配置全局异常类

      • /**
         * @author QianShuang
         */
        //包路径不能写表达式 *.**.controller
        @RestControllerAdvice(basePackages = "com.miracle.springdemo.controller")
        public class ValidatorErrorControllerAdvice {
            @ExceptionHandler(value = {MethodArgumentNotValidException.class,BindException.class})
            //入参可以是request对象
            public Map<String,String> defaultValidatorErrorHandle(Exception exception) {
                BindingResult bindingResult;
                if (exception instanceof MethodArgumentNotValidException) {
                    bindingResult = ((MethodArgumentNotValidException)exception).getBindingResult();
                }else {
                    bindingResult = ((BindException)exception).getBindingResult();
                }
                Map<String,String> result = new HashMap<>(16);
                result.put("对象名称", bindingResult.getObjectName());
                bindingResult.getFieldErrors().forEach(fieldError -> {
                    result.put(fieldError.getField(),fieldError.getDefaultMessage());
                });
                result.put("status","400");
                return result;
            }
        }
        
    • 校验类编写

      • //BindingResult bindingResult对象不用添加在参数列表会直接抛出异常,通过全局异常捕获即可    
        @PostMapping("/employee")
            public String getEmployee(@RequestBody @Validated(Employee.Query.class) Employee employee) {
                List<Employee> employees = employeeService.selectByExample(employee);
                return employees.toString();
            }
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值