攔截器是指通過統(tǒng)一攔截從瀏覽器發(fā)往服務器的請求來完成功能的增強
應用場景:解決一些共性問題,比如權限驗證、亂碼等
spring boot中使用攔截器:
1、創(chuàng)建一個類MyWebConfig繼承WebMvcConfigurerAdapter,并重寫addInterceptors方法
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {
@Autowired
MyiInterceptor myiInterceptor;
/**
*注冊 攔截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
?//多個攔截器組成一個攔截器鏈
// addPathPatterns添加攔截規(guī)則
// excludePathPatterns排除攔截
//攔截器myiInterceptor只攔截'/111'的請求,不攔截'/helloWorld'
registry.addInterceptor(myiInterceptor).addPathPatterns("/111").excludePathPatterns("/helloWorld");
super.addInterceptors(registry);
}
}
2、創(chuàng)建一個自定義攔截器MyiInterceptor實現(xiàn)HandlerInterceptor接口,重寫所有的方法實現(xiàn)自己的業(yè)務
@Component
public classMyiInterceptorimplementsHandlerInterceptor {
/**
*返回值為true請求會繼續(xù)執(zhí)行,false請求終止
*@paramhttpServletRequest請求請求
*@paramhttpServletResponse響應對象
*@paramo被攔截的對象
*@return
*@throwsException
*/
@Override
public booleanpreHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Object o)throwsException {
System.out.println("preHandle方法執(zhí)行了。。。");
httpServletRequest.setCharacterEncoding("utf-8");//設置請求編碼
httpServletResponse.setCharacterEncoding("utf-8");//設置響應編碼
//示例? 沒有登錄時, 轉(zhuǎn)發(fā)到登錄頁? 返回false中斷請求
//httpServletRequest.getRequestDispatcher("/login.html").forward(httpServletRequest,httpServletResponse);
//return false;
return true;
}
/**
*
*@paramhttpServletRequest請求請求
*@paramhttpServletResponse響應對象
*@paramo被攔截的對象
*@parammodelAndView可以在這個對象中設置返回的視圖和試圖內(nèi)容
*@throwsException
*/
@Override
public voidpostHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Object o,ModelAndView modelAndView)throwsException {
System.out.println("postHandle方法執(zhí)行了。。。。");
}
/**
*請求執(zhí)行完銷毀數(shù)據(jù)
*@paramhttpServletRequest請求請求
*@paramhttpServletResponse響應對象
*@paramo被攔截的對象
*@parame
*@throwsException
*/
@Override
public voidafterCompletion(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Object o,Exception e)throwsException {
System.out.println("afterCompletion方法執(zhí)行了。。。");
}
}
多攔截器工作流程:
攔截器和過濾器的區(qū)別:
過濾器Filter依賴servlet容器,基于回調(diào)函數(shù),作用范圍大
攔截器Interceptor依賴框架容器,基于反射機制,只過濾請求