ITeye博客

WebWork框架- Interceptor(拦截器)

pursuer · 2010-09-23 21:30 · webwork · 企业架构 · Markdown

Interceptor(拦截器)将Action共用的行为独立出来,在Action执行前后运行。这也就是我们所说的AOP(Aspect Oriented Programming,面向切面编程),它是分散关注的编程方法,它将通用需求功能从不相关类之中分离出来;同时,能够使得很多类共享一个行为,一旦行为发生变化,不必修改很多类,只要修改这个行为就可以。

Interceptor将很多功能从我们的Action中独立出来,大量减少了我们Action的代码,独立出来的行为具有很好的重用性。XWork、WebWork的许多功能都是有Interceptor实现,可以在配置文件中组装Action用到的Interceptor,它会按照你指定的顺序,在Action执行前后运行。

当你提交对Aciton(默认是.action结尾的Url)的请求时,ServletDispatcher会根据你的请求,去调度并执行相应的Action。在Action执行之前,调用被 Interceptor截取,Interceptor在Action执行前后运行。

我们在用户注册的例子中就使用了取得Request请求参数的拦截器,配置文件中将拦截器params组装到RegisterAction中。“params”在我们的webwork-default.xml配置文件中有定义,webwork-default.xml中拦截器的定义如下:

Interceptor的原理 下面我们来看看Interceptor是如何实现在Action执行前后调用的: Action和Interceptor在框架中的执行,是由ActionInvocation对象调用的。它是用方法:String invoke() throws Exception;来实现的,它首先会依次调用Action对应的Interceptor,执行完成所有的Interceptor之后,再去调用Action的方法,代码如下: if (interceptors.hasNext()) { Interceptor interceptor = (Interceptor) interceptors.next(); resultCode = interceptor.intercept(this); } else { if (proxy.getConfig().getMethodName() == null) { resultCode = getAction().execute(); } else { resultCode = invokeAction(getAction(), proxy.getConfig()); } } 它会在拦截器栈中遍历Interceptor,调用Interceptor的方法: String intercept(ActionInvocation invocation) throws Exception;。 我们一直都提到,Interceptor是在Action前后执行,可是从上面的代码我们看到的却是执行完所有Interceptor的intercept()方法之后再去调用我们的Action。“在Action前后执行”是如何实现的呢?我们来看看抽象类AroundInterceptor的intercept()实现: public String intercept(ActionInvocation invocation) throws Exception { String result = null;

    before(invocation);
    result = invocation.invoke();
    after(invocation, result);

    return result;
}

原来在intercept()方法又对ActionInvocation的invoke()方法进行递归调用,ActionInvocation循环嵌套在intercept()中,一直到语句result = invocation.invoke();执行结束,即:Action执行完并返回结果result,这时Interceptor对象会按照刚开始执行的逆向顺序依次执行结束。这样before()方法将在Action执行前调用,after()方法在Action执行之后运行

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。