【问题标题】:Nested form data binding with Lists of Objects in Spring MVC嵌套表单数据绑定与 Spring MVC 中的对象列表
【发布时间】:2010-04-22 10:35:35
【问题描述】:

我有一个像这样的对象:

public class FormFields extends BaseObject implements Serializable {

private FieldType fieldType; //checkbox, text, radio
private List<FieldValue> value; //FieldValue contains simple string/int information, id, value, label

//other properties and getter/setters


}

我遍历 FormFields 列表,如果 fieldType 不等于单选按钮,我将使用 JSP 输出字段值列表

 <c:forEach items=${formField.value}></c:forEach>

这一切都很好,工作正常。

除此之外,我还检查了 fieldType 是否是收音机,我在其中使用:

<form:radiobuttons path="formFields[${formFieldRow.index}].value" items="${formField.value}" itemLabel="label" cssClass="radio"/>

但是,这会导致我遇到以下错误:

 Failed to convert property value of type [java.lang.String] to required type [java.util.List] for property formFields[11].value; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [com.example.model.FieldValue] for property value[0]: no matching editors or conversion strategy found

我用谷歌搜索了这个并搜索了 Stack Overflow 并找到了对 registerCustomEditor 和类似函数的引用,但我不确定如何正确解决这个问题。

自定义属性编辑器是解决这个问题的方法吗?如果是这样,它将如何工作?

【问题讨论】:

    标签: java forms spring-mvc nested-forms data-binding


    【解决方案1】:

    我认为你的问题是正确的。当您执行 path="formFields[${formFieldRow.index}].value" 时,您将从表单的每个单选按钮返回一个 String 值,Spring 应该知道如何将此 String 值转换为每个 FieldValue 对象以填充 List 值.

    所以您需要创建您的 customEditor 并在您的 initbinder 中将此编辑器关联到 List 类:

    @InitBinder
    public void initBinder(final WebDataBinder binder) {
        binder.registerCustomEditor(FieldValue.class, CustomEditor() ));
    }
    

    您的 CustomEditor 类应该像这样扩展 PropertyEditorSupport:

    public class CustomEditor extends PropertyEditorSupport{  
        public void setAsText(String text) {
            FieldValue field;
            //you have to create a FieldValue object from the string text 
            //which is the one which comes from the form
            //and then setting the value with setValue() method
            setValue(field);
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多