【问题标题】:Spring 3 binding list of object with primitive datatype具有原始数据类型的对象的 Spring 3 绑定列表
【发布时间】:2014-02-04 16:40:12
【问题描述】:

我是初学者,正在使用 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());

下面是弹簧形式

<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]

请指教。

谢谢

【问题讨论】:

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


    【解决方案1】:

    也许尝试将此行从“double”更改为“Double”:

    private double amount;
    

    【讨论】:

    • 是的,我怀疑 CustomNumberEditor 没有生效 - 因为它是针对包装类型 Double 注册的,但 Spring 正在尝试绑定到原始类型“double”。
    • 如果我只想将它绑定到原始类型而不是包装类怎么办?
    • 这项工作正在工作,但我想使用原始数据类型。请指导。
    猜你喜欢
    • 2023-03-03
    • 2020-09-14
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多