Home > Articles > Programming > Java

This chapter is from the book

User Interface Component Model

In addition to the lifecycle description, an overview of JavaServer Faces architecture provides better understanding of the technology.

JavaServer Faces components are the building blocks of a JavaServer Faces view. A component can be a user interface (UI) component or a non-UI component.

JavaServer Faces UI components are configurable, reusable elements that compose the user interfaces of JavaServer Faces applications. A component can be simple, such as a button, or can be compound, such as a table, composed of multiple components.

JavaServer Faces technology provides a rich, flexible component architecture that includes the following:

  • A set of javax.faces.component.UIComponent classes for specifying the state and behavior of UI components
  • A rendering model that defines how to render the components in various ways
  • A conversion model that defines how to register data converters onto a component
  • An event and listener model that defines how to handle component events
  • A validation model that defines how to register validators onto a component
  • A navigation model that defines page navigation and the sequence in which pages are loaded

This section briefly describes each of these pieces of the component architecture.

User Interface Component Classes

JavaServer Faces technology provides a set of UI component classes and associated behavioral interfaces that specify all the UI component functionality, such as holding component state, maintaining a reference to objects, and driving event handling and rendering for a set of standard components.

The component classes are completely extensible, allowing component writers to create their own custom components. See Chapter 6, “Creating Custom UI Components and Other Custom Objects,” for more information.

The abstract base class for all components is javax.faces.component.UIComponent. JavaServer Faces UI component classes extend the UIComponentBase class (a subclass of UIComponent), which defines the default state and behavior of a component. The following set of component classes is included with JavaServer Faces technology:

  • UIColumn: Represents a single column of data in a UIData component.
  • UICommand: Represents a control that fires actions when activated.
  • UIData: Represents a data binding to a collection of data represented by a javax.faces.model.DataModel instance.
  • UIForm: Represents an input form to be presented to the user. Its child components represent (among other things) the input fields to be included when the form is submitted. This component is analogous to the form tag in HTML.
  • UIGraphic: Displays an image.
  • UIInput: Takes data input from a user. This class is a subclass of UIOutput.
  • UIMessage: Displays a localized error message.
  • UIMessages: Displays a set of localized error messages.
  • UIOutcomeTarget: Displays a hyperlink in the form of a link or a button.
  • UIOutput: Displays data output on a page.
  • UIPanel: Manages the layout of its child components.
  • UIParameter: Represents substitution parameters.
  • UISelectBoolean: Allows a user to set a boolean value on a control by selecting or deselecting it. This class is a subclass of the UIInput class.
  • UISelectItem: Represents a single item in a set of items.
  • UISelectItems: Represents an entire set of items.
  • UISelectMany: Allows a user to select multiple items from a group of items. This class is a subclass of the UIInput class.
  • UISelectOne: Allows a user to select one item from a group of items. This class is a subclass of the UIInput class.
  • UIViewParameter: Represents the query parameters in a request. This class is a subclass of the UIInput class.
  • UIViewRoot: Represents the root of the component tree.

In addition to extending UIComponentBase, the component classes also implement one or more behavioral interfaces, each of which defines certain behavior for a set of components whose classes implement the interface.

These behavioral interfaces, all defined in the javax.faces.component package unless otherwise stated, are as follows:

  • ActionSource: Indicates that the component can fire an action event. This interface is intended for use with components based on JavaServer Faces technology 1.1_01 and earlier versions. This interface is deprecated in JavaServer Faces 2.
  • ActionSource2: Extends ActionSource, and therefore provides the same functionality. However, it allows components to use the Expression Language (EL) when they are referencing methods that handle action events.
  • EditableValueHolder: Extends ValueHolder and specifies additional features for editable components, such as validation and emitting value-change events.
  • NamingContainer: Mandates that each component rooted at this component have a unique ID.
  • StateHolder: Denotes that a component has state that must be saved between requests.
  • ValueHolder: Indicates that the component maintains a local value as well as the option of accessing data in the model tier.
  • javax.faces.event.SystemEventListenerHolder: Maintains a list of javax.faces.event.SystemEventListener instances for each type of javax.faces.event.SystemEvent defined by that class.
  • javax.faces.component.behavior.ClientBehaviorHolder: Adds the ability to attach javax.faces.component.behavior.ClientBehavior instances such as a reusable script.

