[英]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.