Friday, September 12, 2008

Orthogonal OGNL


Trying to explain OGNL to a new Struts 2 developer has its challenges. Changes in expression syntax and the whole value stack proposition can be a bit daunting. Add to this the sparse documentation and you have a recipe for confusion.

I would like to clear up the confusion by offering a visual and a brief explanation.


OGNL is the Object Graph Navigation Language (see http://www.ognl.org/ for the full documentation of OGNL). Here, we will cover a few examples of OGNL features that co-exist with the framework. To review basic concepts, refer to OGNL Basics.

The framework uses a standard naming context to evaluate OGNL expressions. The top level object dealing with OGNL is a Map (usually referred as a context map or simply context). OGNL has a notion of there being a root object within the context. In OGNL expressions, the properties of the root object can be referenced without any special "marker" notation. References to other objects are marked with a pound sign (#).

The framework sets the OGNL context to be our ThreadLocal ActionContext, and the OGNL root object to the Struts 2 value stack. The value stack is a set of several objects, but to OGNL it appears to be a single object. Along with the value stack, the framework places other objects in the ActionContext, including Maps representing the application, session, and request contexts. These objects coexist in the ActionContext, alongside the value stack.

The Action instance is always pushed onto the value stack and since the stack is the OGNL root, references to Action properties can omit the # marker.

<s:property value=“customer.address"/>
But, to access other objects in the ActionContext, we must use the # notation so OGNL knows not to look in the root object, but for some other object in the ActionContext.


<s:property value="#session.mySessionPropKey"/> or
<s:property value="#session['mySessionPropKey']"/> or
<s:property value="#request['myRequestPropKey']"/>

The ActionContext is also exposed to Action classes via a static method.

ActionContext.getContext().getSession().put("mySessionPropKey", mySessionObject);

2 comments:

Anonymous said...

Thanks.

Anonymous said...

Email Marketing
very handy, thanx a lot for tis blog .. This was what I was oloking for.