Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

The Example JavaServer Faces Application

Setting Up a Page

Using the Core Tags

Adding UI Components to a Page Using the HTML Component Tags

UI Component Tag Attributes

Theid Attribute

Theimmediate Attribute

Therendered Attribute

Thestyle andstyleClass Attributes

Thevalue andbinding Attributes

Adding a Form Component

Using Text Components

Rendering a Text Field with theinputText Tag

Rendering a Label with theoutputLabel Tag

Rendering a Hyperlink with theoutputLink Tag

Displaying a Formatted Message with theoutputFormat Tag

Rendering a Password Field with theinputSecret Tag

Using Command Components for Performing Actions and Navigation

Rendering a Button with thecommandButton Tag

Rendering a Hyperlink with thecommandLink Tag

Using Data-Bound Table Components

Adding Graphics and Images with thegraphicImage Tag

Laying Out Components with theUIPanel Component

Rendering Components for Selecting One Value

Displaying a Check Box Using theselectBooleanCheckbox Tag

Displaying a Menu Using theselectOneMenu Tag

Rendering Components for Selecting Multiple Values

TheUISelectItem,UISelectItems, andUISelectItemGroup Components

Using theselectItems Tag

Using theselectItem Tag

Displaying Error Messages with themessage andmessages Tags

Using Localized Data

Loading a Resource Bundle

Referencing Localized Static Data

Referencing Error Messages

Using the Standard Converters

Converting a Component's Value

UsingDateTimeConverter

UsingNumberConverter

Registering Listeners on Components

Registering a Value-Change Listener on a Component

Registering an Action Listener on a Component

Using the Standard Validators

Validating a Component's Value

Using theLongRangeValidator

Binding Component Values and Instances to External Data Sources

Binding a Component Value to a Property

Binding a Component Value to an Implicit Object

Binding a Component Instance to a Bean Property

Binding Converters, Listeners, and Validators to Backing Bean Properties

Referencing a Backing Bean Method

Referencing a Method That Performs Navigation

Referencing a Method That Handles an Action Event

Referencing a Method That Performs Validation

Referencing a Method That Handles a Value-change Event

Using Custom Objects

Using a Custom Converter

Using a Custom Validator

Using a Custom Component

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Adding UI Components to a Page Using the HTML Component Tags

The tags defined by the JavaServer Faces standard HTML render kit tag libraryrepresent HTML form components and other basic HTML elements. These components display dataor accept data from the user. This data is collected as part ofa form and is submitted to the server, usually when the userclicks a button. This section explains how to use each of the componenttags shown inTable 10-2.

The next section explains the more important tag attributes that are common tomost component tags. Please refer to theTLD documentation athttp://download.oracle.com/javaee/5/javaserverfaces/1.2/docs/tlddocs/ for acomplete list of tags and their attributes.

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

UI Component Tag Attributes

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

  • id: Uniquely identifies the component.

  • immediate: If set totrue, indicates that any events, validation, and conversion associated with the component should happen in the apply request values phase rather than a later phase.

  • rendered: Specifies a condition in which the component should be rendered. If the condition is not satisfied, the component is not rendered.

  • style: Specifies a Cascading Style Sheet (CSS) style for the tag.

  • styleClass: Specifies a CSS stylesheet class that contains definitions of the styles.

  • value: Identifies an external data source and binds the component’s value to it.

  • binding: Identifies a bean property and binds the component instance to it.

All of the UI component tag attributes (exceptid) can accept expressions, asdefined by the unified EL described inUnified Expression Language.

Theid Attribute

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

Theimmediate Attribute

UIInput components and command components (those that implementActionSource, such as buttons and hyperlinks)can set theimmediate attribute totrue to force events, validations, and conversionsto 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’simmediate value and a command component’simmediate value determines what happens when thecommand component is activated.

Assume that you have a page with a button and a fieldfor entering the quantity of a book in a shopping cart. If boththe button’s and the field’simmediate attributes are set totrue, the new valueof the field will be available for any processing associated with the eventthat is generated when the button is clicked. The event associated with thebutton and the event, validation, and conversion associated with the field are allhandled during the apply request values phase.

