The Java EE 5 Tutorial

Chapter 11 Using JavaServer Faces Technology in JSP Pages

The page author’s responsibility is to design the pages of a JavaServer Faces application. This includes laying out the components on the page and wiring them to backing beans, validators, converters, and other server-side objects associated with the page. This chapter uses the Duke’s Bookstore application and the Coffee Break application (see Chapter 36, The Coffee Break Application) to describe how page authors use the JavaServer Faces tags to perform the following tasks:

This chapter also describes how to include custom objects created by application developers and component writers on a JSP page.

The Example JavaServer Faces Application

The JavaServer Faces technology chapters of this tutorial primarily use a rewritten version of the Duke’s Bookstore example to illustrate the basic concepts of JavaServer Faces technology. This version of the Duke’s Bookstore example includes several JavaServer Faces technology features:

This version of Duke’s Bookstore includes the same pages listed in Table 5–1. It also includes the tut-install/javaeetutorial5/examples/web/bookstore6/web/chooselocale.jsp page, which displays the custom image map that allows you to select the locale of the application. This page is displayed first and advances directly to the bookstore.jsp page after the locale is selected.

The packages of the Duke’s Bookstore application are:

Chapter 12, Developing with JavaServer Faces Technology describes how to program backing beans, custom converters and validators, and event listeners. Chapter 13, Creating Custom UI Components describes how to program event handlers, custom components, renderers, and tag handlers.

The source code for the application is located in the tut-install/javaeetutorial5/examples/web/bookstore6/ directory.

    To deploy and run the application using NetBeans IDE, follow these steps:

  1. Perform all the operations described in Accessing Databases from Web Applications.

  2. In NetBeans 5.5, select File->Open Project.

  3. In the Open Project dialog, navigate to:


    tut-install/javaeetutorial5/examples/web/
  4. Select the bookstore6 folder.

  5. Select the Open as Main Project check box and the Open Required Projects check box.

  6. Click Open Project.

  7. In the Projects tab, right-click the bookstore6 project, and select Undeploy and Deploy.

  8. To run the application, open the bookstore URL http://localhost:8080/bookstore6.

    To deploy and run the application using Ant, follow these steps:

  1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/bookstore6/.

  2. Type ant. This target will spawn any necessary compilations, copy files to the tut-install/javaeetutorial5/examples/web/bookstore6/build/ directory, and create a WAR file and copy it to the tut-install/javaeetutorial5/examples/web/bookstore6/dist/ directory.

  3. Start the Application Server.

  4. Perform all the operations described in Creating a Data Source in the Application Server.

  5. To deploy the example, type ant deploy. The deploy target outputs a URL for running the application. Ignore this URL, and instead use the one shown in the next step.

  6. To run the application, open the bookstore URL http://localhost:8080/bookstore6/.

To learn how to configure the example, refer to the web.xml file, which includes the following elements:

To run the example, open the URL http://localhost:8080/bookstore6 in a browser.

Setting Up a Page

A typical JavaServer Faces page includes the following elements:

This section tells you how to add these elements to your pages and briefly describes the subview tag for including JavaServer Faces pages inside other pages.

To use the JavaServer Faces UI components in your JSP page, you need to give the page access to the two standard tag libraries: the JavaServer Faces HTML render kit tag library and the JavaServer Faces core tag library. The JavaServer Faces standard HTML render kit tag library defines tags that represent common HTML user interface components. The JavaServer Faces core tag library defines tags that perform core actions and are independent of a particular render kit.

Using these tag libraries is similar to using any other custom tag library. This chapter assumes that you are familiar with the basics of using custom tags in JSP pages (see Using Custom Tags).

As is the case with any tag library, each JavaServer Faces tag library must have a TLD that describes it. The html_basic TLD describes the JavaServer Faces standard HTML render kit tag library. The jsf_core TLD describes the JavaServer Faces core tag library.

Refer to the TLD documentation at http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/index.html for a complete list of the JavaServer Faces tags and their attributes.

To use any of the JavaServer Faces tags, you need to include these taglib directives at the top of each page containing the tags defined by these tag libraries:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

The uri attribute value uniquely identifies the TLD. The prefix attribute value is used to distinguish tags belonging to the tag library. You can use other prefixes rather than the h or f prefixes. However, you must use the prefix you have chosen when including the tag in the page. For example, the form tag must be referenced in the page using the h prefix because the preceding tag library directive uses the h prefix to distinguish the tags defined in html_basic.tld:

<h:form ...>

A page containing JavaServer Faces tags is represented by a tree of components. At the root of the tree is the UIViewRoot component. The view tag represents this component on the page. Therefore, all component tags on the page must be enclosed in the view tag, which is defined in the jsf_core TLD:

<f:view>
    ... other JavaServer Faces tags, possibly mixed with other
     content ...
</f:view>

You can enclose other content, including HTML and other JSP tags, within the view tag, but all JavaServer Faces tags must be enclosed within the view tag.

The view tag has four optional attributes:

An advanced developer might implement the methods referenced by beforePhase and afterPhase to perform such functions as initialize or release resources on a per-page basis. This feature is outside of the scope of this tutorial.

The form tag is nested inside of the view tag. As its name suggests, the form tag represents a form, which is submitted when a button or hyperlink on the page is clicked. For the data of other components on the page to be submitted with the form, the tags representing the components must be nested inside the form tag. See Adding a Form Component for more details on using the form tag.

If you want to include a page containing JavaServer Faces tags within another JSP page that includes JavaServer Faces tags, you must enclose the entire nested page in a subview tag. You can add the subview tag on the parent page and nest a jsp:include inside it to include the page:

<f:subview id="myNestedPage">
    <jsp:include page="theNestedPage.jsp" />
</f:subview>

You can also include the subview tag inside the nested page, but it must enclose all the JavaServer Faces tags on the nested page.

The subview tag has two optional attributes: binding and rendered. The binding attribute binds to a component that implements NamingContainer. One potential use case of binding a subview component to a bean is if you want to dynamically add components to the subview in the backing bean.

The rendered attribute can be set to true or false, indicating whether or not the components nested in the subview tag should be rendered.

In summary, a typical JSP page that uses JavaServer Faces tags will look somewhat like this:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
    <h:form>
        other JavaServer Faces tags and core tags,
         including one or more button or hyperlink components for
         submitting the form
    </h:form>
</f:view>

The sections Using the Core Tags and Adding UI Components to a Page Using the HTML Component Tags describe how to use the core tags from the JavaServer Faces core tag library and the component tags from the JavaServer Faces standard HTML render kit tag library.

Using the Core Tags

The tags included in the JavaServer Faces core tag library are used to perform core actions that are independent of a particular render kit. These tags are listed in Table 11–1.

Table 11–1 The jsf_core Tags

Tag Categories 

Tags 

Functions 

Event-handling tags 

actionListener

Registers an action listener on a parent component 

phaseListener

Registers a PhaseListener instance on a UIViewRoot component

setPropertyActionListener

Registers a special action listener whose sole purpose is to push a value into a backing bean when a form is submitted 

valueChangeListener

Registers a value-change listener on a parent component 

Attribute configuration tag

attribute

Adds configurable attributes to a parent component 

Data conversion tags

converter

Registers an arbitrary converter on the parent component 

convertDateTime

Registers a DateTime converter instance on the parent component

convertNumber

Registers a Number converter instance on the parent component

Facet tag

facet

Signifies a nested component that has a special relationship to its enclosing tag 

Localization tag 

loadBundle

Specifies a ResourceBundle that is exposed as a Map

Parameter substitution tag

param

Substitutes parameters into a MessageFormat instance and adds query string name-value pairs to a URL

Tags for representing items in a list 

selectItem

Represents one item in a list of items in a UISelectOne or UISelectMany component

selectItems

Represents a set of items in a UISelectOne or UISelectMany component

Container tag

subview

Contains all JavaServer Faces tags in a page that is included in another JSP page containing JavaServer Faces tags 

Validator tags

validateDoubleRange

Registers a DoubleRangeValidator on a component

validateLength

Registers a LengthValidator on a component

validateLongRange

Registers a LongRangeValidator on a component

validator

Registers a custom validator on a component

Output tag 

verbatim

Generates a UIOutput component that gets its content from the body of this tag

Container for form tags 

view

Encloses all JavaServer Faces tags on the page 

These tags are used in conjunction with component tags and are therefore explained in other sections of this tutorial. Table 11–2 lists the sections that explain how to use specific jsf_core tags.

Table 11–2 Where the jsf_core Tags Are Explained

Tags 

Where Explained 

Event-handling tags 

Registering Listeners on Components

Data conversion tags

Using the Standard Converters

facet

Using Data-Bound Table Components and Laying Out Components with the UIPanel Component

loadBundle

Rendering Components for Selecting Multiple Values

param

Displaying a Formatted Message with the outputFormat Tag

selectItem and selectItems

The UISelectItem, UISelectItems, and UISelectItemGroup Components

subview

Setting Up a Page

verbatim

Rendering a Hyperlink with the outputLink Tag

view

Setting Up a Page

Validator tags

Using the Standard Validators and Creating a Custom Validator

Adding UI Components to a Page Using the HTML Component Tags

The tags defined by the JavaServer Faces standard HTML render kit tag library represent HTML form components and other basic HTML elements. These components display data or accept data from the user. This data is collected as part of a form and is submitted to the server, usually when the user clicks a button. This section explains how to use each of the component tags shown in Table 10–2.

The next section explains the more important tag attributes that are common to most component tags. Please refer to the TLD documentation at http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/index.html for a complete list of tags and their attributes.

For each of the components discussed in the following sections, Writing Bean Properties explains how to write a bean property bound to a particular UI component or its value.

UI Component Tag Attributes

In general, most of the component tags support these attributes:

All of the UI component tag attributes (except id) can accept expressions, as defined by the unified EL described in Unified Expression Language.

The id Attribute

The id attribute is not required for a component tag except in the case when another component or a server-side class must refer to the component. If you don’t include an id attribute, the JavaServer Faces implementation automatically generates a component ID. Unlike most other JavaServer Faces tag attributes, the id attribute only takes expressions using the immediate evaluation syntax, which uses the ${} delimiters.

The immediate Attribute

UIInput components and command components (those that implement ActionSource, such as buttons and hyperlinks) can set the immediate attribute to true to force events, validations, and conversions to be processed during the apply request values phase of the life cycle. Page authors need to carefully consider how the combination of an input component’s immediate value and a command component’s immediate value determines what happens when the command component is activated.

