Using <c:when> with an enumeration

♀尐吖头ヾ 提交于 2019-12-20 05:25:08

问题


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 string and use the == operator, but maybe that's not the way.

So, my question is: how do I use the &lt;c:when&gt; tag to compare a property to an enumeration value?


回答1:


... 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'}" />



回答2:


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}" />  


来源:https://stackoverflow.com/questions/5093861/using-cwhen-with-an-enumeration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!