I've seen several questions that are similar, but I have yet to find an answer that solves this problem. I have a Spring MVC form that is backed by a command object with a primitive property:
public class MyBean {
private int counter;
public int getCounter() {
return counter;
}
public void setCounter( int counter ) {
this.counter = counter;
}
}
In the JSP form, I have (abbreviated for clarity):
<form:form action="count.do">
<form:input id="counter" path="counter"/>
</form:form>
Now, as long as there is a valid number value in the "counter" input field, everything works as expected, but if the field is blank, then I get a form validation error:
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]
I've tried creating a custom property editor to accept null values (initializing it in initBinder() ), but this only works if I create a non-primitive set of wrapper accessors:
binder.registerCustomEditor( Integer.class, new CustomNumberEditor(Integer.class, true) );
So, is there a way to bind a field on the form to a primitive type without creating the non-primitive wrappers, and still handle blank values (I'd like to set them to 0 rather than erroring out)? If so, would you mind posting a simple example?
Many thanks, Peter