权限之参数的校验工具-validator(重点)需复习

第一步:在pom.xml添加依赖

    
    
      javax.validation
      validation-api
      1.1.0.Final
    
    
      org.hibernate
      hibernate-validator
      5.2.4.Final
    

第二步:写BeanValidator类

package com.mall.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mall.exception.ParamException;
import org.apache.commons.collections.MapUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

public class BeanValidator {

    private static ValidatorFactory validatorFactory= Validation.buildDefaultValidatorFactory();

    public static Map validate(T t,Class... groups){
        Validator validator=validatorFactory.getValidator();
        Set validateResult=validator.validate(t,groups);
        if(validateResult.isEmpty()){
            return Collections.emptyMap();
        }else{
            LinkedHashMap errors= Maps.newLinkedHashMap();
            Iterator iterator=validateResult.iterator();
            while(iterator.hasNext()){
                ConstraintViolation violation= (ConstraintViolation) iterator.next();
                errors.put(violation.getPropertyPath().toString(),violation.getMessage());
            }
            return errors;
        }
    }

    public static Map validateList(Collection collection){
        //判断是否为空值
        Preconditions.checkNotNull(collection);
        Iterator iterator=collection.iterator();
        Map errors;
        do{
            if(!iterator.hasNext()){
                return Collections.emptyMap();
            }
            Object object=iterator.next();
            errors=validate(object,new Class[0]);
        }while(errors.isEmpty());
        return errors;
    }

    public static Map validateObject(Object first,Object... objects){
        if(objects!=null&&objects.length>0){
            return validateList(Lists.asList(first,objects));
        }else{
            return validate(first,new Class[0]);
        }
    }

    public static void check(Object param) throws ParamException {
        Map map=BeanValidator.validateObject(param);
        if(MapUtils.isNotEmpty(map)){
            throw new ParamException(map.toString());
        }
    }
}

第三步:书写请求参数的封装类

package com.mall.param;

import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

@Getter
@Setter
public class TestVo {
    @NotBlank
    private String msg;
    @NotNull
    @Max(value=10,message="id不能大于10")
    @Min(value=0,message="id至少大于0")
    private Integer id;
    @NotEmpty
    private List str;
}

第四步:实现请求

    @RequestMapping("/validate.json")
    @ResponseBody
    public JsonData validate(TestVo testVo) throws ParamException {
        log.info("validate");
        BeanValidator.check(testVo);
//        try{
//            Map map= BeanValidator.validateObject(testVo);
//            if(MapUtils.isNotEmpty(map)){
//                for(Map.Entry entry:map.entrySet()){
//                    log.info("{}{}",entry.getKey(),entry.getValue());
//                }
//            }
//        }catch(Exception e){
//
//        }
        return JsonData.success("test validate");
    }

 

你可能感兴趣的:(java)