Struts2的Stack Context和ValueStack

一、提到Struts2的傳值功能時,常常會見到Stack Context和ValueStack等概念,那麼它們究竟是什麼,有什麼做用呢。 session

ValueStack(值棧):Struts2將OGNL上下文設置爲Struts2中的ActionContext(內部使用的仍然是 app

OgnlContext),並將值棧設爲OGNL的根對象。 jsp

ActionContext:一次Action調用都會建立一個ActionContext
             如:ActionContext ctx = ActionContext.getContext(); spa

Stack Object:放入stack中的對象,通常是action。 .net

Stack Context(map):stack上下文,它包含一系列對象,包括request、session、attr、application map等。 debug

二、訪問Stack Context中的對象的屬性時要使用"#對象名.屬性名"的方式,使用push標籤能夠將原來位於Stack Context中的對象放到ValueStack的棧頂。用push標籤將對象保存在ValueStack的棧頂後,只須要使用"屬性名"就能夠直接訪問了。以下面的例子: 對象

<body>
 <s:bean name="cg.struts.at.User" id="user">
   <s:param name="username" value="'cg'"/>
   <s:param name="password" value="'p123'"/>
 </s:bean>
 <table border="1" width="80%">
  <tr align="center">
   <td colspan="4">用戶信息</td>
  </tr>
  <tr align="center">
   <td>用戶名:</td>
   <td><s:property value="#user.username"/></td>
   <td>密碼:</td>
   <td><s:property value="#user.password"/></td>
  </tr>  
 </table>
 使用push標籤,簡化值的訪問
 <s:push value="#user">
  <table border="1" width="80%">
   <tr align="center">
    <td colspan="4">用戶信息</td>
   </tr>
   <tr align="center">
    <td>用戶名:</td>
    <td><s:property value="username"/></td>
    <td>密碼:</td>
    <td><s:property value="password"/></td>
   </tr>  
  </table>
 </s:push>
</body> blog

三、若是ValueStack棧頂是集合對象的話,一般能夠用iterator標籤取得位於ValueStack的頂端的集合對象,遍歷集合並輸出,遍歷完成後集合對象會被移出ValueStack。 繼承

四、在頁面輸出ValueStack和Stack Context的方法 接口

  只要在<body>標籤中加入<s:debug/>,運行時就能夠生成相應的連接,點擊該連接就能夠顯示stack相關信息。

 五、在Action中得到ActionContext、request、session、application對象的方法

   5.1 缺省狀況下,Struts2的Action類是從ActionSupport類繼承過來的,所以,能夠用下面的語句得到ActionContext對象。

   ActionContext ctx = ActionContext.getContext();

   ctx.put(("address","上海");

   5.2 若是想要在Action類中使用request對象,最簡單的方法就是在定義類的時候實現ServletRequestAware接口。而後就能夠直接在execute()方法中使用request對象,例如:

   request.setAttribute("address","上海");

   5.3 若是想要在Action類中使用session對象,就要在定義類的時候實現SessionAware接口。而後就能夠直接在execute()方法中使用session對象。例如:

   session.put("address","上海");

   5.4 當須要在Action類中使用application對象時,在定義類的時候要實現ServletContextAware接口。而後能夠直接在execute()方法中使用application對象。例如:

   application.setAttribute("address","上海");

六、在jsp中用OGNL表達式獲取不一樣範圍的值

   6.1 獲取地址後面的參數信息(即上海)(http://localhost:8080/strutslogin/login.action?address=上海)的方法以下:

   <s:property value="parameters.address"/>

   6.2 獲取上述request中信息的方法以下:

   <s:property value="#request.address"/>

   6.3 獲取上述session中信息的方法以下:

   <s:property value="#session.address"/>

   6.4 獲取上述application中信息的方法以下:

   <s:property value="#application.address"/>

   6.5 使用"#attr.參數名"的方法訪問各類變量的順序是:

   request>session>application 

 

參考連接:

http://blog.csdn.net/djx123456/article/details/6794581

相關文章
相關標籤/搜索