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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With