在Spring配置文件中設置攔截器。
<mvc:interceptors>
<mvc:interceptor>
<bean class="com.jd.interceptor.Interceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
若要配置攔截特定請求可在<mvc:interceptor>中添加標籤
<mvc:mapping path="/userinfo/*"/>
mvc:mapping用於設置攔截哪些路徑的請求,也可以使用mvc:exclude-mapping用於設置不攔截哪些路徑的請求。
自定義一個實現HandlerInterceptor接口的類並實現接口中定義的抽象方法
public class Interceptor implements HandlerInterceptor{
//該方法在Handler Method之前被調用
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("preHandle");
return true;
}
//該方法在Handler Method之後,渲染視圖之前
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
//該方法在渲染視圖之後被調用,
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion");
}
}
在DispatcherServlet 的 doDispatch 中有
我們進入第一個紅框代碼 applyPreHandle(processedRequest, response)
可以看出在該類中得到所有的攔截器,並逐一執行 preHandle 方法。
而因爲我們上面編寫的攔截器類的 preHandle 方法返回值設置的爲 false ,所以該 if 語句會執行,返回 false 。applyPreHandle 返回值爲 false, 所以 if( !mappedHandler.applyPreHandle(processedRequest, response) 的 if 語句執行。直接返回,結束doDispatch
又該 applyPreHandle 在 mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); 之前,所以不會執行 handle()方法。因此preHandle 常用來實現權限控制,若返回值爲true 請求才會正常執行。
在 mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); 執行完目標方法後 會有第一張圖片的 第三個紅框代碼 mappedHandler.applyPostHandle(processedRequest, response, mv);
同樣也是依次得到攔截器,執行 postHandle 方法。該攔截在執行完目標方法後執行, 常用於對請求域中的屬性或視圖做出修改
然後我們返回 doDispatch ,執行processDispatchResult
進入 processDispatchResult 往下拉 有 mappedHandler.triggerAfterCompletion(request, response, null);
該方法在render 方法執行之後被調用。常用於釋放資源