与JSTL中的枚举值相比 [英] Comparing with enum value in JSTL

查看:178
本文介绍了与JSTL中的枚举值相比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static enum CountryCodes实现EnumConstant {
USA ,CAN,AUS;}

在jsp中,我试图遍历枚举值并执行比较:

 < c:set var =countryCodesvalue =<%= RequestConstants.CountryCodes.values )%>中/> 
< td>< select>
< c:forEach items =$ {countryCodes}var =countryCode>
< c:choose>
< c:当test =$ {CURRENT_INSTITUTION.countryCode == countryCode}>
< option value =$ {countryCode}selected =selected> $ {countryCode}< / option>
< / c:当>
< c:否则>
< option value =$ {countryCode}> $ {countryCode}< / option>
< / c:否则>
< / c:choose>
< / c:forEach>
< / select>< / td>

但是,问题是, CURRENT_INSTITUTION.countryCode 从数据库读取,可能不是枚举值之一。



如果 CURRENT_INSTITUTION.countryCode 是除枚举值之外的值(说 CHN ),则比较会引发以下异常:


java.lang.IllegalArgumentException:no enum const CountryCodes。 CHN定义。


我必须应对这种情况,因为数据库存储旧的数据,这是不健全的,可能包含无效值。



所以有一种比较方法,当 CURRENT_INSTITUTION.countryCode 不是枚举之一时返回false值?或者有没有办法确定 CURRENT_INSTITUION.countryCode 是否是枚举值之一,以便我可以采取适当的措施?

解决方案

在返回名称的枚举中定义一个getter:

  public String getName(){
return name();
}

然后你可以比较字符串。



如果您的EL版本支持方法调用,可以跳过getter并使用 countryCode.name()


I have the follwoing enum in my backend java code:

public static enum CountryCodes implements EnumConstant {
                   USA, CAN, AUS;}

And in the jsp I am trying to iterate through the enum value and do an comparison:

<c:set var="countryCodes" value="<%=RequestConstants.CountryCodes.values()%>" />
<td><select>
   <c:forEach items="${countryCodes}" var="countryCode">
      <c:choose>
         <c:when test="${CURRENT_INSTITUTION.countryCode == countryCode}">
            <option value="${countryCode}" selected="selected">${countryCode}</option>
         </c:when>
         <c:otherwise>
            <option value="${countryCode}">${countryCode}</option>
         </c:otherwise>
      </c:choose>
   </c:forEach>
</select></td>

However, the problem is that, CURRENT_INSTITUTION.countryCode is read from database and might not be one of the enum value.

If the CURRENT_INSTITUTION.countryCode is value other than the enum value, (say CHN), then the comparison throws the following exception:

java.lang.IllegalArgumentException: no enum const CountryCodes.CHN defined.

I have to cope with this situation because the database stores old data, which is not sanity-checked and may contain invalid value.

So is there a way for the comparison to just return false when CURRENT_INSTITUTION.countryCode is not one of the enum value? Or is there a way to determine whether CURRENT_INSTITUION.countryCode is one of the enum value or not, so that I can take proper action based on that?

解决方案

Define a getter in the enum that returns the name:

public String getName() {
    return name();
}

Then you can compare strings.

If your EL version supports method calls, you can skip the getter and use countryCode.name()

这篇关于与JSTL中的枚举值相比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