EL expression in c:choose, can't get it workin

2019-08-25 04:26发布

问题:

I'm trying something (JSF2) like this:

<p>#{projectPageBean.availableMethods}</p>
<c:choose>
  <c:when test="${projectPageBean.availableMethods == true}">
    <p>Abc</p>
  </c:when>
  <c:otherwise>
    <p>Xyz</p>
  </c:otherwise>
</c:choose> 

But this doesn't seem to work, although the EL expression in the top paragraph changes from false to true, the next paragraph always shows Xyz?

I also tried to change the test to:

${projectPageBean.availableMethods}

But still the same problem!

回答1:

First and foremost: JSTL tags runs during view build time, not during view render time.

Your concrete problem suggests that #{projectPageBean} is been set during view render time, such as would happen when definied as <ui:repeat var>, <h:dataTable var>, <p:tabView var>, etc. It's thus null during view build time.

In that case, you should not be using a view build time tag to conditionally render HTML. You should instead use a view render time component to conditionally render HTML. As first choice, use <ui:fragment>:

<p>#{projectPageBean.availableMethods}</p>
<ui:fragment rendered="#{projectPageBean.availableMethods}">
    <p>Abc</p>
</ui:fragment>
<ui:fragment rendered="#{not projectPageBean.availableMethods}">
    <p>Xyz</p>
</ui:fragment> 

By the way, there's in Facelets no need to switch between #{} and ${}. In contrary to JSP, in Facelets the ${} behaves exactly the same as #{}. To avoid potential confusion and maintenance trouble, I recommend to stick to #{} all the time.

See also:

  • Conditional rendering of non-JSF components (plain vanilla HTML and template text)


标签: jsf jstl el