一、提到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
参考连接: