Writing Bean Properties - The Java EE 6 Tutorial (original) (raw)
2. Using the Tutorial Examples
3. Getting Started with Web Applications
4. JavaServer Faces Technology
7. Using JavaServer Faces Technology in Web Pages
8. Using Converters, Listeners, and Validators
9. Developing with JavaServer Faces Technology
Managed Beans in JavaServer Faces Technology
Using the EL to Reference Managed Beans
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
Validating Null and Empty Strings
10. JavaServer Faces Technology: Advanced Concepts
11. Using Ajax with JavaServer Faces Technology
12. Composite Components: Advanced Topics and Example
13. Creating Custom UI Components and Other Custom Objects
14. Configuring JavaServer Faces Applications
16. Uploading Files with Java Servlet Technology
17. Internationalizing and Localizing Web Applications
18. Introduction to Web Services
19. Building Web Services with JAX-WS
20. Building RESTful Web Services with JAX-RS
21. JAX-RS: Advanced Topics and Example
23. Getting Started with Enterprise Beans
24. Running the Enterprise Bean Examples
25. A Message-Driven Bean Example
26. Using the Embedded Enterprise Bean Container
27. Using Asynchronous Method Invocation in Session Beans
Part V Contexts and Dependency Injection for the Java EE Platform
28. Introduction to Contexts and Dependency Injection for the Java EE Platform
29. Running the Basic Contexts and Dependency Injection Examples
30. Contexts and Dependency Injection for the Java EE Platform: Advanced Topics
31. Running the Advanced Contexts and Dependency Injection Examples
32. Introduction to the Java Persistence API
33. Running the Persistence Examples
34. The Java Persistence Query Language
35. Using the Criteria API to Create Queries
36. Creating and Using String-Based Criteria Queries
37. Controlling Concurrent Access to Entity Data with Locking
38. Using a Second-Level Cache with Java Persistence API Applications
39. Introduction to Security in the Java EE Platform
40. Getting Started Securing Web Applications
41. Getting Started Securing Enterprise Applications
42. Java EE Security: Advanced Topics
Part VIII Java EE Supporting Technologies
43. Introduction to Java EE Supporting Technologies
45. Resources and Resource Adapters
46. The Resource Adapter Example
47. Java Message Service Concepts
48. Java Message Service Examples
49. Bean Validation: Advanced Topics
50. Using Java EE Interceptors
51. Duke's Bookstore Case Study Example
52. Duke's Tutoring Case Study Example
53. Duke's Forest Case Study Example
As explained in Managed Beans in JavaServer Faces Technology, a managed bean property can be bound to one of the following items:
- A component value
- A component instance
- A converter implementation
- A listener implementation
- A validator implementation
These properties follow the conventions of JavaBeans components (also called beans). For more information on JavaBeans components, see the JavaBeans Tutorial at http://docs.oracle.com/javase/tutorial/javabeans/index.html.
The component’s tag binds the component’s value to a managed bean property by using its value attribute and binds the component’s instance to a managed bean property by using its binding attribute. Likewise, all the converter, listener, and validator tags use their binding attributes to bind their associated implementations to managed bean properties. See Binding Component Values and Instances to Managed Bean Properties and Binding Converters, Listeners, and Validators to Managed Bean Properties for more information.
To bind a component’s value to a managed bean property, the type of the property must match the type of the component’s value to which it is bound. For example, if a managed bean property is bound to a UISelectBoolean component’s value, the property should accept and return a boolean value or a Boolean wrapper Object instance.
To bind a component instance to a managed bean property, the property must match the type of component. For example, if a managed bean property is bound to a UISelectBoolean instance, the property should accept and return a UISelectBooleanvalue.
Similarly, to bind a converter, listener, or validator implementation to a managed bean property, the property must accept and return the same type of converter, listener, or validator object. For example, if you are using the convertDateTime tag to bind a javax.faces.convert.DateTimeConverter to a property, that property must accept and return a DateTimeConverter instance.
The rest of this section explains how to write properties that can be bound to component values, to component instances for the component objects described inAdding Components to a Page Using HTML Tags, and to converter, listener, and validator implementations.
Writing Properties Bound to Component Values
To write a managed bean property that is bound to a component’s value, you must match the property type to the component’s value.
Table 9-1 lists the javax.faces.component classes and the acceptable types of their values.
Table 9-1 Acceptable Types of Component Values
Component Class | 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 javax.faces.convert.Converter implementation is available |
UIData | array of beans, List of 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, though elements of thearray or List can be any of the standard types |
When they bind components to properties by using the value attributes of the component tags, page authors need to ensure that the corresponding properties match the types of the components’ values.
UIInput and UIOutput Properties
The UIInput and UIOutput component classes are represented by the component tags that begin with h:input and h:output, respectively (for example, h:inputText and h:outputText).
In the following example, an h:inputText tag binds the name component to thename property of a managed bean called CashierBean.
<h:inputText id="name" size="30" value="#{cashier.name}" ...>
The following code snippet from the managed bean CashierBean shows the bean property type bound by the preceding component tag:
private String name = null;
public void setName(String name) { this.name = name; } public String getName() { return this.name; }
As described in Using the Standard Converters, to convert the value of an input or output component, you can either apply a converter or create the bean property bound to the component with the matching type. Here is the example tag, fromUsing DateTimeConverter, that displays the date when items will be shipped.
<h:outputText value="#{cashier.shipDate}"> <f:convertDateTime type="date" dateStyle="full" />
The bean property represented by this tag must have a type of java.util.Date. The following code snippet shows the shipDate property, from the managed bean CashierBean, that is bound by the tag’s value in the preceding example:
private Date shipDate;
public Date getShipDate() { return this.shipDate; } public void setShipDate(Date shipDate) { this.shipDate = shipDate; }
UIData Properties
The UIData component class is represented by the h:dataTable component tag.
UIData components must be bound to one of the managed bean property types listed in Table 9-1. Data components are discussed in Using Data-Bound Table Components. Here is part of the start tag of dataTable from that section:
<h:dataTable id="items" ... value="#{cart.items}" ... var="item">
The value expression points to the items property of a shopping cart bean named cart. The cart bean maintains a map of ShoppingCartItem beans.
The getItems method from the cart bean populates a List with ShoppingCartItem instances that are saved in the items map when the customer adds books to the cart, as shown in the following code segment:
public synchronized List getItems() { List results = new ArrayList(); results.addAll(this.items.values()); return results; }
All the components contained in the UIData component are bound to the properties of the cart bean that is bound to the entire UIData component. For example, here is the h:outputText tag that displays the book title in the table:
<h:commandLink action="#{showcart.details}"> <h:outputText value="#{item.item.title}"/>
The title is actually a hyperlink to the bookdetails.xhtml page. The h:outputText tag uses the value expression #{item.item.title} to bind its UIOutput component to the titleproperty of the Book entity. The first item in the expression is the ShoppingCartIteminstance that the h:dataTable tag is referencing while rendering the current row. The second item in expression refers to the item property of ShoppingCartItem, which returns an Object (in this case, a Book. The title part of the expression refers to the title property of Book. The value of the UIOutput component corresponding to this tag is bound to the title property of the Bookentity:
private String title; ... public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
UISelectBoolean Properties
The UISelectBoolean component class is represented by the component tag h:selectBooleanCheckbox.
Managed bean properties that hold a UISelectBoolean component’s data must be ofboolean or Boolean type. The example selectBooleanCheckbox tag from the section Displaying Components for Selecting One Value binds a component to a property. The following example shows a tag that binds a component value to a boolean property:
<h:selectBooleanCheckbox title="#{bundle.receiveEmails}" value="#{custFormBean.receiveEmails}" > <h:outputText value="#{bundle.receiveEmails}">
Here is an example property that can be bound to the component represented by the example tag:
private boolean receiveEmails = false; ... public void setReceiveEmails(boolean receiveEmails) { this.receiveEmails = receiveEmails; } public boolean getReceiveEmails() { return receiveEmails; }
UISelectMany Properties
The UISelectMany component class is represented by the component tags that begin withh:selectMany (for example, h:selectManyRadio and h:selectManyListbox).
Because a UISelectMany component allows a user to select one or more items from a list of items, this component must map to a bean property of type List or array. This bean property represents the set of currently selected items from the list of available items.
The following example of the selectManyCheckbox tag comes from Displaying Components for Selecting Multiple Values:
<h:selectManyCheckbox id="newslettercheckbox" layout="pageDirection" value="#{cashier.newsletters}"> <f:selectItems value="#{cashier.newsletterItems}"/>
Here is the bean property that maps to the value of the selectManyCheckboxtag from the preceding example:
private String newsletters[] = new String[0];
public void setNewsletters(String newsletters[]) { this.newsletters = newsletters; } public String[] getNewsletters() { return this.newsletters; }
The UISelectItem and UISelectItems components are used to represent all the values in a UISelectMany component. See UISelectItem Properties and UISelectItems Properties for information on writing the bean properties for the UISelectItem and UISelectItems components.
UISelectOne Properties
The UISelectOne component class is represented by the component tags that begin withh:selectOne (for example, h:selectOneRadio and h:selectOneListbox).
UISelectOne properties accept the same types as UIInput and UIOutput properties, 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 an example of the h:selectOneMenu tag from Displaying a Menu Using the h: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}"/>
Here is the bean property corresponding to this tag:
private String shippingOption = "2";
public void setShippingOption(String shippingOption) { this.shippingOption = shippingOption; } public String getShippingOption() { return this.shippingOption; }
Note that shippingOption represents the currently selected item from the list of items in the UISelectOne component.
The UISelectItem and UISelectItems components are used to represent all the values in a UISelectOne component. This is explained in the section Displaying a Menu Using the h:selectOneMenu Tag.
For information on how to write the managed bean properties for theUISelectItem and UISelectItems components, see UISelectItem Properties and UISelectItems Properties.
UISelectItem Properties
A UISelectItem component represents a single value in a set of values in a UISelectMany or a UISelectOne component. A UISelectItem component must be bound to a managed bean property of type javax.faces.model.SelectItem. A SelectItem object is composed of an Object representing the value, along with two String values representing the label and description of the UISelectItem object.
The example selectOneMenu tag from UISelectOne Properties contains selectItem tags that set the values of the list of items in the page. Here is an example of a 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; }
UISelectItems Properties
UISelectItems components are children of UISelectMany and UISelectOne components. Each UISelectItems component is composed of a set of either UISelectItem instances or any collection of objects, such as an array, a list, or even POJOs.
The following code snippet from CashierBean shows how to write the properties for selectItems tags containing SelectItem instances.
private String[] newsletters = new String[0]; ... private static SelectItem[] newsletterItems = { new SelectItem("Duke's Quarterly"), new SelectItem("Innovator's Almanac"), new SelectItem("Duke's Diet and Exercise Journal"), new SelectItem("Random Ramblings") }; ... public void setNewsletters(String[] newsletters) { this.newsletters = newsletters; }
public String[] getNewsletters() { return this.newsletters; }
public SelectItem[] getNewsletterItems() { return newsletterItems; }
Here, the newsletters property represents the SelectItems object, while the newsletterItems property represents a static array of SelectItem objects. The SelectItem class has several constructors; in this example, the argument is an Object that represents both the value of the item and the label that appears in the UISelectMany component 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. The following components bind a component instance to a managed bean property:
<h:selectBooleanCheckbox id="fanClub" rendered="false" binding="#{cashier.specialOffer}" /> <h:outputLabel for="fanClub" rendered="false" binding="#{cashier.specialOfferText}" value="#{bundle.DukeFanClub}" />
The selectBooleanCheckbox tag renders a check box and binds the fanClub UISelectBoolean component to the specialOffer property of CashierBean. The outputLabel tag binds the value of thevalue attribute, which represents the check box’s label, to the specialOfferText property of CashierBean. If the user orders more than $100 worth of books and clicks the Submit button, the submit method of CashierBean sets both components’ rendered properties totrue, causing the check box and label to display when the page is rerendered.
Because the components corresponding to the example tags are bound to the managed bean properties, these properties must match the components’ types. This means that thespecialOfferText property must be of type UIOutput, and the specialOffer property must be of type UISelectBoolean:
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; }
For more general information on component binding, see Managed Beans in JavaServer Faces Technology.
For information on how to reference a managed bean method that performs navigation when a button is clicked, see Referencing a Method That Performs Navigation.
For more information on writing managed bean methods that handle navigation, see Writing a Method to Handle Navigation.
Writing Properties Bound to Converters, Listeners, or Validators
All the standard converter, listener, and validator tags included with JavaServer Faces technology support binding attributes that allow you to bind converter, listener, or validator implementations to managed bean properties.
The following example shows a standard convertDateTime tag using a value expression with its binding attribute to bind the javax.faces.convert.DateTimeConverter instance to the convertDate property of LoginBean:
<h:inputText value="#{LoginBean.birthDate}"> <f:convertDateTime binding="#{LoginBean.convertDate}" />
The convertDate property must therefore accept and return a DateTimeConverter object, as shown here:
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 managed bean property, the managed bean property can modify the attributes of the converter or add new functionality to it. In the case of the preceding example, the property sets the date pattern that the converter uses to parse the user’s input into aDate object.
The managed bean properties that are bound to validator or listener implementations are written in the same way and have the same general purpose.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Legal Notices