# The Java EE 7 Tutorial

# 15.12 Binding Component Values and Instances to Managed Bean Properties

A component tag can wire its data to a managed bean by one of the following methods:

- Binding its component's value to a bean property

- Binding its component's instance to a bean property

To bind a component's value to a managed bean property, a component tag's `value` attribute uses an EL value expression. To bind a component instance to a bean property, a component tag's `binding` attribute uses a value expression.

When a component instance is bound to a managed bean property, the property holds the component's local value. Conversely, when a component's value is bound to a managed bean property, the property holds the value stored in the managed bean. This value is updated with the local value during the Update Model Values phase of the lifecycle. There are advantages to both of these methods.

Binding a component instance to a bean property has the following advantages.

- The managed bean can programmatically modify component attributes.

- The managed bean can instantiate components rather than let the page author do so.

Binding a component's value to a bean property has the following advantages.

- The page author has more control over the component attributes.

- The managed bean has no dependencies on the JavaServer Faces API (such as the component classes), allowing for greater separation of the presentation layer from the model layer.

- The JavaServer Faces implementation can perform conversions on the data based on the type of the bean property without the developer needing to apply a converter.

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

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

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

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

    #{myBean.currentOption}

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

Table 15-3 Examples of Value-Binding Expressions

Value | Expression
--- | ---
A Boolean | `cart.numberOfItems> 0`
A property initialized from a context initialization parameter | `initParam.quantity`
A bean property | `cashierBean.name`
A value in an array | `books[3]`
A value in a collection | `books["fiction"]`
A property of an object in an array of objects | `books[3].price`

The next two sections explain how to use the `value` attribute to bind a component's value to a bean property or other data objects and how to use the `binding` attribute to bind a component instance to a bean property.

## 15.12.1 Binding a Component Value to a Property

To bind a component's value to a managed bean property, you specify the name of the bean and the property using the `value` attribute.

This means that the first part of the EL value expression must match the name of the managed bean up to the first period (`.`) and the part of the value expression after the period must match the property of the managed bean.

For example, in the Duke's Bookstore case study, the `h:dataTable` tag in `bookcatalog.xhtml` sets the value of the component to the value of the `books` property of the `BookstoreBean` backing bean, whose name is `store`:

    <h:dataTable id="books"
                 value="#{store.books}"
                 var="book"
                 headerClass="list-header"
                 styleClass="list-background"
                 rowClasses="list-row-even, list-row-odd"
                 border="1"
                 summary="#{bundle.BookCatalog}">

The value is obtained by calling the backing bean's `getBooks` method, which in turn calls the `BookRequestBean` session bean's `getBooks` method.

If you use the application configuration resource file to configure managed beans instead of defining them in managed bean classes, the name of the bean in the `value` expression must match the `managed-bean-name` element of the managed bean declaration up to the first period (`.`) in the expression. Similarly, the part of the value expression after the period must match the name specified in the corresponding `property-name` element in the application configuration resource file.

For example, consider this managed bean configuration, which configures the `ImageArea` bean corresponding to the top-left book in the image map on the `index.html` page of the Duke's Bookstore case study:

    <managed-bean eager="true">
        ...
        <managed-bean-name>Book201</managed-bean-name>
        <managed-bean-class>dukesbookstore.model.ImageArea</managed-bean-class>
        <managed-bean-scope>application</managed-bean-scope>
        <managed-property>
            ...
            <property-name>shape</property-name>
            <value>rect</value>
        </managed-property>
        <managed-property>
            ...
            <property-name>alt</property-name>
            <value>Duke</value>
        </managed-property>
        ...

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

Although the `bookstore:area` tags on the `index.xhtml` page do not bind to an `ImageArea` property (they bind to the bean itself), you could refer to the property using a value expression from the `value` attribute of the component's tag:

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

See Configuring Managed Beans for information on how to configure beans in the application configuration resource file.

## 15.12.2 Binding a Component Value to an Implicit Object

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

The `bookreceipt.xhtml` page of the Duke's Bookstore case study has a reference to an implicit object:

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

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

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

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

Table 15-4 Implicit Objects

Implicit Object | What It Is
--- | ---
`applicationScope` | A `Map` of the application scope attribute values, keyed by attribute name
`cookie` | A `Map` of the cookie values for the current request, keyed by cookie name
`facesContext` | The `FacesContext` instance for the current request
`header` | A `Map` of HTTP header values for the current request, keyed by header name
`headerValues` | A `Map` of `String` arrays containing all the header values for HTTP headers in the current request, keyed by header name
`initParam` | A `Map` of the context initialization parameters for this web application
`param` | A `Map` of the request parameters for this request, keyed by parameter name
`paramValues` | A `Map` of `String` arrays containing all the parameter values for request parameters in the current request, keyed by parameter name
`requestScope` | A `Map` of the request attributes for this request, keyed by attribute name
`sessionScope` | A `Map` of the session attributes for this request, keyed by attribute name
`view` | The root `UIComponent` in the current component tree stored in the `FacesRequest` for this request

## 15.12.3 Binding a Component Instance to a Bean Property

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

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

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

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

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

The `rendered` attributes of both tags are set to `false` to prevent the check box and its label from being rendered. If the customer makes a large order and clicks the Submit button, the `submit` method of `CashierBean` sets both components' `rendered` properties to `true`, causing the check box and its label to be rendered.

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

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

Writing Properties Bound to Component Instances explains how to write the bean properties bound to the example components.