關於ActionContext.getContext()的用法心得


為了避免與Servlet API耦合在一起,方便Action類做單元測試,Struts 2對HttpServletRequest、HttpSession和ServletContext進行了封裝,構造了三個Map對象來替代這三種對象,在Action中,直接使用HttpServletRequest、HttpSession和ServletContext對應的Map對象來保存和讀取數據。

 

servletContext接口是Servlet中最大的一個接口,呈現了web應用的Servlet視圖。ServletContext實例是通過 getServletContext()方法獲得的,由於HttpServlet繼承Servlet的關系GenericServlet類和HttpServlet類同時具有該方法。 

SevletActionContext是與外面容器耦合的,但可以得到HttpSeveletSession
通過ServletActionContext.getRequest 得到當前HttpServletRequest 對象的
引用,從而直接與Web 容器交互。

 

(一)通過ActionContext來獲取request、session和application對象的LoginAction1

 

[java]  view plain  copy
 
  1. ActionContext context = ActionContext.getContext();   
  2. Map request = (Map)context.get("request");  
  3. Map session = context.getSession();  
  4. Map application = context.getApplication();  
  5. request.put("greeting", "歡迎您來到程序員之家");//在請求中放置歡迎信息。  
  6. session.put("user", user);//在session中保存user對象  
  7. application.put("counter", count);  

  

 

在JSP中讀取

 

[xhtml]  view plain  copy
 
  1. <body><h3>${sessionScope.user.username},${requestScope.greeting}。<br>本站的訪問量是:${applicationScope.counter}</h3>  
  2. </body>  

 

(二)直接使用ActionContex類的put()方法

 

ActionContext.getContext().put("greeting", "歡迎您來到http://www. sunxin.org");

然后在結果頁面中,從請求對象中取出greeting屬性,如下:

${requestScope.greeting} 或者 <%=request.getAttribute("greeting")%>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM