我們知道struts2接受用戶端請求,在Action中進行處理後,将視圖結果傳回。struts2容器自身不依賴于web容器,不用和servlet對象中的請求(request)、響應(response)進行關聯,對于請求的參數,通過paramerInterceptor将參數封裝在Action中,然後通過調用get、set方法将參數值設定進Action之中。如果僅僅擷取參數,可能有時候滿足不了開發的需求,有時我們要擷取request或者response中的資訊,要對其進行設定、處理。
一、ActionContext
是Action執行的上下文,Action的上下文可以看作是一個容器,裡面封裝了請求(Request)、會話(Session)、Application等,這裡面的Request、Session、Application是Map類型的,往裡面封裝的是鍵值對,是以這就展現了struts2不與底層servlet Api打交道,那麼對很多web的相關對象進行封裝,這樣可以達到Action與web層解耦。
用ActionContext得到Map類型的Request、Session、Application。
例子:
擷取request:
Map request = ActionContext.getContext().get("request");
往request裡封裝資料
request.put("name", value);
在前台就可以用request.getAttribute("name");
擷取session
Map session = ActionContext.getContext().getSession();
将資料封裝到session中
session.put("name", value);
在前台頁面上用sessionScope.getAttribute("name");得到session裡面封裝的值。
得到session、request有點差別,得到request用的是get("reqeust"),得到session用的是getSession()
也可以直接對Java Servlet Http的請求(HttpServletRequest)、響應(HttpServletResponse)操作,和上面的例子有點差別,注意差別。
ActionContext ctx = ActionContext.getContext();
HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
用法就和Servlet中的request、response用法一樣
二、ServletActionContext
它繼承ActionContext,是以ServletActionContext也可以得到HttpServetRequest、HttpServletResponse,,它也提供了直接與Servlet相關對象通路的功能,它可以取得的對象有:
(1)javax.servlet.http.HttpServletRequest : HTTPservlet請求對象
(2)javax.servlet.http.HttpServletResponse : HTTPservlet相應對象
(3)javax.servlet.ServletContext : Servlet上下文資訊
(4)javax.servlet.ServletConfig : Servlet配置對象
(5)javax.servlet.jsp.PageContext : Http頁面上下文
如何擷取HttpRequest、HttpResponse
例子
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
然後就可以用request.setAttribute("name", value)方法了。
總結:不難看出,兩者之間還是存在很多共同功能,那麼我們還是根據自己的需求進行選擇,能用ActionContext對象滿足就盡量使用ActionContext,避免讓我們直接去通路Servlet對象。另外,不要在Action還沒執行個體化的時候去通過ActionContext調用方法,因為Action執行個體在ActionContext執行個體之前建立,ActionContext中一些值還沒有設定,會傳回null。