2010-08-13 62 views
8

類型是枚舉屬性中的對象。如何將ENUM綁定到單選按鈕?

的jsp:

<form:radiobutton path="type" value="Male" /> 

的java:

public enum TestType 
{ 
    Male, Female; 
} 

,並得到錯誤

無法從類型轉換值 '男''java.lang.String中爲鍵入「的java .lang.Enum';原因=「java.lang.Enum中不是一個枚舉類型」

+0

我的錯。類型是_Enum type_ 我更改爲_TestType type_,它是可以的! – Alexander 2010-08-17 10:16:40

回答

0

或許,該命令對象的type屬性decalred作爲Enum代替TestType

4

執行如下操作

public enum TestType { 

    MAN("Man"), 
    FEMALE("Female"); 

    private String description; 

    private TestType(String description) { 
     this.description = description; 
    } 

    public String getValue() { 
     return name(); 
    } 

    public void setValue(String value) {} 

    public String getDescription() { 
     return description; 
    } 

    public void setDescription(String description) { 
     this.description = description; 
    } 

} 

而且如下

dataBinder.registerCustomEditor(TestType.class, new PropertyEditorSupport() { 
     @Override 
     public void setAsText(String value) throws IllegalArgumentException { 
      if(StringUtils.isBlank(value)) 
       return; 

      setValue(TestType.valueOf(value)); 
     } 

     @Override 
     public String getAsText() { 
      if(getValue() == null) 
       return ""; 

      return ((TestType) getValue()).name(); 
     } 
    }); 

然後

<form:radiobuttons path="type" items="${testTypeList}" itemLabel="description"/> 

您設置TestType如下

model.addAttribute(TestType.values()); 
註冊自定義粘結劑
+1

這個解決方案一次爲我工作...只改變春天3.0,從 harshit 2011-09-12 22:21:08

+0

@harshit刪除itemLabel屬性,但如何指定itemlabel,上述方法不適用於我... ? – NimChimpsky 2012-03-02 11:55:03

7

可以在spring forum找到更簡單的解決方案,無需任何自定義綁定。

+1

這應該被接受。 – arthur 2013-08-23 09:42:04