我正在尝试使用 jSTL 进行一些网站开发,但我遇到了 以下问题:
我在这里尝试创建一个下拉菜单,其中显示的值是 国家名称,值为国家代码。为此我 在后端 java 代码中有以下枚举:
public static enum CountryCodes implements EnumConstant {
USA, CAN, AUS, GBR, DEU, ESP, GUM, IND, ISR, MEX, NZL, PAN, PRI;
public final String toCountry(){
switch(this){
case USA:
return "United States";
case CAN:
return "Canada";
case AUS:
return "Australia";
case GBR:
return "Great Britan";
case DEU:
return "Germany";
case ESP:
return "Spain";
case GUM:
return "Guam";
case IND:
return "India";
case ISR:
return "Isreal";
case MEX:
return "Mexico";
case NZL:
return "New Zealand";
case PAN:
return "Panama";
case PRI:
return "Puerto Rico";
}
return this.toString();
}
}
jsp代码片段如下:
<c:set var="countryCodes" value="<%=RequestConstants.CountryCodes.values()%>" />
<td>
<select id="<%=RequestConstants.CLModifyPage.COUNTRY_CODE%>"
name="<%=RequestConstants.CLModifyPage.COUNTRY_CODE%>">
<c:forEach items="${countryCodes}" var="countryCode">
<c:choose>
<c:when
test="${sessionScope.CURRENT_INSTITUTION.countryCode == countryCode}">
<option value="${countryCode}" selected="selected">
${countryCode.toCountry()}</option>
</c:when>
<c:otherwise>
<option value="${countryCode}">${countryCode.toCountry()}
</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
</td>
但是上面的代码有两个问题:
countryCode.toCountry()
没有真正起作用...我不确定它应该是什么语法。如果
"${sessionScope.CURRENT_INSTITUTION.countryCode}"
不是有效的枚举值,即,如果它类似于“AAA”,则比较失败并抛出 java.lang. lang.IllegalArgumentException:未定义枚举常量 CountryCodes.AAA。我该如何解决这个问题?
最佳答案
你的方法太复杂了。
按如下方式重新设计您的枚举:
public enum CountryCode {
USA("United States"),
CAN("Canada"),
AUS("Australia");
// ...
private String label;
private CountryCode(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
(请注意,它现在有一个完全有值(value)且更高效的 setter/getter !)
在 servlet 的 init()
方法期间或更好地在 ServletContextListener
期间将枚举值存储在应用程序范围内的 contextInitialized()
方法:
servletContext.setAttribute("countryCodes", CountryCode.values());
最后遍历如下:
<select name="countryCode">
<c:forEach items="${countryCodes}" var="countryCode">
<option value="${countryCode}" ${institution.countryCode == countryCode ? 'selected' : ''}>${countryCode.label}</option>
</c:forEach>
</select>
关于java - 在 JSTL 中使用枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6739918/