用validator 手动校验参数

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

 

A:对实体的校验:

User user =  new User();
user.setPwd("1223eeee");
user.setName("1");
// 需要校验的方法实例
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Set> constraintViolationSet = factory.getValidator().validate(user);

System.out.println("非法参数校验结果条数: " + constraintViolationSet.size());
for(ConstraintViolation item:constraintViolationSet){
    System.out.println("-----xx-:"+item.getMessage() );
}

 

B:对 类中 方法的校验:

// 需要校验的方法实例

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

ExecutableValidator validator = factory.getValidator().forExecutables();

Method method = this.getClass().getMethod("vaildMethod", Integer.class, String.class, String.class);

// 校验参数,应该是有两个非法的参数

Object [] params = new Object[]{100, "", "test"};

// 获得校验结果 Set 集合,有多少个字段校验错误 Set 的大小就是多少 Set> constraintViolationSet = validator.validateParameters(this, method, params);

System.out.println("非法参数校验结果条数: " + constraintViolationSet.size()); constraintViolationSet.forEach(cons -> {

System.out.println("非法消息: " + cons.getMessage());

});

params = new Object[]{10, "build-test", "test"};

constraintViolationSet = validator.validateParameters(this, method, params);

System.out.println("合法参数校验结果条数: " + constraintViolationSet.size());

转载于:https://my.oschina.net/tinglanrmb32/blog/872722

你可能感兴趣的:(用validator 手动校验参数)