Struts中的拦截器学习笔记

时间:2020-12-09 21:39:11

拦截器的意义:

   1、如果有一个比较复杂的逻辑,在没有拦截器的情况下,会把这些需求全部写在action的方法中

      这样会导致方法的结构不好

   2、会把一些重用性的内容写在拦截器中

   3、要把这些重用性比较高的代码以很好的组织形式结合起来,一个拦截器是不够的,所以需要

      拦截器栈

   4、怎么样写一个拦截器

        1、声明一个拦截器

             <interceptors>

                  声明了一个拦截器

                 <interceptorname="imageInterceptor"class="cn.itheima03.struts2.interceptor.MyInterceptor"></interceptor>

                  声明了一个拦截器栈:可以放很多个拦截器

                 <interceptor-stackname="myInterceptor">

                         <interceptor-refname="imageInterceptor"></interceptor-ref>

                          struts2默认执行的拦截器

                          interceptor-ref即能指向拦截器,也能指向拦截器栈

                         <interceptor-refname="defaultStack"></interceptor-ref>

                 </interceptor-stack>

             </interceptors>

        2、使用拦截器

              <default-interceptor-refname="myInterceptor"></default-interceptor-ref>

            这样就可以覆盖struts-default.xml文件的内容了

        3、写的拦截器类必须实现Interceptor接口

               intercept(){

                    returninvocation.invoke();//往下继续执行

               }