org.springframework.boot
spring-boot-starter-validation
2.编写检索电话号自定义注解:
2.1:编写测试接口
@PostMapping("/doLogin")
@ResponseBody
public String doLogin(@Valid LoginVo loginVo){
return "测试成功!";
}
2.2:编写LoginVo实体
@Data
public class LoginVo {
@NotNull(message = "电话号不能为空!")//不能为空
@IsMobile//自定义检索电话号注解
private String mobile;
@NotNull//不能为空
@Length(message = "密码不能为空!")(min = 32)//限制密码最短长度
private String password;
}
2.3:编写返回vo实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RespBean {
private long code;//状态码
private String message;//信息
private Object data;//数据
public static RespBean success(String msg){
return new RespBean(200, msg, null);
}
public static RespBean error(String msg){
return new RespBean(500, msg, null);
}
}
2.4:编写@IsMobile注解类
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@documented
@Constraint(validatedBy = {IsMobilevalidator.class})
public @interface IsMobile {
boolean required() default true;//默认参数为必填
String message() default "手机号码格式错误!";//如果手机号格式不对则会抛异常
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
2.5:编写手机号校验工具类
public class ValidatorUtil {
private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$");
public static Boolean isMobile(String mobile){
if (StringUtils.isEmpty(mobile)){//判断电话号是否为空
return false;
}
Matcher matcher = mobile_pattern.matcher(mobile);//使用正则判断
return matcher.matches();
}
}
2.6:编写自定义参数检索注解类
public class IsMobilevalidator implements ConstraintValidator{ private boolean required = false; @Override public void initialize(IsMobile constraintAnnotation) { required = constraintAnnotation.required();//设置参数不能为空 } @Override public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { if (required){//如果参数不为空则判断电话号是否正确 return ValidatorUtil.isMobile(value); }else { if (StringUtils.isEmpty(value)){ return true; }else { return ValidatorUtil.isMobile(value); } } } }
前端代码省略。。。
2.8:测试结果:
通过测试控制台会抛出一个BindException异常 接下来编写全局异常捕获。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BindException.class)
public RespBean exceptionHandler(BindException e){
if (e instanceof BindException){
return RespBean.error(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());//获取注解中message值
}
return RespBean.error("服务器异常!");
}
}
3.1:测试结果


