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

文章来源:http://blog.csdn.net/smcfy/article/details/5693481

 这个也是我在另外一位仁兄的博客中看到的,原博客的有点长,我把它精简了一下,算看起来比较方便吧。

 

    为了避免与Servlet API耦合在一起,方便Action类做单元测试,Struts 2对HttpServletRequest、HttpSession和ServletContext进行了封装,构造了三个Map对象来替代这三种对象,在Action中,直接使用HttpServletRequest、HttpSession和ServletContext对应的Map对象来保存和读取数据。

(一)通过ActionContext来获取request、session和application对象的LoginAction1

[java]  view plain copy
  1. ActionContext context = ActionContext.getContext();   
  2. Map request = (Map)context.get("request");  
  3. Map session = context.getSession();  
  4. Map application = context.getApplication();  
  5. request.put("greeting""欢迎您来到程序员之家");//在请求中放置欢迎信息。  
  6. session.put("user", user);//在session中保存user对象  
  7. application.put("counter", count);  
  

在JSP中读取

[xhtml]  view plain copy
  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")%>

 

以下是原博客的地址,以备查阅http://apps.hi.baidu.com/share/detail/9065250

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值