【问题标题】:<c:choose><c:when> in JSF page does not work, seems to always evaluate falseJSF 页面中的 <c:choose><c:when> 不起作用,似乎总是评估为 false
【发布时间】:2013-12-26 23:53:49
【问题描述】:

在我的 JSF 页面中,我使用 &lt;c:choose&gt;&lt;c:when&gt; 标记有条件地显示内容。但是,它不起作用,因为它似乎总是评估 false

例如

<h:outputText value="#{pollInfo.active} -" />
<c:choose>
    <c:when test="#{pollInfo.active}">
        <h:outputText value="Active" />
    </c:when>
    <c:otherwise>
        <h:outputText value="Deactive" />
    </c:otherwise>
</c:choose>

肯定有一些带有active=true 的项目,由&lt;h:outputText&gt; 确认,但它只为所有项目打印Deactive。你可以在下图中看到实际的输出:

这是怎么引起的,我该如何解决?

【问题讨论】:

    标签: jsf jsf-2 jstl conditional-rendering


    【解决方案1】:

    症状和屏幕截图表明,#{pollInfo} 表示迭代 UI 组件的当前迭代项,例如 &lt;ui:repeat&gt;&lt;h:dataTable&gt;&lt;p:tabView&gt;&lt;p:dataTable&gt; 等。

    JSTL 标记在视图构建期间运行,即基于 XHTML 源代码构建 JSF 组件树的时刻。此类迭代 UI 组件的 var 属性仅在视图渲染期间可用,即基于 JSF 组件树生成 HTML 输出的那一刻。

    换句话说,它们不会“同步”运行。在视图构建期间,#{pollInfo} 始终为 null

    在这种特殊情况下,您需要 JSF 组件的 rendered 属性。

    <h:outputText value="Active" rendered="#{pollInfo.active}" />
    <h:outputText value="Deactive" rendered="#{not pollInfo.active}" />
    

    或者,如果您打算有条件地渲染较大的代码,请将所有代码都包装在 &lt;ui:fragment&gt; 中:

    <ui:fragment rendered="#{pollInfo.active}">
        <h:outputText value="Active" />
        <!-- Some more components here if necessary. -->
    </ui:fragment>
    <ui:fragment rendered="#{not pollInfo.active}">
        <h:outputText value="Deactive" />
        <!-- Some more components here if necessary. -->
    </ui:fragment>
    

    鉴于您有一个纯 if-else,另一种选择是在 EL 中使用条件运算符:

    <h:outputText value="#{pollInfo.active ? 'Active' : 'Deactive'}" />
    

    额外的好处是,您最终得到的代码要少得多。

    另见:

    【讨论】:

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