简体   繁体   中英

Validate a POJO without using @Valid in Spring MVC

I need to validate a POJO, without using the annotation @Valid as paramether of a method.

I'm stuck at this point:

    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();
        }               
    }

It seems to work, since inside "itr" I have stuff like this::

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

Now, my question is: how can I add "itr" values to BindingResult??? Probably I should cast something...somehow...

Thank you

@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);
    }
}

you should create object of type ObjectError here is a spring doc for the class and you should add it to binding result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM