tags:

views:

1092

answers:

3

I need to use OGNL for reading some properties from Java object. OGNL is completely new thing to me. The documentation available for OGNL is OGNL's website is really confusing to me.

So anyone can provide a simple HelloWorld example for using OGNL (or any link to a tutorial is also helpful).

+3  A: 

Try this:

    Dimension d = new Dimension(2,2);

    String expressionString = "width";
    Object expr = Ognl.parseExpression(expressionString);

    OgnlContext ctx = new OgnlContext();
    Object value = Ognl.getValue(expr, ctx, d);

    System.out.println("Value: " + value);
lewap
A: 

Here is an example helloworld for jython (python that compiles to java).

from ognl import Ognl, OgnlContext
from java.lang import String

exp = Ognl.parseExpression("substring(2, 5)")

print Ognl.getValue(exp, OgnlContext(), String("abcdefghj"))
e5
A: 

If the intention is only to read properties from an object then PropertyUtils.getProperty (from commons-beanutils) may suffice. However, if the intention is to evaluate conditionals and such, then Ognl may benefit.

Here is the same Dimension example with a boolean:

Dimension d = new Dimension();
d.setSize(100,200) ;// width and height

Map<String,Object> map = new HashMap<String,Object)();
map.put("dimension", d);

String expression = "d.width == 100 && d.height == 200";
Object exp = Ognl.parseExpression(expression);
Boolean b = (Boolean) Ognl.getValue(exp,map);
// b would evaluate to true in this case
raja kolluru