SpringMVC拦截器及多拦截器时的执行顺序

拦截器的配置步骤

  1. springmvc.xml中配置多个拦截器
  2. 配置自定义拦截器并实现接口
<!-- 配置springmvc拦截器 -->

<mvc:interceptors>

<mvc:interceptor>

<!-- 对什么url路径进行拦截  /**代表对全路径拦截 -->

<mvc:mapping path="/**"/>

<!-- 注入自定义拦截器到bean标签 -->

<bean class="cn.itcats.ssm.interception.Inteceptor1" />

</mvc:interceptor>

<mvc:interceptor>

<bean class="cn.itcats.ssm.interception.Inteceptor2" />

</mvc:interceptor>

</mvc:interceptors>


    

//拦截器1

public class Inteceptor1 implements HandlerInterceptor{


//方法执行前1

public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {

//返回值boolean类型  决定是否放行

System.out.println("方法执行前1");

return true;

}


//方法执行后1

public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)

throws Exception {

System.out.println("方法执行后1");

}



//页面渲染后1

public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)

throws Exception {

System.out.println("页面渲染后1");


}




//拦截器2

public class Inteceptor2 implements HandlerInterceptor{


//方法执行前2

public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {

//返回值boolean类型  决定是否放行

System.out.println("方法执行前2");

return true;

}


//方法执行后2

public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)

throws Exception {

System.out.println("方法执行后2");

}



//页面渲染后2

public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)

throws Exception {

System.out.println("页面渲染后2");


}


    


SpringMVC拦截器配置后,主要对三个过程进行拦截校验:

  1. 方法执行前(有boolean返回值,返回true则放行)
  2. 方法执行后
  3. 页面渲染后

多个拦截器执行顺序

    如有两个拦截器

    (1)方法执行前返回值都为true,则顺序如下

    方法执行前1   

    方法执行前2

    方法执行后2

    方法执行后1

    页面渲染后1

    页面渲染后2        


方法1和方法2是相对的,取决于springmvc自定义拦截器类配置的先后顺序(这里是自定义拦截器1先于拦截器2)

总结起来: 拦截器1中的方法执行前1先执行,后执行拦截器2中的方法执行前2方法,后拦截器2的方法先于拦截器1的方法执行


    (2)拦截器1中方法执行前1 返回值为false,而拦截器2中方法执行前2返回值为 true 执行顺序如下:

        方法执行前1    //此时被拦截,不放行

总结起来:只执行拦截器1方法执行前的方法,当拦截器1方法执行前被拦截,返回值为false不被放行,后面的拦截器链都不执行,无论2的返回值是true还是false


    

     (3)拦截器1中方法执行前1 返回值为true,而拦截器2中方法执行前2返回值为 false  执行顺序如下:

        方法执行前1

        方法执行前2   //被拦截,不放行

        页面渲染后1



总结执行顺序:

preHandle按拦截器定义顺序调用
postHandler按拦截器定义逆序调用
afterCompletion按拦截器定义逆序调用
postHandler在拦截器链内所有拦截器返成功调用

afterCompletion只有preHandle返回true才调用




        




    


    

猜你喜欢

转载自blog.csdn.net/itcats_cn/article/details/80371639