19

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).

Roman C
  • 49,761
  • 33
  • 66
  • 176
Veera
  • 32,532
  • 36
  • 98
  • 137

4 Answers4

12

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);
paweloque
  • 18,466
  • 26
  • 80
  • 136
  • Do we need that OgnlContext() object? There appears to be a variant of getValue() taking only two arguments. – djna Nov 06 '19 at 13:41
8

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 = "dimension.width == 100 && dimension.height == 200";
Object exp = Ognl.parseExpression(expression);
Boolean b = (Boolean) Ognl.getValue(exp,map);
// b would evaluate to true in this case
Andre
  • 64
  • 1
  • 9
raja kolluru
  • 602
  • 4
  • 5
2

OGNL allows you to access objects fields and methods via string expressions which becomes very useful when you have lose coupled architecture between data and it's consumers. It's using reflection under the hood but definitely speeds up development compared to a pure reflection approach.

Some one line examples

System.out.println(Ognl.getValue("x", new Point(5,5)));
System.out.println(Ognl.getValue("size", new ArrayList<Object>()));

Documentation already has a number of basic and more advanced ognl expressions.

Gorky
  • 1,393
  • 19
  • 21
  • 1
    The Documentation you reference does a great job of explaining the expression language, but it seems to assume that we know about the Ognl and OgnlContext objects and the API they provide. A new usr also needs https://commons.apache.org/proper/commons-ognl/developer-guide.html and actually your couple of examples make that much easier to understand. Thanks. – djna Nov 06 '19 at 13:49
0

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"))
Ethan Heilman
  • 16,347
  • 11
  • 61
  • 88