无法将java.lang.String类型的属性值转换为必需的double类型

时间:2012-05-28 02:42:14

标签: java spring-mvc

每当我在文本框中输入一个空字符串并尝试保存它时出现此错误我有这个错误:

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)

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

我正在使用Spring 3.0.1。我是java和其他相关技术的新手,比如spring。请帮忙。提前谢谢。

3 个答案:

答案 0 :(得分: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)); 
       }
  } 

答案 1 :(得分:4)

我不知道这是否是您问题的原因,但str == ""是一个错误。

如果您正在测试String是否为空,请使用str.isEmpty()str.length() == 0甚至"".equals(str)

==运算符测试以查看两个字符串是否是同一个对象。这并不是你想要的,因为在你正在运行的应用程序中可能有许多不同的String实例代表相同的字符串。在这方面,空字符串与其他字符串没有什么不同。


即使这不是您的问题的原因,您应该修复此错误,并做一个心理记录,不要使用==来测试字符串。 (或者至少,除非你采取特殊措施确保它始终有效......这超出了本Q& A的范围。)

答案 2 :(得分:4)

至于空字符串,我认为问题是你的 0 被转换为 Integer ,而不是 Double 所以你必须使用postfix d 0.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不会为使用这种方法编辑的任何属性创建一堆辅助对象(属性编辑器)。