Spring3 MVC:验证不起作用
性别验证无效。即使在性别文本字段中未输入任何值,表单也会成功验证而不会产生任何错误。
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 />
.