package org.springframework.web.servlet; public interface HandlerInterceptor { boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception; void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception; void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception; }
preHandle:預處理回調方法,實現處理器的預處理(如登陸檢查),第三個參數爲響應的處理器;html
返回值:true表示繼續流程(如調用下一個攔截器或處理器);java
false表示流程中斷(如登陸檢查失敗),不會繼續調用其餘的攔截器或處理器,此時咱們須要經過response來產生響應;web
postHandle:後處理回調方法,實現處理器的後處理(但在渲染視圖以前),此時咱們能夠經過modelAndView(模型和視圖對象)對模型數據進行處理或對視圖進行處理,modelAndView也可能爲null。spring
afterCompletion:整個請求處理完畢回調方法,即在視圖渲染完畢時回調,如性能監控中咱們能夠在此記錄結束時間並輸出消耗時間,還能夠進行一些資源清理,相似於try-catch-finally中的finally,但僅調用處理器執行鏈中preHandle返回true的攔截器的afterCompletion。設計模式
有時候咱們可能只須要實現三個回調方法中的某一個,若是實現
HandlerInterceptor接口的話,三個方法必須實現,無論你需不須要,此時spring提供了一個HandlerInterceptorAdapter適配器(一種適配器設計模式的實現),容許咱們只實現須要的回調方法。服務器
public abstract class HandlerInterceptorAdapter implements HandlerInterceptor { //省略代碼 此處因此三個回調方法都是空實現,preHandle返回true。 }
正常流程mvc
中斷流程app
中斷流程中,好比是HandlerInterceptor2中斷的流程(preHandle返回false),此處僅調用它以前攔截器的preHandle返回true的afterCompletion方法。jsp
DispatcherServlet內部 工做ide
//doDispatch方法 //一、處理器攔截器的預處理(正序執行) HandlerInterceptor[] interceptors = mappedHandler.getInterceptors(); if (interceptors != null) { for (int i = 0; i < interceptors.length; i++) { HandlerInterceptor interceptor = interceptors[i]; if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) { //1.一、失敗時觸發afterCompletion的調用 triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); return; } interceptorIndex = i;//1.二、記錄當前預處理成功的索引 } } //二、處理器適配器調用咱們的處理器 mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); //當咱們返回null或沒有返回邏輯視圖名時的默認視圖名翻譯(詳解4.15.5 RequestToViewNameTranslator) if (mv != null && !mv.hasView()) { mv.setViewName(getDefaultViewName(request)); } //三、處理器攔截器的後處理(逆序) if (interceptors != null) { for (int i = interceptors.length - 1; i >= 0; i--) { HandlerInterceptor interceptor = interceptors[i]; interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv); } } //四、視圖的渲染 if (mv != null && !mv.wasCleared()) { render(mv, processedRequest, response); if (errorView) { WebUtils.clearErrorRequestAttributes(request); } //五、觸發整個請求處理完畢回調方法afterCompletion triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
// triggerAfterCompletion方法 private void triggerAfterCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex, HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception { // 五、觸發整個請求處理完畢回調方法afterCompletion (逆序從1.2中的預處理成功的索引處的攔截器執行) if (mappedHandler != null) { HandlerInterceptor[] interceptors = mappedHandler.getInterceptors(); if (interceptors != null) { for (int i = interceptorIndex; i >= 0; i--) { HandlerInterceptor interceptor = interceptors[i]; try { interceptor.afterCompletion(request, response, mappedHandler.getHandler(), ex); } catch (Throwable ex2) { logger.error("HandlerInterceptor.afterCompletion threw exception", ex2); } } } } }
(1、攔截器實現
package cn.javass.chapter5.web.interceptor; //省略import public class HandlerInterceptor1 extends HandlerInterceptorAdapter {//此處通常繼承HandlerInterceptorAdapter適配器便可 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("===========HandlerInterceptor1 preHandle"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("===========HandlerInterceptor1 postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("===========HandlerInterceptor1 afterCompletion"); } }
以上是HandlerInterceptor1實現,HandlerInterceptor2同理 只是輸出內容爲「HandlerInterceptor2」。
(2、控制器
package cn.javass.chapter5.web.controller; //省略import public class TestController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception { System.out.println("===========TestController"); return new ModelAndView("test"); } }
(3、Spring配置文件chapter5-servlet.xml
<bean name="/test" class="cn.javass.chapter5.web.controller.TestController"/> <bean id="handlerInterceptor1" class="cn.javass.chapter5.web.interceptor.HandlerInterceptor1"/> <bean id="handlerInterceptor2" class="cn.javass.chapter5.web.interceptor.HandlerInterceptor2"/>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="handlerInterceptor1"/>
<ref bean="handlerInterceptor2"/>
</list>
</property>
</bean>
interceptors:指定攔截器鏈,攔截器的執行順序就是此處添加攔截器的順序;
(4、視圖頁面WEB-INF/jsp/test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%System.out.println("==========test.jsp");%>
test page
(5、啓動服務器測試
輸入網址:http://localhost:9080/springmvc-chapter5/test
控制檯輸出:
===========HandlerInterceptor1 preHandle ===========HandlerInterceptor2 preHandle ===========TestController ===========HandlerInterceptor2 postHandle ===========HandlerInterceptor1 postHandle ==========test.jsp ===========HandlerInterceptor2 afterCompletion ===========HandlerInterceptor1 afterCompletion
到此一個正常流程的演示完畢。和圖5-1同樣,接下來看一下中斷的流程。
(1、攔截器
HandlerInterceptor3和HandlerInterceptor4 與 以前的 HandlerInteceptor1和HandlerInterceptor2同樣,只是在HandlerInterceptor4的preHandle方法返回false:
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("===========HandlerInterceptor1 preHandle"); onse.getWriter().print("break");//流程中斷的話須要咱們進行響應的處理 return false;//返回false表示流程中斷
(2、控制器
流程中斷不會執行到控制器,使用以前的TestController控制器。
(3、Spring配置文件chapter5-servlet.xml
<bean id="handlerInterceptor3" class="cn.javass.chapter5.web.interceptor.HandlerInterceptor3"/> <bean id="handlerInterceptor4" class="cn.javass.chapter5.web.interceptor.HandlerInterceptor4"/>
<bean id="handlerInterceptor3" class="cn.javass.chapter5.web.interceptor.HandlerInterceptor3"/> <bean id="handlerInterceptor4" class="cn.javass.chapter5.web.interceptor.HandlerInterceptor4"/>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="handlerInterceptor3"/> <ref bean="handlerInterceptor4"/> </list> </property> </bean>
interceptors:指定攔截器鏈,攔截器的執行順序就是此處添加攔截器的順序;
(4、視圖頁面
流程中斷,不會執行到視圖渲染。
(5、啓動服務器測試
輸入網址:http://localhost:9080/springmvc-chapter5/test
控制檯輸出:
===========HandlerInterceptor3 preHandle ===========HandlerInterceptor4 preHandle ===========HandlerInterceptor3 afterCompletion
此處咱們能夠看到只有HandlerInterceptor3的afterCompletion執行,符合圖5-2的中斷流程。
並且頁面上會顯示咱們在HandlerInterceptor4 preHandle 直接寫出的響應「break」。
提示:推薦能使用servlet規範中的過濾器Filter實現的功能就用Filter實現,由於HandlerInteceptor只有在Spring Web MVC環境下才能使用,所以Filter是最通用的、最早應該使用的。如登陸這種攔截器最好使用Filter來實現。