Spring InitBinder:将float字段的空值或null值绑定为0 [英] Spring InitBinder: bind empty or null values of a float field as 0

查看:138
本文介绍了Spring InitBinder:将float字段的空值或null值绑定为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否可以告诉@InitBinder将表单中的空浮点值转换为0.

I'm just wondering if it's possible to tell an @InitBinder that empty float values in a form would be converted to 0.

我知道float是原始数据类型,但我仍想将null或空值转换为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

推荐答案

是的,您总是可以做到的.Spring有一个CustomNumberEditor,它是可自定义的属性编辑器,可编辑任何Number子类,例如Integer,Long,Float,Double.默认是由BeanWrapperImpl注册的,但是可以通过将其自定义实例注册为自定义编辑器来覆盖.这意味着您可以扩展这样的类

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));
    }

这应该完成任务.

这篇关于Spring InitBinder:将float字段的空值或null值绑定为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