Spring 3具有原始数据类型的对象绑定列表

时间:2014-02-04 16:40:12

标签: java spring spring-mvc data-binding spring-3

我是初学者并使用Spring 3.

我有以下豆子

public class Record {
    private String title;
    private double amount;

    //Getter and Setter
}

public class RecordBean {
    private List<Record> records;

    public RecordBean() {
        this.records = LazyList.lazyList(new ArrayList<Record>(), new InstantiateFactory<Record>(Record.class));
    }

    //Getter and Setter
}

我已将RecordBean添加到model

modelMap.add('recordBean',new RecordBean());

以下是Spring Form

<form:form action="/save" method="POST" commandName="recordBean">

    <form:input path="records[0].title"/>
    <form:input path="records[0].amount"/>

    <form:input path="records[1].title"/>
    <form:input path="records[1].amount"/>

    <input type="submit" value="Save"/>
</form:form>

我还在控制器

中添加了InitBinder
@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
}

现在,如果我为amount[0]输入值并为amount[1]留空并提交表单,则会收到typeMismatch错误。

Field error in object 'recordBean' on field 'records[1].amount': rejected value []; codes [typeMismatch.recordBean.records[1].amount,typeMismatch.recordBean.records.amount,typeMismatch.records[1].amount,typeMismatch.records.amount,typeMismatch.amount,typeMismatch.double,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [recordBean.records[1].amount,records[1].amount]; arguments []; default message [records[1].amount]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'double' for property 'records[1].amount'; nested exception is java.lang.NumberFormatException: empty String]

请告知。

由于

1 个答案:

答案 0 :(得分:1)

也许尝试从这条线路改为:“double”到“Double”:

private double amount;