The ognl.Ognl class contains convenience methods for evaluating OGNL expressions. You can do this in two stages, parsing/compiling 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.
Example of Expression Parsing
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.
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);
}
}
Example of Expression Compilation
 |
If we want a better performance on expression compilation, we could access the ExpressionAccessor directly. Eg. instead of
Ognl.getValue(Ognl.compileExpression(expression), context, rootObject);
Ognl.setValue(Ognl.compileExpression(expression), context, rootObject, value);
we could do
Ognl.compileExpression(expression).get(context, rootObject);
Ognl.compileExpression(expression).set(context, rootObject, value);
|
import ognl.Ognl;
import ognl.OgnlContext;
public class OgnlExpression
{
private Object expression;
public OgnlExpression(String expressionString) throws OgnlException
{
super();
expression = Ognl.compileExpression(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);
}
}