struts2如何获取页面参数

最近在复习struts2的知识。在做实验的时候遇到了“要获取从页面传递到action中的参数”的问题,在Google和Baidu之后,获得解决,并总结如下,以备自己和各位朋友查阅。
[b]1. 将请求参数自动设置到字段中。可借助OGNL完成。[/b]
struts2对OGNL上下文的概念又做了进一步扩充,在struts2中,OGNL上下文通常如下所示:

|--request
|
|--application
|
context map---|--OgnlValueStack(root) [ user, action, OgnlUtil, ... ]
|
|--session
|
|--attr
|
|--parameters

[b]2.在Action里直接获取请求(Request)或会话(Session)的一些信息。[/b] 在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话 (Session)的一些信息,甚至需要直接对Servlet的HTTP请求(HttpServletRequest),响应(HttpServletResponse)操作. 我们需要在Action中取得request请求参数"username"的值:

// 获取页面传递的action参数
ActionContext actiobContext = ActionContext.getContext();
Map paramsMap = actiobContext.getParameters();
String[] attributes = (String[]) paramsMap.get("personId"); // 属性对应的是数组
......

在上面的代码中,ActionContext.getContext()方法的内部实现细节是借助于java.lang.ThreadLocal类来实现的:

static ThreadLocal actionContext = new ThreadLocal();
......
public static ActionContext getContext() {
return (ActionContext) actionContext.get();

// Don't do lazy context creation, as it requires container; the creation of which may
// precede the context creation
//if (context == null) {
// ValueStack vs = ValueStackFactory.getFactory().createValueStack();
// context = new ActionContext(vs.getContext());
// setContext(context);
//}

}

ActionContext(com.opensymphony.xwork.ActionContext)是Action执行时的上下文,上下文可以看作是一个容器(其实我们这里的容器就是一个Map而已),它存放的是Action在执行时需要用到的对象。一般情况, 我们的ActionContext都是通过:
ActionContext context = (ActionContext) actionContext.get();
来获取的。我们再来看看这里的actionContext对象的创建:
static ThreadLocal actionContext = new ActionContextThreadLocal();

ActionContextThreadLocal是实现ThreadLocal的一个内部类.ThreadLocal可以命名为"线程局部变量",它为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突.这样,我们 ActionContext里的属性只会在对应的当前请求线程中可见,从而保证它是线程安全的。
通过ActionContext取得HttpSession:
Map session = ActionContext.getContext().getSession();

[b]3. 通过com.opensymphony.webwork.ServletActionContext类[/b]
这个类直接继承了我们上面介绍的ActionContext,它提供了直接与Servlet相关对象访问的功能,它可以取得的对象有:
[list]
[*]javax.servlet.http.HttpServletRequest //
[*]javax.servlet.http.HttpServletResponse //
[*]javax.servlet.ServletContext //Servlet上下文信息
[*]javax.servlet.ServletConfig //Servlet配置对象
[*]javax.servlet.jsp.PageContext //HTTP页面上下文
[/list]从ServletActionContext里取得Servlet的相关对象:
a.取得HttpServletRequest对象

HttpServletRequest request = ServletActionContext.getRequest();

b.取得HttpServletResponse对象

HttpServletResponse response = ServletActionContext.getResponse();

c.取得ServletContext对象 略。
d.获得ServletConfig对象。

ServletConfig servletConfig = ServletActionContext.getPageContext().getServletConfig();

e.获取PageContext对象。见d。

[b]ServletActionContext 和 ActionContext联系[/b]
[i]ServletActionContext和ActionContext有着一些重复的功能,在我们的Action中,该如何去抉择呢?我们遵循的原则是:如果ActionContext能够实现我们的功能,那最好就不要使用ServletActionContext,让我们的Action尽量不要直接去访问Servlet的相关对象。在使用ActionContext时有一点要注意: 不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许没有设置,这时通过ActionContext取得的值也许是null;同样,HttpServletRequest req = ServletActionContext.getRequest()也不要放在构造函数中,也不要直接将req作为类变量给其赋值。至于原因,我想是因为前面讲到的static ThreadLocal actionContext = new ActionContextThreadLocal(),从这里我们可以看出ActionContext是线程安全的,而 ServletActionContext继承自ActionContext,所以ServletActionContext也线程安全,线程安全要求每个线程都独立进行,所以req的创建也要求独立进行,所以ServletActionContext.getRequest()这句话不要放在构造函数中,也不要直接放在类中,而应该放在每个具体的方法体中(eg:login()、queryAll()、insert()等),这样才能保证每次产生对象时独立的建立了一个req。
[/i]
[b]4.struts2的action中获得request、response、session 和 application[/b]
[i]非IoC方式[/i]
方法一:使用org.apache.struts2.ActionContext类,通过它的静态方法getContext()获取当前Action的上下文对象。以下代码处在一个action的方法中。

