歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Struts2源碼分析獲取request response session

Struts2源碼分析獲取request response session

日期:2017/3/1 10:33:31   编辑:Linux編程

網上介紹有兩種獲取request,response和session的方法,一種是ioc方式的,通過實現SessionAware,ServletRequestAware, ServletResponseAware接口就可以

而另一種則是非ioc方式的,我這主要介紹一下非ioc方式的

1.獲取request

  1. HttpServletRequest req1 = ServletActionContext.getRequest();
  2. HttpServletRequest req2= (HttpServletRequest)ActionContext.getContext().get(ServletActionContext. HTTP_REQUEST );
  3. HttpServletRequest req4= (HttpServletRequest)ActionContext.getContext().get(StrutsStatics. HTTP_REQUEST );
  4. HttpServletRequest req5= (HttpServletRequest)ActionContext.getContext().get("com.opensymphony.xwork2.dispatcher.HttpServletRequest");

其實它們最終是走的一個方法,因為ServletActionContext 繼承了ActionContext

而且因為ServletActionContext.getRequest()的方法是調用了ActionContext裡的方法

同時ServletActionContext. HTTP_REQUEST,StrutsStatics. HTTP_REQUEST常量都是字符串com.opensymphony.xwork2.dispatcher.HttpServletRequest,

它的定義在StrutsStatics接口中,ServletActionContext也繼承了接接口,所有也能直接使用這個常量

2.同理獲取response

  1. HttpServletResponse res1 = ServletActionContext.getResponse();
  2. HttpServletResponse res2= (HttpServletResponse)ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
  3. HttpServletResponse res3= (HttpServletResponse)ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE );
  4. HttpServletResponse res4= (HttpServletResponse)ActionContext.getContext().get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");

3.獲取session 只需要先獲取到request就可以通過request.getSession()來獲取

Copyright © Linux教程網 All Rights Reserved