【SpringBoot】jsr303参数校验

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sms15732621690/article/details/81271656

场景 

       登录验证

       手机号

       密码

实现

引入依赖jar包

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
 </dependency>

添加@Valid注解

自定义mobile参数校验

创建注解接口mobile

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Created by sms on 2018/7/24.
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)  // 约束注解应用的时机
@Documented
@Constraint(validatedBy = {IsMobileValidator.class }) // 与约束注解关联的验证器
public @interface IsMobile {

    boolean required() default true;

    String message() default "手机号码格式有误";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

}

创建注解的实现类IsMobileValidator

import com.imooc.miaosha.util.ValidatorUtil;
import org.springframework.util.StringUtils;

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

/**
 * Created by sms on 2018/7/24.
 */
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)){
               return true;
           }else {
               return ValidatorUtil.isMobile(value);
           }
       }
    }
}

应用注解的实体类

public class LoginVo {

    @NotNull
    @IsMobile
    private String mobile;
    @NotNull
    @Length(min=6)
    private String password;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "LoginVo{" +
                "mobile='" + mobile + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

 

展开阅读全文

没有更多推荐了,返回首页