Java 数据验证

 

在web开发当前就会遇到一些数据有效性验证的相关代码编写。

一般的写法如:

 

public class User {
    public String username;
    public String password;
    public Integer age;
}

 

 

 

public addUser(User user) {

    String username = user.getUsername();
    Integer age = user.getAge();
    String password = user.getPassword();

    String errorMsg = "";
    if(username == null || username.equals("") {
        errotMsg += "用户名不可为空";
    }

    // ..........很多if,有多少个写多少个,太机械了。就一代码搬运工。

}

 

 

 

java 后台验证相关问题:

 

javax.validation.Validator

org.hibernate.validator.internal.engine.ValidatorImpl

 

1、User添加注释

public class User {
    @NotNull
    public String username;

    @NotNull
    public String password;

    @NotNull
    public Integer age;
}

public addUser(User user) {
    Iterator<ConstraintViolation<Object>> iterator = validator.validate(user)
    StringBuilder buf = new StringBuilder(256);
    while (iterator.hasNext()) {
        buf.append(";");
        ConstraintViolation<?> elem = iterator.next();
        if (elem != null) {
            buf.append(elem.getPropertyPath() + elem.getMessage());
        }
    }
    System.out.println(buf);
}

 

 

 

utils 拿去用吧。

public class Validators {

    private static class ValidatorHolder {
        static Validator validator = new Validators().getValidator();
    }

    private final Logger logger = LoggerFactory.getLogger(Validators.class);

    private final ValidatorFactory factory;

    private Validators() {
        try {
            Configuration<?> factoryCfg = Validation.byDefaultProvider().configure();
            factory = factoryCfg.buildValidatorFactory();
        } catch (final ValidationException ex) {
            logger.error("Bean Validation provider can not be found, no validation will be performed");
            throw ex;
        }
    }

    private Validator getValidator() {
        return factory.getValidator();
    }

    /**
     * 校验指定bean的单个属性值
     * @param bean 需要校验的bean
     * @param name 需要校验的属性名
     * @return 需要校验的属性的错误信息
     */
    public static String validateProperty(Object bean, String name) {
        return parseConstraintViolations(ValidatorHolder.validator.validateProperty(bean, name));
    }

    /**
     * 校验指定bean的全部属性
     * @param bean 需要校验的bean
     * @return 所有错误信息
     */
    public static String validate(Object bean) {
        return parseConstraintViolations(ValidatorHolder.validator.validate(bean));
    }

    public static String parseConstraintViolations(Set<ConstraintViolation<Object>> constraintViolations) {
        if (CollectionUtils.isEmpty(constraintViolations)) {
            return null;
        }

        Iterator<ConstraintViolation<Object>> iterator = constraintViolations.iterator();

        ConstraintViolation<Object> first = iterator.next();
        //单个校验错误
        if (!iterator.hasNext()) {
            return  first.getPropertyPath() + first.getMessage();
        }

        // two or more elements
        StringBuilder buf = new StringBuilder(256);             //Java default is 16, probably too small
        if (first != null) {
            buf.append(first.getPropertyPath() + first.getMessage());
        }

        while (iterator.hasNext()) {
            buf.append(";");
            ConstraintViolation<?> elem = iterator.next();
            if (elem != null) {
                buf.append(elem.getPropertyPath() + elem.getMessage());
            }
        }

        return buf.toString();
    }

}

 

 

 

你可能感兴趣的:(Java 数据验证)