【问题标题】:How does a composite component set a property in it's client's backing bean?复合组件如何在其客户端的支持 bean 中设置属性?
【发布时间】:2011-11-01 23:26:10
【问题描述】:

我有一个复合组件,其接口包含以下内容:

<cc:attribute name="model"
                  shortDescription="Bean that contains Location" >
        <cc:attribute name="location" type="pkg.Location"
                      required="true" />
    </cc:attribute>
</cc:interface>

所以我可以使用 #{cc.attrs.model.location} 访问标记中的 Location 对象。

我还从复合组件的支持 bean 访问该对象,如下所示:

    FacesContext fc = FacesContext.getCurrentInstance();
    Object obj = fc.getApplication().evaluateExpressionGet(fc, 
            "#{cc.attrs.model.location}", Location.class);

所以现在我的复合组件已经完成了它的工作——如何从支持 bean 调用模型的 setter 方法? (即 model.setLocation(someValue) ?

【问题讨论】:

    标签: jsf-2 composite-component


    【解决方案1】:

    使用ValueExpression#setValue()。

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ValueExpression valueExpression = facesContext.getApplication().getExpressionFactory()
        .createValueExpression(elContext, "#{cc.attrs.model.location}", Location.class);
    
    valueExpression.setValue(elContext, newLocation);
    

    顺便说一句,Application#evaluateExpressionGet() 在幕后调用 ValueExpression#getValue(),正如其 javadoc 所描述的那样(如果你读过它...)


    与具体问题无关,您是否知道为复合组件创建支持UIComponent 类的可能性?我敢打赌,这比以这种方式摆弄ValueExpressions 要容易得多。然后,您可以使用继承的 getAttributes() 方法来获取 model。

    Model model = (Model) getAttributes().get("model);
    // ...
    

    您可以在我们的composite component wiki page 中找到一个示例。

    【讨论】:

    • 您说的是使用@FacesComponent 注释,对吧?我用复合组件标签发布了关于这个主题的另一个问题,我想这回答了这个问题。
    • 是的,没错。另请参阅链接的 wiki。我还没有看到你的另一个问题。注意适当的标记。这里的人们通常通过(有趣的)标签浏览。
    【解决方案2】:

    “默认”属性呢?它接缝在使用支持组件实现时没有实现。

    xhtml:

    <composite:interface>
        <composite:attribute name="test" 
                             type="java.lang.Boolean" 
                             default="#{false}"/>
    </composite:interface>
    <composite:implementation >
        TEST : #{cc.attrs.test}
    </composite:implementation >
    

    Java 支持实现:

     testValue = (Boolean) getAttributes().get("test");
    

    如果在主 xhtml 中设置了 test 属性没有问题:xhtml 和 java backing 具有相同的值。但是,当未设置默认值时,仅在 xhtml 上: 该 html 包含

    TEST : false 
    

    但是testValue在backing中为null

    【讨论】:

      猜你喜欢
      • 2015-02-26
      • 2014-11-07
      • 2014-11-03
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 2011-06-22
      相关资源
      最近更新 更多