If the button’simmediate attribute is set totrue but the field’simmediateattribute is set tofalse, the event associated with the button is processed withoutupdating the field’s local value to the model layer. This is because anyevents, conversion, or validation associated with the field occurs during its usual phasesof the life cycle, which come after the apply request values phase.

Thebookshowcart.jsp page of the Duke’s Bookstore application has examples of components usingtheimmediate attribute to control which component’s data is updated when certain buttonsare clicked. Thequantity field for each book has itsimmediate attribute settofalse. (Thequantity fields are generated by theUIData component. SeeUsing Data-Bound Table Components,for more information.) Theimmediate attribute of the Continue Shopping hyperlink is set totrue. Theimmediate attribute of the Update Quantities hyperlink is set tofalse.

If you click the Continue Shopping hyperlink, none of the changes entered intothe quantity input fields will be processed. If you click the Update Quantitieshyperlink, the values in the quantity fields will be updated in the shoppingcart.

Therendered Attribute

A component tag uses a Boolean JavaServer Faces expression language (EL) expression, alongwith therendered attribute, to determine whether or not the component will berendered. For example, thecheckcommandLink component on thebookcatalog.jsp page is notrendered if the cart contains no items:

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

Unlike nearly every other JavaServer Faces tag attribute, therendered attribute isrestricted to using rvalue expressions. As explained inUnified Expression Language, rvalue expressions can only readdata; they cannot write the data back to the data source. Therefore, expressionsused withrendered attributes can use the arithmetic operators and literals that rvalueexpressions can use but lvalue expressions cannot use. For example, the expression inthe preceding example uses the> operator.

Thestyle andstyleClass Attributes

Thestyle andstyleClass attributes allow you to specify Cascading Style Sheets (CSS)styles for the rendered output of your component tags.Displaying Error Messages with themessage andmessages Tags describes an exampleof using thestyle attribute to specify styles directly in the attribute.A component tag can instead refer to a CSS stylesheet class. ThedataTabletag on thebookcatalog.jsp page of the Duke’s Bookstore application references the style classlist-background:

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

The stylesheet that defines this class isstylesheet.css, which is included in theapplication. For more information on defining styles, please the seeCascading Style Sheets Specification athttp://www.w3.org/Style/CSS/.

Thevalue andbinding Attributes

A tag representing a component defined byUIOutput or a subclass ofUIOutput usesvalue andbinding attributes to bind its component’s value or instance respectively toan external data source.Binding Component Values and Instances to External Data Sources explains how to use these attributes.

Adding a Form Component

AUIForm component class represents an input form, which includes child components thatcontain data that is either presented to the user or submitted with theform.

Figure 11-1 shows a typical login form, in which a user enters a username 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.

Theform tag represents theUIForm component on the page and enclosesall the components that display or collect data from the user, as shownhere:

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

Theform tag can also include HTML markup to lay out the componentson the page. Theform tag itself does not perform any layout; itspurpose is to collect data and to declare attributes that can be usedby other components in the form. A page can include multipleform tags,but only the values from the form that the user submits will beincluded in the postback.

Using Text Components

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

  • Label, which displays read-only text.

  • Text field, which allows users to enter text, often to be submitted as part of a form.

  • Password field, which is one kind of text field that displays a set of characters, such as asterisks, instead of the password that the user enters.

  • Text area, which is another kind of text field that allow users to enter multiple lines of text.

Figure 11-2 shows examples of these text components.

Figure 11-2 Example Text Components

Screen capture of form.

An editable text component in a JavaServer Faces application is represented by aUIInput component. One example is a text field. A read-only text component ina JavaServer Faces application is represented by aUIOutput component. One example is alabel.

TheUIInput andUIOutput components can each be rendered in four ways todisplay more specialized text components.Table 11-3 lists all the renderers ofUIInputandUIOutput and the tags that represent the component and renderer combination. RecallfromComponent Rendering Model that the name of a tag is composed of thename of the component and the name of the renderer. For example, theinputText tag refers to aUIInput component that is rendered with theTextrenderer.

Table 11-3UIInput andUIOutput Tags

Component

Renderer

Tag

Function

UIInput

Hidden

inputHidden

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

Secret

inputSecret

Thestandard password field: Accepts one line of text with no spaces and displaysit as a set of asterisks as it is typed

