2

我有一个像这样的对象:

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 和类似函数的引用,但我不确定如何正确解决这个问题。

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

4

1 回答 1

2

我认为你的问题是正确的。当您执行 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);
    }
} 
于 2010-04-30T18:41:47.463 回答