Comparing with enum value in JSTL

11,530

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

Share:
11,530
yangsuli
Author by

yangsuli

Updated on June 04, 2022

Comments

  • yangsuli
    yangsuli almost 2 years

    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?