Bean Scopes

Backing Beans

Sometimes it is convenient to design a bean that contains some or all component objects of a web form. Such a bean is called a backing bean for the web form.

For example, we can define a backing bean for the quiz form by adding properties for the form component:

  public class QuizFormBean {      private UIOutput scoreComponent;      private UIInput answerComponent;      // PROPERTY: scoreComponent      public UIOutput getScoreComponent() { return scoreComponent; }      public void setScoreComponent(UIOutput newValue) { scoreComponent = newValue; }      // PROPERTY: answerComponent      public UIInput getAnswerComponent() { return answerComponent; }      public void setAnswerComponent(UIInput newValue) { answerComponent = newValue; }      ...   }     

Output components belong to the UIOutput class and input components belong to the UIInput class. We discuss these classes in greater detail in "The Custom Component Developer's Toolbox" on page 360 of Chapter 9.

Why would you want such a bean? As we show in "Validating Relationships Between Multiple Components" on page 260 of Chapter 6, it is sometimes necessary for validators and event handlers to have access to the actual components on a form. Moreover, visual JSF development environments generally use backing beans (called page beans in Java Studio Creator because a bean is added for every page). These environments automatically generate the property getters and setters for all components that are dragged onto a form.

When you use a backing bean, you need to wire up the components on the form to those on the bean. You use the binding attribute for this purpose:

  <h:outputText binding="#{quizForm.scoreComponent}"/>

When the component tree for the form is built, the getScoreComponent method of the backing bean is called, but it returns null. As a result, an output component is constructed and installed into the backing bean with a call to setScoreComponent.

Backing beans have their uses, but they can also be abused. You should not mix form components and business data in the same bean. If you use backing beans for your presentation data, use a different set of beans for business objects.



Core JavaServerT Faces
Core JavaServer(TM) Faces (2nd Edition)
ISBN: 0131738860
EAN: 2147483647
Year: 2004
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net