• Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing a bean to a page

 
Marwan Adel
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wandering if I can create a bean inside another bean and pass it to a new XHTML

Example:

Bean: FirstBean is binded to FirstPage.xhtml
Bean: SecondBean is binded to SecondPage.xhtml

When pressing submit button in FirstPage.xhtml it will trigger submit method in firstBean which will do some logic and then it will create secondBean instance and then passed to secondPage.xhtml to be rendered

how is this done?
 
Tim Holloway
Bartender
Posts: 18415
58
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Passing a bean to a page" implies things that aren't happening.

JSF is based on the Model/View/Controller paradigm. It consults a View Template (xhtml) to construct linkages between pre-supplied Controllers and one or more Models (backing beans and their properties).

Backing beans are constructed on-demand. If a View references a Managed Bean and it doesn't exist, then JSF will construct it and inject any Managed Properties defined for that bean into the newly-constructed bean. If those Managed Properties are themselves Managed Beans and they don't exist, then they are similarly created by JSF before being injected.

And, in case the switch in terms is confusing, you can (usually) think of a Backing Bean as being a Managed Bean, so the above rule applies to backing beans referenced in View Template EL expressions as well as those referenced in ManagedProperty EL expressions.

For all this to work the way you want, of course, you need the second bean to have a sufficiently durable scope. That is, the second bean has to be Session or Application Scope, and not Request or View scope, since you cannot inject a bean with a shorter scope into a bean with a longer scope and View scope beans are destroyed when you navigate to e new View.

All of which means that while an action method cannot take advantage of the JSF bean factory services to construct the second bean at the time the action method was invoked, an action method can employ beans that were injected as Managed Properties when the bean that contains the action method was constructed. And I have done so very often, in fact.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!