Text

inputText

The standard textfield: Accepts a text string of one line

TextArea

inputTextarea

The standard text area: Acceptsmultiple lines of text

UIOutput

Label

outputLabel

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

Link

outputLink

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

OutputMessage

outputFormat

Displays a localized message

Text

outputText

Displays a text string ofone line

TheUIInput component tags support the following tag attributes in addition to thosedescribed at the beginning ofAdding UI Components to a Page Using the HTML Component Tags. This list does not include allthe attributes supported by theUIInput component tags, just those that pageauthors will use most often. Please refer to thehtml_basic.tld file for the completelist.

  • converter: Identifies a converter that will be used to convert the component’s local data. SeeUsing the Standard Converters for more information on how to use this attribute.

  • converterMessage: Specifies an error message to display when the converter registered on the component fails.

  • dir: Specifies the direction of the text displayed by this component. Acceptable values areLTR, meaning left-to-right, andRTL, meaning right-to-left.

  • label: Specifies a name that can be used to identify this component in error messages.

  • lang: Specifies the code for the language used in the rendered markup, such asen_US.

  • required: Takes aboolean value that indicates whether or not the user must enter a value in this component.

  • requiredMessage: Specifies an error message to display when the user does not enter a value into the component.

  • validator: Identifies a method expression pointing to a backing bean method that performs validation on the component’s data. SeeReferencing a Method That Performs Validation for an example of using thevalidator tag.

  • validatorMessage: Specifies an error message to display when the validator registered on the component fails to validate the component’s local value.

  • valueChangeListener: Identifies a method expression that points to a backing bean method that handles the event of entering a value in this component. SeeReferencing a Method That Handles a Value-change Event for an example of usingvalueChangeListener.

TheUIOutput component tags support theconverter tag attribute in addition tothose listed inAdding UI Components to a Page Using the HTML Component Tags. The rest of this section explains how to useselected tags listed inTable 11-3. The other tags are written in a similarway.

Rendering a Text Field with theinputText Tag

TheinputText tag is used to display a text field. It representsthe combination of aText renderer and aUIInput component. A similar tag, theoutputText tag, displays a read-only, single-line string. It represents the combination of aText renderer and aUIOutput component. This section shows you how to use theinputText tag. TheoutputText tag is written in a similar way.

Here is an example of aninputText tag from thebookcashier.jsp page:

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

Thelabel attribute specifies a user-friendly name that will be used in thesubstitution parameters of error messages displayed for this component.

Thevalue attribute refers to thename property ofCashierBean. This property holdsthe data for thename component. After the user submits the form,the value of thename property inCashierBean will be set tothe text entered in the field corresponding to this tag.

Therequired attribute causes the page to reload with errors displayed if theuser does not enter a value in thename text field. The JavaServerFaces implementation checks whether the value of the component is null or isan empty String.

If your component must have a non-null value or aString valueat least one character in length, you should add arequired attributeto your component tag and set it totrue. If your tag doeshave arequired attribute that is set totrue and the value isnull or a zero-length string, no other validators registered on the tag arecalled. If your tag does not have arequired attribute set totrue, othervalidators registered on the tag are called, but those validators must handle thepossibility of anull or zero-length string.

TherequiredMessage attribute references an error message from a resource bundle, which isdeclared in the application configuration file. Refer toRegistering Custom Error Messages for details on how todeclare and reference the resource bundle.

Rendering a Label with theoutputLabel Tag

TheoutputLabel tag is used to attach a label to a specified inputfield for accessibility purposes. Thebookcashier.jsp page uses anoutputLabel tag to render thelabel of a check box:

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

Thefor attribute of theoutputLabel tag maps to theid ofthe input field to which the label is attached. TheoutputText tag nestedinside theoutputLabel tag represents the actual label component. Thevalue attribute on theoutputText tag indicates the text that is displayed next to the input field.

Instead of using anoutputText tag for the text displayed as a label,you can simply use theoutputLabel tag’svalue attribute. The following codesnippet shows what the previous code snippet would look like if it usedthevalue attribute of theoutputLabel tag to specify the text of thelabel.

