监听器 PreResultListener
创建MyRreResultListener类
该类连接PreResultListener
接口
beforeResult(ActionInvocation arg0, String arg1)
方法
String
类型的arg1
参数 他表示被拦截Action的方法返回值
package com.xxx.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.PreResultListener;
//监听器
public class MyRreResultListener implements PreResultListener {
@Override
public void beforeResult(ActionInvocation arg0, String arg1) {
System.out.println("我是MyRreResultListener监听器");
System.out.println("监听结果 = "+arg1);
}
}
现在就创建拦截器同时装入监听器(刚刚自己创建的MyRreResultListener)
package com.xxx.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
//调用监听器的拦截器
public class MyInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation arg0) throws Exception {
System.out.println("我是MyInterceptor拦截器");
//addPreResultListener()把监听器添加到拦截器中
arg0.addPreResultListener(new MyRreResultListener());
String result=arg0.invoke();
return result;
}
}
Action类我就随便创建一个测试咯
package com.xxx.action;
import com.opensymphony.xwork2.ActionSupport;
public class MyAction extends ActionSupport {
@Override
public String execute() throws Exception {
System.out.println("我是MyAction的execute()方法");
return SUCCESS;
}
}
配置struts.xml
只需要把 包含监听器的拦截器 配置到action中
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- struts2的action必须放在一个指定的包空间下定义 -->
<package name="default" extends="struts-default" namespace="/">
<interceptors>
<interceptor name="pre" class="com.xxx.interceptor.MyInterceptor"/>
</interceptors>
<action name="my" class="com.xxx.action.MyAction">
<result name="success">/NewFile.jsp</result>
<interceptor-ref name="defaultStack" /><!-- 使用系统拦截器 -->
<interceptor-ref name="pre" />
</action>
</package>
</struts>
打开tomeat 执行一下看看
可以看得出 顺序 是
拦截器 →Action→监听器(监听结果)
感觉监听器这东西好高大上
对于初学者的我并感觉不到有什么用- -