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

12.  Developing with JavaServer Faces Technology

Writing Bean Properties

Writing Properties Bound to Component Values

UIInput andUIOutput Properties

UIData Properties

UISelectBoolean Properties

UISelectMany Properties

UISelectOne Properties

UISelectItem Properties

UISelectItems Properties

Writing Properties Bound to Component Instances

Writing Properties Bound to Converters, Listeners, or Validators

Performing Localization

Creating a Resource Bundle

Localizing Dynamic Data

Localizing Messages

Creating a Message with a Message Factory

UsingFacesMessage to Create a Message

Creating a Custom Converter

Implementing an Event Listener

Implementing Value-Change Listeners

Implementing Action Listeners

Creating a Custom Validator

Implementing the Validator Interface

Creating a Custom Tag

Writing the Tag Handler

Writing the Tag Library Descriptor

Writing Backing Bean Methods

Writing a Method to Handle Navigation

Writing a Method to Handle an Action Event

Writing a Method to Perform Validation

Writing a Method to Handle a Value-Change Event

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

Writing Bean Properties

As explained inBacking Beans, a backing bean property can be bound to oneof the following items:

  • A component value

  • A component instance

  • A Converter implementation

  • A Listener implementation

  • A Validator implementation

These properties follow JavaBeans component conventions (seeJavaBeans Components).

The UI component’s tag binds the component’s value to a property using itsvalueattribute and binds the component’s instance to a property using itsbinding attribute,as explained inBinding Component Values and Instances to External Data Sources. Likewise, all the converter, listener, and validator tags use theirbinding attributes to bind their associated implementations to backing bean properties, as explainedinBinding Converters, Listeners, and Validators to Backing Bean Properties.

To bind a component’s value to a backing bean property, the type ofthe property must match the type of the component’s value to which itis bound. For example, if a backing bean property is bound toaUISelectBoolean component’s value, the property should accept and return aboolean valueor aBoolean wrapperObject instance.

To bind a component instance, the property must match the component type. Forexample, if a backing bean property is bound to aUISelectBoolean instance, the propertyshould accept and returnUISelectBoolean.

Similarly, in order to bind a converter, listener, or validator implementation to aproperty, the property must accept and return the same type of converter, listener,or validator object. For example, if you are using theconvertDateTime tagto bind aDateTime converter to a property, that property must accept andreturn aDateTime instance.

The rest of this section explains how to write properties that canbe bound to component values, to component instances for the component objects described inAdding UI Components to a Page Using the HTML Component Tags, and to converter, listener, and validator implementations.

Writing Properties Bound to Component Values

To write a backing bean property bound to a component’s value, you mustknow the types that the component’s value can be so that you canmake the property match the type of the component’s value.

Table 12-1 lists all the component classes described inAdding UI Components to a Page Using the HTML Component Tags and the acceptable typesof their values.

When page authors bind components to properties using thevalue attributes of thecomponent tags, they need to ensure that the corresponding properties match the typesof the components’ values.

Table 12-1 Acceptable Types of Component Values

Component

Acceptable Types of Component Values

UIInput,UIOutput,UISelectItem,UISelectOne

Any ofthe basic primitive and numeric types or any Java programming language object typefor which an appropriateConverter implementation is available.

UIData

array of beans,List of beans, singlebean,java.sql.ResultSet,javax.servlet.jsp.jstl.sql.Result,javax.sql.RowSet.

UISelectBoolean

boolean orBoolean.

UISelectItems

java.lang.String,Collection,Array,Map.

UISelectMany

array orList. Elementsof thearray orList can be any of the standard types.

UIInput andUIOutput Properties

The following tag binds thename component to thename property ofCashierBean.

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

Here is the bean property bound to thename component:

protected String name = null; public void setName(String name) {    this.name = name;}public String getName() {    return this.name;}

