【问题标题】:Why are these JSTL c:tests not stopping the content from being rendered?为什么这些 JSTL c:tests 没有阻止内容被渲染?
【发布时间】:2012-04-05 06:04:22
【问题描述】:

我只是想向同事演示为什么我们不应该使用 JSTL 标签,但我迷路了,不知道为什么每件事都会被渲染。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:c="http://java.sun.com/jstl/core">    
     <h:outputLabel>#{dummyBean.pageBuild}</h:outputLabel>
     <h:outputLabel>#{dummyBean.pageRerendered}</h:outputLabel>     
     <h:outputLabel>#{dummyBean.pageBuild and !dummyBean.pageRerendered}</h:outputLabel>
     <h:outputLabel>#{dummyBean.pageBuild and dummyBean.pageRerendered}</h:outputLabel>
        <c:if test="#{dummyBean.pageBuild and !dummyBean.pageRerendered}">
             <h:outputLabel value="Section 1"></h:outputLabel>
        </c:if>

        <c:if test="#{dummyBean.pageBuild and dummyBean.pageRerendered}">
            <h:outputLabel value="Section 2"></h:outputLabel>
        </c:if>

</ui:composition>

结果是

true
false
true
false 
Section 1 
Section 2 

我以为他们会是

true
false
true
false 
Section 1 

【问题讨论】:

  • test="false" 看起来不像是一个表达式。它不应该更像 test=${1==0} 吗?我的jstl fu很弱,已经有一段时间了,所以我可能错了。
  • 为什么你认为你不应该使用 JSTL?
  • @erickson 上帝的话,即 balusc :) stackoverflow.com/questions/3342984/… 。顺便说一句,不要说永远不要使用它,但检查rendered =... 更好。
  • @erickson,尝试使用 jstl 渲染复杂的视觉模型变得非常棘手。 (如渲染表和嵌套表单)。使用 jstl 完成的任何事情都可以使用自定义标签更轻松地完成。向新的 Java 程序员教授自定义标签很容易。
  • 在 JSF 的上下文中,我同意正确使用 JSTL 可能很棘手。但我不同意自定义标签比 JSTL 更容易使用。这听起来像 NIH 综合症。

标签: java jsf-2 jstl


【解决方案1】:
<c:if test="true">
     <h:outputLabel value="Section 1.1"></h:outputLabel>
</c:if>

<c:if test="false">
    <h:outputLabel value="Section 2.2"></h:outputLabel>
</c:if>

test="true"test="false" 将始终计算为布尔值 true,因为它是有效且非空的 String 值。

您可能打算改用 test="#{true}"test="#{false}"

<c:if test="#{true}">
     <h:outputLabel value="Section 1.1" />
</c:if>

<c:if test="#{false}">
    <h:outputLabel value="Section 2.2" />
</c:if>

另一个问题是 JSTL 标记的 XML 命名空间是错误的,您使用的是 Facelets 1.x 而您使用的是 JSF 2.x。应该是

xmlns:c="http://java.sun.com/jsp/jstl/core"

关于在 JSF 中使用 JSTL,请查看以下答案:JSTL in JSF2 Facelets... makes sense?

【讨论】:

  • 在你回答之前已经检查过并且刚刚在我的 cmets 中提到过 :) 。对于我的问题,虽然` '
  • 我从问题中删除了section1.1 and section2.2,但是section1 and section2 上面的输出根据我的预期显示为真或假。
  • 使用&lt;c:if test="#{false}"&gt; 也不会阻止&lt;h:outputLabel value="Section 2.2" /&gt; 的显示。
  • 核心 taglib 的 XML 命名空间是错误的,因此它们根本不会被解析并解释为纯 HTML。
  • 我有正确的命名空间,但如果我这样做 它不会进入条件。
猜你喜欢
  • 2021-02-27
  • 2013-07-21
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
相关资源
最近更新 更多