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