如何在提交表单时从Spring下拉列表填充Form

时间:2013-05-18 08:41:57

标签: spring spring-mvc

我的代码列出了我想要查看的数据,但是当我点击提交时,它无法填充支持表单,但下面有例外。如何使绑定工作?我得到的异常是Mismatch类型,试图在期望对象时在List中插入一个String。这是有道理的。

实施例

<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和标签。

Link to above sample code以及

以外的例外情况

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

HTH

1 个答案:

答案 0 :(得分:1)

我认为问题在于Spring不知道如何将选定的选项值(在您提交表单时,作为名为“myTypes”的HTTP参数)发布到您的应用程序的字符串转换为MyType对象。你应该配置一个Formatter&lt; MyType&gt;并将其注册到Spring FormatterRegistry(请参阅Spring doc),让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选项。 &lt;的路径表格:选择&gt;应该命名为“myType”而不是“myTypes”,尤其是它应该引用Form对象中的MyType属性而不是List&lt; MyType&gt;属性。也许您应该将可用的MyType对象的第一个列表命名为“availableTypes”,并创建名为“selectedType”的第二个属性,以绑定与GUI上所选选项对应的MyType对象。

相关问题