【发布时间】:2012-02-02 20:47:01
【问题描述】:
我见过几个类似的问题,但我还没有找到解决这个问题的答案。我有一个 Spring MVC 表单,它由具有原始属性的命令对象支持:
public class MyBean {
private int counter;
public int getCounter() {
return counter;
}
public void setCounter( int counter ) {
this.counter = counter;
}
}
在 JSP 表单中,我有(为清楚起见而缩写):
<form:form action="count.do">
<form:input id="counter" path="counter"/>
</form:form>
现在,只要“计数器”输入字段中有一个有效的数字值,一切都会按预期进行,但如果该字段为空白,则会收到表单验证错误:
org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'MyBean' on field 'counter': rejected value []; codes [methodInvocation.MyBean.counter,methodInvocation.counter,methodInvocation.float,methodInvocation]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [MyBean.counter,counter]; arguments []; default message [counter]]; default message [Property 'counter' threw exception; nested exception is java.lang.IllegalArgumentException]
我尝试创建一个自定义属性编辑器来接受空值(在 initBinder() 中对其进行初始化),但这仅在我创建一组非原始包装访问器时才有效:
binder.registerCustomEditor( Integer.class, new CustomNumberEditor(Integer.class, true) );
那么,有没有办法在不创建非原始包装器的情况下将表单上的字段绑定到原始类型,并且仍然处理空白值(我想将它们设置为 0 而不是出错)?如果是这样,您介意发布一个简单的示例吗?
非常感谢, 彼得
【问题讨论】:
标签: forms spring model-view-controller binding javabeans