在Spring MVC中不使用@Valid验证POJO

时间:2015-11-27 07:08:39

标签: java jsp spring-mvc

我需要使用注释@Valid作为方法的参数来验证POJO,不带

我在这一点上陷入困​​境:

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Menu>> constraintViolations=validator.validate(menu);
    //Menu is my Pojo

    if (!constraintViolations.isEmpty()) {
        Iterator itr = constraintViolations.iterator();
        while(itr.hasNext()){
            Object o = itr.next();
        }               
    }

它似乎有效,因为内部&#34; itr&#34;我有这样的东西::

oConstraintViolationImpl{interpolatedMessage='size must be between 3 and 50', propertyPath=titolo, rootBeanClass=class com.springgestioneerrori.model.Menu, messageTemplate='{javax.validation.constraints.Size.message}'}

现在,我的问题是:如何添加&#34; itr&#34;值BindingResult ???可能我应该投一些东西......不知何故......

谢谢

1 个答案:

答案 0 :(得分:1)

@Test
public void testBindingResult(BindingResult result,Set<ConstraintViolation<String>> violations){
    for (  ConstraintViolation<String> constraintViolation : violations) {
        ObjectError error=new ObjectError("object",constraintViolation.getMessage());
        result.addError(error);
    }
}

你应该创建ObjectError here类型的对象是该类的spring文档,你应该将它添加到绑定结果。