AsUsing the Standard Converters describes, to convert the value of aUIInput orUIOutput component, youcan either apply a converter or create the bean property bound tothe component with the desired type. Here is the example tag explained inUsingDateTimeConverter that displays the date books will be shipped:

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

The application developer must ensure that the property bound to the component representedby this tag has a type ofjava.util.Date. Here is theshipDate property inCashierBean:

protected Date shipDate;public Date getShipDate() {    return this.shipDate;}public void setShipDate(Date shipDate) {    this.shipDate = shipDate;}

SeeBinding Component Values and Instances to External Data Sources for more information on applying aConverter implementation.

UIData Properties

UIData components must be bound to one of the types listed inTable 12-1.TheUIData component from thebookshowcart.jsp page of the Duke’s Bookstore example isdiscussed in the sectionUsing Data-Bound Table Components. Here is part of the start tag ofdataTable from that section:

<h:dataTable     ...    value="#{cart.items}"    var="item" >

The value expression points to theitems property of theShoppingCart bean. TheShoppingCart bean maintains a map ofShoppingCartItem beans.

ThegetItems method fromShoppingCart populates aList withShoppingCartItem instances that are savedin the items map from when the customer adds books to thecart:

public synchronized List getItems() {    List results = new ArrayList();    results.addAll(this.items.values());    return results;}

All the components contained in theUIData component are bound to theproperties of theShoppingCart bean that is bound to the entireUIDatacomponent. For example, here is theoutputText tag that displays the book title inthe table:

<h:commandLink action="#{showcart.details}">    <h:outputText value="#{item.item.title}"/></h:commandLink>

The book title is actually a hyperlink to thebookdetails.jsp page. TheoutputText taguses the value expression#{item.item.title} to bind itsUIOutput component to thetitle property of theBook bean. The firstitem in the expression istheShoppingCartItem instance that thedataTable tag is referencing while rendering thecurrent row. The seconditem in the expression refers to theitem property ofShoppingCartItem, which returns aBook bean. Thetitle part of the expression refersto thetitle property ofBook. The value of theUIOutput component corresponding tothis tag is bound to thetitle property of theBook bean:

private String title = null;public String getTitle() {    return this.title;}public void setTitle(String title) {    this.title=title;}
UISelectBoolean Properties

Properties that hold theUISelectBoolean component’s data must be ofboolean orBoolean type. The exampleselectBooleanCheckbox tag from the sectionRendering Components for Selecting One Value binds a componentto a property. Here is an example that binds a component value toa property:

<h:selectBooleanCheckbox title="#{bundle.receiveEmails}"     value="#{custFormBean.receiveEmails}" ></h:selectBooleanCheckbox><h:outputText value="#{bundle.receiveEmails}">

Here is an example property that can be bound to the componentrepresented by the example tag:

    protected boolean receiveEmails = false;        ...    public void setReceiveEmails(boolean receiveEmails) {        this.receiveEmails = receiveEmails;    }    public boolean getReceiveEmails() {        return receiveEmails;    }
UISelectMany Properties

Because aUISelectMany component allows a user to select one or more items froma list of items, this component must map to a bean property oftypeList orarray. This bean property represents the set of currently selecteditems from the list of available items.

Here is the exampleselectManyCheckbox tag fromRendering Components for Selecting Multiple Values:

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

Here is a bean property that maps to thevalue of thisselectManyCheckboxexample:

protected String newsletters[] = new String[0];public void setNewsletters(String newsletters[]) {    this.newsletters = newsletters;}public String[] getNewsletters() {    return this.newsletters;}

As explained in the sectionRendering Components for Selecting Multiple Values, theUISelectItem andUISelectItems components are used torepresent all the values in aUISelectMany component. SeeUISelectItem Properties andUISelectItems Properties forinformation on how to write the bean properties for theUISelectItem andUISelectItemscomponents.

UISelectOne Properties

