Bean验证不起作用

Adr*_*ien 2 java spring hibernate spring-mvc bean-validation

我目前正在学习spring,但我仍然坚持使用不适用于我的bean的验证注释.我真的不明白什么失踪,我需要一只手:)

我有一个控制器:

@Controller
public class CirclesController {

    @RequestMapping(value = "/createCircle", method = RequestMethod.POST)
    public ModelAndView createCircle(@Valid Circle circle, BindingResult res) {

        if (res.hasErrors()) {
            System.out.println("Can't validate this form..");
        else
            System.out.println("Created new circle : " + circle);
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一个豆子:

public class Circle {

    @Size(min = 5)                 // This is what I try to validate
    private String      name;

public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

我配置了web.xml

<listener>
    <listener-class>
    org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:conf/dao-context.xml
        classpath:conf/services-context.xml
        classpath:conf/beans-context.xml
    </param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

我的项目看起来像那样:

项目

*-context.xml包含component-scan和anotation-config标记:

<context:component-scan base-package="com.test.app.[package-name]">
</context:component-scan>
<context:annotation-config></context:annotation-config>
<tx:annotation-driven></tx:annotation-driven>
Run Code Online (Sandbox Code Playgroud)

我有所有的外部库(hibernate,hibernate-api,javax.validation)并且在运行时没有错误...但是当我填写字段"name"时,不到5个字符,我总是得到"创建新的圆圈:圈{name = txt}"而不是"无法验证此表单..".

编辑:

这是我的类路径:

类路径

和servlet-context.xml:

<context:component-scan base-package="com.test.app.controllers"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsps/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>
Run Code Online (Sandbox Code Playgroud)

Mas*_*ave 7

提供依赖项列表和circles-servlet.xml将为您的问题提供完整的上下文.

然而,就我所看到的,可能只有两件事情遗失.首先确保你有类似hibernate-validator路径上的验证提供程序,第二个确保你有

 <mvc:annotation-driven />
Run Code Online (Sandbox Code Playgroud)

您的circles-servlet.xml中的元素支持对使用@Valid注释的控制器的参数对象启用验证

评论后更新

bean验证具有更新的规范,因此您应该按以下方式对齐依赖项

hibernate-validator-5.x.x 
validation-api-1.1.x
Run Code Online (Sandbox Code Playgroud)

这将实现JSR-349

要么

hibernate-validator-4.x.x
validation-api-1.0.x.
Run Code Online (Sandbox Code Playgroud)

它实现了JSR-303

您在评论中的问题意味着您很可能混合了依赖项,因此将hibernate-validator-5.xx与validation-api-1.0.x一起使用或者错过了相反的方式