網上介紹有兩種獲取request,response和session的方法,一種是ioc方式的,通過實現SessionAware,ServletRequestAware, ServletResponseAware接口就可以
而另一種則是非ioc方式的,我這主要介紹一下非ioc方式的
1.獲取request
- HttpServletRequest req1 = ServletActionContext.getRequest();
- HttpServletRequest req2= (HttpServletRequest)ActionContext.getContext().get(ServletActionContext. HTTP_REQUEST );
- HttpServletRequest req4= (HttpServletRequest)ActionContext.getContext().get(StrutsStatics. HTTP_REQUEST );
- 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
- HttpServletResponse res1 = ServletActionContext.getResponse();
- HttpServletResponse res2= (HttpServletResponse)ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
- HttpServletResponse res3= (HttpServletResponse)ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE );
- HttpServletResponse res4= (HttpServletResponse)ActionContext.getContext().get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
3.獲取session 只需要先獲取到request就可以通過request.getSession()來獲取