struts2中访问servlet API
Struts2中的Action沒(méi)有與任何Servlet API耦合,,但對(duì)于WEB應(yīng)用的控制器而言,不訪(fǎng)問(wèn)Servlet API幾乎是不可能的,例如需要跟蹤HTTP Session狀態(tài)等。Struts2中提供了一個(gè)ActionContext類(lèi),Struts2的Action可以通過(guò)該類(lèi)來(lái)訪(fǎng)問(wèn)Servlet API。
ActionContext類(lèi)中包含的幾個(gè)常用方法:
Object get(Object key):該方法類(lèi)似于調(diào)用HttpServletRequest的getAttribute(String name)方法。
Map getApplication:返回一個(gè)Map對(duì)象,該對(duì)象模擬了該應(yīng)用的ServletContext實(shí)例。
static ActionContext getContext():靜態(tài)方法,獲取系統(tǒng)的ActionContext實(shí)例。
Map getParameters():獲取所有的請(qǐng)求參數(shù)。類(lèi)似于調(diào)用HttpServletRequest對(duì)象的getParameterMap()方法。
Map getSession():返回一個(gè)Map對(duì)象,該Map對(duì)象模擬了HttpSession實(shí)例。
void setApplication(Map application):直接傳入一個(gè)Map實(shí)例,將該Map實(shí)例里的key-value對(duì)轉(zhuǎn)換成application的屬性名、屬性值。
void setSession(Map session):直接傳入一個(gè)Map實(shí)例,將該Map實(shí)例里的key-value對(duì)轉(zhuǎn)換成session的屬性名、屬性值。
例子:
public class TextAction implements Action{
public String execute() throws Exception{
ActionContext ctx=ActionContext.getContext(); //獲取ActionContext實(shí)例
Integet counter=(Integer)ctx.getApplication().get("counter"); ? //獲取application范圍的屬性值
return SUCCESS;
? ? ? ? ? ? ? ?}
? ? ? ?}
雖然struts2提供了ActionContext來(lái)訪(fǎng)問(wèn)Servlet API,但這種訪(fǎng)問(wèn)不是直接獲得servlet API的實(shí)例,為了在Action中訪(fǎng)問(wèn)Servlet API,struts2中還提供了以下幾個(gè)接口:
ServletContextAware:實(shí)現(xiàn)該接口的Action可以直接訪(fǎng)問(wèn)WEB應(yīng)用的ServletContext實(shí)例。
ServletRequestAware:實(shí)現(xiàn)該接口的Action可以直接訪(fǎng)問(wèn)WEB應(yīng)用的HttpServletRequest實(shí)例。
ServletResponseAware:實(shí)現(xiàn)該接口的Action可以直接訪(fǎng)問(wèn)服務(wù)器響應(yīng)的HttpServletResponse實(shí)例。
除此之外,為了能直接訪(fǎng)問(wèn)Servlet API,struts2還提供了一個(gè)ServletActionContext工具類(lèi),這個(gè)類(lèi)包含了如下幾個(gè)靜態(tài)方法:
static PageContext getPageContext():取得WEB應(yīng)用的PageContext對(duì)象。
static HttpServletRequset getRequets():取得Web應(yīng)用的HttpServletRequset對(duì)象。
static HttpServletRsponse getResponse():取得WEB應(yīng)用的HttpServletResponse對(duì)象。
static ServletContext getServletContext():取得WEB應(yīng)用的ServletContext對(duì)象。
轉(zhuǎn)載于:https://www.cnblogs.com/ChanSS/p/5492380.html
總結(jié)
以上是生活随笔為你收集整理的struts2中访问servlet API的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: angularJs中ngModel的坑
- 下一篇: 软件评价