SpringMVC form:options items属性:究竟期望什么?


问题内容

我还是SpringMVC的新手(和jstl一样)。我正在尝试从对象列表中填充选择中的选项。我已经找到了一种使用c:forEach的方法,但是我一直在想有一种方法可以使form:options方法起作用。

我已经浏览了一下,在这里我可以找到与Items属性的官方文档最接近的地方>>
http://static.springsource.org/spring/docs/2.0.x/reference/spring-form.tld
.html#spring-
form.tld.options

它说items属性是

“用于生成内部’option’标签的对象的Collection,Map或数组”

我的困惑是正在寻找什么样的集合,地图或对象数组。他们需要采用什么格式?它是专门寻找String类型的Collection还是数组?我可以用吗

List<MyObject>

如果是这样,那么MyObject必须具有什么才能使其有效(即方法,变量)?

目前,当我尝试使用MyObject时,出现了一个异常提示-

ConverterNotFoundException:未找到能够从com.example.MyObject类型转换为java.lang.String类型的转换器

我需要做一个转换器吗?那会去哪里?那将如何工作?我已经搜索了该错误消息,但还没有真正找到我要执行的操作…(大多数是有关Roo的结果)

MyObject类如下所示:

public class MyObject{
    private String company;
    private Customer customer;
    private Address customerAddress;

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Address getCustomerAddress() {
        return customerAddress;
    }

    public void setCustomerAddress(Address customerAddress) {
        this.customerAddress = customerAddress;
    }
}

并且我正在尝试像这样使用它:

<form:select path="myObjectList">
    <form:option value="0"/>
    <form:options items="myObjectList" /> 
</form:select>

有人知道这种方法有什么错误吗?或者,我应该使用

List<String>

完成我在做什么?

编辑 这里的堆栈跟踪>> http://pastebin.com/2c5XBCmG


问题答案:

Spring文档说这有关items的属性form:options标签:

items属性通常填充有item对象的集合或数组。如果已指定,则itemValue和itemLabel只是引用那些item对象的bean属性;否则,item对象本身将被字符串化。或者,您可以指定项目映射,在这种情况下,映射键将解释为选项值,并且映射值对应于选项标签。如果恰好同时指定了itemValue和/或itemLabel,则item
value属性将应用于地图键,item label属性将应用于地图值。

简而言之,如果您需要使用Custom Beans列表作为items属性,则还需要使用itemValueand
itemLabel属性。就我个人而言,我更喜欢使用LinkedHashMapMaps-具体来说是实例- 来填充我的选择标签,但这只是一个问题。

改编来自Spring文档的示例,您的代码应如下所示:

 <form:select path="commandAttribute">
      <form:option value="-" label="--Please Select"/>
      <form:options items="${countryList}" itemValue="company" itemLabel="company"/>
 </form:select>

我使用的company属性,既itemValueitemLabel,但你可以自由地选择适合您的需求的属性。