2012-07-28 123 views
2

我建立Web應用程序在春天和希望顯示枚舉值作爲一個標籤* .JSPJSTL枚舉標籤

我的枚舉:

public enum Type {BODY_WEIGHT, WEIGHTS}; 

現在,我在表格中顯示它使用:

  <form:select path="type" items="${typeLabels}" itemValue="value" itemLabel="label"> 
       <form:options/> 
      </form:select> 

「typelabels」 是簡單的對象映射枚舉值的一個標籤的列表:

List<ExerciseType> typeLabels = new ArrayList<ExerciseType>(); 
    typeLabels.add(new ExerciseType(Type.BODY_WEIGHT, "Body weight")); 
    typeLabels.add(new ExerciseType(Type.WEIGHTS, "With weights")); 

這很好。

現在我想用枚舉的屬性顯示對象列表:

  <c:forEach var="exercise" items="${list}" > 
      <tr> 
       <td>${exercise.title}</td> 
       <td>${exercise.description}</td> 
       <td>${exercise.type}</td> 
      </tr> 
      </c:forEach> 

很明顯,現在我越來越喜歡「BODY_WEIGHT」和「權係數」值。

有沒有辦法提供枚舉值和他們的標籤之間的映射列表類似於前面的例子?

因爲我想稍後本地化應用程序,所以我不想在枚舉中使用類似BODY_WEIGHT(「體重」)的硬編碼標籤。

謝謝!

利奧

回答

3

助理資源包你的枚舉,包含枚舉名作爲鍵和枚舉標籤的值。然後使用<fmt:setBundle/><fmt:message>用enum名稱作爲鍵來顯示相關標籤:

<fmt:setBundle basename="com.foo.bar.resources.Type" var="typeBundle"/> 
<fmt:message key="${exercise.type}" bundle="${typeBundle}"/> 
+0

謝謝! 我使用了標籤,因爲我已經有了本地化包加載,但是這背後的想法是一樣的。 我也改變了我顯示選項列表的方式 - 我發現非常好的自定義標籤可以做到這一點 - 使用相同的消息包: http://www.springjutsu.org/2011/03/binding-enums-with- i8n本地化支持/ – Leonti 2012-07-29 15:50:07

0
public enum UserType { 
ADMIN("Admin"), USER("User"), TEACHER("Teacher"), STUDENT("Student"); 

private String code; 

UserType(String code) { 
    this.code = code; 
} 

public String getCode() { 
    return code; 
} 


public static UserType fromCode(String userType) { 
    for (UserType uType : UserType.values()) { 
     if (uType.getCode().equals(userType)) { 
      return uType; 
     } 
    } 
    throw new UnsupportedOperationException("The code " + userType + " is not supported!"); 
} 

}

在控制器需要設置如下模式:

ModelAndView model = new ModelAndView("/home/index"); 

model.addObject(「user」,new User()); model.addObject(「types」,UserType.values());

在JSP中,你可以如下得到它:

<form:select path="userType"> 
     <form:option value="" label="Chose Type" /> 
     <form:options items="${types}" itemLabel="code" /> 
    </form:select>