2010-04-22 122 views
1

結合我有這樣一個對象,以便:通過FormFields的列表,並且如果所述字段類型不等於一個單選按鈕我輸出列表嵌套表格數據與對象列表Spring MVC中

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 


} 

我環在JSP中使用字段值的方法

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

這是一切都很好,工作正常。

這個之外我有,如果字段類型是一個收音機,我用支票:

<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和類似函數的引用,但我不確定如何正確解決這個問題。

是自定義屬性編輯器的方式去與此?如果是這樣,它將如何工作?

回答

2

我認爲你是正確的是什麼問題。當您執行path =「formFields [$ {formFieldRow.index}] .value」時,您將從表單的每個單選按鈕中返回一個String值,並且Spring應該知道如何將此String值轉換爲每個FieldValue對象以填充List值。

所以,你需要創建customEditor並在initbinder准此編輯器列表類:

@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); 
    } 
}