validation校验----可以用来对于请求bean的必填参数进行校验

validation的另一种用法,这种用法更加简单便捷
校验工具类:

package com.alibaba.banff.web.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

    /**
     * 校验工具类
     * 
     * @author lizhilong
     */
    public class ValidationUtils {
    
        private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    
        public static  ValidationResult validateEntity(T obj) {
            ValidationResult result = new ValidationResult();
            Set> set = validator.validate(obj, Default.class);
            // if( CollectionUtils.isNotEmpty(set) ){
            if (set != null && set.size() != 0) {
                result.setHasErrors(true);
                Map errorMsg = new HashMap();
                for (ConstraintViolation cv : set) {
                    errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
                }
                result.setErrorMsg(errorMsg);
            }
            return result;
        }

    public static  ValidationResult validateProperty(T obj, String propertyName) {
        ValidationResult result = new ValidationResult();
        Set> set = validator.validateProperty(obj, propertyName, Default.class);
        if (set != null && set.size() != 0) {
            result.setHasErrors(true);
            Map errorMsg = new HashMap();
            for (ConstraintViolation cv : set) {
                errorMsg.put(propertyName, cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }
}

校验工具类返回的数据ValidationResult(省略getset)

package com.aliyun.prophet.facade.partner.flaw;
import java.util.Map;

/**
 * 校验结果
 * 
 * @author lizhilong
 */
public class ValidationResult {

    // 校验结果是否有错
    private boolean             hasErrors;

    // 校验错误信息
    private Map<String, String> errorMsg;
}



Person类(省略getset):

package com.aliyun.prophet.facade.partner.flaw;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;

public class Person {
    @Length(max=20,message="姓名长度不能大于20")
    @NotEmpty(message="姓名不能为空")
    private String name;
    @Range(min = 0, max = 1, message = "性别只能输入只能输入0或1")
    private Integer gender;
    private Integer age;
}


使用方法:

/**
 * 
 * @author: lizhilong
 */
public class Test {
    @org.junit.Test
    public void testValidation(){
        Person person = new Person();
        person.setAge(12);
        person.setGender(2);
//       person.setName("李智龙");
        ValidationResult result = ValidationUtils.validateEntity(person);
        Map map = result.getErrorMsg();
        boolean isError = result.isHasErrors();
        System.out.println("isError: " +isError);
        System.out.println(map);
    }
}
打印结果:

isError: true
{gender=性别只能输入只能输入0或1, name=姓名不能为空}

对于ValidationResult校验结果我们还可以进一步的封装

/**
     *这个方法的作用就是对于ValidationResult  返回结果
     *
     * @param request
     */
    private String validateParam(S request) {
        StringBuilder sbd = new StringBuilder();
        ValidationResult result = ValidationUtil.validateEntity(request);
        if (result.isHasErrors()) {
            result.getErrorMsg().forEach((k, v) -> {
                sbd.append(v).append("&");
            });
        }
        return sbd.deleteCharAt(sbd.length() - 1).toString();
    }

validation结合spring用法,其中包含注解的含义,链接地址:javax.validation结合spring最佳实践,

你可能感兴趣的:(validation校验----可以用来对于请求bean的必填参数进行校验)