一.非Ioc方式
这种方式主要是利用了com.opensymphony.xwork2.ActionContext类以及org.apache.struts2.ServletActionContext类,具体的方法如下所示。
获得request对象:
1).HttpServletRequest request = ServletActionContext.getRequest ();2).ActionContext ct= ActionContext.getContext();HttpServletRequest request=(HttpServletRequest)ct.get(ServletActionContext.HTTP_REQUEST);
获得response对象:
1).HttpServletResponse response= ServletActionContext.getResponse ();2).ActionContext ct= ActionContext.getContext(); HttpServletResponse response=(HttpServletResponse )ct.get(ServletActionContext.HTTP_RESPONSE);
二:IOC方式
Action在继承ActionSupport的同时还要实现ServletRequestAware和ServletResponseAware接口
-
- package com.iterator.action;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import org.apache.struts2.interceptor.ServletResponseAware;
- import com.opensymphony.xwork2.ActionSupport;
- public class Struts2GetServletRequestAction extends ActionSupport implements
- ServletRequestAware, ServletResponseAware {
- private static final long serialVersionUID = 1L;
- private HttpServletRequest request;
- private HttpServletResponse response;
- public void setServletRequest(HttpServletRequest request) {
- this.request=request;
- }
- public void setServletResponse(HttpServletResponse response) {
- this.response=response;
- }
- @Override
- public String execute() throws Exception {
- System.out.println("requestUsername=" + request.getParameter("username") + ",requestPassword=" + request.getParameter("password"));
- return SUCCESS;
- }
- }