ActionContext ctx = ActionContext.getContext();
ctx.put("liuwei", "andy"); //request.setAttribute("liuwei", "andy");
Map session = ctx.getSession(); //session

HttpServletRequest request = (HttpServletRequest) ctx.get(StrutsStatics.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) ctx.get(StrutsStatics.HTTP_RESPONSE);
// 或者
HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);
// ServletActionContext.APPLICATION;
// ServletActionContext.SESSION;
// ServletActionContext.PAGE_CONTEXT;

// 获取页面(传递)的参数
Enumeration parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String parameterName = (String) parameterNames.nextElement();
System.out.println(" ---- " + parameterName);
}

ActionContext ctx = ActionContext.getContext();
ctx.put("liuwei", "andy"); //request.setAttribute("liuwei", "andy");
Map session = ctx.getSession(); //session

这里的session是个Map对象, 在Struts2中底层的session都被封装成了Map类型. 我们可以直接操作这个Map对象进行对session的写入和读取操作, 而不用去直接操作HttpSession对象.
方法二:使用org.apache.struts2.ServletActionContext类

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

private HttpServletRequest req;

// 这条语句放在这个位置是错误的,同样把这条语句放在构造方法中也是错误的。
// private HttpServletRequest req = ServletActionContext.getRequest();

public String login() {
req = ServletActionContext.getRequest(); //req的获得必须在具体的方法中实现
user = new User();
user.setUserId(userId);
user.setPassword(password);
if (userDAO.isLogin(user)) {
req.getSession().setAttribute("user", user);
return SUCCESS;
}
return LOGIN;
}

public String queryAll() {
req = ServletActionContext.getRequest(); //req的获得必须在具体的方法中实现
userList = userDAO.queryAll();
req.getSession().setAttribute("uList", userList);
return SUCCESS;
}
}

方法三:

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
private Map request;
private Map session;
private Map application;

public LoginAction() {
this.request = (Map) ActionContext.getContext().get("request");
this.session = ActionContext.getContext().getSession();
this.application = ActionContext.getContext().getApplication();
}

public String execute() {
this.request.put("r1", "r1");
this.session.put("s1", "s1");
this.application.put("a1", "a1");

return SUCCESS;
}
}

方法四:

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
private HttpServletRequest request;
private HttpSession session;
private ServletContext application;

public LoginAction() {
request = ServletActionContext.getRequest();
session = request.getSession();
application = session.getServletContext();
}

public String execute() {
request.setAttribute("r1", "r1");
session.setAttribute("s1", "s1");
application.setAttribute("a1", "a1");
return SUCCESS;
}
}

[i]IoC方式(即使用Struts2 Aware拦截器)[/i]
要使用IoC方式,我们首先要告诉Struts2的IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。
方法一:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

public class UserAction implements SessionAware, ServletRequestAware, ServletResponseAware, ApplicationAware {

private HttpServletRequest request;
private HttpServletResponse response;
private HttpSession session;
private Map<String, Object> application;

@Override
public void setApplication(Map<String, Object> application) {
this.application = application;
}

@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}

@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}

@Override
public void setSession(Map<String, Object> session) {
/*this.session = (HttpSession) session;*/
this.session = request.getSession();
}

public String login() {
//
// 此处使用request, response, session, application对象来获取相关的参数
//

// 业务代码
}

}


方法二:

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

public class UserAction implements ServletRequestAware, ServletResponseAware, SessionAware, ApplicationAware {

private Map<String, Object> request;
private Map<String, Object> response;
private Map<String, Object> session;
private Map<String, Object> application;

@Override
public void setApplication(Map<String, Object> application) {
this.application = application;
}

@Override
public void setServletRequest(HttpServletRequest request) {
this.request = (Map<String, Object>) request;
}

@Override
public void setServletResponse(HttpServletResponse response) {
this.response = (Map<String, Object>) response;
}

@Override
public void setSession(Map<String, Object> session) {
/*this.session = (HttpSession) session;*/
this.session = session;
}

public String login() {
//
// 此处使用request, response, session, application对象来获取相关的参数
//

// 业务代码
}

public String execute() {
//
request.put("r1", "r1");
//
session.put("s1", "s1");
//
application.put("a1", "a1");

return SUCCESS;
}

}

方法三:

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements ServletRequestAware {
private HttpServletRequest request;
private HttpSession session;
private ServletContext application;

@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
this.session = request.getSession();
this.application = session.getServletContext();
}

public String execute() {
request.setAttribute("r1", "r1");
session.setAttribute("s1", "s1");
application.setAttribute("a1", "a1");
return SUCCESS;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值