【问题标题】:c:choose with multiple c:when - fall-through switchc:choose with multiple c:when - 直通开关
【发布时间】:2013-11-09 15:33:13
【问题描述】:

如果我的 jsf 页面上有此代码:

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

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

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

它将像带有casebreak 的java switch 语句一样工作 - 如果第一个何时为真,第二个将不会被测试,对吧?

我应该写什么来获得“switch 声明与case 但没有break”:

当第一个 C:when 为真时,添加到页面中,当第二个为真时,也添加到页面中

【问题讨论】:

    标签: jsf loops jstl break


    【解决方案1】:

    因此,您基本上是在寻找一个贯穿式开关。 &lt;c:choose&gt; 不可能做到这一点,因为它代表了真正的 if-else...。 JSTL 不提供任何用于直通开关的标记。

    您最好的选择是使用多个&lt;c:if&gt;s,其中您还将前面的条件检查为or 条件。

    <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>
    ...
    

    当您使用 JSF 时,另一种方法是使用组件的 rendered 属性。

    <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>
    ...
    

    不同之处在于它是在视图渲染期间而不是在视图构建期间评估的。因此,例如,如果您在基于当前迭代行的 &lt;h:dataTable&gt; 中使用它,则 &lt;c:if&gt; 不会按您期望的方式工作。另见JSTL in JSF2 Facelets... makes sense?

    要消除条件检查样板,您可以使用&lt;c:set&gt; 创建新的 EL 变量。这两种方法都适用。

    <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>
    ...
    

    【讨论】:

      【解决方案2】:

      我认为c:when 是不可能的。您可以改用c:if

      <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>
      

      【讨论】:

        猜你喜欢
        • 2011-12-15
        • 2011-11-23
        • 1970-01-01
        • 2011-11-18
        • 1970-01-01
        • 1970-01-01
        • 2013-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多