应用JSF技术开发(Developing with JavaServer Faces Technology:chapter11)《注:未完成》
2006-09-01 11:24
513 查看
应用JSF技术开发
Chapter 10 演示了页面作者可以通过页面上的组件标签和core标签将组件和服务器端对象绑定。应用开发者的职责就是编写JSF应用的服务器端对象。这些对象包括后台beans,转换器,事件处理和验证器。这一章用Duke的书店应用(see The Example JavaServer Faces Application, page 308)讲解应用开发者的职责包括:对后台bean编程
本地化应用程序
创建用户定义转换器和验证器
实现事件监听器
编写后台bean方法来执行导航处理,数据验证和事件处理
编写bean属性
已在page295解释过,一个后台bean属性可以被和以下条目绑定:一个组件值
一个组件实例
一个转换器实现
一个监听器实现
一个验证器实现
这些属性遵循了JavaBeans组件的规则(see JavaBeans Components, page 131).
UI组件标签用值attribute把其值绑定到一个属性,并且,把组件实例绑定attribute。具体介绍Binding Component Values and Instances to External Data Sources (page 361).同样,所有的转换器,监听器,验证器标签用绑定的attribute来把他们的实现和后台bean属性绑定,具体解释 Binding Converters, Listeners, and Validators to Backing Bean Properties (page 367).
把组件值和后台bean属性绑定,后台bean属性必须和组件值的类型相匹配。举例,如果后台bean属性需要绑定到一个
UISelectBoolean值,则这个bean的相应属性应该接受boolean或Boolean包装类实例作为返回值。
为了绑定一个组件实例,bean的属性必须和组件类型匹配。举例,如果一个后台bean属性需要绑定到
UISelectBoolean实例,则其属性就应该接受并返回
UISelectBoolean。
同样,为了绑定一个转换器,监听器,或验证器实现到一个属性,这个属性必须接受并返回同样类型的转换器,监听器或验证器对象。举例,如果你用
convertDateTime标签绑定
DateTime转换器到一个属性,则这个属性必须接受并返回
DateTime实例。
下面的章节介绍了如何编写能被绑定到组件值的属性,组件属性描述Adding UI Components to a Page Using the HTML Component Tags (page 316), 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 must know the types that the component's value can be so that you can make the property match the type of the component's value.Table 11-1 lists all the component classes described in Adding UI Components to a Page Using the HTML Component Tags (page 316) and the acceptable types of their values.
When page authors bind components to properties using the
valueattributes of the component tags, they need to ensure that the corresponding properties match the types of the components' values.
Component | Acceptable Types of Component Values |
---|---|
UIInput, UIOutput, UISelectItem, UISelectOne | Any of the basic primitive and numeric types or any Java programming language object type for which an appropriate Converterimplementation is available. |
UIData | arrayof beans, Listof beans, single bean, java.sql.ResultSet, javax.servlet.jsp.jstl.sql.Result, javax.sql.RowSet. |
UISelectBoolean | boolean or Boolean. |
UISelectItems | java.lang.String, Collection, Array, Map. |
UISelectMany | array or List. Elements of the array or List can be any of the standard types. |
UIInput and UIOutput Properties
The following tag binds thenamecomponent to the
nameproperty of
CashierBean.
<h:inputText id="name" size="50" value="#{cashier.name}" required="true"> <f:valueChangeListener type="com.sun.bookstore6.listeners.NameChanged" /> </h:inputText>
Here is the bean property bound to the
namecomponent:
protected String name = null; public void setName(String name) { this.name = name; } public String getName() { return this.name; }[/code]
As Using the Standard Converters (page 349) describes, to convert the value of a
UIInputor
UIOutputcomponent, you can either apply a converter or create the bean property bound to the component with the desired type. Here is the example tag explained in Using DateTimeConverter (page 352) 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 represented by this tag has a type of
java.util.Date. Here is the
shipDateproperty in
CashierBean:
protected Date shipDate; public Date getShipDate() { return this.shipDate; } public void setShipDate(Date shipDate) { this.shipDate = shipDate; }[/code]
See Binding Component Values and Instances to External Data Sources (page 361) for more information on applying a
Converterimplementation.
UIData Properties
UIDatacomponents must be bound to one of the types listed in Table 11-1. The
UIDatacomponent from the
bookshowcart.jsppage of the Duke's Bookstore example is discussed in the section Using Data-Bound Table Components (page 329). Here is part of the start tag of
dataTablefrom that section:
<h:dataTable id="items" ... value="#{cart.items}" var="item" >
The value expression points to the
itemsproperty of the
ShoppingCartbean. The
ShoppingCartbean maintains a map of
ShoppingCartItembeans.
The
getItemsmethod from
ShoppingCartpopulates a
Listwith
ShoppingCartIteminstances that are saved in the items map from when the customer adds books to the cart:
public synchronized List getItems() { List results = new ArrayList(); results.addAll(this.items.values()); return results; }
All the components contained in the
UIDatacomponent are bound to the properties of the
ShoppingCartbean that is bound to the entire
UIDatacomponent. For example, here is the
outputTexttag that displays the book title in the table:
<h:commandLink action="#{showcart.details}"> <h:outputText value="#{item.item.title}"/> </h:commandLink>
The book title is actually a hyperlink to the
bookdetails.jsppage. The
outputTexttag uses the value expression
#{item.item.title}to bind its
UIOutputcomponent to the
titleproperty of the
Bookbean. The first
itemin the expression is the
ShoppingCartIteminstance that the
dataTabletag is referencing while rendering the current row. The second
itemin the expression refers to the
itemproperty of
ShoppingCartItem, which returns a
Bookbean. The
titlepart of the expression refers to the
titleproperty of
Book. The value of the
UIOutputcomponent corresponding to this tag is bound to the
titleproperty of the
Bookbean:
private String title = null; public String getTitle() { return this.title; } public void setTitle(String title) { this.title=title; }
UISelectBooleanProperties
Properties that hold theUISelectBooleancomponent's data must be of
booleanor
Booleantype. The example
selectBooleanCheckboxtag from the section Rendering Components for Selecting One Value (page 337) binds a component to a property. Here is an example that binds a component value to a 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 component represented by the example tag:
protected boolean receiveEmails = false; ... public void setReceiveEmails(boolean receiveEmails) { this.receiveEmails = receiveEmails; } public boolean getReceiveEmails() { return receiveEmails; }[/code]
UISelectMany Properties
Because aUISelectManycomponent allows a user to select one or more items from a list of items, this component must map to a bean property of type
Listor
array. This bean property represents the set of currently selected items from the list of available items.
Here is the example
selectManyCheckboxtag from Rendering Components for Selecting Multiple Values (page 339):
<h:selectManyCheckbox id="newsletters" layout="pageDirection" value="#{cashier.newsletters}"> <f:selectItems value="#{newsletters}"/> </h:selectManyCheckbox>
Here is a bean property that maps to the
valueof this
selectManyCheckboxexample:
protected String newsletters[] = new String[0]; public void setNewsletters(String newsletters[]) { this.newsletters = newsletters; } public String[] getNewsletters() { return this.newsletters; }
As explained in the section Rendering Components for Selecting Multiple Values (page 339), the
UISelectItemand
UISelectItemscomponents are used to represent all the values in a
UISelectManycomponent. See UISelectItem Properties and UISelectItemsProperties for information on how to write the bean properties for the
UISelectItemand
UISelectItemscomponents.
UISelectOne Properties
UISelectOneproperties accept the same types as
UIInputand
UIOutputproperties. This is because a
UISelectOnecomponent represents the single selected item from a set of items. This item can be any of the primitive types and anything else for which you can apply a converter.
Here is the example
selectOneMenutag from Displaying a Menu Using the selectOneMenu Tag (page 338):
<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>
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 that
shippingOptionrepresents the currently selected item from the list of items in the
UISelectOnecomponent.
As explained in the section Displaying a Menu Using the selectOneMenu Tag (page 338), the
UISelectItemand
UISelectItemscomponents are used to represent all the values in a
UISelectOnecomponent. See UISelectItem Properties and UISelectItemsProperties for information on how to write the backing bean properties for the
UISelectItemand
UISelectItemscomponents.
UISelectItem Properties
AUISelectItemcomponent represents one value in a set of values in a
UISelectManyor
UISelectOnecomponent. The backing bean property that a
UISelectItemcomponent is bound to must be of type
SelectItem. A
SelectItemobject is composed of an
Objectrepresenting the value, along with two
Stringsrepresenting the label and description of the
SelectItemobject.
The Duke's Bookstore application does not use any
UISelectItemcomponents whose values are bound to backing beans. The example
selectOneMenutag from Displaying a Menu Using the selectOneMenu Tag (page 338) contains
selectItemtags that set the values of the list of items in the page. Here is an example bean property that can set the values for this list in the bean:
SelectItem itemOne = null; SelectItem getItemOne(){ return itemOne; } void setItemOne(SelectItem item) { itemOne = item; }
UISelectItemsProperties
UISelectItemscomponents are children of
UISelectManyand
UISelectOnecomponents. Each
UISelectItemscomponent is composed of either a set of
SelectIteminstances or a set of
SelectItemGroupinstances. As described in Using the selectItems Tag (page 342), a
SelectItemGroupis composed of a set of
SelectIteminstances. This section describes how to write the properties for
selectItemstags containing
SelectIteminstances and for
selectItemstags containing
SelectItemGroupinstances.
Properties for SelectItems Composed of SelectItem Instances
Using the selectItems Tag (page 342) describes how the newsletters list of the Duke's Bookstore application is populated using the application configuration resource file. You can also populate the
SelectItemswith
SelectIteminstances programmatically in the backing bean. This section explains how to do this.
In your backing bean, you create a list that is bound to the
SelectItemcomponent. Then you define a set of
SelectItemobjects, set their values, and populate the list with the
SelectItemobjects. Here is an example code snippet that shows how to create a
SelectItemsproperty:
import javax.faces.component.SelectItem; ... protected ArrayList options = null; protected SelectItem newsletter0 = new SelectItem("200", "Duke's Quarterly", ""); ... //in constructor, populate the list options.add(newsletter0); options.add(newsletter1); options.add(newsletter2); ... public SelectItem getNewsletter0(){ return newsletter0; } void setNewsletter0(SelectItem firstNL) { newsletter0 = firstNL; } // Other SelectItem properties public Collection[] getOptions(){ return options; } public void setOptions(Collection[] options){ this.options = new ArrayList(options); }
The code first initializes
optionsas a list. Each newsletter property is defined with values. Then, each newsletter
SelectItemis added to the list. Finally, the code includes the obligatory
setOptionsand
getOptionsaccessor methods.
Properties for SelectItems Composed of SelectItemGroup Instances
The preceding section explains how to write the bean property for a
SelectItemscomponent composed of
SelectIteminstances. This section explains how to change the example property from the preceding section so that the
SelectItemsis composed of
SelectItemGroupinstances.
Let's separate the newsletters into two groups: One group includes Duke's newsletters, and the other group includes the Innovator's Almanac and Random Ramblings newsletters.
In your backing bean, you need a list that contains two
SelectItemGroupinstances. Each
SelectItemGroupinstance contains two
SelectIteminstances, 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 initializes
optionsGroupas a list. The
optionsGrouplist contains two
SelectItemGroupobjects. Each object is initialized with the label of the group appearing in the list or menu; a value; a Boolean indicating whether or not the label is disabled; and an array containing two
SelectIteminstances. Then each
SelectItemGroupis added to the list. Finally, the code includes the
setOptionsGroupand
getOptionsGroupaccessor methods so that the tag can access the values. The
selectItemstag references the
optionsGroupproperty to get the
SelectItemGroupobjects for populating the list or menu on the page.
Writing Properties Bound to Component Instances
A property bound to a component instance returns and accepts a component instance rather than a component value. Here are the tags described in Binding a Component Instance to a Bean Property (page 366) that bind components to backing 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>
As Binding a Component Instance to a Bean Property (page 366) explains, the
selectBooleanCheckboxtag renders a checkbox and binds the
fanClub
UISelectBooleancomponent to the
specialOfferproperty of
CashierBean. The
outputLabeltag binds the
fanClubLabelcomponent (which represents the checkbox's label) to the
specialOfferTextproperty of
CashierBean. If the user orders more than $100 (or 100 euros) worth of books and clicks the Submit button, the
submitmethod of
CashierBeansets both components'
renderedproperties to
true, causing the checkbox and label to display when the page is rerendered.
Because the components corresponding to the example tags are bound to the backing bean properties, these properties must match the components' types. This means that the
specialOfferTextproperty must be of
UIOutputtype, and the
specialOfferproperty must be of
UISelectBooleantype:
UIOutput specialOfferText = null;
public UIOutput getSpecialOfferText() {
return this.specialOfferText;
}
public void setSpecialOfferText(UIOutput specialOfferText) {
this.specialOfferText = specialOfferText;
}
UISelectBooleanspecialOffer = null;
public UISelectBooleangetSpecialOffer() {
return this.specialOffer;
}
public void setSpecialOffer(UISelectBooleanspecialOffer) {
this.specialOffer = specialOffer;
}
See Backing Beans (page 295) for more general information on component binding.
See Referencing a Method That Performs Navigation (page 370) for information on how to reference a backing bean method that performs navigation when a button is clicked.
See Writing 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 with JavaServer Faces technology support binding attributes that allow page authors to bind converter, listener, or validator implementations to backing bean properties.The following example from Binding Converters, Listeners, and Validators to Backing Bean Properties (page 367) shows a standard
convertDateTimetag using a value expression with its
bindingattribute to bind the
DateTimeConverterinstance to the
convertDateproperty of
LoginBean.:
<h:inputText value="#{LoginBean.birthDate}"> <f:convertDateTime binding="#{LoginBean.convertDate}" /> </h:inputText>
The
convertDateproperty must therefore accept and return a
DateTimeConverterobject, as shown here:
private DateTimeConverter convertDate; public DateTimeConverter getConvertDate() { ... return convertDate; { public void setConvertDate(DateTimeConverter convertDate) { convertDate.setPattern([code]"EEEEEEEE, MMM dd, yyyy");this.convertDate = convertDate;
} [/code]
因为converter被绑定到后台bean属性上,后台bean属性可以修改converter的属性或者给它添加新功能。在前面的例子里,converter会解析用户输入数据将其转化成Date对象。
The backing bean properties that are bound to validator or listener implementations are written in the same way and have the same general purpose.
相关文章推荐
- JSF技术介绍(JavaServer Faces Technology:chapter 9)《注:未完成》
- JavaServer Faces 技术使Web应用程序开发变得更容易
- JSF 组件开发 - Java ServerFaces 及代码示例
- 在JSP页面中应用JSF技术(Using JavaServer Faces Technology in JSP Pages chapter10)《注:未完成》
- Web Tier to Go With Java EE 5: Summary of New Features in JavaServer Faces 1.2 Technology
- Developing Web Applications with JavaServer Faces
- JSF(Java Server Face)与在Web UI实现托拽式快速开发的应用
- JSF(Java Server Face)与在Web UI实现托拽式快速开发的应用
- JSF(Java Server Face)与在Web UI实现托拽式快速开发的应用
- Looking at JavaServer Faces: Rich Internet Components with JSF
- JSF(JavaServer Faces) 介绍
- Ubuntu Feisty 下开发 JNI 应用步骤 (Java调用C/C++的技术)
- 用JavaServer Faces开发Web应用(1)
- 用JavaServer Faces开发Web应用(3)
- JavaServer Faces (JSF) vs Struts
- 用JavaServer Faces开发Web应用
- OpenJWeb(1.6) Java Web应用快速开发平台技术白皮书
- 应用Java技术开发WAP应用程序
- JNI(Java Native Interface)技术在嵌入式软件开发中的应用
- 【Java】--Javaserver faces(JSF) 03