zoukankan      html  css  js  c++  java
  • hibernate validator工具类

    一、相关的gradle配置文件

       // https://mvnrepository.com/artifact/javax.el/javax.el-api
        compile group: 'javax.el', name: 'javax.el-api', version: '3.0.0'
        // https://mvnrepository.com/artifact/org.glassfish.web/javax.el
        compile group: 'org.glassfish.web', name: 'javax.el', version: '2.2.6'
        // https://mvnrepository.com/artifact/org.hibernate/hibernate-validator
        compile group: 'org.hibernate', name: 'hibernate-validator', version: '5.4.1.Final'

    二、validate接口支持泛型参数

    public static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        
        public String validObject(Object msg) {
            String result = ConstantUtil.VALID_PASS;
            Validator validator = factory.getValidator();
            Set<ConstraintViolation<Object>> constraintViolations = validator.validate(msg);
            if(constraintViolations.isEmpty()){
                return result; 
            }
            StringBuffer buff = new StringBuffer();
            for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
                buff.append(constraintViolation.getInvalidValue());
                buff.append(":");
                buff.append(constraintViolation.getMessage());
                buff.append("!
    ");
            }
            return buff.toString().substring(0,buff.toString().length()-1);
        }

    三、调用示例

    public MsgBaseResponse processEmService(Emp em) {
            MsgBaseResponse response = new MsgBaseResponse();
            String validResult = validUtil.validObject(em);
            if (validResult.equals(ConstantUtil.VALID_PASS)) {
                //TODO: the Operate and data.
                System.out.println("valid success, can write to store.");
                response.setData("");
            } else {
                response.setResult(-1);
                response.setData(validResult);
            }
            return response;
  • 相关阅读:
    Postman:Pre-request Script
    PHP修改脚本最大执行时间和最大内存限制
    PHP函数:array_chunk
    PHP出现SSL certificate:unable to get local issuer certificate的解决办法
    Linux命令:chown
    PHP函数:fopen
    PHP常量:JSON_UNESCAPED_UNICODE
    Android -- 贝塞尔曲线公式的推导和简单使用
    Java -- 浅入Java反射机制
    Java -- 深入浅出GC自动回收机制
  • 原文地址:https://www.cnblogs.com/yoyotl/p/6946618.html
Copyright © 2011-2022 走看看