这是我在别的博客里看到的,感觉不错,收藏下来
为了避免与servlet Api耦合在一起,Struts2对HttpServletRequest、HttpSession和ServletContext 三个对象进行了封装。使用三个Map对应这三个对象。在Action中直接使用这三个对象对应的Map,来保存到和读取出三个对象中的数据。。
(1)使用ActionContext 获得三个request、session、application三个对象的LoginAction1
ActionContext context = ActionContext.getContext();
Map request = context.get("request"); // 获得HttpServletRequest的对象
Map session = context.getSession(); //获得HttpSession 对象
Map Application = context.getApplication(); // 获得ServletContext 对象
// 使用三个对应的Map
- 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")%>