Spring InitBinder: bind empty or null values of a float field as 0
bind, spring, spring-mvc
Solution
Yes you could always do that .Spring have a `CustomNumberEditor` which is a customizable property editor for any Number subclass like Integer, Long, Float, Double.It is registered by default by BeanWrapperImpl,but, can be overridden by registering custom instance of it as custom editor.It means you could extend a class like this
public class MyCustomNumberEditor extends CustomNumberEditor{
public MyCustomNumberEditor(Class<? extends Number> numberClass, NumberFormat numberFormat, boolean allowEmpty) throws IllegalArgumentException {
super(numberClass, numberFormat, allowEmpty);
}
public MyCustomNumberEditor(Class<? extends Number> numberClass, boolean allowEmpty) throws IllegalArgumentException {
super(numberClass, allowEmpty);
}
@Override
public String getAsText() {
//return super.getAsText();
return "Your desired text";
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
super.setAsText("set your desired text");
}
}
And then register it normally in you controller:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Float.class,new MyCustomNumberEditor(Float.class, true));
}
This should do the task.
Problem
I'm just wondering if it's possible to tell an @InitBinder that empty float values in a form would be converted to 0. I know that float is a primitive data type but I'd still like to convert null or empty values to 0. If that is possible, how can i achieve that? Otherwise I'll just make a workaround using a String instead of a float