首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

《研磨struts2》第七章 值栈跟OGNL 之 7.4 ActionContext和ServletActionContext

2012-08-16 
《研磨struts2》第七章 值栈和OGNL 之 7.4 ActionContext和ServletActionContext7.4??ActionContext和Servle

《研磨struts2》第七章 值栈和OGNL 之 7.4 ActionContext和ServletActionContext

7.4??ActionContext和ServletActionContext

7.4.1??再探ActionContext

前面已经了解到ActionContext是Action执行时的上下文,里面存放着Action在执行时需要用到的对象,我们也称之为广义值栈。

?????? Struts2在每次执行Action之前都会创建新的ActionContext,在同一个线程里ActionContext里面的属性是唯一的,这样Action就可以在多线程中使用。

1:ActionContext的线程安全性

?????? 那么Struts2是如何保证ActionContext的线程安全性呢?

?????? 看看ActionContext对象的代码,示例如下:

?

图7.7 使用ServletRequestAware的结果页面

?????? 当然,你也可以以同样的方式去使用ServletResponseAware,这里就不去赘述了。

7.4.3?ActionContext和ServletActionContext

根据前面的讲述,你会发现,ActionContext和ServletActionContext有着一些重复的功能,都能够获取到Web对象的数据,但是又有些不同。

?????? 通常情况下,可以这么认为:ActionContext主要负责值的操作;ServletActionContext主要负责获取Servlet对象。

那么在Action中,该如何去抉择呢?建议的原则是:

  • 优先使用ActionContext
  • 只有ActionContext不能满足功能要求的时候,才使用ServletActionContext

    总之,要尽量让Action与Web无关,这对于Action的测试和复用都是极其有好处的。

    ?????? 另外还有一点需要注意:在使用ActionContext时,不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许还没有设置,这时通过ActionContext取得的值也许是null。

    ?

    私塾在线网站原创《研磨struts2》系列

    转自请注明出处:【http://sishuok.com/forum/blogPost/list/0/4072.html】

    欢迎访问http://sishuok.com获取更多内容

热点排行