Assume that you have a page with a button and a field for entering the quantity of a book in a shopping cart. If both the button’s and the field’s immediate attributes are set to true, the new value of the field will be available for any processing associated with the event that is generated when the button is clicked. The event associated with the button and the event, validation, and conversion associated with the field are all handled during the apply request values phase.

If the button’s immediate attribute is set to true but the field’s immediate attribute is set to false, the event associated with the button is processed without updating the field’s local value to the model layer. This is because any events, conversion, or validation associated with the field occurs during its usual phases of the life cycle, which come after the apply request values phase.

The bookshowcart.jsp page of the Duke’s Bookstore application has examples of components using the immediate attribute to control which component’s data is updated when certain buttons are clicked. The quantity field for each book has its immediate attribute set to false. (The quantity fields are generated by the UIData component. See Using Data-Bound Table Components, for more information.) The immediate attribute of the Continue Shopping hyperlink is set to true. The immediate attribute of the Update Quantities hyperlink is set to false.

If you click the Continue Shopping hyperlink, none of the changes entered into the quantity input fields will be processed. If you click the Update Quantities hyperlink, the values in the quantity fields will be updated in the shopping cart.

The rendered Attribute

A component tag uses a Boolean JavaServer Faces expression language (EL) expression, along with the rendered attribute, to determine whether or not the component will be rendered. For example, the check commandLink component on the bookcatalog.jsp page is not rendered if the cart contains no items:

<h:commandLink id="check"
    ...
    rendered="#{cart.numberOfItems > 0}">
    <h:outputText
        value="#{bundle.CartCheck}"/>
</h:commandLink>

Unlike nearly every other JavaServer Faces tag attribute, the rendered attribute is restricted to using rvalue expressions. As explained in Unified Expression Language, rvalue expressions can only read data; they cannot write the data back to the data source. Therefore, expressions used with rendered attributes can use the arithmetic operators and literals that rvalue expressions can use but lvalue expressions cannot use. For example, the expression in the preceding example uses the > operator.

The style and styleClass Attributes

The style and styleClass attributes allow you to specify Cascading Style Sheets (CSS) styles for the rendered output of your component tags. Displaying Error Messages with the message and messages Tags describes an example of using the style attribute to specify styles directly in the attribute. A component tag can instead refer to a CSS stylesheet class. The dataTable tag on the bookcatalog.jsp page of the Duke’s Bookstore application references the style class list-background:

<h:dataTable id="books"
    ...
    styleClass="list-background"
    value="#{bookDBAO.books}"
    var="book">

The stylesheet that defines this class is stylesheet.css, which is included in the application. For more information on defining styles, please the see Cascading Style Sheets Specification at http://www.w3.org/Style/CSS/.

The value and binding Attributes

A tag representing a component defined by UIOutput or a subclass of UIOutput uses value and binding attributes to bind its component’s value or instance respectively to an external data source. Binding Component Values and Instances to External Data Sources explains how to use these attributes.

Adding a Form Component

A UIForm component class represents an input form, which includes child components that contain data that is either presented to the user or submitted with the form.

Figure 11–1 shows a typical login form, in which a user enters a user name and password, and submits the form by clicking the Login button.

Figure 11–1 A Typical Form

Screen capture of form with User Name and Password text
fields and a Login button.

The form tag represents the UIForm component on the page and encloses all the components that display or collect data from the user, as shown here:

<h:form>
... other JavaServer Faces tags and other content...
</h:form>

The form tag can also include HTML markup to lay out the components on the page. The form tag itself does not perform any layout; its purpose is to collect data and to declare attributes that can be used by other components in the form. A page can include multiple form tags, but only the values from the form that the user submits will be included in the postback.

Using Text Components

Text components allow users to view and edit text in web applications. The basic kinds of text components are:

Figure 11–2 shows examples of these text components.

Figure 11–2 Example Text Components

Screen capture of form. "User Name" labels a text field.
"Password" labels a password field. "Comments" labels a text area.

An editable text component in a JavaServer Faces application is represented by a UIInput component. One example is a text field. A read-only text component in a JavaServer Faces application is represented by a UIOutput component. One example is a label.

The UIInput and UIOutput components can each be rendered in four ways to display more specialized text components. Table 11–3 lists all the renderers of UIInput and UIOutput and the tags that represent the component and renderer combination. Recall from Component Rendering Model that the name of a tag is composed of the name of the component and the name of the renderer. For example, the inputText tag refers to a UIInput component that is rendered with the Text renderer.

Table 11–3 UIInput and UIOutput Tags

Component 

Renderer 

Tag 

Function 

UIInput

Hidden

inputHidden

Allows a page author to include a hidden variable in a page 

Secret

inputSecret

The standard password field: Accepts one line of text with no spaces and displays it as a set of asterisks as it is typed 

Text

inputText

The standard text field: Accepts a text string of one line 

TextArea

inputTextarea

The standard text area: Accepts multiple lines of text 

UIOutput

Label

outputLabel

The standard read-only label: Displays a component as a label for a specified input field 

Link

outputLink

Displays an <a href> tag that links to another page without generating an action event

OutputMessage

outputFormat

Displays a localized message 

Text

outputText

Displays a text string of one line 

The UIInput component tags support the following tag attributes in addition to those described at the beginning of Adding UI Components to a Page Using the HTML Component Tags. This list does not include all the attributes supported by the UIInput component tags, just those that page authors will use most often. Please refer to the html_basic.tld file for the complete list.

The UIOutput component tags support the converter tag attribute in addition to those listed in Adding UI Components to a Page Using the HTML Component Tags. The rest of this section explains how to use selected tags listed in Table 11–3. The other tags are written in a similar way.

Rendering a Text Field with the inputText Tag

The inputText tag is used to display a text field. It represents the combination of a Text renderer and a UIInput component. A similar tag, the outputText tag, displays a read-only, single-line string. It represents the combination of a Text renderer and a UIOutput component. This section shows you how to use the inputText tag. The outputText tag is written in a similar way.

Here is an example of an inputText tag from the bookcashier.jsp page:

<h:inputText id="name" label="Customer Name" size="50"
    value="#{cashier.name}"
    required="true"
     requiredMessage="#{customMessages.CustomerName}">
     <f:valueChangeListener
         type="com.sun.bookstore6.listeners.NameChanged" />
 </h:inputText>

The label attribute specifies a user-friendly name that will be used in the substitution parameters of error messages displayed for this component.

The value attribute refers to the name property of CashierBean. This property holds the data for the name component. After the user submits the form, the value of the name property in CashierBean will be set to the text entered in the field corresponding to this tag.

The required attribute causes the page to reload with errors displayed if the user does not enter a value in the name text field. The JavaServer Faces implementation checks whether the value of the component is null or is an empty String.

If your component must have a non-null value or a String value at least one character in length, you should add a required attribute to your component tag and set it to true. If your tag does have a required attribute that is set to true and the value is null or a zero-length string, no other validators registered on the tag are called. If your tag does not have a required attribute set to true, other validators registered on the tag are called, but those validators must handle the possibility of a null or zero-length string.

The requiredMessage attribute references an error message from a resource bundle, which is declared in the application configuration file. Refer to Registering Custom Error Messages for details on how to declare and reference the resource bundle.

Rendering a Label with the outputLabel Tag

The outputLabel tag is used to attach a label to a specified input field for accessibility purposes. The bookcashier.jsp page uses an outputLabel tag to render the label of a check box:

<h:selectBooleanCheckbox
     id="fanClub"
    rendered="false"
    binding="#{cashier.specialOffer}" />
<h:outputLabel for="fanClub"
    rendered="false"
    binding="#{cashier.specialOfferText}"  >
    <h:outputText id="fanClubLabel"
        value="#{bundle.DukeFanClub}" />
</h:outputLabel>
...

The for attribute of the outputLabel tag maps to the id of the input field to which the label is attached. The outputText tag nested inside the outputLabel tag represents the actual label component. The value attribute on the outputText tag indicates the text that is displayed next to the input field.

Instead of using an outputText tag for the text displayed as a label, you can simply use the outputLabel tag’s value attribute. The following code snippet shows what the previous code snippet would look like if it used the value attribute of the outputLabel tag to specify the text of the label.

<h:selectBooleanCheckbox
     id="fanClub"
    rendered="false"
    binding="#{cashier.specialOffer}" />
    <h:outputLabel for="fanClub"
        rendered="false"
        binding="#{cashier.specialOfferText}"
         value="#{bundle.DukeFanClub}" />
    </h:outputLabel>
...

Rendering a Hyperlink with the outputLink Tag

The outputLink tag is used to render a hyperlink that, when clicked, loads another page but does not generate an action event. You should use this tag instead of the commandLink tag if you always want the URL (specified by the outputLink tag’s value attribute) to open and do not have to perform any processing when the user clicks on the link. The Duke’s Bookstore application does not utilize this tag, but here is an example of it:

<h:outputLink value="javadocs">
    Documentation for this demo
</h:outputLink>

The text in the body of the outputLink tag identifies the text the user clicks to get to the next page.

Displaying a Formatted Message with the outputFormat Tag

The outputFormat tag allows a page author to display concatenated messages as a MessageFormat pattern, as described in the API documentation for java.text.MessageFormat (see http://java.sun.com/javase/6/docs/api/java/text/MessageFormat.html). Here is an example of an outputFormat tag from the bookshowcart.jsp page of the Duke’s Bookstore application:

<h:outputFormat value="#{bundle.CartItemCount}">
    <f:param value="#{cart.numberOfItems}"/>
</h:outputFormat>

The value attribute specifies the MessageFormat pattern. The param tag specifies the substitution parameters for the message.

In the example outputFormat tag, the value for the parameter maps to the number of items in the shopping cart. When the message is displayed on the page, the number of items in the cart replaces the {0} in the message corresponding to the CartItemCount key in the bundle resource bundle:

Your shopping cart contains " + "{0,choice,0#no items|1#one item|1< {0} items

This message represents three possibilities:

The value of the parameter replaces the {0} from the message in the sentence in the third bullet. This is an example of a value-expression-enabled tag attribute accepting a complex EL expression.

An outputFormat tag can include more than one param tag for those messages that have more than one parameter that must be concatenated into the message. If you have more than one parameter for one message, make sure that you put the param tags in the proper order so that the data is inserted in the correct place in the message.

A page author can also hard code the data to be substituted in the message by using a literal value with the value attribute on the param tag.

Rendering a Password Field with the inputSecret Tag

The inputSecret tag renders an <input type="password"> HTML tag. When the user types a string into this field, a row of asterisks is displayed instead of the text the user types. The Duke’s Bookstore application does not include this tag, but here is an example of one:

<h:inputSecret redisplay="false"
    value="#{LoginBean.password}" />

In this example, the redisplay attribute is set to false. This will prevent the password from being displayed in a query string or in the source file of the resulting HTML page.

Using Command Components for Performing Actions and Navigation

The button and hyperlink components are used to perform and action, such as submitting a form, and for navigating to another page.

Command components in JavaServer Faces applications are represented by the UICommand component, which performs an action when it is activated. The UICommand component supports two renderers: Button and Link as UICommand component renderers.

The commandButton tag represents the combination of a UICommand component and a Button renderer and is rendered as a button. The commandLink tag represents the combination of a UICommand component and a Link renderer and is rendered as a hyperlink.

In addition to the tag attributes listed in Adding UI Components to a Page Using the HTML Component Tags, the commandButton and commandLink tags can use these attributes:

See Referencing a Method That Performs Navigation for more information on using the action attribute.

See Referencing a Method That Handles an Action Event for details on using the actionListener attribute.

Rendering a Button with the commandButton Tag

The bookcashier.jsp page of the Duke’s Bookstore application includes a commandButton tag. When a user clicks the button, the data from the current page is processed, and the next page is opened. Here is the commandButton tag from bookcashier.jsp:

<h:commandButton value="#{bundle.Submit}"
     action="#{cashier.submit}"/>

Clicking the button will cause the submit method of CashierBean to be invoked because the action attribute references the submit method of the CashierBean backing bean. The submit method performs some processing and returns a logical outcome. This is passed to the default NavigationHandler, which matches the outcome against a set of navigation rules defined in the application configuration resource file.

The value attribute of the preceding example commandButton tag references the localized message for the button’s label. The bundle part of the expression refers to the ResourceBundle that contains a set of localized messages. The Submit part of the expression is the key that corresponds to the message that is displayed on the button. For more information on referencing localized messages, see Rendering Components for Selecting Multiple Values. See Referencing a Method That Performs Navigation for information on how to use the action attribute.

Rendering a Hyperlink with the commandLink Tag

The commandLink tag represents an HTML hyperlink and is rendered as an HTML <a> element. The commandLink tag is used to submit an action event to the application. See Implementing Action Listeners for more information on action events.

A commandLink tag must include a nested outputText tag, which represents the text the user clicks to generate the event. The following tag is from the chooselocale.jsp page from the Duke’s Bookstore application.

<h:commandLink id="NAmerica" action="bookstore"
     actionListener="#{localeBean.chooseLocaleFromLink}">
     <h:outputText value="#{bundle.English}" />
</h:commandLink>

This tag will render the following HTML:

<a id="_id3:NAmerica" href="#"
     onclick="document.forms[’_id3’][’_id3:NAmerica’].
    value=’_id3:NAmerica’;
     document.forms[’_id3’].submit();
     return false;">English</a>

Note –

The commandLink tag will render JavaScript. If you use this tag, make sure your browser is JavaScript-enabled.


Using Data-Bound Table Components

Data-bound table components display relational data in a tabular format. Figure 11–3 shows an example of this kind of table.

Figure 11–3 Table on the bookshowcart.jsp Page

Screen capture of cart, showing quantities, titles, prices,
and Remove Item buttons.

In a JavaServer Faces application, the UIData component supports binding to a collection of data objects. It does the work of iterating over each record in the data source. The standard Table renderer displays the data as an HTML table. The UIColumn component represents a column of data within the table. Here is a portion of the dataTable tag used by the bookshowcart.jsp page of the Duke’s Bookstore example:

<h:dataTable id="items"
     captionClass="list-caption"
    columnClasses="list-column-center, list-column-left,
         list-column-right, list-column-center"
    footerClass="list-footer"
    headerClass="list-header"
    rowClasses="list-row-even, list-row-odd"
    styleClass="list-background"
    summary="#{bundle.ShoppingCart}"
    value="#{cart.items}"
    var="item">
    <h:column headerClass="list-header-left">
        <f:facet name="header">
            <h:outputText value="#{bundle.ItemQuantity}" />
        </f:facet>
        <h:inputText id="quantity" size="4"
            value="#{item.quantity}" >
            ...
        </h:inputText>
        ...
    </h:column>
    <h:column>
        <f:facet name="header">
            <h:outputText value="#{bundle.ItemTitle}"/>
        </f:facet>
        <h:commandLink action="#{showcart.details}">
            <h:outputText value="#{item.item.title}"/>
        </h:commandLink>
    </h:column>
    ...
    <f:facet name="footer"
        <h:panelGroup>
            <h:outputText value="#{bundle.Subtotal}"/>
            <h:outputText value="#{cart.total}" />
                <f:convertNumber type="currency" />
            </h:outputText>
        </h:panelGroup>
    </f:facet>
    <f:facet name="caption"
        <h:outputText value="#{bundle.Caption}"/>
</h:dataTable>

Figure 11–3 shows a data grid that this dataTable tag can display.

The example dataTable tag displays the books in the shopping cart as well as the quantity of each book in the shopping cart, the prices, and a set of buttons, which the user can click to remove books from the shopping cart.

The column tags represent columns of data in a UIData component. While the UIData component is iterating over the rows of data, it processes the UIColumn component associated with each column tag for each row in the table.

The UIData component shown in the preceding code example iterates through the list of books (cart.items) in the shopping cart and displays their titles, authors, and prices. Each time UIData iterates through the list of books, it renders one cell in each column.

The dataTable and column tags use facets to represent parts of the table that are not repeated or updated. These include headers, footers, and captions.

In the preceding example, column tags include facet tags for representing column headers or footers. The column tag allows you to control the styles of these headers and footers by supporting the headerClass and footerClass attributes. These attributes accept space-separated lists of CSS style classes, which will be applied to the header and footer cells of the corresponding column in the rendered table.

Facets can have only one child, and so a panelGroup tag is needed if you want to group more than one component within a facet. Because the facet tag representing the footer includes more than one tag, the panelGroup is needed to group those tags. Finally, this dataTable tag includes a facet tag with its name attribute set to caption, causing a table caption to be rendered below the table.

This table is a classic use case for a UIData component because the number of books might not be known to the application developer or the page author at the time the application is developed. The UIData component can dynamically adjust the number of rows of the table to accommodate the underlying data.

The value attribute of a dataTable tag references the data to be included in the table. This data can take the form of

All data sources for UIData components have a DataModel wrapper. Unless you explicitly construct a DataModel wrapper, the JavaServer Faces implementation will create one around data of any of the other acceptable types. See Writing Bean Properties for more information on how to write properties for use with a UIData component.

The var attribute specifies a name that is used by the components within the dataTable tag as an alias to the data referenced in the value attribute of dataTable.

In the dataTable tag from the bookshowcart.jsp page, the value attribute points to a list of books. The var attribute points to a single book in that list. As the UIData component iterates through the list, each reference to item points to the current book in the list.

The UIData component also has the ability to display only a subset of the underlying data. This is not shown in the preceding example. To display a subset of the data, you use the optional first and rows attributes.

The first attribute specifies the first row to be displayed. The rows attribute specifies the number of rows, starting with the first row, to be displayed. For example, if you wanted to display records 2 through 10 of the underlying data, you would set first to 2 and rows to 9. When you display a subset of the data in your pages, you might want to consider including a link or button that causes subsequent rows to display when clicked. By default, both first and rows are set to zero, and this causes all the rows of the underlying data to display.

The dataTable tag also has a set of optional attributes for adding styles to the table:

Each of these attributes can specify more than one style. If columnClasses or rowClasses specifies more than one style, the styles are applied to the columns or rows in the order that the styles are listed in the attribute. For example, if columnClasses specifies styles list-column-center and list-column-right and if there are two columns in the table, the first column will have style list-column-center, and the second column will have style list-column-right.

If the style attribute specifies more styles than there are columns or rows, the remaining styles will be assigned to columns or rows starting from the first column or row. Similarly, if the style attribute specifies fewer styles than there are columns or rows, the remaining columns or rows will be assigned styles starting from the first style.

Adding Graphics and Images with the graphicImage Tag

In a JavaServer Faces application, the UIGraphic component represents an image. The graphicImage tag is used to render a UIGraphic component on a page. The Duke’s Bookstore application uses a graphicImage tag to display the map image on the chooselocale.jsp page:

<h:graphicImage id="mapImage" url="/template/world.jpg"
     alt="#{bundle.chooseLocale}" usemap="#worldMap" />

The url attribute specifies the path to the image. It also corresponds to the local value of the UIGraphic component so that the URL can be retrieved, possibly from a backing bean. The URL of the example tag begins with a /, which adds the relative context path of the web application to the beginning of the path to the image.

The title attribute specifies the alternative text displayed when the user mouses over the image. In this example, the title attribute refers to a localized message. See Performing Localization for details on how to localize your JavaServer Faces application.

The usemap attribute refers to the image map defined by the custom component, MapComponent, which is on the same page. See Chapter 13, Creating Custom UI Components for more information on the image map.

Laying Out Components with the UIPanel Component

In a JavaServer Faces application, you use the UIPanel component as a layout container for a set of component components. When you use the renderers from the HTML render kit, UIPanel is rendered as an HTML table. This component differs from UIData in that UIData can dynamically add or delete rows to accommodate the underlying data source, whereas UIPanel must have the number of rows predetermined. Table 11–4 lists all the renderers and tags corresponding to the UIPanel component.

Table 11–4 UIPanel Renderers and Tags

Renderer 

Tag 

Renderer Attributes 

Function 

Grid

panelGrid

columnClasses, columns, footerClass, headerClass, panelClass, rowClasses

Displays a table 

Group

panelGroup

layout

Groups a set of components under one parent 

The panelGrid tag is used to represent an entire table. The panelGroup tag is used to represent rows in a table. Other UI component tags are used to represent individual cells in the rows.

The panelGrid tag has a set of attributes that specify CSS stylesheet classes: columnClasses, footerClass, headerClass, panelClass, and rowClasses. These stylesheet attributes are optional. The panelGrid tag also has a columns attribute. The columns attribute is required if you want your table to have more than one column because the columns attribute tells the renderer how to group the data in the table.

If the headerClass attribute value is specified, the panelGrid must have a header as its first child. Similarly, if a footerClass attribute value is specified, the panelGrid must have a footer as its last child.

The Duke’s Bookstore application includes three panelGrid tags on the bookcashier.jsp page. Here is a portion of one of them:

<h:panelGrid columns="3" headerClass="list-header"
    rowClasses="list-row-even, list-row-odd"
    styleClass="list-background"
    title="#{bundle.Checkout}">
    <f:facet name="header">
        <h:outputText value="#{bundle.Checkout}"/>
    </f:facet>
    <h:outputText value="#{bundle.Name}" />
    <h:inputText id="name" size="50"
         value="#{cashier.name}"
        required="true">
         <f:valueChangeListener
             type="listeners.NameChanged" />
    </h:inputText>
    <h:message styleClass="validationMessage" for="name"/>
    <h:outputText value="#{bundle.CCNumber}"/>
    <h:inputText id="ccno" size="19"
        converter="CreditCardConverter" required="true">
         <bookstore:formatValidator
             formatPatterns="9999999999999999|
                9999 9999 9999 9999|9999-9999-9999-9999"/>
    </h:inputText>
    <h:message styleClass="validationMessage"  for="ccno"/>
    ...
</h:panelGrid>

This panelGrid tag is rendered to a table that contains components for the customer of the bookstore to input personal information. This panelGrid tag uses stylesheet classes to format the table. The CSS classes are defined in the stylesheet.css file in the tut-install/javaeetutorial5/examples/web/bookstore6/web/ directory. The list-header definition is

.list-header {
     background-color: #ffffff;
    color: #000000;
    text-align: center;
}

Because the panelGrid tag specifies a headerClass, the panelGrid must contain a header. The example panelGrid tag uses a facet tag for the header. Facets can have only one child, and so a panelGroup tag is needed if you want to group more than one component within a facet. Because the example panelGrid tag has only one cell of data, a panelGroup tag is not needed.

The panelGroup tag has one attribute, called layout, in addition to those listed in UI Component Tag Attributes. If the layout attribute has the value block then an HTML div element is rendered to enclose the row; otherwise, an HTML span element is rendered to enclose the row. If you are specifying styles for the panelGroup tag, you should set the layout attribute to block in order for the styles to be applied to the components within the panelGroup tag. This is because styles such as those that set width and height are not applied to inline elements, which is how content enclosed by the span element is defined.

A panelGroup tag can also be used to encapsulate a nested tree of components so that the tree of components appears as a single component to the parent component.

The data represented by the nested component tags is grouped into rows according to the value of the columns attribute of the panelGrid tag. The columns attribute in the example is set to 3, and therefore the table will have three columns. In which column each component is displayed is determined by the order that the component is listed on the page modulo 3. So if a component is the fifth one in the list of components, that component will be in the 5 modulo 3 column, or column 2.

Rendering Components for Selecting One Value

Another common UI component is one that allows a user to select one value, whether it be the only value available or one of a set of choices. The most common examples of this kind of component are:

Figure 11–4 shows examples of these components.

Figure 11–4 Example Select One Components

Screen capture of radio buttons, check box, drop-down
menu, and list box.

Displaying a Check Box Using the selectBooleanCheckbox Tag

The UISelectBoolean class defines components that have a boolean value. The selectBooleanCheckbox tag is the only tag that JavaServer Faces technology provides for representing boolean state. The Duke’s Bookstore application includes a selectBooleanCheckbox tag on the bookcashier.jsp page:

<h:selectBooleanCheckbox
     id="fanClub"
    rendered="false"
    binding="#{cashier.specialOffer}" />
<h:outputLabel
     for="fanClub"
    rendered="false"
    binding="#{cashier.specialOfferText}">
     <h:outputText
         id="fanClubLabel"
        value="#{bundle.DukeFanClub}" />
</h:outputLabel>

This example tag displays a check box to allow users to indicate whether they want to join the Duke Fan Club. The label for the check box is rendered by the outputLabel tag. The actual text is represented by the nested outputText tag. Binding a Component Instance to a Bean Property discusses this example in more detail.

Displaying a Menu Using the selectOneMenu Tag

A UISelectOne component allows the user to select one value from a set of values. This component can be rendered as a list box, a set of radio buttons, or a menu. This section explains the selectOneMenu tag. The selectOneRadio and selectOneListbox tags are written in a similar way. The selectOneListbox tag is similar to the selectOneMenu tag except that selectOneListbox defines a size attribute that determines how many of the items are displayed at once.

The selectOneMenu tag represents a component that contains a list of items, from which a user can choose one item. The menu is also commonly known as a drop-down list or a combo box. The following code snippet shows the selectOneMenu tag from the bookcashier.jsp page of the Duke’s Bookstore application. This tag allows the user to select a shipping method:

<h:selectOneMenu   id="shippingOption"
    required="true"
    value="#{cashier.shippingOption}">
    <f:selectItem
        itemValue="2"
        itemLabel="#{bundle.QuickShip}"/>
    <f:selectItem
        itemValue="5"
        itemLabel="#{bundle.NormalShip}"/>
    <f:selectItem
        itemValue="7"
        itemLabel="#{bundle.SaverShip}"/>
 </h:selectOneMenu>

The value attribute of the selectOneMenu tag maps to the property that holds the currently selected item’s value. You are not required to provide a value for the currently selected item. If you don’t provide a value, the first item in the list is selected by default.

Like the selectOneRadio tag, the selectOneMenu tag must contain either a selectItems tag or a set of selectItem tags for representing the items in the list. The UISelectItem, UISelectItems, and UISelectItemGroup Components explains these tags.

Rendering Components for Selecting Multiple Values

In some cases, you need to allow your users to select multiple values rather than just one value from a list of choices. You can do this using one of the following kinds of components:

Figure 11–5 shows examples of these components.

Figure 11–5 Example Select Many Components

Screen capture of check box set, drop-down menu, and
list box.

The UISelectMany class defines a component that allows the user to select zero or more values from a set of values. This component can be rendered as a set of check boxes, a list box, or a menu. This section explains the selectManyCheckbox tag. The selectManyListbox tag and selectManyMenu tag are written in a similar way.

A list box differs from a menu in that it displays a subset of items in a box, whereas a menu displays only one item at a time when the user is not selecting the menu. The size attribute of the selectManyListbox tag determines the number of items displayed at one time. The list box includes a scroll bar for scrolling through any remaining items in the list.

The selectManyCheckbox tag renders a set of check boxes, with each check box representing one value that can be selected. Duke’s Bookstore uses a selectManyCheckbox tag on the bookcashier.jsp page to allow the user to subscribe to one or more newsletters:

<h:selectManyCheckbox
    id="newsletters"
    layout="pageDirection"
    value="#{cashier.newsletters}">
    <f:selectItems
        value="#{newsletters}"/>
</h:selectManyCheckbox>

The value attribute of the selectManyCheckbox tag identifies the CashierBean backing bean property, newsletters, for the current set of newsletters. This property holds the values of the currently selected items from the set of check boxes. You are not required to provide a value for the currently selected items. If you don’t provide a value, the first item in the list is selected by default.

The layout attribute indicates how the set of check boxes are arranged on the page. Because layout is set to pageDirection, the check boxes are arranged vertically. The default is lineDirection, which aligns the check boxes horizontally.

The selectManyCheckbox tag must also contain a tag or set of tags representing the set of check boxes. To represent a set of items, you use the selectItems tag. To represent each item individually, you use a selectItem tag for each item. The following subsection explains these tags in more detail.

The UISelectItem, UISelectItems, and UISelectItemGroup Components

UISelectItem and UISelectItems represent components that can be nested inside a UISelectOne or a UISelectMany component. UISelectItem is associated with a SelectItem instance, which contains the value, label, and description of a single item in the UISelectOne or UISelectMany component.

The UISelectItems instance represents either of the following:

Figure 11–6 shows an example of a list box constructed with a SelectItems component representing two SelectItemGroup instances, each of which represents two categories of beans. Each category is an array of SelectItem instances.

Figure 11–6 An Example List Box Created Using SelectItemGroup Instances

Screen capture of list box with two groups of items.

The selectItem tag represents a UISelectItem component. The selectItems tag represents a UISelectItems component. You can use either a set of selectItem tags or a single selectItems tag within your selectOne or selectMany tag.

The advantages of using the selectItems tag are as follows:

The advantages of using selectItem are as follows:

For more information on writing component properties for the UISelectItems components, see Writing Bean Properties. The rest of this section shows you how to use the selectItems and selectItem tags.

Using the selectItems Tag

Here is the selectManyCheckbox tag from the section Rendering Components for Selecting Multiple Values:

<h:selectManyCheckbox
    id="newsletters"
    layout="pageDirection"
    value="#{cashier.newsletters}">
    <f:selectItems
        value="#{newsletters}"/>
</h:selectManyCheckbox>

The value attribute of the selectItems tag is bound to the newsletters managed bean, which is configured in the application configuration resource file. The newsletters managed bean is configured as a list:

<managed-bean>
    <managed-bean-name>newsletters</managed-bean-name>
    <managed-bean-class>
        java.util.ArrayList</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
    <list-entries>
        <value-class>javax.faces.model.SelectItem</value-class>
        <value>#{newsletter0}</value>
        <value>#{newsletter1}</value>
        <value>#{newsletter2}</value>
        <value>#{newsletter3}</value>
    </list-entries>
</managed-bean>
<managed-bean>
<managed-bean-name>newsletter0</managed-bean-name>
<managed-bean-class>
    javax.faces.model.SelectItem</managed-bean-class>
<managed-bean-scope>none</managed-bean-scope>
<managed-property>
    <property-name>label</property-name>
    <value>Duke’s Quarterly</value>
</managed-property>
<managed-property>
    <property-name>value</property-name>
    <value>200</value>
</managed-property>
</managed-bean>
...

As shown in the managed-bean element, the UISelectItems component is a collection of SelectItem instances. See Initializing Array and List Properties for more information on configuring collections as beans.

You can also create the list corresponding to a UISelectMany or UISelectOne component programmatically in the backing bean. See Writing Bean Properties for information on how to write a backing bean property corresponding to a UISelectMany or UISelectOne component.

The arguments to the SelectItem constructor are:

UISelectItems Properties describes in more detail how to write a backing bean property for a UISelectItems component.

Using the selectItem Tag

The selectItem tag represents a single item in a list of items. Here is the example from Displaying a Menu Using the selectOneMenu Tag:

<h:selectOneMenu
       id="shippingOption" required="true"
     value="#{cashier.shippingOption}">
    <f:selectItem
        itemValue="2"
        itemLabel="#{bundle.QuickShip}"/>
    <f:selectItem
        itemValue="5"
        itemLabel="#{bundle.NormalShip}"/>
    <f:selectItem
        itemValue="7"
        itemLabel="#{bundle.SaverShip}"/>
 </h:selectOneMenu>

The itemValue attribute represents the default value of the SelectItem instance. The itemLabel attribute represents the String that appears in the drop-down menu component on the page.

The itemValue and itemLabel attributes are value-binding-enabled, meaning that they can use value-binding expressions to refer to values in external objects. They can also define literal values, as shown in the example selectOneMenu tag.

Displaying Error Messages with the message and messages Tags

The message and messages tags are used to display error messages when conversion or validation fails. The message tag displays error messages related to a specific input component, whereas the messages tag displays the error messages for the entire page.

Here is an example message tag from the guessNumber application, discussed in Steps in the Development Process:

<h:inputText id="userNo" value="#{UserNumberBean.userNumber}">
    <f:validateLongRange minimum="0" maximum="10" />
 <h:commandButton id="submit"
         action="success" value="Submit" /><p>
<h:message
     style="color: red;
     font-family: ’New Century Schoolbook’, serif;
     font-style: oblique;
     text-decoration: overline" id="errors1" for="userNo"/>

The for attribute refers to the ID of the component that generated the error message. The error message is displayed at the same location that the message tag appears in the page. In this case, the error message will appear after the Submit button.

The style attribute allows you to specify the style of the text of the message. In the example in this section, the text will be red, New Century Schoolbook, serif font family, and oblique style, and a line will appear over the text. The message and messages tags support many other attributes for defining styles. Please refer to the TLD documentation for more information on these attributes.

Another attribute the messages tag supports is the layout attribute. Its default value is list, which indicates that the messages are displayed in a bulleted list using the HTML ul and li elements. If you set the attribute to table, the messages will be rendered in a table using the HTML table element.

The preceding example shows a standard validator is registered on input component. The message tag displays the error message associated with this validator when the validator cannot validate the input component’s value. In general, when you register a converter or validator on a component, you are queueing the error messages associated with the converter or validator on the component. The message and messages tags display the appropriate error messages that are queued on the component when the validators or converters registered on that component fail to convert or validate the component’s value.

All the standard error messages that come with the standard converters and validators are listed in section 2.5.4 of the JavaServer Faces specification. An application architect can override these standard messages and supply error messages for custom converters and validators by registering custom error messages with the application by means of the message-bundle element of the application configuration file. Referencing Error Messages explains more about error messages.

Using Localized Data

JavaServer Faces applications make use of three different kinds of data that can be localized:

This section discusses how to access the first two kinds of data from the page. Performing Localization explains how to produce localized error messages as well as how to localize dynamic data. If you are not familiar with the basics of localizing web applications, see Chapter 15, Internationalizing and Localizing Web Applications.

All data in the Duke’s Bookstore application have been localized for Spanish, French, German, and American English. The image map on the first page allows you to select your preferred locale. See Chapter 13, Creating Custom UI Components for information on how the image map custom component was created.

All the localized data is stored in resource bundles, which are represented as either ResourceBundle classes or text files, usually with the extension .properties. For more information about resource bundles, see http://java.sun.com/docs/books/tutorial/i18n/index.html.

After the application developer has produced a resource bundle, the application architect puts it in the same directory as the application classes. The static text data for the Duke’s Bookstore application is stored in a ResourceBundle class called BookstoreMessages. The error messages are stored in another resource bundle called ApplicationMessages. After the resource bundles have been created and before their data can be accessed, they must be made available to the application, as explained in the following section.

Loading a Resource Bundle

To reference error messages or static data from the page, you first need to make available the resource bundle containing the data.

To make available resource bundles that contain static data, you need to do one of two things:

Here is an example loadBundle tag from bookstore.jsp:

<f:loadBundle var="bundle"
    basename="messages.BookstoreMessages" />

The basename attribute value specifies the fully-qualified class name of the ResourceBundle class, which in this case is located in the messages package of the bookstore application.

The var attribute is an alias to the ResourceBundle class. This alias can be used by other tags in the page in order to access the localized messages.

In the case of resource bundles that contain error messages, you need to register the resource bundle with the application in the configuration file using the message-bundle element, as explained in Registering Custom Error Messages. One exception is if you are referencing the error messages from the input component attributes described in Referencing Error Messages. In that case, you load the resource bundles containing these messages in the same way you load resource bundles containing static text.

Referencing Localized Static Data

To reference static localized data from a resource bundle, you use a value expression from an attribute of the component tag that will display the localized data. You can reference the message from any component tag attribute that is enabled to accept value expressions.

The value expression has the notation var.message, in which var matches the var attribute of the loadBundle tag or the var element in the configuration file, and message matches the key of the message contained in the resource bundle, referred to by the var attribute. Here is an example from bookstore.jsp:

<h:outputText value="#{bundle.Talk}"/>

Notice that bundle matches the var attribute from the loadBundle tag and that Talk matches the key in the ResourceBundle.

Another example is the graphicImage tag from chooselocale.jsp:

<h:graphicImage id="mapImage" url="/template/world.jpg"
     alt="#{bundle.ChooseLocale}"
    usemap="#worldMap" />

The alt attribute is enabled to accept value expressions. In this case, the alt attribute refers to localized text that will be included in the alternative text of the image rendered by this tag.

See Creating Custom Component Classes and Enabling Component Properties to Accept Expressions for information on how to enable value binding on your custom component’s attributes.

Referencing Error Messages

A JavaServer Faces page uses the message or messages tags to access error messages, as explained in Displaying Error Messages with the message and messages Tags.

The error messages that these tags access include:

When a converter or validator is registered on an input component, the appropriate error message is automatically queued on the component.

A page author can override the error messages queued on a component by using the following attributes of the component’s tag:

All three attributes are enabled to take literal values and value expressions. If an attribute uses a value expression, this expression references the error message in a resource bundle. This resource bundle must be made available to the application in one of the following ways:

Conversely, the message-bundle element must be used to make available to the application those resource bundles containing custom error messages that are queued on the component as a result of a custom converter or validator being registered on the component.

The bookcashier.jsp page includes an example of the requiredMessage attribute using a value expression to reference an error message:

<h:inputText id="ccno" size="19"
    required="true"
    requiredMessage="#{customMessages.ReqMessage}" >
    ...
</h:inputText>
<h:message styleClass="error-message"  for="ccno"/>

The value expression that requiredMessage is using in this example references the error message with the ReqMessage key in the resource bundle, customMessages.

This message replaces the corresponding message queued on the component and will display wherever the message or messages tag is placed on the page.

See Registering Custom Error Messages and Registering Custom Localized Static Text for information on how to use the message-bundle and resource-bundle element to register resource bundles that contain error messages.

Using the Standard Converters

The JavaServer Faces implementation provides a set of Converter implementations that you can use to convert component data. For more information on the conceptual details of the conversion model, see Conversion Model.

The standard Converter implementations, located in the javax.faces.convert package, are as follows:

Each of these converters has a standard error message associated with them. If you have registered one of these converters onto a component on your page, and the converter is not able to convert the component’s value, the converter’s error message will display on the page. For example, the error message that displays if BigIntegerConverter fails to convert a value is:


{0} must be a number consisting of one or more digits

In this case the {0} substitution parameter will be replaced with the name of the input component on which the converter is registered. See section 2.4.5 of the JavaServer Faces specification, version 1.2, for a complete list of error messages.

Two of the standard converters (DateTimeConverter and NumberConverter) have their own tags, which allow you to configure the format of the component data using the tag attributes. Using DateTimeConverter discusses using DateTimeConverter. Using NumberConverter discusses using NumberConverter. The following section explains how to convert a component’s value including how to register the other standard converters with a component.

Converting a Component’s Value

To use a particular converter to convert a component’s value, you need to register the converter onto the component. You can register any of the standard converters on a component in one of four ways:

As an example of the second approach, if you want a component’s data to be converted to an Integer, you can simply bind the component’s value to a property similar to this:

Integer age = 0;
public Integer getAge(){ return age;}
public void setAge(Integer age) {this.age = age;}

If the component is not bound to a bean property, you can employ the third technique by using the converter attribute on the component tag:

<h:inputText
    converter="javax.faces.convert.IntegerConverter" />

This example shows the converter attribute referring to the fully-qualified class name of the converter. The converter attribute can also take the ID of the component. If the converter is a custom converter, the ID is defined in the application configuration resource file (see Application Configuration Resource File).

The data corresponding to this example inputText tag will be converted to a java.lang.Integer. Notice that the Integer type is already a supported type of the NumberConverter. If you don’t need to specify any formatting instructions using the convertNumber tag attributes, and if one of the other converters will suffice, you can simply reference that converter using the component tag’s converter attribute.

Finally, you can nest a converter tag within the component tag and use either the converter tag’s converterId attribute or its binding attribute to reference the converter.

The converterId attribute must reference the converter’s ID. Again, if the converter is a custom converter, the value of converterID must match the ID in the application configuration resource file; otherwise it must match the ID as defined in the converter class. Here is an example:

<h:inputText value="#{LoginBean.Age}" />
    <f:converter converterId="Integer" />
</h:inputText>

Instead of using the converterId attribute, the converter tag can use the binding attribute. The binding attribute must resolve to a bean property that accepts and returns an appropriate Converter instance. See Binding Converters, Listeners, and Validators to Backing Bean Properties for more information.

Using DateTimeConverter

You can convert a component’s data to a java.util.Date by nesting the convertDateTime tag inside the component tag. The convertDateTime tag has several attributes that allow you to specify the format and type of the data. Table 11–5 lists the attributes.

Here is a simple example of a convertDateTime tag from the bookreceipt.jsp page:

<h:outputText id= "shipDate" value="#{cashier.shipDate}">
    <f:convertDateTime dateStyle="full" />
</h:outputText>

When binding the DateTime converter to a component, ensure that the backing bean property to which the component is bound is of type java.util.Date. In the case of the preceding example, cashier.shipDate must be of type java.util.Date.

Here is an example of a date and time that the preceding tag can display:


Saturday, Feb 22, 2003

You can also display the same date and time using this tag:

<h:outputText value="#{cashier.shipDate}">
    <f:convertDateTime
         pattern="EEEEEEEE, MMM dd, yyyy" />
</h:outputText>

If you want to display the example date in Spanish, you can use the locale attribute:

<h:inputText value="#{cashier.shipDate}">
    <f:convertDateTime dateStyle="full"
         locale="Locale.SPAIN"
        timeStyle="long" type="both" />
</h:inputText>

This tag would display


sabado 23 de septiembre de 2006

Please refer to the Customizing Formats lesson of the Java Tutorial at http://java.sun.com/docs/books/tutorial/i18n/format/simpleDateFormat.html for more information on how to format the output using the pattern attribute of the convertDateTime tag.

Table 11–5 convertDateTime Tag Attributes

Attribute 

Type 

Description 

binding

DateTimeConverter

Used to bind a converter to a backing bean property 

dateStyle

String

Defines the format, as specified by java.text.DateFormat, of a date or the date part of a date string. Applied only if type is date (or both) and pattern is not defined. Valid values: default, short, medium, long, and full. If no value is specified, default is used.

locale

String or Locale

Locale whose predefined styles for dates and times are used during formatting or parsing. If not specified, the Locale returned by FacesContext.getLocale will be used.

pattern

String

Custom formatting pattern that determines how the date/time string should be formatted and parsed. If this attribute is specified, dateStyle, timeStyle, and type attributes are ignored.

timeStyle

String

Defines the format, as specified by java.text.DateFormat, of a time or the time part of a date string. Applied only if type is time and pattern is not defined. Valid values: default, short, medium, long, and full. If no value is specified, default is used.

timeZone

String or TimeZone

Time zone in which to interpret any time information in the date string.

type

String

Specifies whether the string value will contain a date, a time, or both. Valid values are date, time, or both. If no value is specified, date is used.

Using NumberConverter

You can convert a component’s data to a java.lang.Number by nesting the convertNumber tag inside the component tag. The convertNumber tag has several attributes that allow you to specify the format and type of the data. Table 11–6 lists the attributes.

The bookcashier.jsp page of Duke’s Bookstore uses a convertNumber tag to display the total prices of the books in the shopping cart:

<h:outputText value="#{cart.total}" >
    <f:convertNumber type="currency"/>
</h:outputText>

When binding the Number converter to a component, ensure that the backing bean property to which the component is bound is of primitive type or has a type of java.lang.Number. In the case of the preceding example, cart.total is of type java.lang.Number.

Here is an example of a number this tag can display


$934

This number can also be displayed using this tag:

<h:outputText id="cartTotal"
     value="#{cart.Total}" >
    <f:convertNumber pattern="
$####"
 />
</h:outputText>

Please refer to the Customizing Formats lesson of the Java Tutorial at http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html for more information on how to format the output using the pattern attribute of the convertNumber tag.

Table 11–6 convertNumber Attributes

Attribute 

Type 

Description 

binding

NumberConverter

Used to bind a converter to a backing bean property 

currencyCode

String

ISO 4217 currency code, used only when formatting currencies. 

currencySymbol

String

Currency symbol, applied only when formatting currencies. 

groupingUsed

boolean

Specifies whether formatted output contains grouping separators. 

integerOnly

boolean

Specifies whether only the integer part of the value will be parsed. 

locale

String or Locale

Locale whose number styles are used to format or parse data.

maxFractionDigits

int

Maximum number of digits formatted in the fractional part of the output. 

maxIntegerDigits

int

Maximum number of digits formatted in the integer part of the output. 

minFractionDigits

int

Minimum number of digits formatted in the fractional part of the output. 

minIntegerDigits

int

Minimum number of digits formatted in the integer part of the output. 

pattern

String

Custom formatting pattern that determines how the number string is formatted and parsed. 

type

String

Specifies whether the string value is parsed and formatted as a number, currency, or percentage. If not specified, number is used.

Registering Listeners on Components

An application developer can implement listeners as classes or as backing bean methods. If a listener is a backing bean method, the page author references the method from either the component’s valueChangeListener attribute or its actionListener attribute. If the listener is a class, the page author can reference the listener from either a valueChangeListener tag or an actionListener tag and nest the tag inside the component tag in order to register the listener on the component.

Referencing a Method That Handles an Action Event and Referencing a Method That Handles a Value-change Event describe how a page author uses the valueChangeListener and actionListener attributes to reference backing bean methods that handle events.

The Duke’s Bookstore application includes a ValueChangeListener implementation class but does not use an ActionListener implementation class. This section explains how to register the NameChanged value-change listener and a hypothetical LocaleChange action listener implementation on components. Implementing Value-Change Listeners explains how to implement NameChanged. Implementing Action Listeners explains how to implement the hypothetical LocaleChange listener.

Registering a Value-Change Listener on a Component

A page author can register a ValueChangeListener implementation on a component that implements EditableValueHolder by nesting a valueChangeListener tag within the component’s tag on the page. The valueChangeListener tag supports two attributes:

A page author must use one of these attributes to reference the value-change listener. The type attribute accepts a literal or a value expression. The binding attribute only accepts a value expression, which must point to a backing bean property that accepts and returns a ValueChangeListener implementation.

Following is the tag corresponding to the name component from the bookcashier.jsp page. It uses the type attribute to reference a value-change listener:

<h:inputText  id="name" size="50" value="#{cashier.name}"
     required="true">    
     <f:valueChangeListener type="listeners.NameChanged" />
</h:inputText>

The type attribute specifies the custom NameChanged listener as the ValueChangeListener implementation to register on the name component.

After this component tag is processed and local values have been validated, its corresponding component instance will queue the ValueChangeEvent associated with the specified ValueChangeListener to the component.

The binding attribute is used to bind a ValueChangeListener implementation to a backing bean property. It works in a similar way to the binding attribute supported by the standard converter tags. Binding Component Values and Instances to External Data Sources explains more about binding listeners to backing bean properties.

Registering an Action Listener on a Component

A page author can register an ActionListener implementation on a UICommand component by nesting an actionListener tag within the component’s tag on the page. Similarly to the valueChangeListener tag, the actionListener tag supports both the type and binding attributes. A page author must use one of these attributes to reference the action listener.

Duke’s Bookstore does not use any ActionListener implementations. Here is one of the commandLink tags on the chooselocale.jsp page, changed to reference an ActionListener implementation rather than a backing bean method:

<h:commandLink id="NAmerica" action="bookstore">
     <f:actionListener type="listeners.LocaleChange" />
</h:commandLink>

The type attribute of the actionListener tag specifies the fully qualified class name of the ActionListener implementation. Similarly to the valueChangeListener tag, the actionListener tag also supports the binding attribute. Binding Converters, Listeners, and Validators to Backing Bean Properties explains more about how to bind listeners to backing bean properties.

When this tag’s component is activated, the component’s decode method (or its associated Renderer) automatically queues the ActionEvent implementation associated with the specified ActionListener implementation onto the component.

In addition to the actionListener tag that allows you register a custom listener onto a component, the core tag library includes the setPropertyActionListener tag. You use this tag to register a special action listener onto the ActionSource instance associated with a component. When the component is activated, the listener will store the object referenced by the tag’s value attribute into the object referenced by the tag’s target attribute.

The bookcatalog.jsp page uses setPropertyActionListener with two components: the commandLink component used to link to the bookdetails.jsp page and the commandButton component used to add a book to the cart:

<c:forEach items="#{bookDBAO.books}" var="book"
     varStatus="stat">
    <c:set var="book" scope="request" value="${book}"/>
        ...
    <h:commandLink action="#{catalog.details}"
        value="#{book.title}">
        <f:setPropertyActionListener
             target="#{requestScope.book}" value="#{book}"/>
    </h:commandLink>
    ...
    <h:commandButton id="add"
        action="#{catalog.add}" value="#{bundle.CartAdd}">
        <f:setPropertyActionListener
             target="#{requestScope.book}" value="#{book}"/>
    </h:commandButton>
    <c:remove var="book" scope="request"/>
</c:forEach>

As shown in the preceding code, the commandLink and commandButton components are within a forEach tag, which iterates over the list of books. The var attribute refers to a single book in the list of books.

The object referenced by the var attribute of a forEach tag is in page scope. However, in this case, you need to put this object into request scope so that when the user activates the commandLink component to go to bookdetails.jsp or activates the commandButton component to go to bookcatalog.jsp, the book data is available to those pages. Therefore, the setPropertyActionListener tag is used to set the current book object into request scope when the commandLink or commandButton component is activated.

In the preceding example, the setPropertyActionListener tag’s value attribute references the book object. The setPropertyActionListener tag’s target attribute references the value expression requestScope.book, which is where the book object referenced by the value attribute is stored when the commandLink or the commandButton component is activated.

Using the Standard Validators

JavaServer Faces technology provides a set of standard classes and associated tags that page authors and application developers can use to validate a component’s data. Table 11–7 lists all the standard validator classes and the tags that allow you to use the validators from the page.

Table 11–7 The Validator Classes

Validator Class 

Tag 

Function 

DoubleRangeValidator

validateDoubleRange

Checks whether the local value of a component is within a certain range. The value must be floating-point or convertible to floating-point. 

LengthValidator

validateLength

Checks whether the length of a component’s local value is within a certain range. The value must be a java.lang.String.

LongRangeValidator

validateLongRange

Checks whether the local value of a component is within a certain range. The value must be any numeric type or String that can be converted to a long.

All these validator classes implement the Validator interface. Component writers and application developers can also implement this interface to define their own set of constraints for a component’s value.

Similarly to the standard converters, each of these validators has one or more standard error messages associated with it. If you have registered one of these validators onto a component on your page, and the validator is not able to validate the component’s value, the validator’s error message will display on the page. For example, the error message that displays when the component’s value exceeds the maximum value allowed by LongRangeValidator is the following:


{1}: Validation Error: Value is greater than allowable maximum of "{0}"

In this case the {1} substitution parameter is replaced by the component’s label or ID, and the {0} substitution parameter is replaced with the maximum value allowed by the validator.

See section 2.5.4 of the JavaServer Faces specification for the complete list of error messages. See Displaying Error Messages with the message and messages Tags for information on how to display validation error messages on the page when validation fails.

Validating a Component’s Value

In order to validate a component’s value using a particular validator, you need to register the validator on the component. You have three ways to do this:

See Referencing a Method That Performs ValidationReferencing a Method That Performs Validation for more information on using the validator attribute.

The validatorId attribute works similarly to the converterId attribute of the converter tag, as described in Converting a Component’s Value. See Binding Converters, Listeners, and Validators to Backing Bean Properties for more information on using the binding attribute of the validator tag.

Keep in mind that validation can be performed only on components that implement EditableValueHolder because these components accept values that can be validated.

Using the LongRangeValidator

The Duke’s Bookstore application uses a validateLongRange tag on the quantity input field of the bookshowcart.jsp page:

<h:inputText id="quantity" size="4"
     value=
"#{item.quantity}
" >
    <f:validateLongRange minimum="1"/>
</h:inputText>
<h:message for="quantity"/>

This tag requires that the user enter a number that is at least 1. The size attribute specifies that the number can have no more than four digits. The validateLongRange tag also has a maximum attribute, with which you can set a maximum value of the input.

The attributes of all the standard validator tags accept value expressions. This means that the attributes can reference backing bean properties rather than specify literal values. For example, the validateLongRange tag in the preceding example can reference a backing bean property called minimum to get the minimum value acceptable to the validator implementation:

<f:validateLongRange minimum="#{ShowCartBean.minimum}" />

Binding Component Values and Instances to External Data Sources

As explained in Backing Beans, a component tag can wire its component’s data to a back-end data object by doing one of the following:

A component tag’s value attribute uses a value expression to bind the component’s value to an external data source, such as a bean property. A component tag’s binding attribute uses a value expression to bind a component instance to a bean property.

When a component instance is bound to a backing bean property, the property holds the component’s local value. Conversely, when a component’s value is bound to a backing bean property, the property holds the value stored in the backing bean. This value is updated with the local value during the update model values phase of the life cycle. There are advantages to both of these techniques.

Binding a component instance to a bean property has these advantages:

Binding a component’s value to a bean property has these advantages:

In most situations, you will bind a component’s value rather than its instance to a bean property. You’ll need to use a component binding only when you need to change one of the component’s attributes dynamically. For example, if an application renders a component only under certain conditions, it can set the component’s rendered property accordingly by accessing the property to which the component is bound.

When referencing the property using the component tag’s value attribute, you need to use the proper syntax. For example, suppose a backing bean called MyBean has this int property:

int currentOption = null;
int getCurrentOption(){...}
void setCurrentOption(int option){...}

The value attribute that references this property must have this value-binding expression:

#{MyBean.currentOption}

In addition to binding a component’s value to a bean property, the value attribute can specify a literal value or can map the component’s data to any primitive (such as int), structure (such as an array), or collection (such as a list), independent of a JavaBeans component. Table 11–8 lists some example value-binding expressions that you can use with the value attribute.

Table 11–8 Example Value-binding Expressions

Value 

Expression 

A Boolean 

cart.numberOfItems > 0

A property initialized from a context init parameter

initParam.quantity

A bean property 

CashierBean.name

Value in an array 

books[3]

Value in a collection 

books["fiction"]

Property of an object in an array of objects 

books[3].price

The next two sections explain in more detail how to use the value attribute to bind a component’s value to a bean property or other external data sources and how to use the binding attribute to bind a component instance to a bean property.

Binding a Component Value to a Property

To bind a component’s value to a bean property, you specify the name of the bean and the property using the value attribute. As explained in Backing Beans, the value expression of the component tag’s value attribute must match the corresponding managed bean declaration in the application configuration resource file.

This means that the name of the bean in the value expression must match the managed-bean-name element of the managed bean declaration up to the first period (.) in the expression. Similarly, the part of the value expression after the period must match the name specified in the corresponding property-name element in the application configuration resource file.

For example, consider this managed bean configuration, which configures the ImageArea bean corresponding to the North America part of the image map on the chooselocale.jsp page of the Duke’s Bookstore application:

<managed-bean>
    <managed-bean-name> NA </managed-bean-name>
    <managed-bean-class> model.ImageArea </managed-bean-class>
    <managed-bean-scope> application </managed-bean-scope>
    <managed-property>
        <property-name>shape</property-name>
        <value>poly</value>
    </managed-property>
    <managed-property>
        <property-name>alt</property-name>
        <value>NAmerica</value>
    </managed-property>
    ...
</managed-bean>

This example configures a bean called NA, which has several properties, one of which is called shape.

Although the area tags on the chooselocale.jsp page do not bind to an ImageArea property (they bind to the bean itself), to do this, you refer to the property using a value expression from the value attribute of the component’s tag:

<h:outputText value="#{NA.shape}" />

Much of the time you will not include definitions for a managed bean’s properties when configuring it. You need to define a property and its value only when you want the property to be initialized with a value when the bean is initialized.

If a component tag’s value attribute must refer to a property that is not initialized in the managed-bean configuration, the part of the value-binding expression after the period must match the property name as it is defined in the backing bean.

See Application Configuration Resource File for information on how to configure beans in the application configuration resource file.

Writing Bean Properties explains in more detail how to write the backing bean properties for each of the component types.

Binding a Component Value to an Implicit Object

One external data source that a value attribute can refer to is an implicit object.

The bookreceipt.jsp page of the Duke’s Bookstore application includes a reference to an implicit object from a parameter substitution tag:

<h:outputFormat title="thanks" value="#{bundle.ThankYouParam}">
    <f:param value="#{sessionScope.name}"/>
</h:outputFormat>

This tag gets the name of the customer from the session scope and inserts it into the parameterized message at the key ThankYouParam from the resource bundle. For example, if the name of the customer is Gwen Canigetit, this tag will render:


Thank you, Gwen Canigetit, for purchasing your books from us.

The name tag on the bookcashier.jsp page has the NameChanged listener implementation registered on it. This listener saves the customer’s name in the session scope when the bookcashier.jsp page is submitted. See Implementing Value-Change Listeners for more information on how this listener works. See Registering a Value-Change Listener on a Component to learn how the listener is registered on the tag.

Retrieving values from other implicit objects is done in a similar way to the example shown in this section. Table 11–9 lists the implicit objects that a value attribute can refer to. All of the implicit objects except for the scope objects are read-only and therefore should not be used as a value for a UIInput component.

Table 11–9 Implicit Objects

Implicit Object 

What It Is 

applicationScope

A Map of the application scope attribute values, keyed by attribute name

cookie

A Map of the cookie values for the current request, keyed by cookie name

facesContext

The FacesContext instance for the current request

header

A Map of HTTP header values for the current request, keyed by header name

headerValues

A Map of String arrays containing all the header values for HTTP headers in the current request, keyed by header name

initParam

A Map of the context initialization parameters for this web application

param

A Map of the request parameters for this request, keyed by parameter name

paramValues

A Map of String arrays containing all the parameter values for request parameters in the current request, keyed by parameter name

requestScope

A Map of the request attributes for this request, keyed by attribute name

sessionScope

A Map of the session attributes for this request, keyed by attribute name

view

The root UIComponent in the current component tree stored in the FacesRequest for this request

Binding a Component Instance to a Bean Property

A component instance can be bound to a bean property using a value expression with the binding attribute of the component’s tag. You usually bind a component instance rather than its value to a bean property if the bean must dynamically change the component’s attributes.

Here are two tags from the bookcashier.jsp page that bind components to bean properties:

<h:selectBooleanCheckbox
     id="fanClub"
    rendered="false"
    binding="#{cashier.specialOffer}" />
<h:outputLabel for="fanClub"
    rendered="false"        
    binding="#{cashier.specialOfferText}"  >
    <h:outputText id="fanClubLabel"
        value="#{bundle.DukeFanClub}"
    />
</h:outputLabel>

The selectBooleanCheckbox tag renders a check box and binds the fanClub UISelectBoolean component to the specialOffer property of CashierBean. The outputLabel tag binds the component representing the check box’s label to the specialOfferText property of CashierBean. If the application’s locale is English, the outputLabel tag renders:


I’d like to join the Duke Fan Club, free with my purchase of over $100

The rendered attributes of both tags are set to false, which prevents the check box and its label from being rendered. If the customer orders more than $100 (or 100 euros) worth of books and clicks the Submit button, the submit method of CashierBean sets both components’ rendered properties to true, causing the check box and its label to be rendered.

These tags use component bindings rather than value bindings because the backing bean must dynamically set the values of the components’ rendered properties.

If the tags were to use value bindings instead of component bindings, the backing bean would not have direct access to the components, and would therefore require additional code to access the components from the FacesContext instance to change the components’ rendered properties.

Writing Properties Bound to Component Instances explains how to write the bean properties bound to the example components and also discusses how the submit method sets the rendered properties of the components.

Binding Converters, Listeners, and Validators to Backing Bean Properties

As described previously in this chapter, a page author can bind converter, listener, and validator implementations to backing bean properties using the binding attributes of the tags used to register the implementations on components.

This technique has similar advantages to binding component instances to backing bean properties, as described in Binding Component Values and Instances to External Data Sources. In particular, binding a converter, listener, or validator implementation to a backing bean property yields the following benefits:

Whether you are binding a converter, listener, or validator to a backing bean property, the process is the same for any of the implementations:

For example, say that you want to bind the standard DateTime converter to a backing bean property because the application developer wants the backing bean to set the formatting pattern of the user’s input rather than let the page author do it. First, the page author registers the converter onto the component by nesting the convertDateTime tag within the component tag. Then, the page author references the property with the binding attribute of the convertDateTime tag:

<h:inputText value="#{LoginBean.birthDate}">
    <f:convertDateTime binding="#{LoginBean.convertDate}" />
</h:inputText>

The convertDate property would look something like this:

private DateTimeConverter convertDate;
public DateTimeConverter getConvertDate() {
    ...
    return convertDate;
{
public void setConvertDate(DateTimeConverter convertDate) {
    convertDate.setPattern("EEEEEEEE, MMM dd, yyyy");
    this.convertDate = convertDate;
}

See Writing Properties Bound to Converters, Listeners, or Validators for more information on writing backing bean properties for converter, listener, and validator implementations.

Referencing a Backing Bean Method

A component tag has a set of attributes for referencing backing bean methods that can perform certain functions for the component associated with the tag. These attributes are summarized in Table 11–10.

Table 11–10 Component Tag Attributes That Reference Backing Bean Methods

Attribute 

Function 

action

Refers to a backing bean method that performs navigation processing for the component and returns a logical outcome String

actionListener

Refers to a backing bean method that handles action events 

validator

Refers to a backing bean method that performs validation on the component’s value 

valueChangeListener

Refers to a backing bean method that handles value-change events 

Only components that implement ActionSource can use the action and actionListener attributes. Only components that implement EditableValueHolder can use the validator or valueChangeListener attributes.

The component tag refers to a backing bean method using a method expression as a value of one of the attributes. The method referenced by an attribute must follow a particular signature, which is defined by the tag attribute’s definition in the TLD. For example, the definition of the validator attribute of the inputText tag in html_basic.tld is the following:

void validate(javax.faces.context.FacesContext,
     javax.faces.component.UIComponent, java.lang.Object)

The following four sections give examples of how to use the four different attributes.

Referencing a Method That Performs Navigation

If your page includes a component (such as a button or hyperlink) that causes the application to navigate to another page when the component is activated, the tag corresponding to this component must include an action attribute. This attribute does one of the following

The bookcashier.jsp page of the Duke’s Bookstore application has a commandButton tag that refers to a backing bean method that calculates the shipping date. If the customer has ordered more than $100 (or 100 euros) worth of books, this method also sets the rendered properties of some of the components to true and returns null; otherwise it returns receipt, which causes the bookreceipt.jsp page to display. Here is the commandButton tag from the bookcashier.jsp page:

<h:commandButton
    value="#{bundle.Submit}"
    action="#{cashier.submit}" />

The action attribute uses a method expression to refer to the submit method of CashierBean. This method will process the event fired by the component corresponding to this tag.

Writing a Method to Handle Navigation describes how to implement the submit method of CashierBean.

The application architect must configure a navigation rule that determines which page to access given the current page and the logical outcome, which is either returned from the backing bean method or specified in the tag. See Configuring Navigation Rules for information on how to define navigation rules in the application configuration resource file.

Referencing a Method That Handles an Action Event

If a component on your page generates an action event, and if that event is handled by a backing bean method, you refer to the method by using the component’s actionListener attribute.

The chooselocale.jsp page of the Duke’s Bookstore application includes some components that generate action events. One of them is the NAmerica component:

<h:commandLink id="NAmerica" action="bookstore"
     actionListener="#{localeBean.chooseLocaleFromLink}">

The actionListener attribute of this component tag references the chooseLocaleFromLink method using a method expression. The chooseLocaleFromLink method handles the event of a user clicking on the hyperlink rendered by this component.

Writing a Method to Handle an Action Event describes how to implement a method that handles an action event.

Referencing a Method That Performs Validation

If the input of one of the components on your page is validated by a backing bean method, you refer to the method from the component’s tag using the validator attribute.

The Coffee Break application includes a method that performs validation of the email input component on the checkoutForm.jsp page. Here is the tag corresponding to this component:

<h:inputText id="email" value="#{checkoutFormBean.email}"
    size="25" maxlength="125"
    validator="#{checkoutFormBean.validateEmail}"/>

This tag references the validate method described in Writing a Method to Perform Validation using a method expression.

Referencing a Method That Handles a Value-change Event

If you want a component on your page to generate a value-change event and you want that event to be handled by a backing bean method, you refer to the method using the component’s valueChangeListener attribute.

The name component on the bookcashier.jsp page of the Duke’s Bookstore application references a ValueChangeListener implementation that handles the event of a user entering a name in the name input field:

<h:inputText
     id="name"
     size="50"
     value="#{cashier.name}"
     required="true">
    <f:valueChangeListener type="listeners.NameChanged" />
</h:inputText>

For illustration, Writing a Method to Handle a Value-Change Event describes how to implement this listener with a backing bean method instead of a listener implementation class. To refer to this backing bean method, the tag uses the valueChangeListener attribute:

<h:inputText
     id="name"
     size="50"
     value="#{cashier.name}"
     required="true"
    valueChangeListener="#{cashier.processValueChange}" />
</h:inputText>

The valueChangeListener attribute of this component tag references the processValueChange method of CashierBean using a method expression. The processValueChange method handles the event of a user entering his name in the input field rendered by this component.

Writing a Method to Handle a Value-Change Event describes how to implement a method that handles a ValueChangeEvent.

Using Custom Objects

As a page author, you might need to use custom converters, validators, or components packaged with the application on your JSP pages.

A custom converter is applied to a component in one of the following ways:

A custom validator is applied to a component in one of the following ways:

To use a custom component, you add the custom tag associated with the component to the page.

As explained in Setting Up a Page, you must ensure that the TLD that defines any custom tags is packaged in the application if you intend to use the tags in your pages. TLD files are stored in the WEB-INF/ directory or subdirectory of the WAR file or in the META-INF/ directory or subdirectory of a tag library packaged in a JAR file.

You also need to include a taglib declaration in the page so that the page has access to the tags. All custom objects for the Duke’s Bookstore application are defined in bookstore.tld. Here is the taglib declaration that you would include on your page so that you can use the tags from this TLD:

<%@ taglib uri="/WEB-INF/bookstore.tld" prefix="bookstore" %>

When including the custom tag in the page, you can consult the TLD to determine which attributes the tag supports and how they are used.

The next three sections describe how to use the custom converter, validator, and UI components included in the Duke’s Bookstore application.

Using a Custom Converter

As described in the previous section, to apply the data conversion performed by a custom converter to a particular component’s value, you must either reference the custom converter from the component tag’s converter attribute or from a converter tag nested inside the component tag.

If you are using the component tag’s converter attribute, this attribute must reference the Converter implementation’s identifier or the fully-qualified class name of the converter. The application architect provides this identifier when registering the Converter implementation with the application, as explained in Registering a Custom Converter. Creating a Custom Converter explains how a custom converter is implemented.

The identifier for the credit card converter is CreditCardConverter. The CreditCardConverter instance is registered on the ccno component, as shown in this tag from the bookcashier.jsp page:

<h:inputText id="ccno"
    size="19"
    converter="CreditCardConverter"
    required="true">
    ...
</h:inputText>

By setting the converter attribute of a component’s tag to the converter’s identifier or its class name, you cause that component’s local value to be automatically converted according to the rules specified in the Converter implementation.

Instead of referencing the converter from the component tag’s converter attribute, you can reference the converter from a converter tag nested inside the component’s tag. To reference the custom converter using the converter tag, you do one of the following:

Using a Custom Validator

To register a custom validator on a component, you must do one of the following:

Here is the custom formatValidator tag from the ccno field on the bookcashier.jsp page of the Duke’s Bookstore application:

<h:inputText id="ccno" size="19"
    ...
    required="true">
    <bookstore:formatValidator
         formatPatterns="9999999999999999|9999 9999 9999 9999|
        9999-9999-9999-9999" />
</h:inputText>
<h:message styleClass="validationMessage"  for="ccno"/>

This tag validates the input of the ccno field against the patterns defined by the page author in the formatPatterns attribute.

You can use the same custom validator for any similar component by simply nesting the custom validator tag within the component tag.

Creating a Custom Validator describes how to create the custom validator and its custom tag.

If the application developer who created the custom validator prefers to configure the attributes in the Validator implementation rather than allow the page author to configure the attributes from the page, the developer will not create a custom tag for use with the validator.

    In this case, the page author must nest the validator tag inside the tag of the component whose data needs to be validated. Then the page author needs to do one of the following:

  1. Set the validator tag’s validatorId attribute to the ID of the validator that is defined in the application configuration resource file. Registering a Custom Validator explains how to configure the validator in the application configuration resource file.

  2. Bind the custom Validator implementation to a backing bean property using the validator tag’s binding attribute, as described in Binding Converters, Listeners, and Validators to Backing Bean Properties.

The following tag registers a hypothetical validator on a component using a validator tag and references the ID of the validator:

<h:inputText id="name" value="#{CustomerBean.name}"
            size="10" ... >
    <f:validator validatorId="customValidator" />
    ...
</h:inputText>

Using a Custom Component

In order to use a custom component in a page, you need to declare the tag library that defines the custom tag that renders the custom component, as explained in Using Custom Objects, and you add the component’s tag to the page.

The Duke’s Bookstore application includes a custom image map component on the chooselocale.jsp page. This component allows you to select the locale for the application by clicking on a region of the image map:

...
<h:graphicImage id="mapImage" url="/template/world.jpg"
    alt="#{bundle.chooseLocale}"
    usemap="#worldMap" />
    <bookstore:map id="worldMap" current="NAmericas"
         immediate="true"
        action="bookstore"
        actionListener="#{localeBean.chooseLocaleFromMap}">
        <bookstore:area id="NAmerica" value="#{NA}"
             onmouseover="/template/world_namer.jpg"
             onmouseout="/template/world.jpg"
            targetImage="mapImage" />
        ...
        <bookstore:area id="France" value="#{fraA}"
            onmouseover="/template/world_france.jpg"
             onmouseout="/template/world.jpg"
            targetImage="mapImage" />
</bookstore:map>

The standard graphicImage tag associates an image (world.jpg) with an image map that is referenced in the usemap attribute value.

The custom map tag that represents the custom component, MapComponent, specifies the image map, and contains a set of area tags. Each custom area tag represents a custom AreaComponent and specifies a region of the image map.

On the page, the onmouseover and onmouseout attributes specify the image that is displayed when the user performs the actions described by the attributes. The page author defines what these images are. The custom renderer also renders an onclick attribute.

In the rendered HTML page, the onmouseover, onmouseout, and onclick attributes define which JavaScript code is executed when these events occur. When the user moves the mouse over a region, the onmouseover function associated with the region displays the map with that region highlighted. When the user moves the mouse out of a region, the onmouseout function redisplays the original image. When the user clicks a region, the onclick function sets the value of a hidden input tag to the ID of the selected area and submits the page.

When the custom renderer renders these attributes in HTML, it also renders the JavaScript code. The custom renderer also renders the entire onclick attribute rather than let the page author set it.

The custom renderer that renders the map tag also renders a hidden input component that holds the current area. The server-side objects retrieve the value of the hidden input field and set the locale in the FacesContext instance according to which region was selected.

Chapter 13, Creating Custom UI Components describes the custom tags in more detail and also explains how to create the custom image map components, renderers, and tags.