2013-06-22 27 views
1

這裏是我的控制器相關代碼:Spring MVC的形式:單選按鈕標籤未設定值屬性

@ModelAttribute("store_location_types") 
public StoreLocationType[] getStoreLocationTypes() { 
    return StoreLocationType.values(); 
} 

這裏是StoreLocationType的定義,在同一個控制器定義:

private enum StoreLocationType { 
    PHYSICAL("Physical"), 
    ONLINE("Online"); 

    private String displayName; 
    private String value; 

    private StoreLocationType(String displayName) { 
     this.displayName = displayName; 
     this.value = this.name(); 
    } 

    public String getDisplayName() { 
     return this.displayName; 
    } 

    public String getValue() { 
     return this.value; 
    } 
} 

這裏相關的JSP代碼:

 <li> 
      <label>Location Type:</label> 
      <form:radiobuttons path="StoreLocationType" items="${store_location_types}" itemLabel="displayName" itemValue="value"/> 
     </li> 

以下是頁面呈現時生成的內容:

<li> 
     <label>Location Type:</label>    
     <span> 
      <input id="StoreLocationType1" name="StoreLocationType" type="radio" value="">       
      <label for="StoreLocationType1">Physical</label> 
     </span> 
     <span> 
      <input id="StoreLocationType2" name="StoreLocationType" type="radio" value="">  
      <label for="StoreLocationType2">Online</label> 
     </span> 
    </li> 

值屬性未使用我的枚舉的「值」字段填充。我在這裏做錯了什麼?我希望看到的是:

 <span> 
      <input id="StoreLocationType1" name="StoreLocationType" type="radio" value="PHYSICAL">       
      <label for="StoreLocationType1">Physical</label> 
     </span> 
     <span> 
      <input id="StoreLocationType2" name="StoreLocationType" type="radio" value="ONLINE">  
      <label for="StoreLocationType2">Online</label> 
     </span> 

輸入變量的值屬性應該是StorLocationType.ONLINE.getValue()的值

回答

0

我解決它使用多個標籤的單選按鈕,而不是一個單一的單選按鈕標籤。

這裏是JSP的代碼:

<c:forEach var="item" items="${store_location_types}"> 
    <form:radiobutton path="StoreLocationType" value="${item.value}"/>${item.displayName} 
</c:forEach> 

我用普通的對象從數據庫中,所以在我的情況值爲ID和顯示字符串的說明。但是這也應該與枚舉一起工作。

1

我在代碼中找不到任何問題。當我測試它時效果很好。

但在這種情況下,你可以用更簡單的方法做到這一點。您不需要在枚舉中添加value字段。如果您省略<form:radiobuttons>itemValue屬性,則Spring會將值爲itemValue屬性的枚舉實例的名稱。

所以你可以這樣做。

枚舉

private enum StoreLocationType { 
    PHYSICAL("Physical"), 
    ONLINE("Online"); 

    private String displayName; 

    private StoreLocationType(String displayName) { 
     this.displayName = displayName; 
    } 

    public String getDisplayName() { 
     return this.displayName; 
    } 
} 

JSP

<label>Location Type:</label> 
<form:radiobuttons path="StoreLocationType" 
    items="${store_location_types}" itemLabel="displayName" />