UICommand implements ActionSource2 and StateHolder. UIOutput and component classes that extend UIOutput implement StateHolder and ValueHolder. UIInput and component classes that extend UIInput implement EditableValueHolder, StateHolder, and ValueHolder. UIComponentBase implements StateHolder.

Only component writers will need to use the component classes and behavioral interfaces directly. Page authors and application developers will use a standard component by including a tag that represents it on a page. Most of the components can be rendered in different ways on a page. For example, a UICommand component can be rendered as a button or a hyperlink.

The next section explains how the rendering model works and how page authors can choose to render the components by selecting the appropriate tags.

Component Rendering Model

The JavaServer Faces component architecture is designed such that the functionality of the components is defined by the component classes, whereas the component rendering can be defined by a separate renderer class. This design has several benefits, including the following:

  • Component writers can define the behavior of a component once but create multiple renderers, each of which defines a different way to render the component to the same client or to different clients.
  • Page authors and application developers can change the appearance of a component on the page by selecting the tag that represents the appropriate combination of component and renderer.

A render kit defines how component classes map to component tags that are appropriate for a particular client. The JavaServer Faces implementation includes a standard HTML render kit for rendering to an HTML client.

The render kit defines a set of javax.faces.render.Renderer classes for each component that it supports. Each Renderer class defines a different way to render the particular component to the output defined by the render kit. For example, a UISelectOne component has three different renderers. One of them renders the component as a set of radio buttons. Another renders the component as a combo box. The third one renders the component as a list box. Similarly, a UICommand component can be rendered as a button or a hyperlink, using the h:commandButton or h:commandLink tag. The command part of each tag corresponds to the UICommand class, specifying the functionality, which is to fire an action. The Button or Link part of each tag corresponds to a separate Renderer class that defines how the component appears on the page.

Each custom tag defined in the standard HTML render kit is composed of the component functionality (defined in the UIComponent class) and the rendering attributes (defined by the Renderer class).

The section “Adding Components to a Page Using HTML Tags” in The Java EE 6 Tutorial: Basic Concepts lists all supported component tags and illustrates how to use the tags in an example.

The JavaServer Faces implementation provides a custom tag library for rendering components in HTML.

Conversion Model

A JavaServer Faces application can optionally associate a component with server-side object data. This object is a JavaBeans component, such as a managed bean. An application gets and sets the object data for a component by calling the appropriate object properties for that component.

When a component is bound to an object, the application has two views of the component’s data:

  • The model view, in which data is represented as data types, such as int or long.
  • The presentation view, in which data is represented in a manner that can be read or modified by the user. For example, a java.util.Date might be represented as a text string in the format mm/dd/yy or as a set of three text strings.

The JavaServer Faces implementation automatically converts component data between these two views when the bean property associated with the component is of one of the types supported by the component’s data. For example, if a UISelectBoolean component is associated with a bean property of type java.lang.Boolean, the JavaServer Faces implementation will automatically convert the component’s data from String to Boolean. In addition, some component data must be bound to properties of a particular type. For example, a UISelectBoolean component must be bound to a property of type boolean or java.lang.Boolean.

Sometimes you might want to convert a component’s data to a type other than a standard type, or you might want to convert the format of the data. To facilitate this, JavaServer Faces technology allows you to register a javax.faces.convert.Converter implementation on UIOutput components and components whose classes subclass UIOutput. If you register the Converter implementation on a component, the Converter implementation converts the component’s data between the two views.

You can either use the standard converters supplied with the JavaServer Faces implementation or create your own custom converter. Custom converter creation is covered in Chapter 6, “Creating Custom UI Components and Other Custom Objects.”

Event and Listener Model

The JavaServer Faces event and listener model is similar to the JavaBeans event model in that it has strongly typed event classes and listener interfaces that an application can use to handle events generated by components.

The JavaServer Faces specification defines three types of events: application events, system events, and data-model events.

Application events are tied to a particular application and are generated by a UIComponent. They represent the standard events available in previous versions of JavaServer Faces technology.

An event object identifies the component that generated the event and stores information about the event. To be notified of an event, an application must provide an implementation of the listener class and must register it on the component that generates the event. When the user activates a component, such as by clicking a button, an event is fired. This causes the JavaServer Faces implementation to invoke the listener method that processes the event.

