springmvc(3)攔截器HandlerInterceptor源碼的簡單解析,spring攔截器源碼
其實攔截器就是我們的AOP編程。攔截器在我們的實際項目中實用性比較大的,比如:日誌記錄,許可權過濾,身分識別驗證,效能監控等等。下面就簡單的來研究一下攔截器:
public interface HandlerInterceptor {
//在處理器適配器執行前調用 前面講過 為各種處理器適配 通俗的講意思就是說在執行controller的方法
//之前執行,返回true或者是false,true代表的是執行和面的邏輯,即執行後面的處理器或者攔截器
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
//在執行完適配的調用方法後,產生視圖之前執行,官方是這樣解析的:
// but before the DispatcherServlet renders the view.
void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception; //在所以的操作以後執行 void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception;
很明顯的看出來這是一個介面,我們在平時使用的時候,也是直接實現介面的方式的,具體每一個方法的作用也都將了一下,為了更好了理解這幾個方法調用的時機,我們來進行測試一下:
攔截器:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("<===========preHandle=============>"+System.currentTimeMillis()); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("<===========postHandle=============>"+System.currentTimeMillis()); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("<===========afterCompletion=============>"+System.currentTimeMillis()); }
controller:
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mv=new ModelAndView(); System.out.println("Controller"+System.currentTimeMillis()); mv.setViewName("index"); return mv; }
jsp:
<%
long endTime=System.currentTimeMillis();
System.out.println("Jsp:"+endTime);
%>
執行完以後控制台列印:
<===========preHandle=============>1451574182055Controller1451574182055<===========postHandle=============>1451574182055Jsp:1451574182179<===========afterCompletion=============>1451574182179
這也驗證了上面說法。
也許會有這樣的疑惑,業務需求可能只需要繼承一個方法,那怎麼辦,看其他幾個比較煩人(處女座)。這時候我們就可以通過繼承HandlerInterceptorAdapter 這個抽象類別了,
這個不用解釋了吧,你可以選擇繼承任意幾個來完成自己的商務邏輯。