我只是想知道是否可以告诉@InitBinder 表单中的空浮点值将转换为0。
我知道 float 是一种原始数据类型,但我仍然想将 null 或空值转换为 0。
如果这是可能的,我怎么能做到这一点?
否则,我将使用字符串而不是浮点数来解决
最佳答案
将 CustomNumberEditor 的子类定义为
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());
}
}
}
然后在你的 Controller 类中(我为我的所有应用程序 Controller 创建一个 BaseController,我的应用程序中的所有数字基元类型都需要这种行为,所以我只需在我的 BaseController 中定义它),为各种基元类型注册绑定(bind)器。
注意 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));
....
}
关于Spring InitBinder : bind empty or null values of a float field as 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14976566/