如果要实现拦截器的功能就需要在拦截器中添加以下逻辑操作,如下
package come.intercepterDemo;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class Myinterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation arg0) throws Exception {
// TODO Auto-generated method stub
//拦截方法
HelloWorldAction helloworldaction=(HelloWorldAction) arg0.getAction();
System.out.println("拦截器信息:HelloWorld拦截器! ");
//执行action或者执行下一个拦截器
String result=arg0.invoke();
//提示Action执行完毕
System.out.println("拦截器信息,Action执行完毕! ");
//根据处理结果处理其他业务
if(result.equals("success"))
{
//dosomething();
}
.......
return result;
}
}
但是如果按上面做了会降低代码的复用性,这与struts2框架所倡导的优雅、简洁的代码风格相违背。
哈哈,不要着急,因为Struts2框架为我们提供了一个接口PreResultListener接口。实现这个接口,就可以监听Action特定方法执行后的结果,并做进一步雨后处理。(可以看PreResultListener的API文档,我们看哈) 。
这个回调方法在Action执行之后,拦截器result被调用。该接口中只有一个方法,如下所示。该接口中有两个参数,其中resultCode就是Action执行后返回的结果。
void veforeResult(ActionInvocation invocation, String resultCode)
我们可以开发自己的监听类,但是要实现PreResultListener接口,并重写
void veforeResult(ActionInvocation invocation, String resultCode)
如下:
Package com.demo;
Import com.opensymphony.xwork2.ActionInvocation;
Import com.opensymphony.xwork2.interceptor.PreResultListener;
Public class MyListener implements PreResultListener{
//监听方法
Public void beforeResult(ActionInvocation arg0, String arg1){
System.out.println("InterceptorListener监听执行结果…… "+arg1);
}
}
下面将InterceptorListener加入拦截器Myinterceptor:
package come.intercepterDemo;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class Myinterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation arg0) throws Exception {
// TODO Auto-generated method stub
//拦截方法
HelloWorldAction helloworldaction=(HelloWorldAction) arg0.getAction();
//注册一个InterceptorListener
Arg0.addPreResultListener(new MyListener());
System.out.println("拦截器信息:HelloWorld拦截器! ");
//执行action或者执行下一个拦截器
String result=arg0.invoke();
//提示Action执行完毕
System.out.println("拦截器信息,Action执行完毕! ");
//根据处理结果处理其他业务
if(result.equals("success"))
{
//dosomething();
}
.......
return result;
}
}
这样,在拦截器中注册InterceptorListener,就可以实现拦截器与业务逻辑松耦合。
执行结构就有:
拦截器信息:HelloWorld拦截器!
Action信息,正在执行Action……
InterceptorListener监听执行结果…… success
拦截器信息,Action执行完毕!