0

我的代码列出了我想查看的数据,但是当我点击提交时,它无法填充支持表单,下面有异常。我怎样才能使绑定工作?我得到的异常是不匹配类型,在期望对象时尝试在列表中插入一个字符串。这是有道理的。

例子

<tr>
<td><form:select id="myTypes" path="myTypes" multiple="false">
       <form:option value="NONE" label="--- Select ---" />
       <form:options items="${form.myTypes}" itemValue="id" itemLabel="label"/>
     </form:select>
</td>
<td><form:errors path="myTypes" cssClass="error" /></td>

这就是表格的样子

public class MyForm {
   List<MyType> myTypes;

   public List<MyType> getMyTypes() {
      return myTypes;
   } 

   public void setMyTypes(List<MyType> myTypes) {
      this.myTypes = myTypes;
   }      
}

当然 MyType 有 id 和 label。

链接到上面的示例代码和下面的异常

HTTP Status 500 - Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors

Field error in object 'Form' on field 'myTypes': rejected value [8768743658734587345]; codes [typeMismatch.Form.myTypes,typeMismatch.myTypes,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [myForm.myTypes,myTypes]; arguments []; default message [myTypes]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'myTypes'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.x.x.MyTypeEntity] for property 'myTypes[0]': no matching editors or conversion strategy found]

解决方案:

确保您映射到单个元素而不是列表:) 它应该类似于

 <form:select path="someEntity[${status.index}].myType.id">

高温高压

4

1 回答 1

1

我认为问题在于 Spring 不知道如何将选定的选项值(当您提交表单时作为名为“myTypes”的 HTTP 参数发布到您的应用程序的字符串)转换为 MyType 对象。您应该配置一个 Formatter< MyType > 并将其注册到 Spring FormatterRegistry(请参阅 Spring 文档),以让 Spring 知道如何将传入的 String 转换为 MyType 对象。

    public class MyTypeFormatter implements Formatter<MyType> {
    @Override
    public MyType parse(String text, Locale locale) throws ParseException {
        return myTypeService.getType(text); // for example
    }

    public String print(MyType t, Locale locale) {
        return t.getId();// for example
    };
}

顺便说一句,如果可以的话,由于您的下拉列表不是多个,这意味着您将只选择一个可用的 MyType 选项。< form:select > 的路径应该命名为“myType”而不是“myTypes”,特别是,它应该引用 Form 对象中的 MyType 属性,而不是 List< MyType > 属性。也许您应该将可用 MyType 对象的第一个列表命名为“availableTypes”并创建第二个名为“selectedType”的属性来绑定与 GUI 上选定选项对应的 MyType 对象。

于 2013-05-18T21:42:03.507 回答