Java中的参数验证(非Spring版)

2019-10-23  本文已影响0人  老梁Java

1. Java中的参数验证(非Spring版)

1.1. 前言

    <!--jsr 303-->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    @PostMapping("/save/valid")
    public RspDTO save(@RequestBody @Validated UserDTO userDTO) {
        userService.save(userDTO);
        return RspDTO.success();
    }
@Data
public class UserDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    /*** 用户ID*/
    @NotNull(message = "用户id不能为空")
    private Long userId;
    
    /** 用户名*/
    @NotBlank(message = "用户名不能为空")
    @Length(max = 20, message = "用户名不能超过20个字符")
    @Pattern(regexp = "^[\\u4E00-\\u9FA5A-Za-z0-9\\*]*$", message = "用户昵称限制:最多20字符,包含文字、字母和数字")
    private String username;
    
    /** 手机号*/
    @NotBlank(message = "手机号不能为空")
    @Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "手机号格式有误")
    private String mobile;

    /**性别*/
    private String sex;

    /** 邮箱*/
    @NotBlank(message = "联系邮箱不能为空")
    @Email(message = "邮箱格式不对")
    private String email;

    /** 密码*/
    private String password;

    /*** 创建时间 */
    @Future(message = "时间必须是将来时间")
    private Date createTime;

}

1.2. 方案

1.2.1. 主方法

import org.springframework.validation.annotation.Validated;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Date;
import java.util.Set;
import java.util.stream.Stream;

/**
 * @author laoliangliang
 * @date 2019/10/22 15:19
 */
public class ValidLearn {
    public static void main(String[] args) {
        ValidLearn learn = new ValidLearn();
        learn.testValid(new Order().setIdcard("33062119981012361X").setName("  ").setCreateDate(new Date()));
    }

    public void testValid(@Validated Order order) {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        //分组Insert.class则id为空不检验
        Set<ConstraintViolation<Order>> validate = validator.validate(order, Insert.class);
        Stream.of(validate).forEach(action -> {
            for (ConstraintViolation<Order> orderConstraintViolation : action) {
                String message = orderConstraintViolation.getMessage();
                System.out.println(message);
            }
        });
    }
}

1.2.2. 实体类

/**
 * @author laoliangliang
 * @date 2019/10/21 16:44
 */
@Data
@Accessors(chain = true)
public class Order {

    @NotNull(message = "id不能为空",groups = Update.class)
    private Long id;

    @NotEmpty(message = "name is not null",groups = Insert.class)
    private String name;

    @Future(message = "必须之后的时间")
    private Date createDate;

    @IdCardValid(message = "idcard 不合法")
    private String idcard;
}

1.2.3. group分组

import javax.validation.groups.Default;

/**
 * @author laoliangliang
 * @date 2019/10/22 16:32
 */
public interface Update extends Default {
}
import javax.validation.groups.Default;

/**
 * @author laoliangliang
 * @date 2019/10/22 16:32
 */
public interface Insert extends Default {
}

1.2.4. 自定义注解

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author laoliangliang
 * @date 2019/10/22 15:55
 */
public class IdCardValidator implements ConstraintValidator<IdCardValid, Object> {

    private Pattern pattern = Pattern.compile("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])" +
            "\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
    @Override
    public void initialize(IdCardValid idCardValid) {
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        Matcher matcher = pattern.matcher(o.toString());
        return matcher.matches();
    }
}
/**
 * @author laoliangliang
 * @date 2019/10/22 15:53
 */
@Documented
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IdCardValidator.class)
public @interface IdCardValid {

    String message() default "身份证不合法";

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

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

1.3. 总结

欢迎访问收藏作者知识点整理,没注册的请点击这里

上一篇下一篇

猜你喜欢

热点阅读