Table of Contents
OGNL as a language allows for the navigation of Java objects through a concise syntax that allows for specifying, where possible, symmetrically settable and gettable values. The language specifies a syntax that attempts to provide as high a level of abstraction as possible for navigating object graphs; this usually means specifying paths through and to JavaBeans properties, collection indices, etc. rather than directly accessing property getters and setters (collectively know as accessors).
The normal usage of OGNL is to embed the language inside of other constructs to provide a place for flexible binding of values from one place to another. An example of this is a web application where values need to be bound from a model of some sort to data transfer objects that are operated on by a view. Another example is an XML configuration file wherein values are generated via expressions which are then bound to configured objects.
The ognl.Ognl
class contains convenience methods for evaluating OGNL expressions. You can do this in two stages, parsing an expression into an internal form and then using that internal form
to either set or get the value of a property; or you can do it in a single stage, and get or set a property using the String form of the expression directly. It is more efficient to pre-compile the expression to it's parsed form,
however, and this is the recommended usage.
OGNL expressions can be evaluated without any external context, or they can be provided with an execution environment that sets up custom extensions to modify the way that expressions are evaluated.
The following example illustrates how to encapsulate the parsing of an OGNL expression within an object so that execution will be more efficient. The class then takes an OgnlContext
and a root object to
evaluate against.
Example 1.1. Expression Class
import ognl.Ognl; import ognl.OgnlContext; public class OgnlExpression { private Object expression; public OgnlExpression(String expressionString) throws OgnlException { super(); expression = Ognl.parseExpression(expressionString); } public Object getExpression() { return expression; } public Object getValue(OgnlContext context, Object rootObject) throws OgnlException { return Ognl.getValue(getExpression(), context, rootObject); } public void setValue(OgnlContext context, Object rootObject, Object value) throws OgnlException { Ognl.setValue(getExpression(), context, rootObject, value); } }