Struts2中访问三种对象有多种方式大致可分为两类 与servlet API解耦的访问方式 和与servlet API耦合的访问方式
<wbr><strong>一 、与servlet API解耦的访问方式</strong></wbr>
<wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr><wbr>为了方便对Action类做单元测试,Struts2对HttpServletRequest,HttpSession和<wbr>ServletContext<wbr>进 <wbr>行了封装,构造三个Map来代替,在Action中用这些Map来存取对象<br><wbr><br><wbr><strong>ActionContext</strong>是action这行的上下文.<br><wbr>使用<strong><strong>ActionContext</strong></strong>对象来获取三种对象</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
ActionContext act=ActionContext.getContext(); Map request=(Map)act.get("request"); Map session=(Map)act.getSession(); Map applicant=(Map)act.getApplication(); ((Map)act.get("request")).put("str", "request"); ((Map)act.get("session")).put("str", "session"); ((Map)act.get("application")).put("str", "application");
除上述方法外,还可以实现
<wbr><strong>org.apache.struts2.interceptor.ApplicationAware;<br><wbr>org.apache.struts2.interceptor.RequestAware;<br><wbr>org.apache.struts2.interceptor.SessionAware;</wbr></wbr></strong></wbr>
接口分别实现applicantion,request,session对象;
private Map request;//变量名称必须为request,下面的方法是从接口中实现的。 public void setRequest(Map<String, Object> request) { this.request=request; } private Map session;//变量名称必须为session,下面的方法是从接口中实现的。 public void setSession(Map<String, Object> session) { this.session=session; } private Map applicantion;;//变量名称必须为applicantion,下面的方法是从接口中实现的 public void setApplication(Map<String, Object> applicantion) { this.applicantion=applicantion; }
<wbr></wbr>
与servlet API耦合的访问方式
<wbr></wbr>
需要使用ServeltActionContext,这个是ActionContext的子类提供了访问servletAPI的静态方法
HttpServletRequest request=ServletActionContext.getRequest(); HttpSession session=request.getSession(); ServletContext applicantion=ServletActionContext.getServletContext(); HttpServletResponse response=ServletActionContext.getResponse();
<wbr>除了上述方法外还可以通过实现接口来获取三个对象:</wbr>
实现接口
org.apache.struts2.interceptor.ServletRequestAware;
org.apache.struts2.interceptor.ServletResponseAware;
<wbr></wbr>
分别获取对象request,response
private HttpServletRequest request; public void setServletRequest(HttpServletRequest request) { this.request=request; } private HttpServletResponse response; public void setServletResponse(HttpServletResponse response) { this.response=response; }
或实现org.apache.struts2.util.ServletContextAware;获取ServletContext
public void setServletContext(ServletContext context) { // TODO Auto-generated method stub }