Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OGNL Hello World in Java

Tags:

ognl

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

like image 676
Veera Avatar asked Apr 24 '09 13:04

Veera


2 Answers

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);
like image 52
paweloque Avatar answered Oct 19 '22 03:10

paweloque


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
like image 8
raja kolluru Avatar answered Oct 19 '22 02:10

raja kolluru