关于ActionContext.getContext()的用法心得

来源:互联网 发布:台服 mac 魔兽世界 编辑:程序博客网 时间:2024/05/17 08:19

这是我在别的博客里看到的,感觉不错,收藏下来


为了避免与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  

        

  1. request.put("greeting""欢迎您来到程序员之家");//在请求中放置欢迎信息。  
  2. session.put("user", user);//在session中保存user对象  
  3. application.put("counter", count);  



  4.                   
  5. 使用Jsp 读取
    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")%>

0 0