Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JSP EL enum value always empty [duplicate]

Tags:

java

enums

jsp

jstl

el

When trying to get an EL condition working I found that enum values are completely ignored. This seems to me contrary to the spec.

<c:out value='${com.foobar.data.BookingStatus.FAILED}' />
<c:out value='${BookingStatus.FAILED}' />
<c:out value='${com.foobar.data.BookingStatus.failed}' />
<c:out value='${BookingStatus.failed}' />
<c:if test="${empty BookingStatus.FAILED }">empty</c:if>

To my surprise these all evaluate to empty. Why is the Enum class not recognized? This is happening in a current stable Tomcat instance.

Can this be a classpath issue? The Enum is used successfully in controller code but nowhere else in JSPs. It is supplied in a jar in the lib directory of the deployment.

UPDATE:

My intention is to compare a supplied Integer to an Enum's property like this:

<c:when test='${bookingInformation.bookingStatus eq BookingStatus.FAILED.code}'>
    FOOBARFAIL
</c:when>

Unfortunately the value being checked can't be changed and will remain an Integer. The Enum looks as follow (simplified):

public enum BookingStatus {

    COMPLETED(0), FAILED(1);

    private final int code;

    private BookingStatus(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

}

I want to avoid to hard code the Integer value of FAIL etc. and use the enum instead for the comparison.

like image 987
sibidiba Avatar asked Jan 05 '11 16:01

sibidiba


2 Answers

That's because EL in its current version does not support accessing enums nor calling enum constants. This support is only available per EL 3.0.

It's unclear what your intent is, but it's good to know that you can compare enum properties as a String in EL. They are namely resolved as a String.

Assuming that you've a bean which look like this:

public class Booking {
    public enum Status { NEW, PROGRESS, SUCCESS, FAILED }

    private Status status;

    public Status getStatus() {
        return status;
    }
}

Then you could test the Status.FAILED condition as follows:

<c:if test="${booking.status == 'FAILED'}">
    Booking status is FAILED.
</c:if>

See also:

  • How to reference constants in EL?
like image 56
BalusC Avatar answered Oct 07 '22 23:10

BalusC


As BalusC indicated, you cannot access enums using EL, however, you can do this:

<c:set var="enumFailed" value="<%=BookingStatus.FAILED%>"/>

<c:if test="${enumFailed.code == bookingInformation.bookingStatus}">
    ...
</c:if>

It would be ideal if bookingInformation.bookingStatus was an enum and not an int, but if re-factoring your app is out of the question due to its legacy nature, then my above example should help. You'd need a <c:set/> for each value of the enum (appears to just be two in your example).

like image 35
Steven Benitez Avatar answered Oct 07 '22 21:10

Steven Benitez