添加依赖
<!--validation组件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
使用@Valid注解
public RespBean doLogin(@Valid LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
return iUserService.doLogin(loginVo,request,response);
}
当使用了@Valid注解,LoginVo类里变量的注解才会生效
import com.xxxx.seckill.validator.IsMobile;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
@Data
public class LoginVo {
@NotNull
@IsMobile//自动校验
private String mobile;
@NotNull
@Length(min=32)
private String password;
}
自定义注解
import com.xxxx.seckill.vo.IsMobileValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
//检验手机号的标准
@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 {};
}
这个上边的注解其实都是从NotNull注解里粘过来做了点小改动的,
@Constraint( validatedBy = {IsMobileValidator.class})表示引入IsMobileValidator类
import com.xxxx.seckill.utils.ValidatorUtil;
import com.xxxx.seckill.validator.IsMobile;
import org.thymeleaf.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
//创建自定义规则
public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
private boolean required=false;
@Override
public void initialize(IsMobile constraintAnnotation) {
//初始化,判断是否是必填的
required=constraintAnnotation.required();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if(required) {//如果是必填的
return ValidatorUtil.isMobile(value);
}
else {//如果是非必填
if(StringUtils.isEmpty(value)) {//如果value是空的,则直接返回true
return true;
}
else {//如果不是空,则校验
return ValidatorUtil.isMobile(value);
}
}
}
}
ValidatorUtil类
import org.springframework.util.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//校准手机号格式
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();
}
}
这样判断获得的字符串是不是电话号码的注解就自定义好了。