struts2 三种步骤与Servlet API 的交互详解

struts2 三种方法与Servlet API 的交互详解

struts2 提供了三种方法去实现了与Servlet API 的交互,这三种方法又可分为两种方式IOC和非IOC
方法一:与Servlet API解耦的访问方式(IoC方式)
为了避免与Servlet API耦合在一起,方便Action类做单元测试,Struts2
HttpServletRequest、HttpSession和ServletContext进行了封装,构造了三个Map对象来替代这三种对象,在Action中,直接使用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对象。

注意:如果使用上述方法,则必须在execute()方法中进行初始化,例如:


  ActionContext context = ActionContext.getContext();
   
        Map request = (Map)context.get("request");
        Map session = context.getSession();
   Map application = context.getApplication();

   
   application.put("application", "--application");
   session.put("user","--session");
   request.put("hello", "world");
    /**ActionContext 的put(*,*)和get()与request.setAttribute()和request.getAttribute()相似*/
     // 与request.setAttribute("hello", "world")类似   context.put("hello", "world");  
         // request.getAttribute("hello")类似   context.get("hello");

方法二:与Servlet API耦合的访问方式(非IoC方式)

org.apache.struts2.ServletActionContext作为辅助类(Helper Class),

HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();

//注意通过ServletActionContext不能直接取得session,要先得到request然后调用request.getSession()方法
HttpSession session = request.getSession();

方法三:ServletRequestAware,ServletResponseAware接口实现

首先实现接口,然后实现request或response对象。

在action中

 private HttpServletRequest request;

public void setServletRequest(HttpServletRequest request) {

        
this.request=request;
    }

struts2会自动调用setServletRequest(HttpServletRequest request) ,使当前的HttpServletRequest指向action中的私有变量request,随后在execute()中可直接使用;