自定义工具类实现validate参数校验

前言

博主github

博主个人博客http://blog.healerjean.com

相信项目中做一些htttp接口,避免不了要对参数进行校验,大多数情况下,其实我们只是校验是否为NULL就可以了

1、通过注解实现各种状态的字段

1.1、引入依赖

默认的版本是6.0.9.Final 使用过程中NotBlank会显示红色,所以这里讲版本降低,这样就不会显示红色了

   <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-validatorartifactId>
            <exclusions>
                <exclusion>
                    <artifactId>validation-apiartifactId>
                    <groupId>javax.validationgroupId>
                exclusion>
            exclusions>
            
            <version>4.3.2.Finalversion>
        dependency>
        <dependency>
            <artifactId>validation-apiartifactId>
            <groupId>javax.validationgroupId>
        dependency>


1.2、注解

  • 1、如果变量传入的时候是NULL,则不会校验 类似于 @AssertTrue @Size(min=, max=) 等

  • 2、为了我们以后方便, 所有校验属性必须加组,方便阅读



空检查
@Null       验证对象是否为null
@NotNull    验证对象是否不为null, 无法查检长度为0的字符串
Hibernate 
@NotEmpty   检查约束元素是否为NULL或者是EMPTY.
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.

Booelan检查
@AssertTrue     验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  
 
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=) 验证字符串的长度
 
日期检查
@Past           验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern(regexp="[1-9]{1,3}", message="数量X: 必须为正整数,并且0

1.3、config

@Configuration
public class ValidatorConfiguration {


    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
        processor.setValidator(validator());
        return processor;
    }

    @Bean
    public static Validator validator() {
        return ValidateUtils.validator;
    }
}

1.3、DTO类

1.3.1、被校验对象 JavaBean

package com.hlj.vialidate.data;

import com.hlj.vialidate.ValidateGroup;
import com.hlj.vialidate.inter.NameInclude;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;

/**
 * @author HealerJean
 * @version 1.0v
 * @Description
 * 注意点
 * 1、 下面出了判断空的注解之外,必须有值才回校验
 * 2、 所有校验属性必须加组,方便阅读
 * @ClassName JavaBean
 * @date 2019/4/17  14:08.
 */
@Data
public class JavaBean  extends BaseBean{


    @NotBlank(message = "name 为空 ",groups = ValidateGroup.HealerJean.class)
    @Size(min = 1,max = 5,message = "name  @Size(min = 1,max = 5  字符串长度 最低为1 最大为5",groups = ValidateGroup.HealerJean.class)
    private String name ;

    @Size(min = 1,max = 2, message = "list @Size(min = 1,max = 2 集合大小 最低为1 最大为2",groups = ValidateGroup.HealerJean.class)
    private List<String> list;

    @Length(min = 1,max = 5,message = "@Length(min = 1,max = 5 字符串长度 最低为1 最大为5",groups = ValidateGroup.HealerJean.class)
    private String strLength;

    @Min(value = 5,         message = "strNum  @Min(value = 5,message =  字符串(数字的字符串大小判断)【数字类型的变量都可以】",groups = ValidateGroup.HealerJean.class)
    private String strNum ;

    @Range(min = 1,max = 10 ,message = "strRange @Range(min = 1,max = 10  最小为1,最大为10  ",groups = ValidateGroup.HealerJean.class)
    private String strRange ;

    @DecimalMin(value = "100.1",message = "小数值的判断,最小为 100.1",groups = ValidateGroup.HealerJean.class)
    private String strDecimal ;

    @Digits(integer = 2,fraction = 2,message = "strDigts  @Digits(integer = 2,fraction = 2  整数最高2位,小数最高2位",groups = ValidateGroup.HealerJean.class)
    private String strDigts;

    @AssertFalse(message = " @AssertFalse 必须为false " ,groups = ValidateGroup.HealerJean.class)
    private Boolean assertFalse ;

    /**
     * 内部对象校验
     */
    @Valid
    @NotNull(message = "内部对象不能为空" ,groups = ValidateGroup.HealerJean.class)
    private InnerBean innerBean ;

    /**
     * 自定义注解校验
     */
    @NameInclude(message = "类型必须是type value必须是HealerJean" ,type = "Mail",groups = {ValidateGroup.HealerJean.class})
    private String myName ;




}

1.3.2、父类

package com.hlj.vialidate.data;

import com.hlj.vialidate.ValidateGroup;
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;

/**
 * @author HealerJean
 * @version 1.0v
 * @ClassName BaseBean
 * @date 2019/6/11  16:38.
 * @Description
 */
@Data
public class BaseBean {

    @NotBlank(message = "父类String 不能为空",groups = ValidateGroup.HealerJean.class)
    private String fatherString;

}

1.3.3、内部使用使用类

package com.hlj.vialidate.data;

import com.hlj.vialidate.ValidateGroup;
import lombok.Data;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;

/**
 * @author HealerJean
 * @version 1.0v
 * @ClassName InnerBean
 * @date 2019/6/11  16:39.
 * @Description
 */
@Data
public class InnerBean {

    @NotBlank(message = "innerBean不能为空",groups = ValidateGroup.HealerJean.class)
    @Length(max = 2,message = "innerNname 长度最长为2",groups = ValidateGroup.HealerJean.class)
    private String innerNname ;
}

1.4、校验工具类

package com.hlj.utils;

