引用:https://www.cnblogs.com/yang-yz/p/17576507.html
Validator
校验框架遵循了 jsr-303验证规范(参数校验规范)
JSR
: java specification requests
为了解决开发人员在校验参数方面,少写代码
依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>
可以校验json传递,,表单传递,,只传递一个属性也可以
@RestController
@Validated
public class ValidController {@GetMapping("/test")public void test03(@Email String email){System.out.println("email");}@GetMapping("/range")public void test05(@Range.List({@Range(min = 1,max = 10),@Range(min = 2,max = 8)}) Integer range){System.out.println("range = " + range);}@GetMapping("/sex")public void test06(@EnumString(value = {"male","female"},message = "性别不详") String sex){System.out.println("sex = " + sex);}@PostMapping("/update")public void test04(@RequestBody @Validated(value = ValidGroup.Crud.Create.class) ValidVo validVo){System.out.println("validVo = " + validVo);}
}
可以自定义校验: 按照自己的校验规则校验
分组校验: 根据不同的组去校验,,,一个VO对象,,在更新和新增的时候,,传递参数的校验规格是不同的,,更新的时候需要携带id,,新增不需要,,可以去创建两个不同的VO,,,也可以使用分组校验,,在更新的时候使用更新的分组,,,,创建的时候使用创建的分组
定义分组标识:
public interface ValidGroup extends Default {interface Crud extends ValidGroup{interface Create extends Crud{}interface Update extends Crud{}interface Query extends Crud{}interface Delete extends Crud{}}
}
在使用注解的时候,,将分组带进去,,
@Data
public class ValidVo {@NotNull(groups = {ValidGroup.Crud.Update.class},message = "更新不能为空")@Null(groups = {ValidGroup.Crud.Create.class},message = "创建id必须为空")private String id;@Rangeprivate Integer age;
}
在校验的时候,,标明是哪一个分组:
使用代码校验
public static void main(String[] args) {ValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();ValidVo validVo = new ValidVo();validVo.setId("1");validVo.setAge(3);Set<ConstraintViolation<ValidVo>> validate = validator.validate(validVo, ValidGroup.Crud.Update.class);System.out.println("validate = " + validate);Set<ConstraintViolation<ValidVo>> validate1 = validator.validate(validVo, ValidGroup.Crud.Create.class);System.out.println("validate1 = " + validate1);}
全局处理参数异常
javax.validation.ConstraintViolationException
,org.springframework.validation.BindException
,org.springframework.web.bind.MethodArgumentNotValidException
自定义参数校验
定义一个注解,,一个实现ConstraintValidator的类
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER})
@Constraint(validatedBy = EnumStringValidator.class)
public @interface EnumString {String message() default "value is not in enum";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};// 枚举的所有中文值String[] value();@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER})@interface List{EnumString[] value();}}
public class EnumStringValidator implements ConstraintValidator<EnumString,String> {private List<String> enumStringList;@Overridepublic void initialize(EnumString constraintAnnotation) {String[] value = constraintAnnotation.value();this.enumStringList = Arrays.asList(value);}@Overridepublic boolean isValid(String value, ConstraintValidatorContext context) {if(value == null){return true;}boolean contains = enumStringList.contains(value);return contains;}
}