您的位置:首页 > 其它

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

2014-10-09 21:25 246 查看
这个也是我在另外一位仁兄的博客中看到的,原博客的有点长,我把它精简了一下,算看起来比較方便吧。

为了避免与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://www. sunxin.org");

然后在结果页面中,从请求对象中取出greeting属性,例如以下:

${requestScope.greeting} 或者 <%=request.getAttribute("greeting")%>

下面是原博客的地址,以备查阅http://apps.hi.baidu.com/share/detail/9065250
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: