OGNL表达式

简介

OGNL是Object-Graph Navigation Language的缩写,它是一种功能强大的表达式语言,通过它简单一致的表达式语法,可以存取对象的任意属性,调用对象的方法,遍历整个对象的结构图,实现字段类型转化等功能。它使用相同的表达式去存取对象的属性。
OGNL不仅仅可以视图导航.支持比EL表达式更加丰富的功能.

使用OGNL准备工作

导包

clipboard.png

代码准备

@Test
//准备工作
public void fun1() throws Exception{
    //准备Root
    User rootUser = new User("tom",18);
    //准备Context
    Map<String,User> context = new HashMap<String,User>();
    context.put("user1", new User("jack",18));
    context.put("user2", new User("rose",22));

    //准备ONGLContext
    OgnlContext oc = new OgnlContext();
    //将rootUser作为root部分
    oc.setRoot(rootUser);
    //将context这个Map作为Context部分
    oc.setValues(context);
    //书写OGNL
    Ognl.getValue("", oc, oc.getRoot());
}

题外:EL十一大内置对象
requestScope、responseScope、applicationScope、pageScope、pageContext、params、paramsValues、header、headerValues、cookie、initParams

语法

取值

//取出root中user对象的name属性
String name = (String) Ognl.getValue("name", oc, oc.getRoot());
Integer age = (Integer) Ognl.getValue("age", oc, oc.getRoot());
//取出context中键为user1对象的name属性
String name = (String) Ognl.getValue("#user1.name", oc, oc.getRoot());
String name2 = (String) Ognl.getValue("#user2.name", oc, oc.getRoot());
Integer age = (Integer) Ognl.getValue("#user2.age", oc, oc.getRoot());

为属性赋值

//将root中的user对象的name属性赋值
Ognl.getValue("name='jerry'", oc, oc.getRoot());
// 多个表达式可以在括号中连着写,若有多个返回值,只会取最后一个
String name2 = (String) Ognl.getValue("#user1.name='jack',#user1.name", oc, oc.getRoot());

调用方法

//调用root中user对象的setName方法
Ognl.getValue("setName('lilei')", oc, oc.getRoot());
String name = (String) Ognl.getValue("getName()", oc, oc.getRoot());
// 多个表达式可以在括号中连着写,若有多个返回值,只会取最后一个    
String name2 = (String) Ognl.getValue("#user1.setName('lucy'),#user1.getName()", oc, oc.getRoot());

调用静态方法

String name = (String) Ognl.getValue("@cn.zhli13.ognl.DemoUtils@echo('hello word!')", oc, oc.getRoot());
//Double pi = (Double) Ognl.getValue("@java.lang.Math@PI", oc, oc.getRoot());
//Math是ognl内置的静态对象,可以双@
Double pi = (Double) Ognl.getValue("@@PI", oc, oc.getRoot());

创建对象(List,Map)

//创建list对象
Integer size = (Integer) Ognl.getValue("{'tom','jerry','jack','rose'}.size()", oc, oc.getRoot());
String name = (String) Ognl.getValue("{'tom','jerry','jack','rose'}[0]", oc, oc.getRoot());
String name2 = (String) Ognl.getValue("{'tom','jerry','jack','rose'}.get(1)", oc, oc.getRoot());

//创建Map对象
Integer size2 = (Integer) Ognl.getValue("#{'name':'tom','age':18}.size()", oc, oc.getRoot());
String name3  = (String) Ognl.getValue("#{'name':'tom','age':18}['name']", oc, oc.getRoot());
Integer age  = (Integer) Ognl.getValue("#{'name':'tom','age':18}.get('age')", oc, oc.getRoot());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值