Using <c:when> with an enumeration
I have a JSP portlet that needs to display different markup according to the value of a bean's property which is of an enumeration type
public enum State {
CANCELED, COMPLETED
}
I used the following code to do the switch
<c:choose>
<c:when test="#{item.state == 'COMPLETED'}">
<img src="ok.gif" />
</c:when>
<c:when test="#{item.state == 'CANCELED'}">
<img src="ko.gif" />
</c:when>
</c:choose>
but it doesn't work. Interestingly enough, it returns false in both cases. The item object (inside an ICEFaces data table) is a backing bean with a State
getter+setter property.
I have been told to compare the enumeration to a st开发者_StackOverflow社区ring and use the ==
operator, but maybe that's not the way.
So, my question is: how do I use the <c:when>
tag to compare a property to an enumeration value?
... The item object (inside an ICEFaces data table) ...
Then JSTL indeed doesn't work. It runs during view build time, not during view render time. Basically you can visualize it as follows: JSTL runs from top to bottom first and then hands over the generated result containing JSF tags only to JSF which in turn runs from top to bottom again. At the moment JSTL encounters the iterated JSF datatable #{item}
, it is null
and thus it will always evaulate false
and JSF will retrieve neither of those images from JSTL.
You want to use a JSF tag instead. I'd suggest <h:graphicImage>
in combination with the rendered
attribute.
<h:graphicImage value="ok.gif" rendered="#{item.state == 'COMPLETED'}" />
<h:graphicImage value="ko.gif" rendered="#{item.state == 'CANCELED'}" />
Perhaps it is just me, but I don't like doing string comparisons in jsp tags. Instead I would provide comparison methods like the following:
public boolean isStateCompleted()
{
return State.COMPLETED.equals(state);
}
public boolean isStateCanceled()
{
return State.CANCELED.equals(state);
}
And I would reference them in the jsp either as follows:
<c:choose>
<c:when test="#{item.stateCompleted}">
<img src="ok.gif" />
</c:when>
<c:when test="#{item.stateCanceled}">
<img src="ko.gif" />
</c:when>
</c:choose>
or like this:
<h:graphicImage value="ok.gif" rendered="#{item.stateCompleted}" />
<h:graphicImage value="ko.gif" rendered="#{item.stateCanceled}" />
精彩评论