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代码如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="user" class="blog.wlb.net.oschina.my.UserAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
success.jsp代码如下所示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>参数接收页面</title>
</head>
<body>
UserName:${#username}<br/>
Password:${#password}<br/>
Age:${#age}<br/>
</body>
</html>
最终结果如下图所示:
二、知识扩展
(1)访问ActionContext当中的属性方法
访问ActionContext当中属性的方法为:{#属性名}
(2)Struts2中对ActionContext访问的容错性
如果使用{属性名}这种不加“#”的方式也是可以访问的,但是这种是利用了Struts2中的容错性,强烈建议不要这样写。