Struts2与Servlet API解耦

如果开发过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:

 

Java代码  复制代码
  1. ActionContext.getContext() .put(key,value);  

其实这个方法就相当于servlet API中的

Java代码  复制代码
  1. HttpServletRequest.setAttribute(key,value);  

 

2.ServletRequestAware and ServletResponseAware

 

在action中使用时,都必须实现这两种接口.然后实现其中的方法.不推荐使用

 

3.ServletActionContext

 

为全接口继承了ActionContext,其方法都为静态,可以直接调用

如:

Java代码  复制代码
  1. HttpServletRequest request= ServletActionServlet.getRequest();  

 

 

综上所述,这三种方法的使用先后顺序为:

ActionContext

ServletActionContext

ServletRequestAware and ServletResponseAware

但是第一种方法无法获得 HttpServletRequestHttpServletResponse对象.

其它两种可以

你可能感兴趣的:(thread,servlet,单元测试)