二十、ValueStack的常用方法

二十、ValueStack的常用方法

  • void set(String key,Object value):先获取根栈栈顶的Map,如果不存在,压入一个新的Map

public String execute() throws Exception {

        ValueStack vs = ActionContext.getContext().getValueStack();

        vs.set("p1", "pp1");

        vs.set("p2", "pp2");

        vs.push(new Date());//把一个对象压入栈顶

        vs.set("p3", "pp3");

        return SUCCESS;

    }

 

  • void setValue(String ,Object):String是一个OGNL表达式。如果表达式以#开头,操作contextMap。

    如果不是,设置根栈中对象的某个属性,从顶到尾依次搜寻。

public String execute() throws Exception {

        ValueStack vs = ActionContext.getContext().getValueStack();

        vs.push(new Date());

        // 把一个对象压入栈顶

        vs.push(new Date());

        // 从栈顶搜索对象的属性,并设置month的值

        vs.setValue("[1].month", 10);

        vs.setValue("#month", 10);

 

        // 从栈顶开始搜索所有对象的shit属性:setShit,都没有报错

        vs.setValue("shit", "hehe");

 

        return SUCCESS;

    }

 

  • Object findValue(String expr):参数是一个OGNL表达式。如果以#开头,

    从contextMap中找key值所对应的对象。如果不是以#开头,搜索根栈中对象的属性(getter方法)

特别注意:如果编写的表达式不是以#开头,先搜索根栈对象的所有属性,

如果没有找到,会把它当做key值到contextMap中找。

public String execute() throws Exception {

        ValueStack vs = ActionContext.getContext().getValueStack();

        vs.push(new Date());

        // 把一个对象压入栈顶

        vs.push(new Date());

        // 从栈顶搜索对象的属性,并设置month的值

        vs.setValue("[1].month", 10);

        vs.setValue("#month", 10);

 

        // 从栈顶开始搜索所有对象的shit属性:setShit,都没有报错

        //vs.setValue("shit", "hehe");

 

        return SUCCESS;

    }

 

Jsp页面代码:

<%

        ValueStack vs = ActionContext.getContext().getValueStack();

        Object obj1 = vs.findValue("month");

        System.out.println(obj1);

        //打印第二个对象的month属性

        obj1 = vs.findValue("[1].month");

        System.out.println(obj1);

        obj1 = vs.findValue("request");//不建议

        System.out.println(obj1);

        obj1 = vs.findValue("#request");

        System.out.println(obj1);

    %>

 

  • String findString(String expr):把OGNL表达式获取的对象转换成String

public String execute() throws Exception {

        ValueStack vs = ActionContext.getContext().getValueStack();

        vs.setValue("#now", new Date());

        String s1 = vs.findString("#now");// 有没有错

        // 没有错的,显示的时候,Struts2框架还有个类型转换器的存在。已经把Date类型转换成了String

        System.out.println(s1);

        

        vs.setValue("#p1", "new Person()");

        //此版本会自动调用toString方法

        String s2 = vs.findString("#p1");

        System.out.println(s2);

 

        return SUCCESS;

    }

 

原文地址:https://www.cnblogs.com/Prozhu/p/5886516.html