Skip Headers

Oracle® Application Development Framework Developer's Guide 10g Release 3 (10.1.3) B25386-01 |
| Home | Solution Area | Contents | Index

Previous | Next |

# 4.5 Creating and Using a Backing Bean for a Web Page

In JSF, backing beans are JavaBeans used mainly to provide UI logic and to manage data between the web tier and the business tier of the application (similar to a data transfer object). Typically you have one backing bean per JSF page. The backing bean contains the logic and properties for the UI components used on the page. For example, to programmatically change a UI component as a result of some user activity or to execute code before or after an ADF declarative action method, you provide the necessary code in the page's backing bean and bind the component to the corresponding property or method in the bean.

For a backing bean to be available when the application starts, you register it as a managed bean with a name and scope in `faces-config.xml`. At runtime whenever the managed bean is referenced on a page through a JSF EL value or method binding expression, the JSF implementation automatically instantiates the bean, populates it with any declared, default values, and places it in the managed bean scope as defined in `faces-config.xml`.

## 4.5.1 How to Create and Configure a Backing Bean

The Overview mode of the JSF Configuration Editor lets you create and configure a backing bean declaratively. Suppose you have a JSF page with the filename `SRDemopage.jspx`. Now you want to create a backing bean for the page.

To create and configure a backing bean as a managed bean:

1. In the Application Navigator, double-click faces-config.xml to open it in the default editor.

2. At the bottom of the editor, select the Overview tab to open the file in JSF Configuration Editor (Overview).

3. In the element list on the left, select Managed Beans.

4. Click New to open the Create Managed Bean dialog.

5. In the dialog, specify the following for a managed bean:

   - Name: Enter a unique identifier for the managed bean (e.g., `backing_SRDemopage`). This identifier determines how the bean will be referred to within the application using EL expressions, instead of using the bean's fully-qualified class name.

   - Class: Enter the fully qualified class name (e.g., `oracle.srdemo.view.backing.SRDemopage`). This is the JavaBean that contains the properties that hold the data for the page, along with the corresponding accessor methods and any other methods (such as navigation or validation) used by the bean. This can be an existing class or a new class.

   - Scope: This determines the scope within which the bean is stored. The valid scope values are:

     - application: The bean is available for the duration of the web application. This is helpful for global beans such as LDAP directories.

     - request: The bean is available from the time it is instantiated until a response is sent back to the client. This is usually the life of the current page. Backing beans for pages usually use this scope.

     - session: The bean is available to the client throughout the client's session.

     - none: The bean is instantiated each time it is referenced

6. Select the Generate Class If It Does Not Exist checkbox to let JDeveloper create the Java class for you. If you've already created the Java class, don't select this checkbox.

Note: At this point, you haven't defined a strict relationship between the JSF page and the backing bean. You've simply configured a backing bean in `faces-config.xml`, which you can now reference via JSF EL expressions on a page. To define a strict relationship between a page and a backing bean, see Section 4.5.3, "How to Use a Backing Bean in a JSF Page".

## 4.5.2 What Happens When You Create and Configure a Backing Bean

If you select the Generate Class If It Does Not Exist checkbox, JDeveloper creates a new Java class using the fully qualified class name set as the value of Class. The new file appears within the Application Sources node of the ViewController project in the Application Navigator as illustrated in Figure 4-9.

Figure 4-9 Backing Bean for SRDemopage.jspx in the Navigator

To edit the backing bean class, double-click the file in the Application Navigator (for example, SRDemopage.java) to open it in the source editor. If it's a new class, you would see something similar to Example 4-11.

Example 4-11 Empty Java Class Created by JDeveloper

    package oracle.srdemo.view.backing;

    public class SRDemopage {
        public SRDemopage() {
        }
    }

In `faces-config.xml`, JDeveloper adds the backing bean configuration using the `<managed-bean>` element, as shown in Example 4-12.

Example 4-12 Registering a Managed Bean in the faces-config.xml File

    <faces-config xmlns="http://java.sun.com/JSF/Configuration">
      ...

      <!-- Page backing beans typically use request scope-->
      <managed-bean>
        <managed-bean-name>backing_SRDemopage</managed-bean-name>
        <managed-bean-class>oracle.srdemo.view.backing.SRDemopage</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
      </managed-bean>
      ...
    </faces-config>

Note: For a backing bean to access the ADF Model binding layer at runtime, the backing bean must inject the ADF binding container. For information about how this is done, see Section 4.5.7, "Using ADF Data Controls and Backing Beans".

## 4.5.3 How to Use a Backing Bean in a JSF Page

