自定义一个拦截器需要三步:
1、自定义一个实现Interceptor接口(或者继承自AbstractInterceptor)的类。
2、在strutx.xml中注册上一步中定义的拦截器。
33、在需要使用的Action中引用上述定义的拦截器,为了方便也可将拦截器定义为默认的拦截器,这样在不加特殊声明的情况下所有的Action都被这个拦截器拦截。
定义拦截器:
其实在Struts2里面,要实现自定义的拦截器是非常简单的,只要写一个实现Interceptor接口的类就可以了。
也就是说,所有的拦截器都要实现com.opensymphony.xwork2.interceptor.Interceptor接口,这个接口中定义如下:
package cn.wjq.study.Interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* 自定义拦截器
* @author Administrator
*
*/
public class MyInterceptor implements Interceptor{
private String dbOrFile;
//为属性dbOrFile提供set方法
public void setDbOrFile(String dbOrFile) {
this.dbOrFile = dbOrFile;
}
/**
* 销毁
*/
public void destroy() {
// TODO Auto-generated method stub
System.out.println("自定义拦截器MyInterceptor 销毁");
}
/**
* 初始化
* 当服务启动时执行此方法,以后不再执行
*/
public void init() {
// TODO Auto-generated method stub
System.out.println("自定义拦截器MyInterceptor 初始化");
System.out.println("接到dbOrFile的参数=="+this.dbOrFile);
if("db".equals(dbOrFile)){
System.out.println("将日志记录到数据库");
}else{
System.out.println("将日志记录到文件");
}
}
public String intercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
System.out.println("在action执行之前执行");
String result=invocation.invoke();
System.out.println("在Result运行之后执行");
return result;
}
}
拦截器注册、引用、传参:
<package name="login" namespace="/login" extends="default" > <interceptors> <!-- 自定义拦截器 --> <interceptor name="myInterceptor" class="cn.wjq.study.Interceptor.MyInterceptor"></interceptor> </interceptors> <action name="loginAction" class="cn.wjq.study.login.action.LoginAction" method="login"> <!-- 登陆成功,跳转到welcome.jsp页面 --> <result name="toWelcome">/login/welcome.jsp</result> <!--如果验证没有通过,跳转到下面的页面 --> <result name="input">/login/login.jsp</result> <!-- 引用自定义拦截器,同时引用公共拦截器栈 --> <interceptor-ref name="myInterceptor"> <!-- 向自定义拦截器中传入参数 --> <param name="dbOrFile">db</param> </interceptor-ref> <interceptor-ref name="pubStack"></interceptor-ref> </action> </package>
方法的基本说明如下:
- init方法就类似于构造方法,用于初始化一些相关资源
- destory方法类似于析构方法,用于释放资源
- intercept方法,就是拦截器执行的处理方法,我们要实现的功能主要就写在这个方法里面。
对于intercept方法,再说明几点:
(1)在intercept方法中写“invocation.invoke();”,这句话的意思是继续运行拦截器后续的处理,如果这个拦截器后面还有拦截器,那么会继续运行,一直到运行Action,然后执行Result。
如果intercept方法中没有写“invocation.invoke();”这句话,那就意味着对请求的运行处理到此为止,不再继续向后运行了,换句话说,后续的拦截器和Action就不再执行了。而是在这里返回Result字符串,直接去进行Result处理了。
(2)在“invocation.invoke();”这句话之前写的功能,会在Action运行之前执行
(3)在“invocation.invoke();”这句话之后写的功能,会在Result运行之后执行
(4)intercept方法的返回值就是最终要返回的Result字符串,这个只是在前面没有执行Result的时候才有效,也就是前面没有“invocation.invoke();”这句话的时候,这个返回值就相当于是最终要返回的Result字符串,然后才执行相应的Result处理。