如果开发过struts1.0的朋友应该知道其与servlet API是偶合的,然而struts2将Action与servlet API进行解偶.它方便了单元测试.struts2提供了三种方法对servlet API进行解偶.下面就这三种方法讲解一下:
1.ActionContext
这个接口对应到servlet API是HttpServletRequest
其中的两个主要方法get和 put 对应到HttpServletRequest的是getAttribute和setAttribute.
这样,我们只需要在execute中用ActionContext接口就能间接地操纵servlet API
查阅ActionContext的文档,我们发现其有一个static method. it`s getContext() .
the method returns the ActionContext specific to the current thread. the ActionContext for the current thread, is never null.
所以我们可以在Action中这样操纵servlet:
其实这个方法就相当于servlet API中的
2.ServletRequestAware and ServletResponseAware
在action中使用时,都必须实现这两种接口.然后实现其中的方法.不推荐使用
3.ServletActionContext
为全接口继承了ActionContext,其方法都为静态,可以直接调用
如:
综上所述,这三种方法的使用先后顺序为:
ActionContext
ServletActionContext
ServletRequestAware and ServletResponseAware
但是第一种方法无法获得 HttpServletRequest或HttpServletResponse对象.
其它两种可以