UISelectOne properties accept the same types asUIInput andUIOutput properties. Thisis because aUISelectOne component represents the single selected item from a setof items. This item can be any of the primitive types and anythingelse for which you can apply a converter.

Here is the exampleselectOneMenu tag 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>

Here is the property corresponding to this tag:

protected String shippingOption = "2";public void setShippingOption(String shippingOption) {    this.shippingOption = shippingOption;}public String getShippingOption() {    return this.shippingOption;}

Note thatshippingOption represents the currently selected item from the list of itemsin theUISelectOne component.

As explained in the sectionDisplaying a Menu Using theselectOneMenu Tag, theUISelectItem andUISelectItems components areused to represent all the values in aUISelectOne component. SeeUISelectItem Properties andUISelectItems Properties for information on how to write the backing bean properties for theUISelectItem andUISelectItems components.

UISelectItem Properties

AUISelectItem component represents one value in a set of values in aUISelectMany orUISelectOne component. The backing bean property that aUISelectItem component is boundto must be of typeSelectItem. ASelectItem object is composed of anObject representing the value, along with twoStrings representing the label and description oftheSelectItem object.

The Duke’s Bookstore application does not use anyUISelectItem components whose values are boundto backing beans. The exampleselectOneMenu tag fromDisplaying a Menu Using theselectOneMenu Tag containsselectItem tagsthat set the values of the list of items in the page. Hereis an example bean property that can set the values for thislist in the bean:

SelectItem itemOne = null;SelectItem getItemOne(){    return itemOne;}void setItemOne(SelectItem item) {    itemOne = item;}
UISelectItems Properties

UISelectItems components are children ofUISelectMany andUISelectOne components. EachUISelectItems component is composedof either a set ofSelectItem instances or a set ofSelectItemGroup instances. Asdescribed inUsing theselectItems Tag, aSelectItemGroup is composed of a set ofSelectItem instances. Thissection describes how to write the properties forselectItems tags containingSelectItem instancesand forselectItems tags containingSelectItemGroup instances.

Properties forSelectItems Composed ofSelectItem Instances

Using theselectItems Tag describes how the newsletters list of the Duke’s Bookstore application is populated usingthe application configuration resource file. You can also populate theSelectItems withSelectItem instances programmatically in the backing bean. This section explains how to dothis.

In your backing bean, you create a list that is bound totheSelectItem component. Then you define a set ofSelectItem objects, set theirvalues, and populate the list with theSelectItem objects. Here is an examplecode snippet that shows how to create aSelectItems property:

import javax.faces.component.SelectItem;...protected ArrayList options = null;protected SelectItem newsletter0 =     new SelectItem("200", "Duke’s Quarterly", "");...//in constructor, populate the listoptions.add(newsletter0);options.add(newsletter1);options.add(newsletter2);...public SelectItem getNewsletter0(){    return newsletter0;}void setNewsletter0(SelectItem firstNL) {    newsletter0 = firstNL;}// Other SelectItem propertiespublic Collection[] getOptions(){    return options;}public void setOptions(Collection[] options){    this.options = new ArrayList(options);}

The code first initializesoptions as a list. Each newsletter property is definedwith values. Then, each newsletterSelectItem is added to the list. Finally,the code includes the obligatorysetOptions andgetOptions accessor methods.

Properties forSelectItems Composed ofSelectItemGroup Instances

The preceding section explains how to write the bean property for aSelectItems component composed ofSelectItem instances. This section explains how to change theexample property from the preceding section so that theSelectItems is composed ofSelectItemGroup instances.

Let’s separate the newsletters into two groups: One group includes Duke’s newsletters, andthe other group includes theInnovator’s Almanac andRandom Ramblings newsletters.

In your backing bean, you need a list that contains twoSelectItemGroupinstances. EachSelectItemGroup instance contains twoSelectItem instances, each representing a newsletter:

