【问题标题】:How to populate Form from Spring dropdown when form is submitted提交表单时如何从 Spring 下拉列表中填充表单
【发布时间】:2023-03-29 15:50:01
【问题描述】:

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

例子

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

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

【问题讨论】:

  • 你的模型属性真的有一个名为“myTypes”的属性吗?它有二传手吗?您可以发布异常堆栈跟踪吗?
  • 添加异常和表单代码

标签: spring spring-mvc


【解决方案1】:

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

【讨论】:

  • 重复有点微妙,这是此解决方案最重要的部分The path of the &lt; form:select &gt; should be named "myType" instead of "myTypes" and especially.... 我非常感谢您的回复,因为它为我指明了正确的方向。谢谢!。顺便说一句,不需要格式化程序。我能够侥幸逃脱。
猜你喜欢
  • 2016-12-02
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 2014-07-06
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多