1.Validator基本使用
1.引入SpringValidator启动器
<!--JSR303-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.在需要检验的参数前添加@Valid注解
public Result<Boolean> doLogin(@Valid LoginVo loginVo)
3.校验类上添加注解
public class LoginVo {
@NotNull
private String mobile;
@NotNull
@Max(32)
@Min(6)
private String password;
}
2.自定义参数校验器
1.模仿提供的注解实现自定义注解
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
validatedBy = {IsMobileValidator.class} //此处的validateBy指的是校验逻辑类
)
public @interface IsMobile {
String message() default "{javax.validation.constraints.NotNull.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
boolean required() default true;
}
2.实现校验逻辑类
//<T,E> 这里的T指的是注解类型 E指的是需要校验数据的类型
public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
private boolean required = false;
@Override
public void initialize(IsMobile isMobile) {//利用此处可以获取原注解中方法默认参数
required = isMobile.required();
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if(required){
return ValidatorUtils.isMobile(s);
}else{
if (StringUtils.isEmpty(s)) {
return true;
}else{
return ValidatorUtils.isMobile(s);
}
}
}
}