2012-05-28 48 views
7

林每當我在文本框中輸入一個空字符串有這個錯誤,並嘗試將其保存林有此錯誤:未能java.lang.String類型的屬性值轉換爲所需的類型雙

Failed to convert property value of type java.lang.String to 
    required type double for property customerAcctSetting.maxAllowableAmount; 
nested exception is java.lang.IllegalArgumentException: Cannot convert value of 
    type [java.lang.String] to required type [double] for 
    property maxAllowableAmount: 
PropertyEditor [bp.ar.util.NumberFormatUtil$CustomerDoubleEditor] returned 
    inappropriate value 

但當我輸入一個無效的數字格式,如「DDD」我有這樣的錯誤:

Failed to convert property value of type java.lang.String to required 
    type double for property customerAcctSetting.maxAllowableAmount; 
nested exception is java.lang.NumberFormatException: For input string: "ddd" 

我有這樣的粘合劑在我的控制器:

@InitBinder 
public void initBinder(WebDataBinder binder) { 
    NumberFormatUtil.registerDoubleFormat(binder); 
} 

而且我有一個類NumberFormatUtil.java實現靜態函數registerDoubleFormat(binder):使用Spring 3.0.1

NumberFormatUtil.java

public static void registerDoubleFormat (WebDataBinder binder) { 
    binder.registerCustomEditor(Double.TYPE, new CustomerDoubleEditor()); 
} 

private static class CustomerDoubleEditor extends PropertyEditorSupport{  
    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)); 
    } 
} 

林。我對Java和Spring等其他相關技術很陌生。請幫忙。提前致謝。

+0

那麼答案是什麼?閱讀春季論壇似乎這應該只是工作。我得到一個「無法將類型[java.lang.Double]的屬性值轉換爲屬性...所需的類型[java.lang.Double]」,這使我暈眩。 –

回答

4

我不知道這是你問題的原因,但str == ""是一個錯誤。

如果您正在測試以查看字符串是否爲空,請使用str.isEmpty()str.length() == 0或甚至"".equals(str)

==運算符測試以查看兩個字符串是否是相同的對象。這不會做你想做的事情,因爲在運行的應用程序中可以有許多不同的String實例來表示相同的字符串。在這方面,空字符串與其他字符串沒有區別。


即使這不是你的問題的原因,您應該修復這個bug,並進行了精神注意不要使用==測試字符串。 (或者至少,除非你已經採取了特殊的措施,以確保它會一直工作...這超出了Q的範圍& A.)

+0

剛剛嘗試過,並沒有奏效。也許問題在別的地方。我正在盡力弄清楚。無論如何感謝您的建議。 – NinjaBoy

5

更改setAsText()方法喜歡這裏,

public void setAsText(String str) { 
     if(str == null || str.trim().equals("")) { 
      setValue(0d); // you want to return double 
     } else { 
      setValue(Double.parseDouble(str)); 
     } 
    } 
+0

你應該檢查它是否爲空 –

+0

感謝您的建議鮑里斯,所以我編輯它。 –

4

至於空字符串,我想的問題是,你的澆鑄到整數,不所以你必須使用後綴d0.0D;

至於NumberFormatException,我看不到任何轉換器無法將其轉換的問題。如果你想爲皈依錯誤的自定義消息,你應該把這一信息轉達給你的信息屬性文件以下DefaultMessageCodeResolver 我認爲這將是像typeMismatch.java.lang.Double = "invalid floating point number" 並在bean配置有消息源的語義

<bean id="messageSource" 
    class="org.springframework.context.support.ResourceBundleMessageSource"> 
    <property name="basenames"> 
     <list> 
      <value>exceptions</value><!--- that means you have exceptions.properties in your class path with the typeMismatch string specified above--> 
     </list> 
    </property> 
    </bean> 

此外,屬性編輯器的概念現在已過時,new API with converters是要走的路,因爲spring不會爲使用此方法編輯的任何屬性創建一堆幫助對象(屬性編輯器)。

相關問題