访问支持组件中的JSF2组合组件属性

Tuk*_*uaz 6 primefaces composite-component jsf-2

我正在开发一个JSF2/Primefaces应用程序,我在访问此组件的支持bean中复合组件的接口中定义的属性时遇到问题.

我的组件定义如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:composite="http://java.sun.com/jsf/composite">

<composite:interface componentType="testComponent">
    <composite:attribute name="text" required="true" type="java.lang.String" />
</composite:interface>

<composite:implementation>

    <h:outputText value="Passed text is: #{cc.attrs.text}" />

</composite:implementation>

</html>
Run Code Online (Sandbox Code Playgroud)

它存储在名为text.xhtml:application/src/main/webapp/resources/my_componentdirectory 的文件中.

我在另一个页面(这是一个Facelets组合元素)上使用此组件,如下所示:

<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:myc="http://java.sun.com/jsf/composite/my_component"
    template="./resources/templates/template.xhtml">

<ui:define name="content"> 
    <h:form id="products">
        <myc:test id="test" text="A text" />
    </h:form>
</ui:define>    

</ui:composition>
Run Code Online (Sandbox Code Playgroud)

支持组件类定义如下:

package my.application.component;

import javax.faces.component.FacesComponent;
import javax.faces.component.UINamingContainer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@FacesComponent ( value="testComponent" )
public class TestComponent extends UINamingContainer {
    Logger log = LoggerFactory.getLogger(TestComponent.class);

    public TestComponent() {
        log.debug("TestComponent constructor");
        log.debug("getAttributes().size(): " + getAttributes().size());
    }
}
Run Code Online (Sandbox Code Playgroud)

组件本身按预期工作.使用页面呈现Passed text is: A text输出.此外,记录器输出显示来自TestComponent构造函数的日志消息,因此组件xml定义似乎与TestComponent该类正确绑定.

现在,问题getAttributes()TestComponent构造函数中调用的方法总是返回一个零大小的映射.如果我理解正确,我应该能够text使用调用访问组件接口中声明的属性:

getAttributes().get("text");

TestComponent类中,但它总是返回,null因为属性map是空的.

我还尝试text使用调用访问该属性:

String text = FacesContext.getCurrentInstance().getApplication(). evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{cc.attrs.text}", String.class));

但它也解决了null.

我究竟做错了什么?任何提示将非常感激,因为我不知道接下来要尝试什么.

/ Tukasz.

Mik*_*aun 5

我的猜测是构造函数引用这些属性还为时过早.

JSF将首先构造一个支持组件的实例,然后在某些时候为它提供对其属性的引用.在稍后调用的方法中,例如编码方法,您应该可以访问它们.

  • 也许有人应该提出请求?`@ FacesComponent`中的`@ PostConstruct`会很棒! (2认同)