1. 創(chuàng)建類(lèi)實(shí)現(xiàn)HandlerInterceptor接口,重寫(xiě)需要的方法。
- preHandle方法是controller方法執(zhí)行前攔截的方法
- 可以使用request或者response跳轉(zhuǎn)到指定的頁(yè)面
- return true放行,執(zhí)行下一個(gè)攔截器,如果沒(méi)有攔截器,執(zhí)行controller中的方法。
- return false不放行,不會(huì)執(zhí)行controller中的方法。
- postHandle是controller方法執(zhí)行后執(zhí)行的方法,在頁(yè)面(jsp)視圖執(zhí)行前。
- 可以使用request或者response跳轉(zhuǎn)到指定的頁(yè)面
- 如果指定了跳轉(zhuǎn)的頁(yè)面,那么controller方法跳轉(zhuǎn)的頁(yè)面將不會(huì)顯示。
- postHandle方法是在頁(yè)面(jsp)執(zhí)行后執(zhí)行
- request或者response不能再跳轉(zhuǎn)頁(yè)面了
package cn.test.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定義攔截器
*/
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle start...");
return true;
}
}
2. 配置攔截器類(lèi)(springmvc.xml)
<!--配置攔截器-->
<mvc:interceptors>
<mvc:interceptor>
<!--攔截-->
<mvc:mapping path="/*"/>
<!-- <mvc:exclude-mapping path=""/> 不攔截-->
<bean class="cn.test.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
3. 配置多個(gè)攔截器
1. 定義新類(lèi)
2. 配置新的攔截器