1、提到Struts2的傳值功能時,經常會見到Stack Context和Value Stack,不理解的話很容易暈掉。
- ValueStack(值棧):Struts2將OGNL上下文設置為Struts2中的ActionContext(內部使用的仍然是
OgnlContext),並將值棧設為OGNL的根對象。
- StackContext(map):stack上下文,它包含一系列對象,包括request、session、attr、applicationmap等。
2、訪問Stack Context中的對象的屬性時要使用"#對象名.屬性名"的方式,
使用push標簽可以將原來位於StackContext中的對象放到ValueStack的棧頂。
用push標簽將對象保存在ValueStack的棧頂后,只需要使用"屬性名"就可以直接訪問了。
如下面的例子:
1 <body> 2 <s:bean name="cg.struts.at.User"id="user"> 3 <s:param name="username" value="'cg'"/> 4 <s:param name="password" value="'p123'"/> 5 </s:bean> 6 <table border="1" width="80%"> 7 <tr align="center"> 8 <td colspan="4">用戶信息</td> 9 </tr> 10 <tr align="center"> 11 <td>用戶名:</td> 12 <td><s:property value="#user.username"/></td> 13 <td>密碼:</td> 14 <td><s:property value="#user.password"/></td> 15 </tr> 16 </table>
使用push標簽,簡化值的訪問
1 <s:push value="#user"> 2 <table border="1" width="80%"> 3 <tr align="center"> 4 <td colspan="4">用戶信息</td> 5 </tr> 6 <tr align="center"> 7 <td>用戶名:</td> 8 <td><s:property value="username"/></td> 9 <td>密碼:</td> 10 <td><s:property value="password"/></td> 11 </tr> 12 </table> 13 </s:push> 14 </body>
3、如果ValueStack棧頂是集合對象的話,通常可以用iterator標簽取得位於ValueStack的頂端的集合對象,
遍歷集合並輸出,遍歷完成后集合對象會被移出ValueStack。
4、在頁面輸出ValueStack和Stack Context的方法
只要在<body>標簽中加入<s:debug/>,運行時就可以生成相應的鏈接,點擊該鏈接就可以顯示stack相關信息。
6、在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