<h:selectBooleanCheckbox        rendered="false"    binding="#{cashier.specialOffer}" />    <h:outputLabel for="fanClub"        rendered="false"        binding="#{cashier.specialOfferText}"         value="#{bundle.DukeFanClub}" />    </h:outputLabel>...
Rendering a Hyperlink with theoutputLink Tag

TheoutputLink tag is used to render a hyperlink that, when clicked, loadsanother page but does not generate an action event. You should use thistag instead of thecommandLink tag if you always want the URL (specifiedby theoutputLink tag’svalue attribute) to open and do not haveto perform any processing when the user clicks on the link. The Duke’sBookstore application does not utilize this tag, but here is an example ofit:

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

The text in the body of theoutputLink tag identifies the text theuser clicks to get to the next page.

Displaying a Formatted Message with theoutputFormat Tag

TheoutputFormat tag allows a page author to display concatenated messages as aMessageFormat pattern, as described in the API documentation forjava.text.MessageFormat (seehttp://download.oracle.com/javase/6/docs/api/java/text/MessageFormat.html). Hereis an example of anoutputFormat tag from thebookshowcart.jsp page of theDuke’s Bookstore application:

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

Thevalue attribute specifies theMessageFormat pattern. Theparam tag specifies the substitution parametersfor the message.

In the exampleoutputFormat tag, thevalue for the parameter maps to thenumber of items in the shopping cart. When the message is displayed onthe page, the number of items in the cart replaces the{0}in the message corresponding to theCartItemCount key in thebundle resource bundle:

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

This message represents three possibilities:

  • Your shopping cart contains no items.

  • Your shopping cart contains one item.

  • Your shopping cart contains{0} items.

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

AnoutputFormat tag can include more than oneparam tag for thosemessages that have more than one parameter that must be concatenated into themessage. If you have more than one parameter for one message, make surethat you put theparam tags in the proper order so that thedata is inserted in the correct place in the message.

A page author can also hard code the data to be substitutedin the message by using a literal value with thevalue attribute ontheparam tag.

Rendering a Password Field with theinputSecret Tag

TheinputSecret tag renders an<input type="password"> HTML tag. When the user types a stringinto this field, a row of asterisks is displayed instead of the textthe user types. The Duke’s Bookstore application does not include this tag, buthere is an example of one:

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

In this example, theredisplay attribute is set tofalse. This will preventthe password from being displayed in a query string or in thesource 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 assubmitting a form, and for navigating to another page.

Command components in JavaServer Faces applications are represented by theUICommand component, whichperforms an action when it is activated. TheUICommand component supports tworenderers:Button andLink asUICommand component renderers.

ThecommandButton tag represents the combination of aUICommand component and aButtonrenderer and is rendered as a button. ThecommandLink tag represents the combination ofaUICommand component and aLink renderer and is rendered as a hyperlink.

In addition to the tag attributes listed inAdding UI Components to a Page Using the HTML Component Tags, thecommandButton andcommandLink tags can use these attributes:

  • action, which is either a logical outcomeString or a method expression pointing to a bean method that returns a logical outcomeString. In either case, the logical outcomeString is used by the defaultNavigationHandler instance to determine what page to access when theUICommand component is activated.

  • actionListener, which is a method expression pointing to a bean method that processes an action event fired by theUICommand component.

SeeReferencing a Method That Performs Navigation for more information on using theaction attribute.

SeeReferencing a Method That Handles an Action Event for details on using theactionListener attribute.

Rendering a Button with thecommandButton Tag

Thebookcashier.jsp page of the Duke’s Bookstore application includes acommandButton tag. When auser clicks the button, the data from the current page is processed, andthe next page is opened. Here is thecommandButton tag frombookcashier.jsp:

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

Clicking the button will cause thesubmit method ofCashierBean to be invoked becausetheaction attribute references thesubmit method of theCashierBean backing bean. Thesubmit method performs some processing and returns a logical outcome. This is passedto the defaultNavigationHandler, which matches the outcome against a set of navigationrules defined in the application configuration resource file.

Thevalue attribute of the preceding examplecommandButton tag references the localized message forthe button’s label. Thebundle part of the expression refers to theResourceBundlethat contains a set of localized messages. TheSubmit part of the expressionis the key that corresponds to the message that is displayed on thebutton. For more information on referencing localized messages, seeRendering Components for Selecting Multiple Values. SeeReferencing a Method That Performs Navigation forinformation on how to use theaction attribute.

Rendering a Hyperlink with thecommandLink Tag

ThecommandLink tag represents an HTML hyperlink and is rendered as an HTML<a> element. ThecommandLink tag is used to submit an action eventto the application. SeeImplementing Action Listeners for more information on action events.

AcommandLink tag must include a nestedoutputText tag, which represents the text theuser clicks to generate the event. The following tag is from thechooselocale.jsppage from the Duke’s Bookstore application.

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

This tag will render the following HTML:

<a href="#"    >English</a>

Note -ThecommandLink tag will render JavaScript. If you use this tag, make sureyour browser is JavaScript-enabled.


Using Data-Bound Table Components

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

Figure 11-3 Table on thebookshowcart.jsp Page

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

In a JavaServer Faces application, theUIData component supports binding to a collectionof data objects. It does the work of iterating over each record inthe data source. The standardTable renderer displays the data as an HTMLtable. TheUIColumn component represents a column of data within the table. Hereis a portion of thedataTable tag used by thebookshowcart.jsp pageof the Duke’s Bookstore example:

<h:dataTable     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 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 thisdataTable tag can display.

The exampledataTable tag displays the books in the shopping cart as wellas the quantity of each book in the shopping cart, the prices, anda set of buttons, which the user can click to remove booksfrom the shopping cart.

Thecolumn tags represent columns of data in aUIData component. WhiletheUIData component is iterating over the rows of data, it processes theUIColumn component associated with eachcolumn tag for each row in the table.

TheUIData component shown in the preceding code example iterates through the listof books (cart.items) in the shopping cart and displays their titles, authors, andprices. Each timeUIData iterates through the list of books, it renders one cellin each column.

ThedataTable andcolumn tags use facets to represent parts of the tablethat are not repeated or updated. These include headers, footers, and captions.

In the preceding example,column tags includefacet tags for representing columnheaders or footers. Thecolumn tag allows you to control the styles ofthese headers and footers by supporting theheaderClass andfooterClass attributes. These attributes acceptspace-separated lists of CSS style classes, which will be applied to the headerand footer cells of the corresponding column in the rendered table.

Facets can have only one child, and so apanelGroup tag is neededif you want to group more than one component within afacet. Becausethe facet tag representing the footer includes more than one tag, thepanelGroupis needed to group those tags. Finally, thisdataTable tag includes afacettag with itsname attribute set tocaption, causing a table caption to berendered below the table.

This table is a classic use case for aUIData component because thenumber of books might not be known to the application developer or thepage author at the time the application is developed. TheUIData component candynamically adjust the number of rows of the table to accommodate the underlyingdata.

Thevalue attribute of adataTable tag references the data to be includedin the table. This data can take the form of

  • A list of beans

  • An array of beans

  • A single bean

  • Ajavax.faces.model.DataModel

  • Ajava.sql.ResultSet

  • Ajavax.servlet.jsp.jstl.sql.ResultSet

  • Ajavax.sql.RowSet

All data sources forUIData components have aDataModel wrapper. Unless youexplicitly construct aDataModel wrapper, the JavaServer Faces implementation will create one arounddata of any of the other acceptable types. SeeWriting Bean Properties for more information onhow to write properties for use with aUIData component.

Thevar attribute specifies a name that is used by the components withinthedataTable tag as an alias to the data referenced in thevalueattribute ofdataTable.

In thedataTable tag from thebookshowcart.jsp page, thevalue attribute pointsto a list of books. Thevar attribute points to a single bookin that list. As theUIData component iterates through the list, each reference toitem points to the current book in the list.

TheUIData component also has the ability to display only a subset ofthe underlying data. This is not shown in the preceding example. To displaya subset of the data, you use the optionalfirst androwsattributes.

Thefirst attribute specifies the first row to be displayed. Therows attributespecifies the number of rows, starting with the first row, to be displayed.For example, if you wanted to display records 2 through 10 of theunderlying data, you would setfirst to 2 androws to 9.When you display a subset of the data in your pages, you mightwant to consider including a link or button that causes subsequent rows todisplay when clicked. By default, bothfirst androws are set tozero, and this causes all the rows of the underlying data to display.

ThedataTable tag also has a set of optional attributes for adding stylesto the table:

  • captionClass: Defines styles for the table caption

  • columnClasses: Defines styles for all the columns

  • footerClass: Defines styles for the footer

  • headerClass: Defines styles for the header

  • rowClasses: Defines styles for the rows

  • styleClass: Defines styles for the entire table

Each of these attributes can specify more than one style. IfcolumnClassesorrowClasses specifies more than one style, the styles are applied to thecolumns or rows in the order that the styles are listed in theattribute. For example, ifcolumnClasses specifies styleslist-column-center andlist-column-right and if there aretwo columns in the table, the first column will have stylelist-column-center,and the second column will have stylelist-column-right.

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

Adding Graphics and Images with thegraphicImage Tag

In a JavaServer Faces application, theUIGraphic component represents an image. ThegraphicImage tagis used to render aUIGraphic component on a page. The Duke’s Bookstore applicationuses agraphicImage tag to display the map image on thechooselocale.jsp page:

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

Theurl attribute specifies the path to the image. It also corresponds tothe local value of theUIGraphic component so that the URL can beretrieved, possibly from a backing bean. The URL of the example tag beginswith a/, which adds the relative context path of the web applicationto the beginning of the path to the image.

Thetitle attribute specifies the alternative text displayed when the user mouses overthe image. In this example, thetitle attribute refers to a localized message. SeePerforming Localization for details on how to localize your JavaServer Faces application.

Theusemap attribute refers to the image map defined by the custom component,MapComponent, which is on the same page. SeeChapter 13, Creating Custom UI Components for more information onthe image map.

Laying Out Components with theUIPanel Component

In a JavaServer Faces application, you use theUIPanel component as a layout containerfor a set of component components. When you use the renderers from theHTML render kit,UIPanel is rendered as an HTML table. This component differsfromUIData in thatUIData can dynamically add or delete rows to accommodate theunderlying data source, whereasUIPanel must have the number of rows predetermined.Table 11-4lists all the renderers and tags corresponding to theUIPanel component.

Table 11-4UIPanel 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 oneparent

ThepanelGrid tag is used to represent an entire table. ThepanelGroup tag isused to represent rows in a table. Other UI component tags areused to represent individual cells in the rows.

ThepanelGrid tag has a set of attributes that specify CSS stylesheet classes:columnClasses,footerClass,headerClass,panelClass, androwClasses. These stylesheet attributes are optional. ThepanelGridtag also has acolumns attribute. Thecolumns attribute is required if you wantyour table to have more than one column because thecolumns attributetells the renderer how to group the data in the table.

If theheaderClass attribute value is specified, thepanelGrid must have a headeras its first child. Similarly, if afooterClass attribute value is specified, thepanelGridmust have a footer as its last child.

The Duke’s Bookstore application includes threepanelGrid tags on thebookcashier.jsp page. Hereis 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 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 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>

ThispanelGrid tag is rendered to a table that contains components for thecustomer of the bookstore to input personal information. ThispanelGrid tag uses stylesheetclasses to format the table. The CSS classes are defined in thestylesheet.cssfile in thetut-install/javaeetutorial5/examples/web/bookstore6/web/ directory. Thelist-header definition is

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

Because thepanelGrid tag specifies aheaderClass, thepanelGrid must contain a header. TheexamplepanelGrid tag uses afacet tag for the header. Facets canhave only one child, and so apanelGroup tag is needed ifyou want to group more than one component within afacet. Because theexamplepanelGrid tag has only one cell of data, apanelGroup tag isnot needed.

ThepanelGroup tag has one attribute, calledlayout, in addition to thoselisted inUI Component Tag Attributes. If thelayout attribute has the valueblock then anHTMLdiv element is rendered to enclose the row; otherwise, an HTMLspanelement is rendered to enclose the row. If you are specifying styles forthepanelGroup tag, you should set thelayout attribute toblock inorder for the styles to be applied to the components within thepanelGrouptag. This is because styles such as those that set width and heightare not applied to inline elements, which is how content enclosed by thespan element is defined.

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

The data represented by the nested component tags is grouped into rows accordingto the value of the columns attribute of thepanelGrid tag. Thecolumnsattribute in the example is set to3, and therefore the table will havethree columns. In which column each component is displayed is determined by theorder that the component is listed on the page modulo 3. Soif a component is the fifth one in the list of components, thatcomponent 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 selectone value, whether it be the only value available or one of aset of choices. The most common examples of this kind of component are:

  • A check box, which represents boolean state

  • A set of radio buttons

  • A drop-down menu, which displays a scrollable list

  • A list box, which displays an unscrollable list

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 theselectBooleanCheckbox Tag

TheUISelectBoolean class defines components that have aboolean value. TheselectBooleanCheckbox tagis the only tag that JavaServer Faces technology provides for representingboolean state. TheDuke’s Bookstore application includes aselectBooleanCheckbox tag on thebookcashier.jsp page:

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

This example tag displays a check box to allow users to indicatewhether they want to join the Duke Fan Club. The label for thecheck box is rendered by theoutputLabel tag. The actual text is represented bythe nestedoutputText tag.Binding a Component Instance to a Bean Property discusses this example in more detail.

Displaying a Menu Using theselectOneMenu Tag

AUISelectOne component allows the user to select one value from a setof values. This component can be rendered as a list box, a setof radio buttons, or a menu. This section explains theselectOneMenu tag.TheselectOneRadio andselectOneListbox tags are written in a similar way. TheselectOneListbox tag is similar to theselectOneMenu tag except thatselectOneListbox defines asize attribute that determines how many of the items are displayed at once.

TheselectOneMenu tag represents a component that contains a list of items, fromwhich a user can choose one item. The menu is also commonly knownas a drop-down list or a combo box. The following code snippet showstheselectOneMenu tag from thebookcashier.jsp page of the Duke’s Bookstore application. This tagallows the user to select a shipping method:

<h:selectOneMenu      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>

Thevalue attribute of theselectOneMenu tag maps to the property that holdsthe currently selected item’s value. You are not required to provide a valuefor the currently selected item. If you don’t provide a value, the firstitem in the list is selected by default.

Like theselectOneRadio tag, theselectOneMenu tag must contain either aselectItemstag or a set ofselectItem tags for representing the items in the list.TheUISelectItem,UISelectItems, andUISelectItemGroup Components explains these tags.

Rendering Components for Selecting Multiple Values

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

  • A set of check boxes

  • A drop-down menu

  • A list box

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.

TheUISelectMany class defines a component that allows the user to select zeroor more values from a set of values. This component can be renderedas a set of check boxes, a list box, or a menu. Thissection explains theselectManyCheckbox tag. TheselectManyListbox tag andselectManyMenu tag are written ina similar way.

A list box differs from a menu in that it displays asubset of items in a box, whereas a menu displays only one itemat a time when the user is not selecting the menu. Thesizeattribute of theselectManyListbox tag determines the number of items displayed atone time. The list box includes a scroll bar for scrolling through anyremaining items in the list.

TheselectManyCheckbox tag renders a set of check boxes, with each check boxrepresenting one value that can be selected. Duke’s Bookstore uses aselectManyCheckbox tag onthebookcashier.jsp page to allow the user to subscribe to one or morenewsletters:

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

Thevalue attribute of theselectManyCheckbox tag identifies theCashierBean backing bean property,newsletters, for the current set of newsletters. This property holds the values ofthe currently selected items from the set of check boxes. You arenot required to provide a value for the currently selected items. If youdon’t provide a value, the first item in the list is selected bydefault.

Thelayout attribute indicates how the set of check boxes are arranged onthe page. Because layout is set topageDirection, the check boxes are arrangedvertically. The default islineDirection, which aligns the check boxes horizontally.

TheselectManyCheckbox tag must also contain a tag or set of tags representingthe set of check boxes. To represent a set of items, you usetheselectItems tag. To represent each item individually, you use aselectItem tagfor each item. The following subsection explains these tags in more detail.

TheUISelectItem,UISelectItems, andUISelectItemGroup Components

UISelectItem andUISelectItems represent components that can be nested inside aUISelectOne oraUISelectMany component.UISelectItem is associated with aSelectItem instance, which contains thevalue, label, and description of a single item in theUISelectOne orUISelectMany component.

TheUISelectItems instance represents either of the following:

  • A set ofSelectItem instances, containing the values, labels, and descriptions of the entire list of items

  • A set ofSelectItemGroup instances, each of which represents a set ofSelectItem instances

Figure 11-6 shows an example of a list box constructed with aSelectItems component representingtwoSelectItemGroup instances, each of which represents two categories of beans. Each categoryis an array ofSelectItem instances.

Figure 11-6 An Example List Box Created UsingSelectItemGroup Instances

Screen capture of list box with two groups of items.

TheselectItem tag represents aUISelectItem component. TheselectItems tag represents aUISelectItemscomponent. You can use either a set ofselectItem tags or asingleselectItems tag within yourselectOne orselectMany tag.

The advantages of using theselectItems tag are as follows:

  • You can represent the items using different data structures, includingArray,Map andCollection. The data structure is composed ofSelectItem instances orSelectItemGroup instances.

  • You can concatenate different lists together into a singleUISelectMany orUISelectOne component and group the lists within the component, as shown inFigure 11-6.

  • You can dynamically generate values at runtime.

The advantages of usingselectItem are as follows:

  • The page author can define the items in the list from the page.

  • You have less code to write in the bean for theselectItem properties.

For more information on writing component properties for theUISelectItems components, seeWriting Bean Properties. The rest of this section shows you how to use theselectItemsandselectItem tags.

Using theselectItems Tag

Here is theselectManyCheckbox tag from the sectionRendering Components for Selecting Multiple Values:

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

Thevalue attribute of theselectItems tag is bound to thenewslettersmanaged bean, which is configured in the application configuration resource file. Thenewslettersmanaged 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 themanaged-bean element, theUISelectItems component is a collectionofSelectItem instances. SeeInitializing Array and List Properties for more information on configuring collections as beans.

You can also create the list corresponding to aUISelectMany orUISelectOnecomponent programmatically in the backing bean. SeeWriting Bean Properties for information on howto write a backing bean property corresponding to aUISelectMany orUISelectOne component.

The arguments to theSelectItem constructor are:

  • AnObject representing the value of the item

  • AString representing the label that displays in theUISelectMany component on the page

  • AString representing the description of the item

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

Using theselectItem Tag

TheselectItem tag represents a single item in a list of items. Hereis the example fromDisplaying a Menu Using theselectOneMenu Tag:

<h:selectOneMenu       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>

TheitemValue attribute represents the default value of theSelectItem instance. TheitemLabel attributerepresents theString that appears in the drop-down menu component on the page.

TheitemValue anditemLabel attributes are value-binding-enabled, meaning that they can use value-bindingexpressions to refer to values in external objects. They can also define literalvalues, as shown in the exampleselectOneMenu tag.

Displaying Error Messages with themessage andmessages Tags

Themessage andmessages tags are used to display error messages when conversionor validation fails. Themessage tag displays error messages related to a specificinput component, whereas themessages tag displays the error messages for theentire page.

Here is an examplemessage tag from theguessNumber application, discussed inSteps in the Development Process:

<h:inputText value="#{UserNumberBean.userNumber}">    <f:validateLongRange minimum="0" maximum="10" /> <h:commandButton         action="success" value="Submit" /><p><h:message     for="userNo"/>

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

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

Another attribute themessages tag supports is thelayout attribute. Its defaultvalue islist, which indicates that the messages are displayed in a bulletedlist using the HTMLul andli elements. If you set the attribute totable, the messages will be rendered in a table using the HTMLtableelement.

The preceding example shows a standard validator is registered on input component. Themessage tag displays the error message associated with this validator when the validatorcannot validate the input component’s value. In general, when you register a converteror validator on a component, you are queueing the error messages associated withthe converter or validator on the component. Themessage andmessages tags display theappropriate error messages that are queued on the component when the validators orconverters 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 validatorsare listed in section 2.5.4 of the JavaServer Faces specification. An application architectcan override these standard messages and supply error messages for custom converters andvalidators by registering custom error messages with the application by means of themessage-bundle element of the application configuration file.Referencing Error Messages explains more about error messages.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp