Annotations from javax.validation.constraints not working

后端 未结 15 1373
广开言路
广开言路 2020-11-28 06:23

What configuration is needed to use annotations from javax.validation.constraints like @Size, @NotNull, etc.? Here\'s my code:

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 06:30

    For JSR-303 bean validation to work in Spring, you need several things:

    1. MVC namespace configuration for annotations:
    2. The JSR-303 spec JAR: validation-api-1.0.0.GA.jar (looks like you already have that)
    3. An implementation of the spec, such as Hibernate Validation, which appears to be the most commonly used example: hibernate-validator-4.1.0.Final.jar
    4. In the bean to be validated, validation annotations, either from the spec JAR or from the implementation JAR (which you have already done)
    5. In the handler you want to validate, annotate the object you want to validate with @Valid, and then include a BindingResult in the method signature to capture errors.

    Example:

    @RequestMapping("handler.do")
    public String myHandler(@Valid @ModelAttribute("form") SomeFormBean myForm, BindingResult result, Model model) {
        if(result.hasErrors()) {
          ...your error handling...
        } else {
          ...your non-error handling....
        }
    }
    

提交回复
热议问题