Thursday, October 4, 2007

Accessing Managed Beans from backing bean


Sun created JSF as a competition for ASP.net. Though the idea is good, yet, the Sun stuck with the aspect of configuration. So if I need the framework to manage any of my beans automatically, then I need to specify it in faces-config.xml. Lets say my bean is named ResultBean, then I will have to put it as follows

<managed-bean>


<managed-bean-name>Result</managed-bean-name>

<managed-bean-class>org.me.ResultBean</managed-bean-class<

<managed-bean-scope>session</managed-bean-scope>

<managed-bean>

Now let us say there is another bean named ValueSetter, which is also a managed bean, wants to access the ResultBean, then the technique is classic Java technique. It goes something like as under

  • Get a reference to FacesContext which essentially is ServletContex when compared to Servlet
  • From FacesContext reference get current Application object
  • From Application object get a reference to VariableResolver object
  • Call resolveVariable method on it passing reference of the FacesContext and the name of the bean as string (not the class name)
In code it will be as follows

FacesContext context = FacesContext.getCurrentInstance();

ResultBean bean = (ResultBean) context.getApplication().getVariableResolver().resolveVariable(context, "Result");

As you have seen how many objects need to be used. Cant it be made simpler?

No comments: