Struts2请求动作的数据操作---ValueStack 之一

1.利用ValueStack存数据

a、如何获取ValueStack

public class Struts2Demo2 extends ActionSupport{

    public String demo2(){
        //获取ValueStack对象的引用
        //方式1.在页面展开s:debug的标签,找到对象所存的位置。
        //发现在requestMap中,所以可以使用requestMap.get(key)获取
        //拿到actionContext对象
        ActionContext context = ActionContext.getContext();
        //使用ActionContext获取requestMap
        Map<String,Object> requestAttributes = (Map<String, Object>) context.get("request");
        //根据ValueStack的key获取该对象
        ValueStack vs1 = (ValueStack) requestAttributes.get("struts.valueStack");
        System.out.println(vs1);

        //方式2.使用request的getAttribute获取
        ServletRequest request = ServletActionContext.getRequest();
        //使用request对象的getAttribute获取ValueStack对象
        ValueStack vs2 = (ValueStack) request.getAttribute("struts.valueStack");
        System.out.println(vs2);

        //方式 3.使用ActionContext的方法直接获得
        ValueStack vs3 = context.getValueStack();
        System.out.println(vs3);

        //上面这三种方式指向的是同一内存空间
        System.out.println("vs1 HashCode is " + vs1.hashCode());
        System.out.println("vs2 HashCode is " + vs2.hashCode());
        System.out.println("vs3 HashCode is " + vs3.hashCode());


        return "success";
    }

控制台输出结果

com.opensymphony.xwork2.ognl.OgnlValueStack@15b2208
com.opensymphony.xwork2.ognl.OgnlValueStack@15b2208
com.opensymphony.xwork2.ognl.OgnlValueStack@15b2208
vs1 HashCode is 22749704
vs2 HashCode is 22749704
vs3 HashCode is 22749704

b、ValueStack中的getRoot()方法:
这里写图片描述
c、CompoundRoot是什么:
这里写图片描述
d、栈操作:

       //栈操作
        ValueStack vs = context.getValueStack();
        Student student = new Student("泰斯特",28);
        //把Students压入栈中
        vs.push(student);

2.取数据:用Struts2的标签(OGNL表达式)在JSP上(用的最多)

使用OGNL表达式来取,struts2的OGNL表达式必须写在struts2标签中。
取contextMap里面ValueStack中对象的属性:直接写属性名

<body> 
      <s:property value="name"/>------<s:property value="age"/>
      <s:debug></s:debug> 
 </body>

注:name和age不是字符串而是OGNL表达式
结果:
这里写图片描述
如果遇有对象属性重名,可以通过OGNL表达式,选择查找的起始位置
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
特殊说明:当s:property不给定value属性时,默认取栈顶对象。
这里写图片描述

OGNL的使用总结:
1.取根中对象的属性,不使用#。
2.取contextMap中key的值,要使用#。

猜你喜欢

转载自blog.csdn.net/lucky_zfx/article/details/79123654