springmvc多個攔截器執行順序及攔截器使用方法

springmvc的攔截器實現HandlerInterceptor接口後,會有三個抽象方法需要實現,分別爲方法前執行preHandle,方法後postHandle,頁面渲染後afterCompletion。

1、當倆個攔截器都實現放行操作時,順序爲preHandle 1,preHandle 2,postHandle 2,postHandle 1,afterCompletion 2,afterCompletion 1

2、當第一個攔截器preHandle返回false,也就是對其進行攔截時,第二個攔截器是完全不執行的,第一個攔截器只執行preHandle部分。

3、當第一個攔截器preHandle返回true,第二個攔截器preHandle返回false,順序爲preHandle 1,preHandle 2 ,afterCompletion 1


總結:

preHandle按攔截器定義順序調用

postHandler按攔截器定義逆序調用

afterCompletion按攔截器定義逆序調用

 

postHandler在攔截器鏈內所有攔截器返成功調用

afterCompletion只有preHandle返回true才調用



攔截器使用


1、先自定義攔截器類,實現HandlerInterceptor接口,並重寫抽象方法進行攔截器的攔截邏輯

public class Interceptor1 implements HandlerInterceptor{
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("方法前 1");
		//判斷用戶是否登陸  如果沒有登陸  重定向到登陸頁面   不放行   如果登陸了  就放行了
		String requestURI = request.getRequestURI();
		if(!requestURI.contains("/login")){
			String username = (String) request.getSession().getAttribute("USER_SESSION");
			if(null == username){
				response.sendRedirect(request.getContextPath() + "/login.action");
				return false;
			}
		}
		return true;
	}
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("方法後 1");	
	}
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("頁面渲染後 1");	
	}
}

2、在springmvc配置文件中進行配置

		<!-- Springmvc的攔截器 -->
		<mvc:interceptors>
			<!-- 多個攔截器 -->
			<mvc:interceptor>
				<mvc:mapping path="/**"/>
				<!-- 自定義的攔截器類 -->
				<bean class="com.iss.springmvc.interceptor.Interceptor1"/>
			</mvc:interceptor>
		</mvc:interceptors>


發佈了40 篇原創文章 · 獲贊 22 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章