struts2(基础3)

一.OGNL表达式
1.1概念
Object-Graph Navigation Language对象视图导航语言,${user.name}这种方式就是对象视图导航。支持比el表达式更强的功能。
1.2使用条件
导包:struts2jar包中包含OGNLjar包,ognl-3.0.6.jar。
准备知识
这里写图片描述

//基本语法演示
public void fun1() throws Exception{
        //准备ONGLContext
            //准备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));
        OgnlContext oc = new OgnlContext();
        //将rootUser作为root部分
        oc.setRoot(rootUser);
        //将context这个Map作为Context部分
        oc.setValues(context);
        //书写OGNL
        Ognl.getValue("", oc, oc.getRoot());
        //操作实例
        //1.取出root中user对象的name属性
        String name = (String)Ognl.getValue("user", oc, oc.getRoot());
        //2.取出context中的值
        String name = (String)Ognl.getValue("#user1.name", oc, oc.getRoot());
        //3.为取出的属性赋值
        Ognl.getValue("name='jerry'",oc, oc.getRoot());
        //输出name为jerry,"name='jerry'"这是赋值,可以和取值串联
        String name = (String)Ognl.getValue("user", oc, oc.getRoot());
        //输出name为jerry,以下为串联
        String name = (String)Ognl.getValue("#user1.name='jerry',#user1.name", oc, oc.getRoot());
        //4.调用方法
        //root下
        String name = (String)Ognl.getValue("getName()", oc, oc.getRoot());
        //context下
        String name = (String)Ognl.getValue("#user1.getName()", oc, oc.getRoot());
        //5.调用静态方法  
        String name = (String)Ognl.getValue("@静态方法完整类名@方法名 如:echo('我是静态回音方法')", oc, oc.getRoot());
        //调用jdk静态方法示例
        Double pi= (Double)Ognl.getValue("@java.lang.Math@PI", oc, oc.getRoot());//也可以@@PI
        //6.创建对象 list|map
        //list--{'',''}
        Integer size =  (Integer)Ognl.getValue("{'tom','jerry'}.size()", oc, oc.getRoot());
        //map--#{'':'','':''}
        Integer size =  (Integer)Ognl.getValue("#{'name':'tom','age':18}.size()", oc, oc.getRoot());            
}
//静态回音方法
public static Object echo(Object o){
    return o ; 
}

二.struts2和OGNL表达式结合
2.1结合原理
这里写图片描述
2.2栈原理
队列:先进先出
栈:先进后出
这里写图片描述
栈可以由list实现
这里写图片描述
先存的最后取出来
这里写图片描述
2.3值栈中两部分内容
2.3.1root中
默认情况下,栈中放置当前访问的Action对象
这里写图片描述
2.3.2Context中
Context部分就是ActionContext数据中心
这里写图片描述
这里写图片描述
2.4结合体现
2.4.1参数接收
这里写图片描述
这里写图片描述
这里写图片描述
如何获得值栈对象,值栈对象与ActionContext对象是互相引用的
这里写图片描述
2.4.2配置文件中
语法:${ognl表达式}
这里写图片描述
2.4.3扩展
扩展:request对象的getAttribute方法
这里写图片描述

猜你喜欢

转载自blog.csdn.net/a974986042/article/details/73927793