struts2中的Action在MVC模式中充当着Servlet的做用,struts2中的Action没有与Servlet耦合,那么在struts2中的Action是怎样访问ServletAPI(一般为HttpServletRequest、HttpSession和ServletContext)的呢?服务器
方法一: strtus2提供了ActionContext类来访问ServletAPI :ActionContext.getContext();来获取ActionContext。session
其get("key")--Object;该方法相似于调用HttpServletRequest的getAttribute(“name”)方法; app
getApplication()--Map;该对象相似于ServletContext实列;对象
getParameters()--Map;相似于调用HttpServletRequest的getParameterMap()方法;接口
getSession()--Map;相似于HttpSession实列;get
setApplication(Map application)--void;传入一个Map实列,将Map里面的key-value转换为application的属性值、属性名。it
setSession(Map session)--void;传入一个Map实列,将Map里面的key-value转换为Session中的属性值、属性名。io
补充一点:Servlet中的HttpServletRequest、HttpSession和ServletContext分别对应JSP内置对象中的request、session、applction。struts2
方法二: 另外一种比较直接的方法就是Action实现对应的接口,ServletConextAware实现该接口后能够直接访问Web应用中的ServletContext实列;ServletRequestAware实现该接口后能够直接访问HttpServletRequest实列;ServletResponseAware实现该接口后可直接访问HttpServletResponse实列;request
方法三:使用ServletActionContext类的ServletActionContext.getRequest()获取 HttpServletRequest;ServletActionContext.getResponse()获取HttpServletResponse;ServletActionContext.getServletContext()获取ServletContext。
注意:虽然咱们能够在Action中拿到HttpSerletResponse实列,可是没法用该实列直接生成服务器响应,Action只控制业务;如response.getWriter().println("hello world")是错误的。