import com.hlj.data.general.AppException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @Description 校验工具
 */
public class ValidateUtils {

    public static Validator validator;

    static {

        validator = Validation
                .byProvider(HibernateValidator.class)
                .configure()
                //快速返回模式,有一个验证失败立即返回错误信息
                .failFast(true)
                .buildValidatorFactory()
                .getValidator();
    }

    /**
     * 静态方法校验使用的
     *
     * @param object
     * @return
     */
    public static String validate(Object object) {
        if(object == null){
            throw new AppException("参数不完整");
        }
        Set<ConstraintViolation<Object>> validate = validator.validate(object);
        return resultValidate(validate);

    }

    /**
     * 静态方法校验使用,并且带分组的
     *
     * @param object
     * @param group
     * @return
     */
    public static String validate(Object object, Class group) {
        if (group == null) {
            return validate(object);
        } else {
            Set<ConstraintViolation<Object>> validate = validator.validate(object, group);
            return resultValidate(validate);
        }
    }


    private static String resultValidate(Set<ConstraintViolation<Object>> validate) {
        if (!validate.isEmpty()) {
            final StringBuffer stringBuffer = new StringBuffer();
            validate.stream().forEach(
                    item -> stringBuffer.append(item.getMessage()).append(","));
            stringBuffer.setLength(stringBuffer.length() - 1);
            return stringBuffer.toString();
        }
        return "success";
    }

}

1.5、组

package com.hlj.vialidate;

/**
 * @author HealerJean
 * @version 1.0v
 * @Description
 * @ClassName CoreValidateGroup
 * @date 2019/4/17  9:30.
 */
public class ValidateGroup {

    public interface HealerJean {};

}

1.6 、测试

1.6.1、Controller

package com.hlj.moudle.validate;


import com.hlj.data.general.ResponseBean;
import com.hlj.utils.ValidateUtils;
import com.hlj.vialidate.data.JavaBean;
import com.hlj.vialidate.ValidateGroup;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @Description
 * @Author HealerJean
 * @Date 2018/3/22  上午10:22.
 */
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "访问正常"),
        @ApiResponse(code = 301, message = "逻辑错误"),
        @ApiResponse(code = 500, message = "系统错误"),
        @ApiResponse(code = 401, message = "未认证"),
        @ApiResponse(code = 403, message = "禁止访问"),
        @ApiResponse(code = 404, message = "url错误")
})
@Api(description = "demo控制器")
@Controller
@RequestMapping("hlj")
@Slf4j
public class VialidateController {


    @ApiOperation(value = "Post接口",
            notes = "Post接口",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = ResponseBean.class
    )
    @PostMapping( value = "validate",produces="application/json;charset=utf-8")
    @ResponseBody
    public ResponseBean post(@RequestBody JavaBean JavaBean){
        String validate = ValidateUtils.validate(JavaBean,ValidateGroup.HealerJean.class);
        if(!"success".equals(validate)){
            log.info("错误信息:{}", validate);
        }
        return ResponseBean.buildSuccess(validate);
    }


}



1.6.2、测试样例

POST http://localhost:8888/hlj/validate
Content-Type: application/json; charset=UTF-8

{
  "name":"1234",
  "strLength":"12345",
  "list": ["list","list2"],
  "strNum":"6",
  "strRange":"9",
  "strDecimal":"100.2",
  "strDigts":"15.66",
  "fatherString":"fatherString",
  "innerBean":{
    "innerNname":"in"
  },
}

2、自定注解实现

可以用于字典校验

4.1、自定义注解

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 自定义注解
 */
@Constraint(validatedBy = {NameIncludeValidator.class})
@Documented
@Target( {  ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface NameInclude {

    String message() ; //报错返回的信息

    Class<?>[] groups() default { }; //被哪个组校验

    String type() ; //自己定义的

    Class<? extends Payload>[] payload() default { };
}

4.2、自定义注解验证数据

package com.hlj.vialidate.inter;


import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 校验数据
 */
public class NameIncludeValidator implements ConstraintValidator<NameInclude, String> {

    private String type;

    /**
     * 获取注解中的值
     * @param constraintAnnotation
     */
    @Override
    public void initialize(NameInclude constraintAnnotation) {
         type = constraintAnnotation.type();
    }

    /**
     * @param value 字段数据
     * @param context
     * @return
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if(StringUtils.isBlank(value)){
            return true;
        }
        if("Mail".equals(type)&&"HealerJean".equals(value)){
            return true ;
        }else {
            return false ;
        }
    }
}

4.3、对象中自定义注解的使用

     /**
     * 自定义注解校验
     */
    @NameInclude(message = "类型必须是type value必须是HealerJean" ,type = "Mail",groups = {ValidateGroup.HealerJean.class})
    @NotNull(message = "自定义校验不能为空",groups = {ValidateGroup.HealerJean.class})
    private String myName ;

4.4、测试

POST http://localhost:8888/hlj/validate
Content-Type: application/json; charset=UTF-8

{
  "name":"1234",
  "strLength":"12345",
  "list": ["list","list2"],
  "strNum":"6",
  "strRange":"9",
  "strDecimal":"100.2",
  "strDigts":"15.66",
  "fatherString":"fatherString",
  "innerBean":{
    "innerNname":"in"
  },
  "myName":"HealerJean"
}

ContactAuthor

你可能感兴趣的:(Utils)