简体   繁体   中英

Spring MVC - Binding Blank Form Values to Primitive Bean Fields

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

I never tryed it but try to register the Editor for int.class (this realy works).

But because the an int can not handle null new CustomNumberEditor(Integer.class, true) will not work.

So you need your own Number Editor that returns for example 0 is not value is defined.

binder.registerCustomEditor( int.class,
     new MyNumberEditorThatConvertsNullToZero() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM