struts2-拦截器

struts2的拦截器是定义在进入到指定的action之前和之后的一系列处理类。

  1. 首先定义一个拦截器类,该类继承于AbstractInterceptor这个抽象类,该类有一个抽象方法:

                public String intercept(ActionInvocation invocation) throws Exception {
                        //在这个方法类进行一些操作
                 System.out.println("Hello World");

                 invocation.invoke();//该方法调用表示继续往下执行调用,在拦截器链向下一个继续调用
                      return null;
                }

  2.在struts.xml中配置拦截器

     <!--interceptors必须配置action之前,以供action引用  -->
        <interceptors>
            <interceptor name="helloInterceptor" class="xxx.xxx.interceptor.HelloInterceptor"/>
        </interceptors>
        <action name="*_*" class="xx.xx.action.{2}Action" method="{1}">
            <!-- 调用自定义的拦截器 -->
            <interceptor-ref name="helloInterceptor"/>
            <!-- 调用struts2默认的拦截器 -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">/{2}/{1}.jsp</result>
        </action>

或者

  <interceptors>
            <interceptor name="helloInterceptor" class="com.gcflowers.action.interceptor.HelloInterceptor"/>

    <!--定义一个拦截器栈,这个拦截器栈中可包含多个拦截器-->
            <interceptor-stack name="helloStack">
                <interceptor-ref name="helloInterceptor"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>       
        </interceptors>
        <action name="*_*" class="com.gcflowers.action.action.{2}Action" method="{1}">
            <!-- 调用自定义的拦截器 -->
            <interceptor-ref name="helloStack"/>
            <result name="success">/{2}/{1}.jsp</result>
        </action>

  3.通过以上配置就可实现一个简单的拦截器,当客户端访问指定的action时,先被拦截器处理,然后才进入action。

posted on 2013-05-18 21:14  zcjava  阅读(102)  评论(0编辑  收藏  举报