struts2 ValueStack的set方法与setValue方法的区别

struts2中 ValueStack的set方法与setValue方法的区别呢?

示例代码:

  1. ActionContext.getContext().getValueStack().setValue("myname22", "ttt");  
  2.  区别:

    (1)setValue 方法必须要求有该属性的setter方法,否则会报错:

    Error setting expression'myname22' with value 'ttt' - [unknown location]

    set方法设置的属性与该action没有任何关系,所以就算action中没有该属性的setter方法,调用

    Java代码  收藏代码
    1. ActionContext.getContext().getValueStack().set("myname22", "ttt");
  3. (2)setValue方法设置的是action的属性(action中有属性myname22),在value stack 中对应的是action的属性;

     

    而set方法设置的属性会放在一个hashmap中,与当前的action没有任何瓜葛,但是两者都在value stack中,set方法设置的属性可以通过 <s:property value="myname22"  />来取值。

     

     

     

    共同点:

     

    (1)setValue和set方法设置的属性可以通过

     

     

    Java代码  收藏代码
    1. String myname2=(String)ServletActionContext.getContext().getValueStack().findValue("myname22");  

     

     

    来取值;

     

     

    (2)在result指向的JSP页面中都可以通过 <s:property value="myname22"  />来取值(setValue方法设置的属性必须要有对应的getter方法)。

     

    action代码:

    Java代码  收藏代码
    1. package example;  
    2.   
    3. import org.apache.struts2.ServletActionContext;  
    4.   
    5. import com.opensymphony.xwork2.ActionContext;  
    6. import com.opensymphony.xwork2.ActionSupport;  
    7.   
    8. public class GetValueAction extends ActionSupport {  
    9.     private static final long serialVersionUID = 4865100826143278474L;  
    10.     private String myname=null;  
    11. //  private String myname22;  
    12.     @Override  
    13.     public String execute() throws Exception {  
    14.         ActionContext.getContext().getValueStack().set("myname22", "ttt");  
    15.         String myname2=(String)ServletActionContext.getContext().getValueStack().findValue("myname22");  
    16. //      System.out.println("myname2: "+this.myname);  
    17.         return super.execute();  
    18.     }  
    19.   
    20.     public String getMyname() {  
    21.         return myname;  
    22.     }  
    23.   
    24.     public void setMyname(String myname) {  
    25.         this.myname = myname;  
    26.     }  
    27.   
    28. //  public String getMyname22() {  
    29. //      return myname22;  
    30. //  }  
    31. //  
    32. //  public void setMyname22(String myname22) {  
    33. //      System.out.println("abc:"+myname22);  
    34. //      this.myname22 = myname22;  
    35. //  }  
    36.       
    37. //  public String getMyname22() {  
    38. //      return myname22;  
    39. //  }  
    40.       
    41.       
    42. }  

     总结:set方法和setValue方法设置的属性都可以通过<s:property value="myname22"  />取值。

posted on 2016-05-26 11:46  肥羊lafe  阅读(301)  评论(0编辑  收藏  举报

导航