JSTL枚举标签

时间:2012-07-28 20:44:56

标签: spring-mvc jstl

我正在Spring中构建Web应用程序,并希望在* .jsp中显示枚举值作为标签

我的枚举:

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"));

哪个效果很好。

现在我想显示以enum作为属性的对象列表:

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

显然现在我正在获得像'BODY_WEIGHT'和'WEIGHTS'这样的价值。

有没有办法提供枚举值及其标签之间的映射列表,类似于上一个示例?

我不想在枚举中用BODY_WEIGHT(“体重”)硬编码标签,因为我想稍后本地化应用程序。

谢谢!

狮子座

2 个答案:

答案 0 :(得分:3)

将资源包与您的枚举关联,包含枚举名称作为键,枚举标签作为值。然后使用<fmt:setBundle/><fmt:message>将枚举名称作为键来显示关联的标签:

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

答案 1 :(得分: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>