结果监听器是指在execute方法执行完,系统会调用结果监听器。结果监听器是一个类,该类实现了PreResultListener接口。PreResultListener接口有一个beforeResult方法,该方法有两个参数,invocation和resultCode,其中invocation是intercept方法中的invocation,resultCode表示execute方法返回的字符串。
以下是演示代码
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.PreResultListener;
public class MyPreResultListener implements PreResultListener{
public void beforeResult(ActionInvocation invocation, String resultCode) {
System.out.println("execute的返回值:" + resultCode);
}
}
要使用结果监听器,还需要在拦截器中用ActionInvocation的addPreResultListener方法进行注册,演示代码如下
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class ExecuteTimeInterceptor extends MethodFilterInterceptor {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String doIntercept(ActionInvocation actionInvocation) throws Exception{
//注册结果监听器
actionInvocation.addPreResultListener(new MyPreResultListener());
System.out.println(getName() + " 开始执行");
long start = System.currentTimeMillis();
String result = actionInvocation.invoke();
long end = System.currentTimeMillis();
System.out.println(getName() + " 执行Action方法的时间:" + (end-start) + "毫秒");
System.out.println(getName() + " 执行结束");
return result;
}
}
以上自建的监听器运行结果是这样的: