Monday, March 2, 2009

Passing Parameters via JSF

JSF allows us to cause updates to via various listeners: actionListseners, disclosureListeners, valueChangeListeners, and phaseListeners to name a few. Sometimes however, you may want to pass a parameter in to a generic method - perhaps to grab the value of an enumeration or access a users ability to view components based on Role.

One little known feature of JSF is that you may access elements of a java.util.Map. This allows us to pass in a key to a map object in one of our contexts, and the map passes back the value pair via the get(Object) method.

The notation in your jsf page would be:

value="${yourContextHandle.mapObject['mapKey']}"

where

yourContextHandle is an object in one of the contexts you use to access backing code
mapObject is a java.util.map that is available on the above object via getMapObject()
mapKey is the parameter passed in to find the object from the map.



In you backing code, generate an object that extends java.util.Map. You will need to implement quite a few methods, so I typically create a base object stub that handles the overriding of the methods beyond get(Object). In the below example, I call this MyBaseJSFMap. Then I extend this object and simply override get(Object);

But how do you get the answer you need?

Consider the following Map :


public Class MyJSFMap extends MyBaseJSFMap{

public Object get(Object o) {
return doSomething((String)o);
}

public String doSomething(String str) {
// your businessLogic here - perhaps a lookup to a database or a pull from a map.
}
}




No comments: