1、首先进行validation组件的依赖导入。

<!-- validation组件-->
    	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <!--版本跟springBoot保持一致-->
        </dependency>

2、在所需要校验参数前添加 @Valid

/**
    * @Description  登录功能
    * @Date 17:20 2022/7/29
    * @Param [loginVo] 中包含了 String mobile 属性
    * @return com.xxxx.seckill.vo.RespBean
    **/
    @RequestMapping("doLogin")
    @ResponseBody
    public RespBean doLogin(@Valid LoginVo loginVo, HttpServletRequest request, HttpServletResponse response){
        log.info("{}",loginVo);
        return userService.doLogin(loginVo, request,response);
    }

3、创建手机号码的校验规则ValidatorUtil类

import org.thymeleaf.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 1.0
 * @description:  手机号码校验类
 * @date 2022/7/29 16:02
 */
public class ValidatorUtil {
		//正则表达式
    private static final Pattern mobile_patten = Pattern.compile("[1]([3-9])[0-9]{9}$");

   /**

    * @Description   手机号码验证方法
    * @Date 16:54 2022/7/29
    * @Param [mobile]
    * @return boolean
    **/
    public static boolean isMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        //匹配原则
        Matcher matcher = mobile_patten.matcher(mobile);
        return matcher.matches();
    }
}

4、找到参数 loginVo

/**
 * @author heyanfeng
 * @version 1.0
 * @description:  登录传来的参数
 * @date 2022/7/29 16:10
 */
@Data
public class LoginVo {
    @NotNull
    @IsMobile
    private String mobile;

    @NotNull
    private String password;
}

5、观察@NotNull注解,对validation组件中的 @NotNull注解进行粘贴、改造出我们可用的 @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 {};
}

6、为了使注解可用,创建IsMobileValidator校验规则类,更具提示更改添加代码。

import com.xxxx.seckill.utils.ValidatorUtil;
import org.thymeleaf.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


/**
 * @Description    IsMobileValidator
 * @Date 17:45 2022/7/29
 * @Param
 * @return
 **/
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
    //  ConstraintValidator.super.initialize(constraintAnnotation);
        //初始化时先获取他是否为必填信息
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (required) {
            //必填则校验手机号
            return ValidatorUtil.isMobile(s);
        } else {
            //非必填直接返回ture
            if (StringUtils.isEmpty(s)) {
                return true;
            } else {
                return ValidatorUtil.isMobile(s);
            }
        }
    }
}

7、输入错误的手机格式进行校验,发现成功的拦截
在这里插入图片描述
8、由于这里没有进行异常的处理,所以只会报错在控制台。针对本异常应创建异常处理枚举,以统一交付的方式,报错添加错误信息返回给前端。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