概述
最近在学习某课的《Java秒杀系统方案优化 高性能高并发实战》,写篇文章来记录一下知识点
Validator
springboot validation为我们提供了常用的校验注解,比如@notNull
,@notBlant
等注解,但有时候这些并不能满足我们的需求。
比如当用户登录的时候需要输入手机号和密码,那么如何判断手机号码格式是否正确呢,这时就需要我们自定义Validator
来校验手机号码
首先在pom.xml引入spring-boot-starter-validation
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
编写ValidatorUtil
工具类,使用正则表达式判断试机号码是否为以1开头的11位数字
/*判断手机号格式是否正确*/
public class ValidatorUtil {
//正则表达式:1\d{10}表示1后面接10位数字
private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}");
public static boolean isMobile(String src) {
if (StringUtils.isEmpty(src)) {
return false;
}
Matcher m = mobile_pattern.matcher(src);
//如果匹配则返回true
return m.matches();
}
}
自定义@IsMobile
来校验前端发送过来的手机号格式是否正确
/**
* 配置 @IsMobile 注解
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})//指定使用范围
@Retention(RUNTIME)////该注解被保留的时间长短 RUNTIME:在运行时有效
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})//指定校验器
public @interface IsMobile {
//是否是必需字段,默认为true
boolean required() default true;
String message() default "手机号码格式错误";
//下面两行是自定义注解需要添加的
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@Target
:表示修饰的范围@Retention
:表示注解被保留的时间长短@Constraint
:指定处理校验规则的类String message()
: 必须有的注解属性字段,该字段是用来定义不符合规则错误信息提示用的boolean required()
:自定义的注解熟悉字段,该字段表示被@IsMobile标注的字段是否是必需字段
可以看到我们在@Constraint(validatedBy = {IsMobileValidator.class})
指定了校验器,接下来看看校验器的实现:
IsMobileValidator
校验器
/**
* 参数校验器
*/
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {
private boolean required = false;
public void initialize(IsMobile constraintAnnotation) {
required = constraintAnnotation.required();
}
//校验
public boolean isValid(String value, ConstraintValidatorContext context) {
if (required) {
//调用工具类对手机号码进行校验
return ValidatorUtil.isMobile(value);
} else {
if (StringUtils.isEmpty(value)) {
return true;
} else {
return ValidatorUtil.isMobile(value);
}
}
}
}
可以看到自定义的校验器需要实现ConstraintValidator
接口实现 initialize
和 isValid
方法,逻辑很简单这里就不多说了,然后来看看如何使用@IsMobile注解:
在mobile字段上标注@IsMobile
注解,在controller对需要校验的参数标注@Valid
注解
/**
* 实体类
*/
public class LoginVo {
@NotNull
//自定义注解
@IsMobile
private String mobile;
@NotNull
@Length(min = 32)
private String password;
/**
* 控制器
*/
@Controller
@RequestMapping("/login")
public class LoginController {
@RequestMapping("/do_login")
@ResponseBody
public Result<Boolean> doLogin(@Valid LoginVo loginVo) {//在需要校验的参数前添加@Valid注解
//登录
userService.login(loginVo);
return Result.success(true);
}
}
Validator校验失败会抛出BindExeption
异常,捕获后返回给前端错误信息
发表回复