实现自定义拦截器:
> 可以实现 Interceptor 接口
> 继承 AbstractInterceptor 抽象类
- 在自定义的拦截器中可以选择不调用 ActionInvocation 的 invoke() 方法. 那么后续的拦截器和 Action 方法将不会被调用.
【1】拦截器实现代码
public class MyInterceptor extends AbstractInterceptor {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("before invocation.invoke...");
String result = invocation.invoke();
System.out.println("after invocation.invoke...");
return "success";
}
}
【2】xml配置
<interceptor name="hello" class="com.web.interceptors.MyInterceptor"></interceptor>
<action name="testToken" class="com.web.token.TokenAction">
<interceptor-ref name="token"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="hello"></interceptor-ref>
<result >/success.jsp</result>
<result name="invalid.token">/token-error.jsp</result>
</action>
此处请求testToken时,将会按照action中拦截器配置顺序执行(如果action中不配置,将会执行 package 中配置的拦截器)
result as follows :
before invocation.invoke...
username...kongqi
after invocation.invoke...
- default-interceptor-stack:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cGcq5CNwQTM4UGOykTOyI2YkBTYyYzX2IDMzEDM5AzLcZDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.jpg)
- testToken请求执行中,拦截器:
- 第一个是配置的token-interceptor
- 最后一个是自定义拦截器;
【3】如果更改拦截器顺序
<action name="testToken" class="com.web.token.TokenAction">
<interceptor-ref name="hello"></interceptor-ref>
<interceptor-ref name="token"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result >/success.jsp</result>
<result name="invalid.token">/token-error.jsp</result>
</action>
- 此时testToken请求执行中,拦截器:
MyInterceptor拦截器为第一位。。
且,更改MyInterceptor:
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("before invocation.invoke...");
/*注销 invocation.invoke()*/
//String result = invocation.invoke();
System.out.println("after invocation.invoke...");
return "success";
}
- 将不会执行下面配置的拦截器与拦截器栈,控制台同样获取不到username:
result as follows :
before invocation.invoke..
after invocation.invoke...
》》此时,更改MyInterceptor的resultCode–input,xml 中配置 :
<action name="testToken" class="com.web.token.TokenAction">
<interceptor-ref name="hello"></interceptor-ref>
<interceptor-ref name="token"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result >/success.jsp</result>
<result name="input">/index.jsp</result>
<result name="invalid.token">/token-error.jsp</result>
</action>
》》将会返回到index.jsp 页面!!!