SpringMVC攔截器

自定義攔截器概述  

  1. Spring MVC也能夠使用攔截器對請求進行攔截處理,用戶能夠自定義攔截器來實現特定的功能,自定義的攔截器能夠實現HandlerInterceptor接口,也能夠繼承HandlerInterceptorAdapter 適配器類  
    • preHandle():這個方法在業務處理器處理請求以前被調用,在該方法中對用戶請求 request 進行處理。
    • postHandle():這個方法在業務處理器處理完請求後,可是DispatcherServlet 向客戶端返回響應前被調用,在該方法中對用戶請求request進行處理。
    • afterCompletion():這個方法在 DispatcherServlet 徹底處理完請求後被調用,能夠在該方法中進行一些資源清理的操做。
    • xml配置攔截器
    • <mvc:interceptors>spring

      <!-- 聲明自定義攔截器 -->數組

      <bean id="firstHandlerInterceptor"mvc

            class="com.atguigu.springmvc.interceptors.FirstHandlerInterceptor"></bean>ide

      </mvc:interceptors>post

    • 自定義攔截器類

      public class FirstHandlerInterceptor implements HandlerInterceptor {ui

       

      @Overridethis

      public void afterCompletion(HttpServletRequest arg0,spa

      HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {.net

      System.out.println(this.getClass().getName() + " - afterCompletion");xml

      }

       

      @Override

      public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,

      Object arg2, ModelAndView arg3) throws Exception {

      System.out.println(this.getClass().getName() + " - postHandle");

      }

    •  

      @Override

      public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,

      Object arg2) throws Exception {

      System.out.println(this.getClass().getName() + " - preHandle");

      return true;

      }

    • 當有多個攔截器時,      * preHandle:按照攔截器數組的正向順序執行      * postHandle:按照攔截器數組的反向順序執行      * afterCompletion:按照攔截器數組的反向順序執行      *       * 當多個攔截器的preHandle有不一樣的值時      * 第一個返回false,第二個返回false:只有第一個preHandle會執行      * 第一個返回true,第二個返回false:兩個(所有)攔截器的preHandle都會執行      * 可是(所有)postHandle都不會執行,而afterCompletion只有第一個(返回false的攔截器以前的全部afterCompletion)會執行      * 第一個返回false,第二個返回true:只有第一個的preHandle會執行

相關文章
相關標籤/搜索