JavaServer Faces supports two kinds of application events: action events and value-change events.

An action event (class javax.faces.event.ActionEvent) occurs when the user activates a component that implements javax.faces.component.ActionSource. These components include buttons and hyperlinks.

A value-change event (class javax.faces.event.ValueChangeEvent) occurs when the user changes the value of a component represented by UIInput or one of its subclasses. An example is selecting a check box, an action that results in the component’s value changing to true. The component types that can generate these types of events are the UIInput, UISelectOne, UISelectMany, and UISelectBoolean components. Value-change events are fired only if no validation errors are detected.

Depending on the value of the immediate property (see “The immediate Attribute” in The Java EE 6 Tutorial: Basic Concepts) of the component emitting the event, action events can be processed during the invoke application phase or the apply request values phase, and value-change events can be processed during the process validations phase or the apply request values phase.

System events are generated by an Object rather than a UIComponent. They are generated during the execution of an application at predefined times. They are applicable to the entire application rather than to a specific component.

A data-model event occurs when a new row of a UIData component is selected.

There are two ways to cause your application to react to action events or value-change events that are emitted by a standard component:

  • Implement an event listener class to handle the event and register the listener on the component by nesting either an f:valueChangeListener tag or an f:actionListener tag inside the component tag.
  • Implement a method of a managed bean to handle the event and refer to the method with a method expression from the appropriate attribute of the component’s tag.

See “Implementing an Event Listener” on page 117 for information on how to implement an event listener. See “Registering Listeners on Components” in The Java EE 6 Tutorial: Basic Concepts for information on how to register the listener on a component.

See “Writing a Method to Handle an Action Event” in The Java EE 6 Tutorial: Basic Concepts and “Writing a Method to Handle a Value-Change Event” in The Java EE 6 Tutorial: Basic Concepts for information on how to implement managed bean methods that handle these events.

See “Referencing a Managed Bean Method” in The Java EE 6 Tutorial: Basic Concepts for information on how to refer to the managed bean method from the component tag.

When emitting events from custom components, you must implement the appropriate event class and manually queue the event on the component in addition to implementing an event listener class or a managed bean method that handles the event. “Handling Events for Custom Components” on page 119 explains how to do this.

Validation Model

JavaServer Faces technology supports a mechanism for validating the local data of editable components (such as text fields). This validation occurs before the corresponding model data is updated to match the local value.

Like the conversion model, the validation model defines a set of standard classes for performing common data validation checks. The JavaServer Faces core tag library also defines a set of tags that correspond to the standard javax.faces.validator.Validator implementations. See “Using the Standard Validators” in The Java EE 6 Tutorial: Basic Concepts for a list of all the standard validation classes and corresponding tags.

Most of the tags have a set of attributes for configuring the validator’s properties, such as the minimum and maximum allowable values for the component’s data. The page author registers the validator on a component by nesting the validator’s tag within the component’s tag.

In addition to validators that are registered on the component, you can declare a default validator which is registered on all UIInput components in the application. For more information on default validators, see “Using Default Validators” on page 159.

The validation model also allows you to create your own custom validator and corresponding tag to perform custom validation. The validation model provides two ways to implement custom validation:

  • Implement a Validator interface that performs the validation.
  • Implement a managed bean method that performs the validation.

If you are implementing a Validator interface, you must also:

  • Register the Validator implementation with the application.
  • Create a custom tag or use an f:validator tag to register the validator on the component.

In the previously described standard validation model, the validator is defined for each input component on a page. The Bean Validation model allows the validator to be applied to all fields in a page. See “Using Bean Validation” in The Java EE 6 Tutorial: Basic Concepts and Chapter 22, “Bean Validation: Advanced Topics,” for more information on Bean Validation.

Navigation Model

The JavaServer Faces navigation model makes it easy to define page navigation and to handle any additional processing that is needed to choose the sequence in which pages are loaded.

In JavaServer Faces technology, navigation is a set of rules for choosing the next page or view to be displayed after an application action, such as when a button or hyperlink is clicked.

Navigation can be implicit or user-defined. Implicit navigation comes into play when user-defined navigation rules are not available. For more information on implicit navigation, see “Implicit Navigation Rules” on page 164.

