Struts——OGNL表达式与Struts2结合
一、OGNL表达式
OGNL:对象视图导航语言. ${user.addr.name} 这种写法就叫对象视图导航.
OGNL不仅仅可以视图导航而且还支持比EL表达式更加丰富的功能.
语法:
public void func() throws OgnlException { // 1.准备Root User rootUser = new User("jiaxin",23); // 2.准备Context Map<String,User> context = new HashMap<String,User>(); context.put("user1",new User("计震宇",22)); context.put("user2",new User("baoyan",25)); // 3.实例化OnglContext OgnlContext oc = new OgnlContext(); // 4.设置进OnglContext中 oc.setRoot(rootUser); oc.setValues(context); // ***************从root中取值*************** String name = (String) Ognl.getValue("name", oc, oc.getRoot()); Integer age = (Integer) Ognl.getValue("age", oc, oc.getRoot()); System.out.println("name:"+name+"\tage:"+age); // ***************从context中取值*************** String name1 = (String) Ognl.getValue("#user1.name", oc, oc.getRoot()); Integer age1 = (Integer) Ognl.getValue("#user1.age", oc, oc.getRoot()); System.out.println("name:"+name1+"\tage:"+age1); // ***************赋值**************** Ognl.getValue("name='计宝宝'", oc, oc.getRoot()); String name2 = (String) Ognl.getValue("name", oc, oc.getRoot()); // 先改值再取值 String name3 = (String) Ognl.getValue("#user1.name='计宝宝',#user1.name", oc, oc.getRoot()); System.out.println(name2+"\t"+name3); // *****************调普通方法**************** String name4 = (String) Ognl.getValue("setName('计震宇'),getName()", oc, oc.getRoot()); String name5 = (String) Ognl.getValue("#user2.setName='张军',#user2.getName()", oc, oc.getRoot()); System.out.println(name4+"\t"+name5); // *****************调用静态方法***************** Double PI = (Double) Ognl.getValue("@java.lang.Math@PI",oc,oc.getRoot()); Double PI2 = (Double) Ognl.getValue("@@PI",oc,oc.getRoot()); System.out.println(PI); // ******************创建List,Map对象**************** Integer len = (Integer) Ognl.getValue("{'ji','zhen','yu','bao'}.size()", oc, oc.getRoot()); String value = (String) Ognl.getValue("{'ji','zhen','yu','bao'}.get(0)", oc, oc.getRoot()); String value2 = (String) Ognl.getValue("{'ji','zhen','yu','bao'}[2]", oc, oc.getRoot()); System.out.println(len+"\t"+value+"\t"+value2); // 字典前面要加“#”,注意和取context中的内个“#”没有任何关系 Integer len2 = (Integer) Ognl.getValue("#{'k1':'v1','k2':'v2'}.size()",oc,oc.getRoot()); String value3 = (String) Ognl.getValue("#{'k1':'v1','k2':'v2'}['k1']",oc,oc.getRoot()); String value4 = (String) Ognl.getValue("#{'k1':'v1','k2':'v2'}['k2']",oc,oc.getRoot()); System.out.println(len2+"\t"+value3+"\t"+value4); }
二、OGNL表达式与Struts2结合
1、三种接收参数的原理
2、获取参数
3、查找顺序