1、提到Struts2的傳值功能時,經常會見到StackContext和ValueStack等概念,那麼它們到底是什麼,有什麼作用呢。
ValueStack(值棧):Struts2將OGNL上下文設置爲Struts2中的ActionContext(內部使用的仍然是
OgnlContext),並將值棧設爲OGNL的根對象。
ActionContext:一次Action調用都會創建一個ActionContext
如:ActionContext ctx = ActionContext.getContext();
Stack Object:放入stack中的對象,一般是action。
StackContext(map):stack上下文,它包含一系列對象,包括request、session、attr、applicationmap等。
2、訪問Stack Context中的對象的屬性時要使用"#對象名.屬性名"的方式,使用push標籤可以將原來位於StackContext中的對象放到ValueStack的棧頂。用push標籤將對象保存在ValueStack的棧頂後,只需要使用"屬性名"就可以直接訪問了。如下面的例子:
<body>
<s:bean name="cg.struts.at.User"id="user">
<s:paramname="username" value="'cg'"/>
<s:paramname="password" value="'p123'"/>
</s:bean>
<table border="1"width="80%">
<tralign="center">
<tdcolspan="4">用戶信息</td>
</tr>
<tralign="center">
<td>用戶名:</td>
<td><s:propertyvalue="#user.username"/></td>
<td>密碼:</td>
<td><s:propertyvalue="#user.password"/></td>
</tr>
</table>
使用push標籤,簡化值的訪問
<s:pushvalue="#user">
<tableborder="1" width="80%">
<tralign="center">
<tdcolspan="4">用戶信息</td>
</tr>
<tralign="center">
<td>用戶名:</td>
<td><s:propertyvalue="username"/></td>
<td>密碼:</td>
<td><s:propertyvalue="password"/></td>
</tr>
</table>
</s:push>
</body>
3、如果ValueStack棧頂是集合對象的話,通常可以用iterator標籤取得位於ValueStack的頂端的集合對象,遍歷集合並輸出,遍歷完成後集合對象會被移出ValueStack。
4、在頁面輸出ValueStack和Stack Context的方法
只要在<body>標籤中加入<s:debug/>,運行時就可以生成相應的鏈接,點擊該鏈接就可以顯示stack相關信息。
5、在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","上海");
6、在jsp中用OGNL表達式獲取不同範圍的值
6.1獲取地址後面的參數信息(即上海)(http://localhost:8080/strutslogin/login.action?address=上海)的方法如下:
<s:propertyvalue="parameters.address"/>
6.2獲取上述request中信息的方法如下:
<s:propertyvalue="#request.address"/>
6.3獲取上述session中信息的方法如下:
<s:propertyvalue="#session.address"/>
6.4獲取上述application中信息的方法如下:
<s:propertyvalue="#application.address"/>
6.5使用"#attr.參數名"的方法訪問各種變量的順序是:
request>session>application
參考鏈接:
http://blog.csdn.net/djx123456/article/details/6794581
http://www.blogjava.net/freeman1984/archive/2011/02/16/344447.html