在Struts2中获取Web页面元素request、response、session、application有两种形式,一种是Map类型,另一种是真实类型HttpServletRequest, HttpSession, ServletContext的引用。一共有四种获取方法 ,如下所示:
第一种:依赖于容器,Map类型:
private Map request; private Map session; private Map application; public LoginAction1(){ request = (Map)ActionContext.getContext().get("request"); session = ActionContext.getContext().getSession(); application = ActionContext.getContext().getApplication(); }
第二种:使用IOC,Map类型,推荐使用的一种方式:
public class LoginAction2 extends ActionSupport implements RequestAware, SessionAware, ApplicationAware { private Map<String, Object> request; private Map<String, Object> session; private Map<String, Object> application; public void setRequest(Map<String, Object> request) { this.request = request; } public void setSession(Map<String, Object> session) { this.session = session; } public void setApplication(Map<String, Object> application) { this.application = application; }
第三种:依赖于容器,原始类型:
private HttpServletRequest request; private HttpSession session; private ServletContext application; public LoginAction3(){ request = ServletActionContext.getRequest(); session = request.getSession(); application = session.getServletContext(); }
第四种:IOC,原始类型
public class LoginAction4 extends ActionSupport implements ServletRequestAware { private HttpServletRequest request; private HttpSession session; private ServletContext application; public void setServletRequest(HttpServletRequest request) { this.request = request; this.session = this.request.getSession(); this.application = this.session.getServletContext(); }