Spring InitBinder: bind empty or null float field values ​​as 0

I'm just wondering if it is possible to tell @InitBinder that empty floats in the form will be converted to 0.

I know that float is a primitive data type, but I would still like to convert null or empty values ​​to 0.

If possible, how can I achieve this?

Otherwise, I will just do a workaround using String instead of float

+5
source share
2 answers

Yes, you can always do this. Spring has one CustomNumberEditor, which is a custom property editor for any subclass of Number, such as Integer, Long, Float, Double.It is registered by default with BeanWrapperImpl, but can be overridden by registering a user instance of it as a custom editor. That means you can 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 usually in the controller:

 @InitBinder
    public void initBinder(WebDataBinder binder) {

       binder.registerCustomEditor(Float.class,new MyCustomNumberEditor(Float.class, true));
    }

This should complete the task.

+2
source

Define subclsss CustomNumberEditor as

import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.util.StringUtils;

public class MyCustomNumberEditor extends CustomNumberEditor {

    public MyCustomNumberEditor(Class<? extends Number> numberClass) throws IllegalArgumentException {
        super(numberClass, true);
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (!StringUtils.hasText(text)) {
            setValue(0);
        }else {
            super.setAsText(text.trim());
        }
    }

}

( BaseController , , BaseController), , , MyCustomNumberEditor Number, .

   @InitBinder
public void registerCustomerBinder(WebDataBinder binder) {
    binder.registerCustomEditor(double.class, new MyCustomNumberEditor(Double.class));
    binder.registerCustomEditor(float.class, new MyCustomNumberEditor(Float.class));
    binder.registerCustomEditor(long.class, new MyCustomNumberEditor(Long.class));
    binder.registerCustomEditor(int.class, new MyCustomNumberEditor(Integer.class));
....    
}
+3

All Articles