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 turn the QuizBean into a backing bean by adding properties for the component on the form:

 

 public class QuizBean {    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 will discuss these classes in greater detail in Chapter 9.

Why would you want such a bean? As we show in Chapters 6 and 7, 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. 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="#{quiz.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 use the user interface components as a repository for business data. If you use backing beans for your forms, you should still use beans for business objects.



core JavaServer Faces
Core JavaServer Faces
ISBN: 0131463055
EAN: 2147483647
Year: 2003
Pages: 121

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