Skip to main content

Using & comparing enumerations (enums) with JSTL

Often in your JSTL pages you will want to test a value of a particular variable before displaying something on the page. Often you are comparing against primitive types or other objects but what if you want to compare against an enumerated type?

Attempting to access the enumeration directly as Colour.BLUE doesn't work as the class/enum isn't available but what you can do it compare objects against their label or enum name.

If we have a Colour enumeration:
public enum Colour {
    RED, GREEN, BLUE
}
and we have a car object which has a getColour() method on it (returning the enumerated type) we can test against it in JSTL by using the specific name:
<c:if test="${car.colour eq 'BLUE'}">

Comments

Bill Comer said…
Andy,

my preferred way to do this is to write a getter method in the enum such as

public boolean getIsBlue() {
.....
}

& then in the jsp you have


which I think looks nicer. It needs to be 'getIsBlue()' because JSTL does not support 'is' methods.