在开发j2ee过程中,通常我们需要访问的Servlet API是:HttpSession,HttpservletRequest,ServletContext,这三者分别对应于JSP的内置对象:session,request和application。在javabean+servlet+jsp模式中,由于servlet继承了HttpServlet,因此可以直接对HttpServletRequest和HttpServletResponse进行操作。但是Struts2的Action继承的是ActionSupport,并未直接与任何Servlet API耦合,因此需要一些其他操作才能访问Servlet API。下面我将举例说明常用的三种方式:

(1)使用ServletActionContext类访问Servlet API:

ServletActionContext中的方法都是静态方法,访问Servlet API的方法主要是以下几个:

方法 说明
static PageContext getPageContext() 用于访问web应用中的PageContext对象,对应于JSP内置对象:Page
static HttpServletRequest getRequest() 用于访问web应用中的HttpServletRequest对象
static HttpServletResponse getResponse() 用于访问web应用中的HttpServletResponse对象
if ("admin".equals(userName) && "123456".equals(password)) {			ServletActionContext.getRequest().setAttribute("success", "登录成功");			return Action.SUCCESS;		} else {			ServletActionContext.getRequest().setAttribute("error", "用户名或密码出错了");			return Action.ERROR;		}

(2)使用ActionContext类访问Servlet API

ActionContext类中包含的几个常用方法:

方法 说明
Map getApplication() 获取封装了ServletContext的Map对象
static ActionContext getContext() 静态方法,获取当前系统的ActionContext实例
Map getParameters() 获取封装了所有请求参数的Map对象
Map getSession() 获取封装了HttpSession的Map对象
ActionContext actionContext = ActionContext.getContext();				if ("admin".equals(userName) && "123456".equals(password)) {			actionContext.put("success", "登录成功");			return Action.SUCCESS;		} else {			actionContext.put("error", "用户名或密码出错了");			return Action.ERROR;		}

(3)通过实现xxxAware接口访问Servlet API

Struts2提供的接口:

方法 说明
ServletContextAware 实现该接口的Action可以直接访问Web应用的ServletContext实例
ServletRequestAware 实现该接口的Action可以直接访问用户请求对象的HttpServletRequest实例
ServletResponseAware 实现该接口的Action可以直接访问服务器响应的HttpServletResponse实例
import javax.servlet.http.HttpServletRequest;import org.apache.struts2.interceptor.ServletRequestAware;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport implements ServletRequestAware{	private static final long serialVersionUID = 1L;	private String userName;	private String password;	private HttpServletRequest request;	public void setServletRequest(HttpServletRequest request) {		this.request = request;			}	public String login() throws Exception {		if ("admin".equals(userName) && "123456".equals(password)) {			request.setAttribute("success", "登录成功");			return Action.SUCCESS;		} else {			request.setAttribute("error", "用户名或密码出错了");			return Action.ERROR;		}	}		public String getUserName() {		return userName;	}	public void setUserName(String userName) {		this.userName = userName;	}	public String getPassword() {		return password;	}	public void setPassword(String password) {		this.password = password;	}}

注:个人推荐使用第一种方式,因为使用起来简单;其次是第二种,但是有个缺陷:只能获取request,而不能获取response;不推荐使用第三种,因为不仅使用麻烦,而且与Servlet API的耦合太大