How to turn on annotation driven validation in Spring 4?

天涯浪子 提交于 2019-11-28 11:44:01
M. Deinum

Judging from your explanation and the following error java.lang.ClassNotFoundException: javax.validation.Validator Spring doesn't see the classes and as such doesn't enable JSF-303 validation.

Make sure that the correct jars are on the classpath and that you have an implementation as well. When using maven adding something like the following should do the trick.

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.3.Final</version>
</dependency>

This will add the needed jars to the WEB-INF/lib directory which in turn lets Spring Web MVC detect it and configure the appropriate bean.

For an explanations of the different annotations you might want to check In Hibernate Validator 4.1+, what is the difference between @NotNull, @NotEmpty, and @NotBlank?.

I see two points in your code that may cause de problem.

1) Instead of <annotation-driven /> use the correct namespace <mvc:annotation-driven/>.

2) On your @Controller change your functions parameters from:

   public String processRegistration(@Valid Spitter spitter, Errors errors,
        Model model) {
    if (errors.hasErrors()) {
        return "registerForm";
    }
    ...

To:

public String processRegistration(@ModelAttribute("spitter") @Valid Spitter spitter, BindingResult result) {

    if (result.hasErrors()) {
        return "registerForm";
    }
    ...

Try it! ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!