Struts2拦截器基本流程

Struts2拦截器(动态代理)
1. 实现接口:Interceptor顶层接口,拦截器都必须直接或间接实现这个接口,后面介绍继承类。public class MyInterceptor implements Interceptor{init()方法 public String intercept(ActionInvocation invocation) throws Exception {
String result = invocation.invoke(); return result;} destroy()方法 }
2. Struts.xml配置:
<package name = “struts2 ” extends = “struts-default”>
<interceptors>
   <interceptor name=”myIntercept” class = “com.test.interceptor.MyInterceptor”>
  <param name = “hello”>world</param>
</interceptor>
   <interceptor-stack name=”mystack”>
      <interceptor-ref name = “myIntercept”></interceptor-ref>
      <interceptor-ref name = “defaultstack”></interceptor>
   </interceptor-stack>
</interceptors>
<default-interceptor-ref name = “myStack”></default-interceptor-ref>
<action name=”register” class = “com.test.action.RegisterAction” method=”test”>
   <result name = “login” class=””>/login.jsp</result>
     
</action>
</package>
extends : 继承Struts2中的包内容,同时也继承了Struts2中的拦截器。
拦截器栈:
<interceptor-stack name = “basicStack”>
   <interceptor-ref name = “exception”>
   <interceptor-ref name = “servletConfig”>
   <interceptor-ref name = “prepare”>

   <interceptor-ref name = “checkbox”>

   <interceptor-ref name = “params”>


</interceptor-stack>
拦截器栈可以由拦截器组成也可以由拦截器栈组成。栈可以包含栈。
当手动的引用一个拦截器时,Struts2就不会将默认的拦截器栈赋到action中引用 。如果想引用默认的拦截器,需要在action标签中添加如下代码:<interceptor-ref name = “defaultStack”></interceptor-ref>

如果没有添加手动的拦截器,那么Struts2会将默认的拦截器添加到action中,如果添加了手动的拦截器,那么默认的拦截器就不会起作用,想使用默认的拦截器,如上所说。
一般在使用拦截器时不是实现Interceptor接口,而是直接继承AbstractInterceptor,AbstractInterceptor也是实现Interceptor接口,他只是使用intercept()方法,而没有实现init()、destroy()方法,

方法过滤拦截器:
细化到拦截某一个方法,而不是指定某个Action,继承MethodFilterInterceptor类。
public class MyInterceptor3 extends MethodFilterInterceptor{
   protected String doIntercept(ActionInvocation invocation ) throws Exception{
   String result = invocation.invoke();
return result;
}
}

Struts.xml配置:
<interceptors>
  <interceptor name = “myInterceptor3” class = “com.test.interceptor.MyInterceptor3”>
  </interceptor>
</interceptors>
<action  method=”test”>
  <interceptor-ref name = “myInterceptor3”>
   <param name=”includeMethods”>test,execute</param>
   <param name=”excludeMethods”>test,execute</param>

</interceptor-ref>
</action>

你可能感兴趣的:(xml,jsp,struts)