2013-02-20 32 views
5

我只是想知道如果有可能告訴一個@InitBinder,在一個空的形式浮點值將被轉換爲0春InitBinder:綁定float字段爲空或空值0

我知道, float是一種原始數據類型,但我仍然希望將空值或空值轉換爲0.

如果可能,我該如何實現這一目標?

否則我會使用字符串而不是浮動的只是做一個變通方法

回答

2

是你總是可以做到這一點.Spring有CustomNumberEditor這是Number的子類整型,長整型,浮點一個可定製的屬性編輯器,Double.It默認情況下,註冊在BeanWrapperImpl中已經,但是,可以通過它註冊自定義實例覆蓋定製editor.It意味着你可以擴展一個類這樣

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

} 

然後在你控制器正常進行註冊:

@InitBinder 
    public void initBinder(WebDataBinder binder) { 

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

這應該完成任務。

+0

謝謝,作品像魅力 – 2013-02-20 10:21:43

+0

歡迎您... – 2013-02-20 10:24:53

3

定義CustomNumberEditor爲的subclsss作爲

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