Struts2中使用ActionContext传递参数
(1)使用背景
在Struts中,一般都是通过View页面通过Post或Get方式像Action提交请求,Action返回逻辑视图,struts再根据struts.xml中的逻辑视图名跳转到物理视图。
当我们需要从Action向物理视图传参数时,可以使用ActionContext来传递参数。
(2)使用示例
Action中的代码如下所示:
package blog.wlb.net.oschina.my;import com.opensymphony.xwork2.ActionContext;public class UserAction { public String test(){ ActionContext.getContext().put("username", "zhangsan"); ActionContext.getContext().put("password", "123456"); ActionContext.getContext().put("age", 26); return "success"; }}
本示例中,通过Actioncontext向View中传递了3个参数分别是username、password、age。
Struts.xml代码如下所示:
/success.jsp
success.jsp代码如下所示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>参数接收页面 UserName:${#username} Password:${#password} Age:${#age}
最终结果如下图所示:
二、知识扩展
(1)访问ActionContext当中的属性方法
访问ActionContext当中属性的方法为:{#属性名}
(2)Struts2中对ActionContext访问的容错性
如果使用{属性名}这种不加“#”的方式也是可以访问的,但是这种是利用了Struts2中的容错性,强烈建议不要这样写。