为了精确定义Action方法执行之后再处理Action返回结果的动作,struts2提供了拦截结果监听器,拦截结果监听器通过手动注册给拦截器。
定义拦截结果监听器,需实现PreResultListener借口,需重写beforeResult()方法。
拦截结果监听器定义:
public class MyPreResultListener implements PreResultListener{
public void beforeResult(ActionInvocation ai,String result){
System.out.println("拦截结果监听器执行,返回的实图:"+result);
}
}
监听器定义:
public class MyPreResultListenerInterceptor extends AbstractInterceptor{
public String intercept(ActionInvocation ai) throws Exception{
ai.addPreResultListener(new com.demo1.interceptor.MyPreResultListener());
System.out.println("拦截器执行");
String result = ai.invoke();
System.out.println("拦截器执行完毕");
return result;
}
}
执行结果:
拦截器执行
Action执行
拦截结果监听器执行,返回的实图:success
拦截器执行完毕
PS:拦截结果监听器的beforeResult方法可以获得ActionInvocation实例,但是千万不能此实例再次调用invoke方法,如果调用invoke()方法会再次进入Action,这样就会进入死循环。