我正在尝试使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
但上面的代码有两个问题:
countryCode.toCountry() 实际上并不起作用......我不确定它应该是什么语法.
如果"${sessionScope.CURRENT_INSTITUTION.countryCode}"不是有效的枚举值,即,如果它类似于"AAA",则比较失败并抛出java.lang.IllegalArgumentException:没有定义枚举const CountryCodes.AAA.我怎么能绕过那个?
Bal*_*usC 10
你的方法太复杂了.
重新设计你的枚举如下:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
(请注意,它现在有一个值得信赖且更有效的吸气剂!)
servlet的过程中存储在应用程序范围的枚举值init()的方法,或者更好的,期间ServletContextListener的contextInitialized()方法:
servletContext.setAttribute("countryCodes", CountryCode.values());
Run Code Online (Sandbox Code Playgroud)
最后遍历如下:
<select name="countryCode">
<c:forEach items="${countryCodes}" var="countryCode">
<option value="${countryCode}" ${institution.countryCode == countryCode ? 'selected' : ''}>${countryCode.label}</option>
</c:forEach>
</select>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12898 次 |
| 最近记录: |