為了避免與Servlet API耦合在一起,方便Action類做單元測試,Struts 2對HttpServletRequest、HttpSession和ServletContext進行了封裝,構造了三個Map物件來替代這三種物件,在Action中,直接使用HttpServletRequest、HttpSession和ServletContext對應的Map物件來儲存和讀取資料。
(一)通過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://sun.org");
然後在結果頁面中,從請求物件中取出greeting屬性,如下:
${requestScope.greeting} 或者 <%=request.getAttribute("greeting")%>