Sunday, October 11, 2009

Accessing JSF Backing Beans From Another JSF Backing Bean

Here is a simple piece of code that lets you access a backing bean from another backing bean. i.e. in the java code of a backing bean in JSF 1.1. A backing bean that exists in the session cannot be directly accessed from the map containing the other session objects. So here is a small workaround.

FacesContext context=FacesContext.getCurrentInstance();
Object obj=context.getApplication().createValueBinding("#{"+ "visit" + "}").getValue(context);

Cast the object to the appropriate backing bean type. That solves the problem.
Hope it helps.

Happy Programming :)

Signing Off
Ryan

Accessing the session from JSF backing beans in JSF 1.1

One of the problems that I faced while developing applications using JSF was the issue of how to access the map containing the session objects in JSF backing beans. I wanted to access the current users session after he makes an attempt to log in and then store a User object in the session on successful login after retrieving his relevant details from the backend.

After a bit of searching i came across a simple and elegant solution. Here is a small excerpt from code.

FacesContext context=FacesContext.getCurrentInstance();
Map session =context.getExternalContext().getSessionMap();

This gets me a handle of the session map. And thats pretty much there is to it.
I hope it helps you if you are struggling with the same issue.

Happy Programming
:)

Signing Off
Ryan Sukale