2015-02-11 56 views
1

我有一些數字字段(但不是強制性的)在我的jsp形式 例如。 kkqty,sogoqty和sesaqty。 所以當用戶不給在這些領域我m,在我的控制器側接收空因此得到空值屬性例外,同時節省這些形式數據如何將空數值字段綁定到默認值0在春天mvc

我POJO(OutletInfo.java)

private Double kkqty; 
private Double sogoqty; 
private Double sesaqty; 

//getter & setters 

@Column(name = "KKqty", nullable = false, precision = 10) 
public Double getKkqty() { 
    return this.kkqty; 
} 

public void setKkqty(Double kkqty) { 
    this.kkqty = kkqty; 
} 

@Column(name = "sogoqty", nullable = false, precision = 10) 
public Double getSogoqty() { 
    return this.sogoqty; 
} 

public void setSogoqty(Double sogoqty) { 
    this.sogoqty = sogoqty; 
} 

@Column(name = "sesaqty", nullable = false, precision = 10) 
public Double getSesaqty() { 
    return this.sesaqty; 
} 

任何輸入我的控制器

@RequestMapping(value = "saveOutletInfo", method = RequestMethod.POST) 
public @ResponseBody String saveOutletInfo(OutletInfo outletInfo,HttpServletRequest request){ 

    System.out.print("KKQTY:"+outletInfo.getKkqty());    
    return this.getMasterService().saveOutletInfo(outletInfo);  
} 

在當我米試圖打印所有數字字段控制,我收到空在這裏,因此不能 保存 。

我需要將空值轉換爲默認值0.0 一種方法我知道我需要檢查所有字段,如果爲空然後將其設置爲0.0但這是非常困難的編碼,所以我希望在這種情況下自動轉換。

我經歷了一些帖子,發現了@InitBinder,但我無法在這種情況下使用它。

財產以後像

@InitBinder
公共無效initBinder(WebDataBinder粘合劑){
binder.registerCustomEditor(Double.class,新CustomNumberEditor爲(Double.class,真));
}

任何人都可以建議如何我可以自動轉換爲所有我的數字字段爲0.0當它爲空。

回答

1

你可以建立一個全球性的init-粘合劑,如

@ControllerAdvice 
public class GlobalBindingInitializer { 

/* global InitBinder */ 

@InitBinder 
public void binder(WebDataBinder binder) { 
    binder.registerCustomEditor(Double.class, new CustomDoubleEditor()); 
} 
} 

東西,

public class CustomDoubleEditor extends PropertyEditorSupport { 
    public CustomDoubleEditor() { 
    } 

    public String getAsText() { 
     Double d = (Double) getValue(); 
     return d.toString(); 
    } 

    public void setAsText(String str) { 
     if (str == "" || str == null) 
      setValue(0); 
     else 
      setValue(Double.parseDouble(str)); 
    } 
} 

但註冊下列編輯器,在你的情況下,更合適的解決方案似乎是簡單地初始化實例變量或設置默認構造函數的值爲0

private Double kkqty = 0.0; 
private Double sogoqty = 0.0; 
private Double sesaqty = 0.0; 
+0

我試過初始化li克這個,但我仍然是空的。 – 2015-02-12 09:40:59

+0

但你使用@InitBinder建議工作得很好.....非常感謝。 :) :) – 2015-02-12 09:56:48