[英]Bean Validation does't work
我目前正在学习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);
}
}
还有一个豆子:
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;
}
}
我配置了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>
我的项目看起来像那样:
* -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>
我有所有的外部库(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>
提供依赖项列表和circles-servlet.xml将为您的问题提供完整的上下文。
然而,就我所看到的,可能只有两件事情遗失。 首先确保你的类路径上有验证提供程序,例如hibernate-validator
,然后确保你有
<mvc:annotation-driven />
您的circles-servlet.xml中的元素支持对使用@Valid注释的控制器的参数对象启用验证
评论后更新
bean验证具有更新的规范,因此您应该按以下方式对齐依赖项
hibernate-validator-5.x.x
validation-api-1.1.x
这将实现JSR-349
要么
hibernate-validator-4.x.x
validation-api-1.0.x.
它实现了JSR-303
您在评论中的问题意味着您很可能混合了依赖项,因此将hibernate-validator-5.xx与validation-api-1.0.x一起使用或者错过了相反的方式
请参见本页底部:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html
将以下内容添加到spring配置中:
<!-- JSR-303/JSR-349 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/>
将@RequestBody注释与@Valid注释一起使用
public ModelAndView createCircle(@Valid @RequestBody Circle circle, BindingResult res) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.