在
Web
應(yīng)用程序開發(fā)中,除了將請求參數(shù)自動設(shè)置到
Action
的字段中,我們往往也需要在
Action
里直接獲取請求
(Request)
或會話(
Session
)的一些信息
,
甚至需要直接對
JavaServlet Http
的請求(
HttpServletRequest
)、響應(yīng)
(HttpServletResponse)
操作。
我們需要在
Action
中取得
request
請求參數(shù)“
username
”的值:
ActionContext context = ActionContext.getContext();
Map params = context.getParameters();
String username = (String) params.get(“username”);
ActionContext
(
com.opensymphony.xwork.ActionContext
)是
Action
執(zhí)行時的上下文,上下文可以看作是一個容器(其實我們這里的容器就是一個
Map
而已),它存放放的是
Action
在執(zhí)行時需要用到的對象
一般情況,我們的
ActionContext
都是通過:
ActionContext context = (ActionContext) actionContext.get();
來獲取的。我們再來看看這里的
actionContext
對象的創(chuàng)建:
static ThreadLocal actionContext = new ActionContextThreadLocal();
,
ActionContextThreadLocal
是實現(xiàn)
ThreadLocal
的一個內(nèi)部類。
ThreadLocal
可以命名為“線程局部變量”,它為每一個使用該變量的線程都提供一個變量值的副本,使每一個線程都可以獨立地改變自己的副本,而不會和其它線程的副本沖突。這樣,我們
ActionContext
里的屬性只會在對應(yīng)的當(dāng)前請求線程中可見,從而保證它是線程安全的。
下面我們看看怎么通過
ActionContext
取得我們的
HttpSession
:
Map session = ActionContext.getContext().getSession()
;
ServletActionContext
(
com.opensymphony.webwork. ServletActionContext
),這個類直接繼承了我們上面介紹的
ActionContext
,它提供了直接與
JavaServlet
相關(guān)對象訪問的功能,它可以取得的對象有:
1、
javax.servlet.http.HttpServletRequest
:
HTTPservlet
請求對象
2、
javax.servlet.http.HttpServletResponse;
:
HTTPservlet
相應(yīng)對象
3、
javax.servlet.ServletContext
:
Servlet
上下文信息
4、
javax.servlet.ServletConfig
:
Servlet
配置對象
5、
javax.servlet.jsp.PageContext
:
Http
頁面上下文
下面我們看看幾個簡單的例子,讓我們了解如何從
ServletActionContext
里取得
JavaServlet
的相關(guān)對象:
1、
取得
HttpServletRequest
對象:
HttpServletRequest request = ServletActionContext. getRequest();
2、
取得
HttpSession
對象:
HttpSession session = ServletActionContext. getRequest().getSession();
ServletActionContext
和
ActionContext
有著一些重復(fù)的功能,在我們的
Action
中,該如何去抉擇呢?我們遵循的原則是:如果
ActionContext
能夠?qū)崿F(xiàn)我們的功能,那最好就不要使用
ServletActionContext
,讓我們的
Action
盡量不要直接去訪問
JavaServlet
的相關(guān)對象。在使用
ActionContext
時有一點要注意:不要在
Action
的構(gòu)造函數(shù)里使用
ActionContext.getContext()
,因為這個時候
ActionContext
里的一些值也許沒有設(shè)置,這時通過
ActionContext
取得的值也許是
null
。
posted on 2006-12-13 19:44
周銳 閱讀(664)
評論(0) 編輯 收藏 所屬分類:
Webwork