Spring MVC - Avoid "nested exception is java.lang.IllegalArgumentException" while mapping blank text field to int type using Spring MVC. Using custom editor to process numeric fields values.
In Spring MVC, while I was capturing numeric value in int type property from the form, I was getting exception if the field is left blank instead of
putting 0. If the numeric field is optional in form, I have to put
default zero value for the numeric field (like phone number field) to
pass the validation of that form. To avoid this situation, we can
register our Custom editor for particular type to process the value for
desired result.
Here is the MyNumberPropertyEditor class that process the Number type values. It sets value 0 to blank property so that validator can get 0 value while validating property.
package utils;
import java.beans.PropertyEditorSupport;
public class MyNumberPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
System.out.println("setAsTest");
if(text.length()==0)text="0";
super.setValue(Integer.parseInt(text));
}
@Override
public String getAsText() {
System.out.println("getAsTest");
return ((Number)this.getValue()).toString();
}
}
You have to register it in initBinder method in controller for the required type using registerCustomEditor method of binder object.
public void initBinder(WebDataBinder binder) {
logger.info("initBinder invoked for :"+binder.getObjectName());
binder.registerCustomEditor(int.class, new MyNumberPropertyEditor());
}
Here is the MyNumberPropertyEditor class that process the Number type values. It sets value 0 to blank property so that validator can get 0 value while validating property.
package utils;
import java.beans.PropertyEditorSupport;
public class MyNumberPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
System.out.println("setAsTest");
if(text.length()==0)text="0";
super.setValue(Integer.parseInt(text));
}
@Override
public String getAsText() {
System.out.println("getAsTest");
return ((Number)this.getValue()).toString();
}
}
You have to register it in initBinder method in controller for the required type using registerCustomEditor method of binder object.
public void initBinder(WebDataBinder binder) {
logger.info("initBinder invoked for :"+binder.getObjectName());
binder.registerCustomEditor(int.class, new MyNumberPropertyEditor());
}
Comments