OGNL表达式

OGNL:对象视图导航语言.  ${user.addr.name} 这种写法就叫对象视图导航.

OGNL不仅仅可以视图导航.支持比EL表达式更加丰富的功能.

1、使用ognl准备工作

(1)导包

struts2 的包中已经包含了.所以不需要导入额外的jar包

(2)代码准备

//准备root
User user = new User("tom",19);
//准备context
Map<String,User> map = new HashMap<String,User>();
map.put("user1", new User("rose",22));
map.put("user1", new User("jack",18));
//创建ognlContext
OgnlContext oc = new OgnlContext();
oc.setRoot(user);
oc.setValues(map);

2、基本取值

//从root中取值
String name = (String) Ognl.getValue("name", oc, oc.getRoot());
System.out.println(name);
		
//从context中取值
Integer age = (Integer) Ognl.getValue("#user1.age", oc, oc.getRoot());
System.out.println(age);

3、赋值

//给root中user对象
Ognl.getValue("name='lisi'", oc, oc.getRoot());
String name = (String) Ognl.getValue("name", oc, oc.getRoot());
System.out.println(name);
		
//给context的map中的对象赋值
//ognl表达式可以写多个,但是如果要取值的话,会只取第一个
Integer age = (Integer) Ognl.getValue("#user1.age=80,#user1.age", oc, oc.getRoot());
System.out.println(age);

4、调用方法

//调用root中user对象的set、get方法
Ognl.getValue("setName('lisi')", oc, oc.getRoot());
String name = (String) Ognl.getValue("getName()", oc,oc.getRoot());
System.out.println(name);
		
//调用context中对象的方法
Integer age = (Integer) Ognl.getValue("#user1.setAge(55),#user1.getAge()", oc, oc.getRoot());
System.out.println(age);

5、调用静态方法

//调用自定义的静态方法
Object object = Ognl.getValue("@club.ityuchao.utils.TestUtils@echo('我他妈烦死了,艹')",oc,oc.getRoot());
System.out.println(object);
		
//调用jdk中的静态方法
//Double pi = (Double) Ognl.getValue("@java.lang.Math@PI", oc, oc.getRoot());
Double pi = (Double) Ognl.getValue("@@PI", oc, oc.getRoot());
System.out.println(pi);

6、创建对象(list,map)

//创建list
Integer size = (Integer) Ognl.getValue("{'lisi','jack','tom','rose'}.size()", oc, oc.getRoot());
String name1 = (String) Ognl.getValue("{'lisi','jack','tom','rose'}[2]", oc, oc.getRoot());
String name2 = (String) Ognl.getValue("{'lisi','jack','tom','rose'}.get(1)", oc, oc.getRoot());
System.out.println(size);
System.out.println(name1);
System.out.println(name2);
		
//创建map
Integer mapSize = (Integer)Ognl.getValue("#{'name':'tom','age':15}.size()", oc, oc.getRoot());
Integer mapAge = (Integer)Ognl.getValue("#{'name':'tom','age':15}['age']", oc, oc.getRoot());
String mapName = (String)Ognl.getValue("#{'name':'tom','age':15}.get('name')", oc, oc.getRoot());
System.out.println(mapSize);
System.out.println(mapAge);
System.out.println(mapName);

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值