Spring Hibernate编码形式参数校验

参考 

https://blog.csdn.net/xing930408/article/details/90297759

https://blog.csdn.net/Summer_Lyf/article/details/85931133


        <!-- validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.14.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.1-b06</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.6</version>
        </dependency>

校验工具类

public class BeanValidator {

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static <T> String validate(T t) {
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t);
        //如果校验有值
        if (validateResult.isEmpty()) {
            return null;
        } else {
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation violation = (ConstraintViolation) iterator.next();
                return violation.getMessage();
            }
            return null;
        }
    }

}

使用方式

        // 传入需要校验的对象
        String errorMessage = BeanValidator.validate(new Object());
        if (errorMessage != null) {
            return Result.fail(errorMessage);
        }

 

展开阅读全文

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

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读