總結(jié)一下SpringBoot下攔截器的使用,步驟很簡(jiǎn)單:
1.自定義自己的攔截類,攔截類需要繼承HandlerInterceptor接口并實(shí)現(xiàn)這個(gè)接口的方法。
@Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { //方法調(diào)用前執(zhí)行 return true;//返回為false,攔截器攔截的方法不會(huì)調(diào)用 } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { //方法執(zhí)行結(jié)束后執(zhí)行 } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { //該方法將在整個(gè)請(qǐng)求完成之后,也就是DispatcherServlet渲染了視圖執(zhí)行, 這個(gè)方法的主要作用是用于清理資源的, }
2.配置類需要繼承WebMvcConfigurerAdapter類
@Autowired private LoginInterceptor loginInterceptor;//自己定義的攔截器類 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor).addPathPatterns("攔截URL,可以不填默認(rèn)全部請(qǐng)求攔截"); }
3.啟動(dòng)SpringBoot應(yīng)用即可。