Composite Components: Advanced Topics and an Example

We are working on a fresh, updated Jakarta EE Tutorial. This section hasn’t yet been updated.

This chapter describes the advanced features of composite components in Jakarta Faces technology.

Attributes of a Composite Component

A composite component is a special type of Jakarta Faces template that acts as a component. If you are new to composite components, see Composite Components before you proceed with this chapter.

You define an attribute of a composite component by using the composite:attribute tag. Commonly Used Attributes of the composite:attribute Tag lists the commonly used attributes of this tag.

Commonly Used Attributes of the composite:attribute Tag
Attribute Description

name

Specifies the name of the composite component attribute to be used in the using page. Alternatively, the name attribute can specify standard event handlers such as action, actionListener, and managed bean.

default

Specifies the default value of the composite component attribute.

required

Specifies whether it is mandatory to provide a value for the attribute.

method-signature

Specifies a subclass of java.lang.Object as the type of the composite component’s attribute. The method-signature element declares that the composite component attribute is a method expression. The type attribute and the method-signature attribute are mutually exclusive. If you specify both, method-signature is ignored. The default type of an attribute is java.lang.Object.

Note: Method expressions are similar to value expressions, but rather than supporting the dynamic retrieval and setting of properties, method expressions support the invocation of a method of an arbitrary object, passing a specified set of parameters and returning the result from the called method (if any).

type

Specifies a fully qualified class name as the type of the attribute. The type attribute and the method-signature attribute are mutually exclusive. If you specify both, method-signature is ignored. The default type of an attribute is java.lang.Object.

The following code snippet defines a composite component attribute and assigns it a default value:

<composite:attribute name="username" default="admin"/>

The following code snippet uses the method-signature element:

<composite:attribute name="myaction"
                     method-signature="java.lang.String action()"/>

The following code snippet uses the type element:

<composite:attribute name="dateofjoining" type="java.util.Date"/>

Invoking a Managed Bean

To enable a composite component to handle server-side data

  1. Invoke a managed bean in one of the following ways:

    • Pass the reference of the managed bean to the composite component.

    • Directly use the properties of the managed bean.

      The example application described in The compositecomponentexample Example Application shows how to use a managed bean with a composite component by passing the reference of the managed bean to the component.

Validating Composite Component Values

Jakarta Faces provides the following tags for validating values of input components. These tags can be used with the composite:valueHolder or the composite:editableValueHolder tag.

Validator Tags lists commonly used validator tags. See Using the Standard Validators for details and a complete list.

Validator Tags
Tag Name Description

f:validateBean

Delegates the validation of the local value to the Bean Validation API.

f:validateRegex

Uses the pattern attribute to validate the wrapping component. The entire pattern is matched against the String value of the component. If it matches, it is valid.

f:validateRequired

Enforces the presence of a value. Has the same effect as setting the required element of a composite component’s attribute to true.

The compositecomponentexample Example Application

The compositecomponentexample application creates a composite component that accepts a name (or any other string). The component interacts with a managed bean that calculates whether the letters in the name, if converted to numeric values, add up to a prime number. The component displays the sum of the letter values and reports whether it is or is not prime.

The compositecomponentexample application has a composite component file, a using page, and a managed bean.

The source code for this application is in the jakartaee-examples/tutorial/web/faces/compositecomponentexample/ directory.

The Composite Component File

The composite component file is an XHTML file, /web/resources/ezcomp/PrimePanel.xhtml. It has a composite:interface section that declares the labels for the name and a command button. It also declares a managed bean, which defines properties for the name.

<composite:interface>
    <composite:attribute name="namePrompt"
                         default="Name, word, or phrase: "/>
    <composite:attribute name="calcButtonText" default="Calculate"/>
    <composite:attribute name="calcAction"
                         method-signature="java.lang.String action()"/>
    <composite:attribute name="primeBean"/>
    <composite:editableValueHolder name="nameVal" targets="form:name"/>
</composite:interface>

