Comparing with enum value in JSTL

*爱你&永不变心* 提交于 2019-12-06 08:41:37

问题


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?


回答1:


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()



来源:https://stackoverflow.com/questions/6749908/comparing-with-enum-value-in-jstl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!