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