1、与Servlet API解耦的访问方式。
a.Struts2对HttpServletRequest、HttpSession、ServletContext进行了封装,构造了三个Map对象来替代这三种对象要获取这三个Map对象,使用ActionContext类。
----->
package pro.action; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class TestAction extends ActionSupport{ public TestAction(){ } public String execute() throws Exception { ActionContext context=ActionContext.getContext(); Map request=(Map)context.get("request"); Map session=context.getSession(); Map application=context.getApplication(); return ""; } // }
b.实现RequestAware、SessionAware、ApplicationAware接口。
---->
package pro.action; import java.util.Map; import org.apache.struts2.interceptor.ApplicationAware; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; public class TestAction extends ActionSupport implements RequestAware,SessionAware,ApplicationAware{ private Map request; private Map session; private Map application; public TestAction(){} public void setRequest(Map request) { this.request=request; } public void setSession(Map session) { this.session=session; } public void setApplication(Map application) { this.application=application; } // }
2、与Servlet API耦合的访问方式。
a.要直接获取HttpServletRequest、HttpServletResponse、ServletContext这些对象,可以使用ServletActionContext类,该类是ActionContext的子类。
public static HttpServletRequest getRequest(); public static ServletContext getServletContext(); public static HttpServletResponse getResponse();
b.实现ServletRequestAware和ServletContextAware接口。
--->
package pro.action; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.util.ServletContextAware; import com.opensymphony.xwork2.ActionSupport; public class TestAction extends ActionSupport implements ServletRequestAware,ServletContextAware{ private HttpServletRequest request; private ServletContext context; public void setServletRequest(HttpServletRequest request) { this.request=request; } public void setServletContext(ServletContext context) { this.context=context; } // }