爲了避免與Servlet API耦合在一起,方便Action類做單元測試,Struts 2對HttpServletRequest、HttpSession和ServletContext進行了封裝,構造了三個Map對象來替代這三種對象,在Action中,直接使用HttpServletRequest、HttpSession和ServletContext對應的Map對象來保存和讀取數據。
(一)通過ActionContext來獲取request、session和application對象的LoginAction1
view plaincopy to clipboardprint?
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);
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中讀取
view plaincopy to clipboardprint?
<body><h3>${sessionScope.user.username},${requestScope.greeting}。<br>本站的訪問量是:${applicationScope.counter}</h3>
</body>
<body><h3>${sessionScope.user.username},${requestScope.greeting}。<br>本站的訪問量是:${applicationScope.counter}</h3>
</body>
(二)直接使用ActionContex類的put()方法
ActionContext.getContext().put("greeting", "你好!");
然後在結果頁面中,從請求對象中取出greeting屬性,如下:
${requestScope.greeting} 或者 <%=request.getAttribute("greeting")%>
轉自:http://blog.sina.com.cn/s/blog_62c732960100um6z.html