User-defined navigation rules are declared in zero or more application configuration resource files, such as faces-config.xml, by using a set of XML elements. The default structure of a navigation rule is as follows:

<navigation-rule>
    <description></description
    <from-view-id></from-view-id>
    <navigation-case>
        <from-action></from-action>
        <from-outcome></from-outcome>
        <if></if>
        <to-view-id></to-view-id>
    </navigation-case>
</navigation-rule>

User-defined navigation is handled as follows:

  • Define the rules in the application configuration resource file.
  • Refer to an outcome String from the button or hyperlink component’s action attribute. This outcome String is used by the JavaServer Faces implementation to select the navigation rule.

Here is an example navigation rule:

<navigation-rule>
    <from-view-id>/greeting.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>success</from-outcome>
        <to-view-id>/response.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>

This rule states that when a command component (such as an h:commandButton or an h:commandLink) on greeting.xhtml is activated, the application will navigate from the greeting.xhtml page to the response.xhtml page if the outcome referenced by the button component’s tag is success. Here is the h:commandButton tag from greeting.xhtml that specifies a logical outcome of success:

<h:commandButton id="submit" action="success"
         value="Submit" />

As the example demonstrates, each navigation-rule element defines how to get from one page (specified in the from-view-id element) to the other pages of the application. The navigation-rule elements can contain any number of navigation-case elements, each of which defines the page to open next (defined by to-view-id) based on a logical outcome (defined by from-outcome).

In more complicated applications, the logical outcome can also come from the return value of an action method in a managed bean. This method performs some processing to determine the outcome. For example, the method can check whether the password the user entered on the page matches the one on file. If it does, the method might return success; otherwise, it might return failure. An outcome of failure might result in the logon page being reloaded. An outcome of success might cause the page displaying the user’s credit card activity to open. If you want the outcome to be returned by a method on a bean, you must refer to the method using a method expression, with the action attribute, as shown by this example:

<h:commandButton id="submit"
     action="#{userNumberBean.getOrderStatus}" value="Submit" />

When the user clicks the button represented by this tag, the corresponding component generates an action event. This event is handled by the default javax.faces.event.ActionListener instance, which calls the action method referenced by the component that triggered the event. The action method returns a logical outcome to the action listener.

The listener passes the logical outcome and a reference to the action method that produced the outcome to the default javax.faces.application.NavigationHandler. The NavigationHandler selects the page to display next by matching the outcome or the action method reference against the navigation rules in the application configuration resource file by the following process:

  1. The NavigationHandler selects the navigation rule that matches the page currently displayed.
  2. It matches the outcome or the action method reference that it received from the default javax.faces.event.ActionListener with those defined by the navigation cases.
  3. It tries to match both the method reference and the outcome against the same navigation case.
  4. If the previous step fails, the navigation handler attempts to match the outcome.
  5. Finally, the navigation handler attempts to match the action method reference if the previous two attempts failed.
  6. If no navigation case is matched, it displays the same view again.

When the NavigationHandler achieves a match, the render response phase begins. During this phase, the page selected by the NavigationHandler will be rendered.

The Duke’s Tutoring case study example application uses navigation rules in the business methods that handle creating, editing, and deleting the users of the application. For example, the form for creating a student has the following h:commandButton tag:

<h:commandButton id="submit"
                 action="#{adminBean.createStudent(studentManager.newStudent)}"
                 value="#{bundle['action.submit']}"/>

The action event calls the dukestutoring.ejb.AdminBean.createStudent method:

public String createStudent(Student student) {
    em.persist(student);
    return "createdStudent";
}

The return value of createdStudent has a corresponding navigation case in the faces-config.xml configuration file:

<navigation-rule>
    <from-view-id>/admin/student/createStudent.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>createdStudent</from-outcome>
        <to-view-id>/admin/index.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>

After the student is created, the user is returned to the Administration index page.

For more information on how to define navigation rules, see “Configuring Navigation Rules” on page 161.

For more information on how to implement action methods to handle navigation, see “Writing a Method to Handle an Action Event” in The Java EE 6 Tutorial: Basic Concepts.

For more information on how to reference outcomes or action methods from component tags, see “Referencing a Method That Performs Navigation” in The Java EE 6 Tutorial: Basic Concepts.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020