The composite component implementation accepts the input value for the name property of the managed bean. The h:outputStylesheet tag specifies the stylesheet as a relocatable resource. The implementation then specifies the format of the output, using properties of the managed bean, as well as the format of error messages. The sum value is rendered only after it has been calculated, and the report of whether the sum is prime or not is rendered only if the input value is validated.

<composite:implementation>
    <h:form id="form">
        <h:outputStylesheet library="css" name="default.css"
                            target="head"/>
        <h:panelGrid columns="2" role="presentation">
            <h:outputLabel for="name"
                           value="#{cc.attrs.namePrompt}"/>
            <h:inputText id="name"
                         size="45"
                         value="#{cc.attrs.primeBean.name}"
                         required="true"/>
        </h:panelGrid>
        <p>
            <h:commandButton id="calcButton"
                             value="#{cc.attrs.calcButtonText}"
                             action="#{cc.attrs.calcAction}">
                <f:ajax execute="name" render="outputGroup"/>
            </h:commandButton>
        </p>

       <h:panelGroup id="outputGroup" layout="block">
            <p>
                <h:outputText id="result" style="color:blue"
                              rendered="#{cc.attrs.primeBean.totalSum gt 0}"
                              value="Sum is #{cc.attrs.primeBean.totalSum}" />
            </p>
            <p>
                <h:outputText id="response" style="color:blue"
                              value="#{cc.attrs.primeBean.response}"
                              rendered="#{!facesContext.validationFailed}"/>
                <h:message id="errors1"
                           showSummary="true"
                           showDetail="false"
                           style="color: #d20005;
                           font-family: 'New Century Schoolbook', serif;
                           font-style: oblique;
                           text-decoration: overline"
                           for="name"/>
            </p>
        </h:panelGroup>
    </h:form>
</composite:implementation>

The Using Page

The using page in this example application, web/index.xhtml, is an XHTML file that invokes the PrimePanel.xhtml composite component file along with the managed bean. It validates the user’s input.

<div id="compositecomponent">
    <ez:PrimePanel primeBean="#{primeBean}" calcAction="#{primeBean.calculate}">
    </ez:PrimePanel>
</div>

The Managed Bean

The managed bean, PrimeBean.java, defines a method called calculate, which performs the calculations on the input string and sets properties accordingly. The bean first creates an array of prime numbers. It calculates the sum of the letters in the string, with 'a' equal to 1 and 'z' equal to 26, and determines whether the value can be found in the array of primes. An uppercase letter in the input string has the same value as its lowercase equivalent.

The bean specifies the minimum and maximum size of the name string, which is enforced by the Bean Validation @Size constraint. The bean uses the @Model annotation, a shortcut for @Named and @RequestScoped, as described in Step 7 of To View the hello1 Web Module Using NetBeans IDE.

@Model
public class PrimeBean {
    ...
    @Size(min=1, max=45)
    private String name;
    ...

    public String calculate() {
        ...
    }
}

Running the compositecomponentexample Example

You can use either NetBeans IDE or Maven to build, package, deploy, and run the compositecomponentexample example.

To Build, Package, and Deploy the compositecomponentexample Example Using NetBeans IDE

  1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).

  2. From the File menu, choose Open Project.

  3. In the Open Project dialog box, navigate to:

    jakartaee-examples/tutorial/web/faces
  4. Select the compositecomponentexample folder.

  5. Click Open Project.

  6. In the Projects tab, right-click the compositecomponentexample project and select Build.

    This command builds and deploys the application.

To Build, Package, and Deploy the compositecomponentexample Example Using Maven

  1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).

  2. In a terminal window, go to:

    jakartaee-examples/tutorial/web/faces/compositecomponentexample/
  3. Enter the following command to build and deploy the application:

    mvn install

To Run the compositecomponentexample Example

  1. In a web browser, enter the following URL:

    http://localhost:8080/compositecomponentexample
  2. On the page that appears, enter a string in the Name, word, or phrase field, then click Calculate.

    The page reports the sum of the letters and whether the sum is prime. A validation error is reported if no value is entered or if the string contains more than 45 characters.