JSF複合組件

JSF通過Facelets提供複合組件(有點類似於Widget)的概念。複合組件是一種特殊類型的範本,它充當應用程式中的一個組成部分。

複合組件由標記標籤和其他現有組件組成。 這個可重複使用的用戶創建的組件具有定制的定義功能,並且可以像任何其他組件一樣具有連接到它的驗證器,轉換器和監聽器。 包含標記標籤和其他組件的任何XHTML頁面都可以轉換為複合組件。

以下表格包含複合標籤以及說明 -

標籤 功能
composite:interface 它用於聲明複合組件的約定。 組合組件可以用作單個組件,其特徵集合是使用合同中聲明的功能的並集。
composite:implementation 它用於定義複合組件的實現。 如果composite:interface元素存在,必須有一個相應的composite:implementation
composite:attribute 它用於聲明一個屬性,該屬性可以被賦予該標籤被聲明的複合組件的一個實例。
composite:insertChildren 它用於在使用頁面中的複合組件標籤中插入子組件。
composite:valueHolder 它用於聲明由該元素嵌套的composite:interface聲明其合同的組合組件暴露了適用於使用頁面中附加對象目標的ValueHolder實現。
composite:editableValueHolder 它用於聲明由該元素嵌套的composite:interface聲明其合同的組合組件暴露了適用於使用頁面中附加對象目標的EditableValueHolder的實現。
composite:actionSource 它用於聲明由該元素嵌套的composite:interface聲明其約定的組合組件,暴露了適用於使用頁面中附加對象目標的ActionSource實現。

在下面的例子中,我們分析一個接受用戶名和電子郵件地址作為輸入的組合組件。

實例

打開NetBeans IDE創建一個名稱為:CompositeComponents 的Web工程,其完整的目錄結構如下所示 -

創建複合組件

在創建組合組件之前,請確保使用正確的命名空間,如下所示。

xmlns:composite="http://xmlns.jcp.org/jsf/composite"

創建一個檔:composite-component.xhtml,代碼如下所示 -

<!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:composite="http://xmlns.jcp.org/jsf/composite"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Composite Component Example</title>
    </h:head>

    <h:body>
        <h2>In composite-component.xhtml Form</h2>
        <composite:interface>
            <composite:attribute name="username" required="false"/>
            <composite:attribute name="email" required="false"/>
        </composite:interface>
        <composite:implementation>
            <h:outputLabel value="User Name " />
            <h:inputText value="#{cc.attrs.username}"/><br/>
            <h:outputLabel value="Email ID "/>
            <h:inputText value="#{cc.attrs.email}"/><br/>
        </composite:implementation>
    </h:body>
</html>

在上面的例子中,composite:interface標籤用於聲明可配置的值。 composite:implementation標籤用於聲明所有XHTML標記和cc.attrs.username用於定義inputText組件的值。 ccs是JSF中複合組件的保留字。 運算式#{cc.attrs.attribute-name}用於訪問為組合組件介面定義的屬性。

上述代碼作為名為composite-component.xhtml的檔存儲在應用程式Web根目錄的 resources/com 檔夾中。

使用複合組件

使用複合組件的網頁通常稱為使用頁面。 使用頁面包含對xml命名空間聲明中複合組件的引用,如下所示:

<html xmlns:co="http://xmlns.jcp.org/jsf/composite/com">

這裏,com是存儲檔的檔夾,co是用於訪問組件的引用。

創建一個檔:index.xhtml,代碼如下所示 -

<!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://xmlns.jcp.org/jsf/html"
      xmlns:co="http://xmlns.jcp.org/jsf/composite/com">
    <h:head>
        <title>Implementing Composite Component</title>
    </h:head>
    <body>
        <h:form>
            <co:composite-component />
        </h:form>
    </body>
</html>

運行專案後,在網頁上將看到以下用戶介面 -


上一篇: JSF Facelets範本 下一篇: JSF Web資源