How to pass information between beans in JSF 2?
I have a scenario and dont have a clear idea for this to work yet.
Here's the example scenario :
- I have a myView.xhtml file that can be displayed as a window popup or a primefaces dialog popup from 2 other container xhtml, let's say container1.xhtml and container2.xhtml (the myView.xhtml is included with something like this ?
<ui:include src="myView.xhtml" />
) - And, we also have the view-scoped beans, let's call them myViewBean, container1Bean and container2Bean
- container1Bean has the property of transactionDate, and container2Bean has a property of transDate
- myViewBean's @PostConstruct method will que开发者_JS百科ry the database based on a parameter of type date.
- On container1.xhtml, if a user clicks on a button that will popup the myView.xhtml, container1Bean should be able to provide it's transactionDate to the myViewBean, and myViewBean will be able to query based on it in the @PostConstruct method.
- On container2.xhtml, if a user clicks on a button that will popup the myView.xhtml, container2Bean should be able to provide it's transDate to the myViewBean, and myViewBean will be able to query based on it in the @PostConstruct method.
I was thinking about using @Inject Container1Bean and @Inject Container2Bean in the MyViewBean, so that inside MyViewBean, i can get the transactionDate of container1Bean or transDate of container2Bean. To decide which container bean is active is to check which one is not null.
But what if the container beans grows, there could be other container beans that make use of the MyViewBean, and the @Inject ContainerXXBean will grow in numbers inside the MyViewBean. There must be other solutions for this.
Please share ideas on how to accomplish this .. Thank you ! :-)
Thank you !
If you want to access only the contents of the other beans you can do that programmatic.
Get the current instance of the FacesContext inside from one bean. And using that context you can grab the instance of other beans.
See this illustration. As per the title of your question, you want to some information between beans. You can accomplish this by calling the other bean's public methods, which may be specifically created for this purpose. (setters-getters).
If container1Bean, myViewBean and container2Bean share some properties, why not putting them in a new bean ? (let's call it sharedBean, but I'm sure you'll find a better name adapted to your case). You could then inject sharedBean using @ManagedProperty in every dependent bean. Let's just try not to have circular references.
I'll also suggest to review your architecture. Are you sure you need all thoses beans, partitionned exactly like this? This sounds like something which will be difficult to maintain.
精彩评论