@valid 手动验证

diy valid 手动验证


常用于操作时候验证数据,增加其准备性。

import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.*;

/**
 * @author wl
 * @date 2020/7/15
 */
public class ValidatorUtils {
    private static Validator validator =  Validation.buildDefaultValidatorFactory()
            .getValidator();

    public static void beanValidate(@Valid Object obj) throws IllegalArgumentException {

        if (obj instanceof Collection){
            ValidCollection validCollection = new ValidCollection();
            validCollection.setList((Collection) obj);
            validate(validCollection);
        }else {
            validate(obj);
        }
    }

    public static void validate(@Valid Object obj) {
        Map<String, String> validatedMsg = new HashMap<>();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
        for (ConstraintViolation<Object> c : constraintViolations) {
            validatedMsg.put(c.getPropertyPath().toString(), c.getMessage());
        }
        Assert.isTrue(ObjectUtils.isEmpty(constraintViolations), validatedMsg.toString());
    }

    /**
     * 导入时验证。若不存在,抛出异常
     * @param addDtos
     */
    public static void verifyImportParam(List<?> addDtos) {
        ArrayList<String> list = new ArrayList<>();
        StringBuilder sb = null;

        Validator validator =  Validation.buildDefaultValidatorFactory()
                .getValidator();
        for (int i = 1; i <= addDtos.size(); i++) {
            sb = new StringBuilder();
            Object item = addDtos.get(i - 1);
            Set<ConstraintViolation<Object>> constraintViolations = validator.validate(item);
            for (ConstraintViolation<Object> c : constraintViolations) {
                sb.append(c.getPropertyPath().toString()).append(":").append(c.getMessage()).append(";");
            }
            if (!StringUtils.isEmpty(sb.toString())) {
                list.add("第" + i + "条:" + sb.toString());
            }
        }
        Assert.isTrue(ObjectUtils.isEmpty(list), list.toString());
    }

    private static class ValidCollection<T> {
        @Valid
        private Collection<T> list;

        public Collection<T> getList() {
            return list;
        }

        public void setList(Collection<T> list) {
            this.list = list;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值