import javax.faces.model.SelectItemGroup;...private ArrayList optionsGroup = null;optionsGroup = new ArrayList(2);private static final SelectItem options1[] = {    new SelectItem("200", "Duke’s Quarterly", "");    new SelectItem("202",         "Duke’s Diet and Exercise Journal", "");};private static final SelectItem options2[] = {    new SelectItem("201", "Innovator’s Almanac", "");    new SelectItem("203", "Random Ramblings", "");};SelectItemGroup group1 =     new SelectItemGroup("Duke’s", null, true, options1);SelectItemGroup group2 =    new SelectItemGroup("General Interest", null, true,         options2);optionsGroup.add(group1);optionsGroup.add(group2);...public Collection getOptionsGroup() {    return optionsGroup;} public void setOptionsGroup(Collection newGroupOptions) {    optionsGroup = new ArrayList(newGroupOptions);}

The code first initializesoptionsGroup as a list. TheoptionsGroup list contains twoSelectItemGroup objects. Each object is initialized with the label of the group appearingin the list or menu; a value; a Boolean indicating whether or notthe label is disabled; and an array containing twoSelectItem instances. Then eachSelectItemGroupis added to the list. Finally, the code includes thesetOptionsGroup andgetOptionsGroupaccessor methods so that the tag can access the values. TheselectItemstag references theoptionsGroup property to get theSelectItemGroup objects for populating thelist or menu on the page.

Writing Properties Bound to Component Instances

A property bound to a component instance returns and accepts a component instancerather than a component value. Here are the tags described inBinding a Component Instance to a Bean Propertythat bind components to backing bean properties:

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

AsBinding a Component Instance to a Bean Property explains, theselectBooleanCheckbox tag renders a check box and binds thefanClubUISelectBoolean component to thespecialOffer property ofCashierBean. TheoutputLabel tag binds thefanClubLabel component (which represents the check box’s label) to thespecialOfferText property ofCashierBean.If the user orders more than $100 (or 100 euros) worth of booksand clicks the Submit button, thesubmit method ofCashierBean sets both components’rendered properties totrue, causing the check box and label to display when thepage is re-rendered.

Because the components corresponding to the example tags are bound to the backingbean properties, these properties must match the components’ types. This means that thespecialOfferText property must be ofUIOutput type, and thespecialOffer property must be ofUISelectBoolean type:

UIOutput specialOfferText = null;public UIOutput getSpecialOfferText() {    return this.specialOfferText;}public void setSpecialOfferText(UIOutput specialOfferText) {    this.specialOfferText = specialOfferText;}UISelectBoolean specialOffer = null;public UISelectBoolean getSpecialOffer() {    return this.specialOffer;}public void setSpecialOffer(UISelectBoolean specialOffer) {    this.specialOffer = specialOffer;}

SeeBacking Beans for more general information on component binding.

SeeReferencing a Method That Performs Navigation for information on how to reference a backing bean method thatperforms navigation when a button is clicked.

SeeWriting a Method to Handle Navigation for more information on writing backing bean methods that handle navigation.

Writing Properties Bound to Converters, Listeners, or Validators

All of the standard converter, listener, and validator tags that are included withJavaServer Faces technology support binding attributes that allow page authors to bind converter,listener, or validator implementations to backing bean properties.

The following example fromBinding Converters, Listeners, and Validators to Backing Bean Properties shows a standardconvertDateTime tag using avalue expression with itsbinding attribute to bind theDateTimeConverter instance to theconvertDate property ofLoginBean:

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

TheconvertDate property must therefore accept and return aDateTimeConverter object, as shownhere:

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

Because the converter is bound to a backing bean property, the backing beanproperty is able to modify the attributes of the converter or addnew functionality to it. In the case of the preceding example, the propertysets the date pattern that the converter will use to parse the user’sinput into aDate object.

The backing bean properties that are bound to validator or listener implementations arewritten in the same way and have the same general purpose.

PreviousContentsNext

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


[8]ページ先頭

©2009-2025 Movatter.jp