Spring3 MVC:验证不起作用 [英] Spring3 MVC: Validation not working
问题描述
性别验证无效。即使在性别文本字段中未输入任何值,表单也会成功验证而不会产生任何错误。
The gender validation is not working. Even if no values are entered in the gender text field, the form is getting validated successfully without throwing any error.
以下是Employee类:
Below is the Employee class:
@Size(min=2,max=10)
private String gender;
// Setters and Getters
以下是Controller方法:
Below is the Controller method:
@RequestMapping(value="done", method = RequestMethod.POST)
public String validateForm(@Valid Employee employee, BindingResult result, ModelMap m){
if(result.hasErrors()){
System.out.println("Validation Failed!!!");
return "main";
}else{
System.out.println("Validation Succeeded!!!");
return "done";
}
}
以下是上下文文件:
<context:annotation-config />
<context:component-scan
base-package="com.XXX" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
以下是jsp文件:
<tr>
<td>
Gender:
</td>
<td>
<form:input path="gender"/>
<form:errors path="gender" cssStyle="color: red;"/>
</td>
</tr>
我无法找到丢失的东西,但它有些愚蠢。请帮助。
I am not able to find out whats missing but its something silly. Please help.
推荐答案
1)所有javax约束在其传递条件中包含隐式或null。如果要捕获空白,则需要添加 @NotNull
,或者重新配置Web绑定器以将空白输入绑定到空字符串而不是空。
1) All of the javax constraints include an implicit "or null" in their pass conditions. If you want to catch blanks you need to either add @NotNull
, or reconfigure the web binder to bind blank inputs to empty string instead of null.
2)< context:annotation-config />
没有打开Spring 3调度程序servlet auto-config magic。如果这样做,您需要定义自己的验证器bean。要使所有内容自动完成,您需要使用< mvc:annotation-driven />
。
2) <context:annotation-config />
does not turn on Spring 3 dispatcher servlet auto-config magic. You need to define your own validator bean if you do that. To enable everything to automagically work you need to use <mvc:annotation-driven />
.
这篇关于Spring3 MVC:验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!