Nir Levy
Nir Levy

Reputation: 4740

JSF multiple backing beans on one page

I have done some reading and playing and I still have some questions I was hoping someone might answer:

So, can I use two or more backing beans in a single JSF page?

<h:intputText value="#{myFirstBean.firstProperty}" />
<h:intputText value="#{mySecondBean.secondProperty}" />

If I can, why should I not do it? (I assume I should not, because nobody does)

If I cannot, why?

Also, I read somewhere something like "on page load the framework would instantiate the backing bean, and populate it if it's a postback". They say the backing bean but I cannot understand how the framework know which backing bean to instantiate.

Upvotes: 9

Views: 16579

Answers (3)

Tuukka Mustonen
Tuukka Mustonen

Reputation: 4831

Other questions have already been answered. However:

Also, I read somewhere something like "on page load the framework would instantiate the backing bean, and populate it if it's a postback". They say the backing bean but I cannot understand how the framework know which backing bean to instantiate.

Beans are resolved by their name. For example, #{myFirstBean.firstProperty} looks for bean named 'myFirstBean' (an instance of class MyFirstBean). You can adjust the name as in:

@ManagedBean(name = "foo")
public class SomeClass { ... }

Then you could reference that via #{foo.firstProperty}.

Upvotes: 3

cetnar
cetnar

Reputation: 9415

Let's clarify some terms:

  • managed beans are JavaBeans components that you can configure using the managed bean facility see
  • backing beans, are a JavaServer Faces managed beans that are associated with the UI components used in a particular page see

So, yes you can use two or more managed beans in a single JSF page, but splitting UI components bindings, listeners, logic etc. that are related to one page into two or more backing beans is still posible but very undesirable and might cause you lot of problems and bad code.

Upvotes: 6

Bozho
Bozho

Reputation: 597076

Why not? It's a perfectly legitimate thing to do. Generally, a page should be associated with one bean (for the sake of good structure), but if you want, for example, to show the current time on each page, you are free to reference your timeBean.currentTime, among other things (of course, using include/templating is preferable here).

Upvotes: 4

Related Questions