引入包
org.springframework.boot:spring-boot-starter-validation
参数校验
@Getter
@Setter
@ToString
public class LoginVo {
@NotBlank
@Pattern(regexp = "\\d")
private String id;
@NotBlank
private String password;
}
获得校验结果
方法1:Errors
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
@PostMapping("/login")
@ResponseBody
public boolean doLogin(@Valid LoginVo vo, Errors errors) {
for (ObjectError error : errors.getAllErrors()) {
System.out.println(error);
}
if (errors.hasErrors()) {
return false;
}
return loginService.login(vo);
}
方法2:异常处理器 (推荐)
@PostMapping("/login")
@ResponseBody
public boolean doLogin(@Valid LoginVo vo) {
return loginService.login(vo);
}
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(BindException.class)
public List validationHandler(BindException e) {
return e.getAllErrors();
}
}
可用的校验约束
javax.validation.constraints
org.hibernate.validator.constraints
自定义校验
注解
将要添加到校验字段上的约束注解
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {MobileValidator.class})
public @interface Mobile {
boolean required() default true;
String message() default "手机号码格式错误";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
校验器
public class MobileValidator implements ConstraintValidator {
/**
* Pattern对象是线程安全的
* Instances of this class are immutable and are safe for use by multiple
* concurrent threads. Instances of the {@link Matcher} class are not safe for
* such use.
*
* 正则表达式来自网络
*/
private static final Pattern MOBILE_PATTERN = Pattern.compile("^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\\d{8}$");
private boolean required = false;
@Override
public void initialize(Mobile constraintAnnotation) {
this.required = constraintAnnotation.required();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return valid(value, this.required);
}
public static boolean valid(String value, boolean required) {
if (StringUtils.hasText(value)) {
var matcher = MOBILE_PATTERN.matcher(value);
return matcher.matches();
} else {
return !required;
}
}
}