2

我正在 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"));

效果很好。

现在我想显示具有枚举作为属性的对象列表:

          <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("Body weight") 之类的东西对枚举中的标签进行硬编码,因为我想稍后本地化应用程序。

谢谢!

狮子座

4

2 回答 2

3

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

<fmt:setBundle basename="com.foo.bar.resources.Type" var="typeBundle"/>
<fmt:message key="${exercise.type}" bundle="${typeBundle}"/>
于 2012-07-28T22:43:29.220 回答
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("类型", UserType.values());

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

<form:select path="userType">
        <form:option value="" label="Chose Type" />
        <form:options items="${types}" itemLabel="code"  />
    </form:select>
于 2017-06-27T04:32:42.503 回答