我正在用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")之类的东西硬编码标签,因为我想稍后本地化应用程序。
谢谢!
狮子座
发布于 2012-07-29 06:43:29
将资源束关联到枚举,将枚举名称作为键,将枚举标签作为值。然后使用<fmt:setBundle/>和<fmt:message>,并将枚举名称作为关键字,以显示关联的标签:
<fmt:setBundle basename="com.foo.bar.resources.Type" var="typeBundle"/>
<fmt:message key="${exercise.type}" bundle="${typeBundle}"/>发布于 2017-06-27 12:32:43
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",新用户());model.addObject("types",UserType.values());
在中,你可以获得如下代码:
<form:select path="userType">
<form:option value="" label="Chose Type" />
<form:options items="${types}" itemLabel="code" />
</form:select>https://stackoverflow.com/questions/11704515
复制相似问题