4

If i have this code on my jsf page:

<c:choose>
    <c:when test="${empty example1}">
    </c:when>

    <c:when test="${empty example2}">
    </c:when>

    <c:otherwise>
    </c:otherwise>     
</c:choose>

it will work like java switch statement with case and break - if first when is true, second won't be test, right ?

What should i write to get "switch statement with case but without break" :

when first C:when is true something add to page and when second is true something is add to page too

kuba44
  • 1,838
  • 9
  • 34
  • 62

2 Answers2

11

You're thus basically looking for a fall-through switch. That isn't possible with <c:choose> as it represents a true if-else.... JSTL does not offer any tags for a fall-through switch.

Your best bet is to use multiple <c:if>s wherein you also check the preceding condition as an or condition.

<c:if test="#{empty example1}">
    ...
</c:if>
<c:if test="#{empty example1 or empty example2}">
    ...
</c:if>
<c:if test="#{empty example1 or empty example2 or empty example3}">
    ...
</c:if>
...

As you're using JSF, an alternative is using component's rendered attribute.

<h:panelGroup rendered="#{empty example1}">
    ...
</h:panelGroup>
<h:panelGroup rendered="#{empty example1 or empty example2}">
    ...
</h:panelGroup>
<h:panelGroup rendered="#{empty example1 or empty example2 or empty example3}">
    ...
</h:panelGroup>
...

The difference is that it's evaluated during view render time instead of during view build time. So if you were for example using this inside a <h:dataTable> based on the currently iterated row, the <c:if> wouldn't have worked the way you'd expect. See also JSTL in JSF2 Facelets... makes sense?

To eliminate the condition checking boilerplate, you could use <c:set> to create new EL variables. This works in both approaches.

<c:set var="show1" value="#{empty example1}" />
<c:set var="show2" value="#{show1 or empty example2}" />
<c:set var="show3" value="#{show2 or empty example3}" />

<h:panelGroup rendered="#{show1}">
    ...
</h:panelGroup>
<h:panelGroup rendered="#{show2}">
    ...
</h:panelGroup>
<h:panelGroup rendered="#{show3}">
    ...
</h:panelGroup>
...
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

I think it isn't possible with c:when. You can use c:if instead:

<c:if test="${empty example1}">
      "example1 empty"
</c:if>

<c:if test="${empty example2}">
     "example2 empty"
</c:if>

<c:if test="${not empty example1 and not empty example2}">
     "both not empty"
</c:if>
unwichtich
  • 13,712
  • 4
  • 53
  • 66