interceptor(攔截器)
攔截器,顧名思義枪蘑,他的作用就是攔截岖免,這個要和過濾器區(qū)分開,過濾器依賴serverlet容器话侧,獲取request和response處理闯参,是基于函數(shù)回調(diào),簡單說就是“去取你想取的”新博,攔截器是通過java反射機制,動態(tài)代理來攔截web請求寥殖,是“拒你想拒絕的”,他只攔截web請求同诫,但不攔截靜態(tài)資源樟澜,Struts2里面就是將攔截器串聯(lián)秩贰,實現(xiàn)對請求的處理,下面以spring 的攔截器為例丙唧,寫個demo
/**
* @author wtzhouc@gmail.com
* @date 2019-04-13 14:50
*/
@Component
public class MyInterceptor implements HandlerInterceptor {
? ? @Override
? ? public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object hanlder) {
? ? ? ? out.println("攔截器.preHandle 開始執(zhí)行觅玻。想际。。");
? ? ? ? out.println(hanlder.getClass().getSimpleName());
? ? ? ? out.println(((HandlerMethod) hanlder).getBean().getClass().getName());
? ? ? ? httpServletRequest.setAttribute("start", currentTimeMillis());
? ? ? ? return true;
? ? }
? ? @Override
? ? public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object hanlder, ModelAndView modelAndView) {
? ? ? ? out.println("攔截器.postHandle 開始執(zhí)行胡本。。侧甫。");
? ? ? ? long start = (long) httpServletRequest.getAttribute("start");
? ? ? ? out.println("postHandle執(zhí)行時間為:" + (currentTimeMillis() - start));
? ? }
? ? @Override
? ? public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object hanlder, Exception e) {
? ? ? ? //會打印兩次 spring里面的basic error 也會被攔截
? ? ? ? out.println("攔截器.afterCompletion 開始執(zhí)行。蹋宦。。");
? ? ? ? long start = (long) httpServletRequest.getAttribute("start");
? ? ? ? out.println("afterCompletion執(zhí)行時間為:" + (currentTimeMillis() - start));
? ? ? ? out.println("\n ex is :" + e+"\n");
? ? }
}