1.
在Struts2開發中,除了將請求參數自動設置到Action的字段中,我們往往也需要在Action裏直接獲取請求(Request)或會話(Session)的一些信息,甚至需要直接對JavaServlet Http的請求(HttpServletRequest),響應(HttpServletResponse)操作.
我們需要在Action中取得request請求參數"username"的值:
ActionContext context = ActionContext.getContext();
Map params = context.getParameters();
String username = (String) params.get("username");
ActionContext(com.opensymphony.xwork.ActionContext)是Action執行時的上下文,上下文可以看作是一個容器(其實我們這裏的容器就是一個Map而已),它存放的是Action在執行時需要用到的對象.
一般情況, 我們的ActionContext都是通過: ActionContext context = (ActionContext) actionContext.get();來獲取的.我們再來看看這裏的actionContext對象的創建:
static ThreadLocal actionContext = new ActionContextThreadLocal();
ActionContextThreadLocal是實現ThreadLocal的一個內部類.ThreadLocal可以命名爲"線程局部變量",它爲每一個使用該變量的線程都提供一個變量值的副本,使每一個線程都可以獨立地改變自己的副本,而不會和其它線程的副本衝突.這樣,我們ActionContext裏的屬性只會在對應的當前請求線程中可見,從而保證它是線程安全的.
通過ActionContext取得HttpSession: Map session = ActionContext.getContext().getSession();
2.
ServletActionContext(com.opensymphony.webwork. ServletActionContext),這個類直接繼承了我們上面介紹的ActionContext,它提供了直接與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頁面上下文
如何從ServletActionContext裏取得Servlet的相關對象:
<1>取得HttpServletRequest對象: HttpServletRequest request = ServletActionContext. getRequest();
<2>取得HttpSession對象: HttpSession session = ServletActionContext. getRequest().getSession();