【问题标题】:In JSF2, how to know if composite component has children?在 JSF2 中,如何知道复合组件是否有子组件?
【发布时间】:2011-06-26 08:51:34
【问题描述】:

我正在写一个复合组件,你有一个特殊的标签,名为:

<composite:insertChildren />

将所有组件的子项插入其中。有没有办法知道组件是否有孩子?就像可以在“渲染”属性上使用的布尔值。

【问题讨论】:

    标签: jsf jsf-2 children composite-component


    【解决方案1】:

    你所追求的基本表达式如下:

    #{cc.childCount} 或更详细:

    #{component.getCompositeComponentParent(component).childCount}

    例如以下复合组件:

    <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"  
        xmlns:cc="http://java.sun.com/jsf/composite"
    >
        <cc:interface/>
    
        <cc:implementation>             
            <h:outputText value="Children: #{cc.childCount}" />
        </cc:implementation>    
    </html>
    

    用于以下 Facelet:

    <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"    
        xmlns:test="http://java.sun.com/jsf/composite/test"    
    >
    
        <h:body>
    
            <test:myCom>
                <h:outputText value="first child" />
                <h:outputText value="second child" />
            </test:myCom>
    
        </h:body>
    </html>
    

    将打印Children: 2

    因此#{cc.childCount != 0} 会告诉你复合组件是否有子组件。

    【讨论】:

    • cc.childCount 只会给你正确的答案,如果你不在复合实现上使用&lt;composite:insertChildren /&gt;
    • 这本身并不能回答问题。由于他想要@squallsv 所指出的&lt;composite:insertChildren /&gt; 的计数,请参阅 gowog、Brian Leatham 或我关于使用此标签时如何获取计数的评论。
    • @JohnYeary 你是对的。感谢大家提交这些答案。虽然这个问题在技术上有点雄心勃勃(操作要求“组件的孩子”),但&lt;composite:insertChildren /&gt; 插入的孩子确实更合乎逻辑。
    【解决方案2】:

    我遇到了同样的问题,并设法在它的 facet 'javax.faces.component.COMPOSITE_FACET_NAME' 中找到了复合组件的子组件。

    在 Java 中是这样的:

    // we are within some method of UIComponent
    UIComponent childrenHolderFacet = getFacets().get("javax.faces.component.COMPOSITE_FACET_NAME");
    Iterator<UIComponent> childrenIt = childrenHolderFacet.getChildren().iterator();
    ...
    

    在 JSF 中是这样的:

    #{component.getFacets().get("javax.faces.component.COMPOSITE_FACET_NAME").children}
    

    希望对你有帮助。

    【讨论】:

    • 不错的发现!总修复,但很高兴你找到它;)对我来说,有效的语法是:#{cc.getFacets().get('javax.faces.component.COMPOSITE_FACET_NAME').children}
    • 因为我们正在寻找计数,所以我不得不通过添加size() 稍微修改它。 #{cc.getFacets().get('javax.faces.component.COMPOSITE_FACET_NAME').children.size()}
    【解决方案3】:

    至少在 Mojarra 上这是行不通的。复合组件的子组件可以正常插入,但访问 #{cc.parent}#{cc.children} 在 2.0.2 上不起作用,#{cc.childCount} 在 2.0.4 上总是返回 0,无论子组件的数量如何。

    【讨论】:

    • #{component.getCompositeComponentParent(component).childCount} 为我工作。你试过吗?
    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 2011-11-27
    • 2018-09-18
    • 2011-09-06
    • 2020-03-01
    • 2012-03-10
    • 2011-11-10
    • 2012-08-20
    相关资源
    最近更新 更多