為了避免與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
- ActionContext context = ActionContext.getContext();
- Map request = (Map)context.get("request");
- Map session = context.getSession();
- Map application = context.getApplication();
- request.put("greeting", "歡迎您來到程序員之家");//在請求中放置歡迎信息。
- session.put("user", user);//在session中保存user對象
- application.put("counter", count);
在JSP中讀取
- <body><h3>${sessionScope.user.username},${requestScope.greeting}。<br>本站的訪問量是:${applicationScope.counter}</h3>
- </body>
(二)直接使用ActionContex類的put()方法
ActionContext.getContext().put("greeting", "歡迎您來到http://www. sunxin.org");
然后在結果頁面中,從請求對象中取出greeting屬性,如下:
${requestScope.greeting} 或者 <%=request.getAttribute("greeting")%>