Once a backing bean is defined with the relevant properties and methods, you use JSF EL expressions such as `#{someBean.someProperty}` or `#{someBean.someMethod}` to bind a UI component attribute to the appropriate property or method in the bean. For example, the following code snippets illustrate value binding expressions and method binding expressions:

    <af:inputText value="#{someBean.someProperty}"/>
    ..
    <af:inputText disabled="#{someBean.anotherProperty}"/>
    ..
    <af:commandButton action=#{someBean.someMethod}"/>
    ..
    <af:inpuText valueChangeListener="#{someBean.anotherMethod}"/>

When such expressions are encountered at runtime, JSF instantiates the bean if it does not already exist in the bean scope that was configured in `faces-config.xml`.

In addition to value and method bindings, you can also bind the UI component's instance to a bean property using the `binding` attribute:

    <af:commandButton binding="#{backing_SRDemopage.commandButton1}"

When the `binding` attribute of a UI component references a property in the bean, JSF creates an instance of the UI component from the page's `UIComponent` tree so that you can programmatically manipulate other attributes of the component. For example, you could change the color of displayed text, disable a button or field, or cause a component not to render, based on some UI logic in the backing bean.

To reiterate, you can bind a component's `value` attribute or any other attribute value to a bean property, or you can bind the component instance to a bean property. Which you choose depends on how much control you need over the component. When you bind a component attribute, the bean's associated property holds the value for the attribute, which can then be updated during the Update Model Values phase of the component's lifecycle. When you bind the component instance to a bean property, the property holds the value of the entire component instance, which means you can dynamically change any other component attribute value.

## 4.5.4 How to Use the Automatic Component Binding Feature

JDeveloper has a feature that lets you automatically bind a UI component instance on a JSF page to a backing bean property. When you turn on the Auto Bind feature for a page, for any UI component that you insert into the page, JDeveloper automatically adds property code in the page's backing bean, and binds the component's `binding` attribute to the corresponding property in the backing bean.

To turn on automatic component binding for a JSF page:

1. Open the JSF page in the visual editor. Select Design at the bottom of the editor window.

2. Choose Design > Page Properties to display the Page Properties dialog.

3. Select Component Binding.

4. Select Auto Bind.

5. Select a managed bean from the dropdown list or click New to configure a new managed bean for the page.

Note: By turning on automatic component binding in a JSF page, you are defining a strict relationship between a page and a backing bean in JDeveloper.

## 4.5.5 What Happens When You Use Automatic Component Binding in JDeveloper

If the Auto Bind feature is turned on for a JSF page, you'll see a special comment line near the end of the page:

    ...
       </f:view>
       <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_SRDemopage-->
    </jsp:root>

In `faces-config.xml`, a similar comment line is inserted at the end of the page's backing bean configuration:

    <managed-bean>
      <managed-bean-name>backing_SRDemopage</managed-bean-name>
      <managed-bean-class>oracle.srdemo.view.backing.SRDemopage</managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
      <!--oracle-jdev-comment:managed-bean-jsp-link:1SRDemopage.jspx-->
    </managed-bean>

When you turn on the Auto Bind feature for a page, JDeveloper does the following for you every time you add a UI component to the page:

- Adds a property and property accessor methods for the component in the backing bean. For example, the next code snippet shows the code added for an `inputText` and a `commandButton` component:

      ...
          private CoreInputText inputText1;
          private CoreCommandButton commandButton1;
      ...
          public void setInputText1(CoreInputText inputText1) {
              this.inputText1 = inputText1;
          }

          public CoreInputText getInputText1() {
              return inputText1;
          }

          public void setCommandButton1(CoreCommandButton commandButton1) {
              this.commandButton1 = commandButton1;
          }

          public CoreCommandButton getCommandButton1() {
              return commandButton1;
          }
      ...

- Binds the component to the corresponding bean property using an EL expression as the value for the `binding` attribute, as shown in this code snippet:

      <af:inputText binding="#{backing_SRDemopage.inputText1}"
      <af:commandButton binding="#{backing_SRDemopage.commandButton1}"

When you turn off the Auto Bind feature for a page, JDeveloper removes the special comments from the JSF page and `faces-config.xml`. The `binding` EL expressions on the page and the associated backing bean code are not deleted.

Tip: When Auto Bind is turned on and you delete a UI component from a page, JDeveloper automatically removes the corresponding property and accessor methods from the page's backing bean.

## 4.5.6 What You May Need to Know About Backing Beans and Managed Beans

Managed beans are any application JavaBeans that are registered in the JSF `faces-config.xml` file. Backing beans are managed beans that contain logic and properties for some or all UI components on a JSF page. If you place, for example, validation and event handling logic in a backing bean, then the code has programmatic access to the UI components on the page.

In this guide, the term backing bean might be used interchangeably with the term managed bean, because all backing beans are managed beans. You can, however, have a managed bean that is not a backing bean—that is, a JavaBean that does not have properties and property getter and setter methods for UI components, but the bean is configured in `faces-config.xml`. Examples of where managed beans that are not backing beans are used in the SRDemo application include beans to:

- Access authenticated user information from the container security

- Create the navigation menu system (menu tabs, menu bars, and global buttons).

- Expose String resources in a bundle via EL expressions

Managed bean properties are any properties of a bean that you would like populated with a value when the bean is instantiated. The set method for each declared property is run once the bean is constructed. To initialize a managed bean's properties with set values, use the `<managed-property>` element in `faces-config.xml`. When you configure a managed property for a managed bean, you declare the property name, its class type, and its default value, as shown in Example 4-13.

Example 4-13 Managed Bean Property Initialization Code in the faces-config.xml File

    <managed-bean>
      <managed-bean-name>tax</managed-bean-name>
      <managed-bean-class>com.jsf.databeans.TaxRateBean</managed-bean-class>
      <managed-bean-scope>application</managed-bean-scope>
      <managed-property>
        <property-name>rate</property-name>
        <property-class>java.lang.Float</property-class>
        <value>5</value>
      </managed-property>
    </managed-bean>

In Example 4-13, the `rate` property is initialized with a value of 5 (converted to a Float) when the bean is instantiated using the EL expression `#{tax.rate}`.

Managed beans and managed bean properties can be initialized as lists or maps, provided that the bean or property type is a List or Map, or implements `java.util.Map` or `java.util.List`. The default types for the values within a list or map is `java.lang.String`.

Example 4-14 shows an example of a managed bean that is a List.

Example 4-14 Managed Bean List in the faces-config.xml File

    <managed-bean>
      <managed-bean-name>options</managed-bean-name>
      <managed-bean-class>java.util.ArrayList</managed-bean-class>
      <managed-bean-scope>application</managed-bean-scope>
      <list-entries>
        <value>Text Only</value>
        <value>Text + HTML</value>
        <value>HTML Only</value>
      </list-entries>
    </managed-bean>

When the application encounters the EL expression `#{options.text}`, a List object is created and initialized with the values from the declared list-entries' values. The `managed-property` element is not declared, but the `list-entries` are child elements of the `managed-bean` element instead.

Tip: Managed beans can only refer to managed properties in beans that have the same scope or a scope with a longer lifespan. For example a `session` scope bean cannot refer to a managed property on a `request` scoped bean.

## 4.5.7 Using ADF Data Controls and Backing Beans

When you use ADF data controls (and hence ADF bindings) in your JSF page, you need to add a `bindings` managed bean property to the page's managed bean configuration so that the backing bean can work programmatically with the ADF binding container at runtime. Example 4-15 shows the `bindings` managed property in the `backing_SRDemopage` managed bean.

Example 4-15 Bindings Managed Property in the faces-config.xml File

    <faces-config xmlns="http://java.sun.com/JSF/Configuration">
      ...
      <managed-bean>
        <managed-bean-name>backing_SRDemopage</managed-bean-name>
        <managed-bean-class>oracle.srdemo.view.backing.SRDemopage</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
        <!--oracle-jdev-comment:managed-bean-jsp-link:SRDemopage.jspx-->
        <managed-property>
          <property-name>bindings</property-name>
          <value>#{bindings}</value>
        </managed-property>
      </managed-bean>
      ...
    </faces-config>

In the backing bean, add the getter and setter methods for the binding container. Example 4-16 shows part of `SRDemopage.java` that contains the relevant backing bean code for `bindings`.

Example 4-16 Bindings Getter and Setter Methods in a Backing Bean

    ...
    import oracle.binding.BindingContainer;

        private BindingContainer bindings;

        public BindingContainer getBindings() {
            return this.bindings;
        }

        public void setBindings(BindingContainer bindings) {
            this.bindings = bindings;
        }

    ...

At runtime, when the application encounters an ADF data binding EL expression that refers to the ADF binding container, such as `#{bindings.bindingObject.propertyName}`, a binding container object is instantiated, which contains specific binding objects and their properties that are available for programmatic manipulation.

For more information about ADF data binding EL expressions and ADF binding properties, see Section 5.6, "Using ADF Databinding EL Expressions".

For an overview of how JSF backing beans work with the ADF Model layer, see Chapter 1, "Introduction to Oracle ADF Applications".