Struts 2提供了多种方式来访问上述的三种对象,归结起来,可以划分为两大类:与Servlet API解耦的访问方式和与Servlet API耦合的访问方式。
与Servlet API解耦的访问方式
为了避免与Servlet API耦合在一起,方便Action类做单元测试,Struts 2对HttpServletRequest、HttpSession和ServletContext进行了封装,构造了三个Map对象来替代这三种对象,在Action中,直接使用HttpServletRequest、HttpSession和ServletContext对应的Map对象来保存和读取数据。
要获取这三个Map对象,可以使用com.opensymphony.xwork2.ActionContext类,ActionContext是action执行的上下文,在ActionContext中保存了action 执行所需的一组对象,包括parameters、request、session、application和locale等。ActionContext 类定义了如下方法,用于获取HttpServletRequest、HttpSession和ServletContext对应的Map对象。
public Object get(Object key)
ActionContext类没有提供类似getRequest()这样的方法来获取封装了HttpServletRequest的Map对象。要得到请求Map对象,你需要为get()方法传递参数“request”。
public Map getSession()
获取封装了HttpSession的Map对象。
public Map getApplication()
获取封装了ServletContext的Map对象。
ActionContext context = ActionContext.getContext(); Map request = (Map)context.get("request"); Map session = context.getSession(); Map application = context.getApplication();
与Servlet API耦合的访问方式
要获得上述对象,关键Struts 2.0中com.opensymphony.xwork2.ActionContext类。通过它的静态方法getContext()获取当前Action的上下文对象。另外,org.apache.struts2.ServletActionContext作为辅助类,可以帮助您快捷地获得这几个对象。
HttpServletRequest request = ServletActionContext.getRequest(); ActionContext ct= ActionContext.getContext(); HttpServletRequest request=HttpServletRequest)ct.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = ServletActionContext.getResponse(); HttpSession session = request.getSession();