JSF and backing beans
After reading a number of articles on JSF, I feel I have a pretty good understanding of how JSF works. However, I cant seem to grasp how to share data between forms/views/jsp. I know I can create a backing bean and use session scope. However, what if one backing bean needs the data that is in another backing bean? Is it possible to reference beans from beans?
Also, how do I keep from tightly coupling beans to views. For example, what if a view (that edits data) can be accessed from multiple contexts. Do they all have to share the same backing bean?
Thanks,
Scott
# 1
Yes, you can get beans from other beans.
Bean backBean = (Bean)FacesContext.getCurrentInstance().getExternalContext().
getSessionMap().get("beanName");
Where object Bean is the managed bean object you are retrieving. This works if it is a session scoped bean. Use "getRequestMap" for request scoped beans. And where "beanName" is the name of the managed-bean as declared in your faces-config.xml.
You do not need to tightly couple beans and views together. Often it makes sense to have some coupling, but it is by no means necessary or always the right decision. The view is independent from the model (as it should be in MVC frameworks). So there is nothing stopping you from referring to several different beans from one JSP.
Hope this helps,
CowKing
# 6
> This applies to ADF only.
I don't know if the libraries that come with JSC are ADF, I believe no.
I'am using JSC with Sun RI 1.1_01. There's the class
com.sun.rave.web.ui.appbase.FacesBean that's in fact not part of the RI but contains the method protected Object getBean(String name).
The Creator itself generats code in all page beans and session beans for getting every managed bean which is stored in a "higher" scope, where "higher" means "application scope > session scope > request scope":
For example:
protected com...SessionBean1 getSessionBean1() {
return (com...SessionBean1) getBean("SessionBean1")
}
is created in all page beans and can't be deleted.
# 8
I get a null
whenever I retrieve a bean that has not been used yet in the request/session. Is there a method that initializes the bean and retrieves it (or do I have to roll my own like below)?
public Bean getBean()
{
Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
Bean bean = (Bean)session.get("beanName");
if(bean == null)
{
bean = new Bean();
session.put("beanName", bean);
}
return bean;
}