2012-07-28 93 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>