總結一下SpringBoot下攔截器的使用,步驟很簡單:ide
1.自定義本身的攔截類,攔截類須要繼承HandlerInterceptor接口並實現這個接口的方法。post
@Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { //方法調用前執行 return true;//返回爲false,攔截器攔截的方法不會調用 } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { //方法執行結束後執行 } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { //該方法將在整個請求完成以後,也就是DispatcherServlet渲染了視圖執行, 這個方法的主要做用是用於清理資源的, }
2.配置類須要繼承WebMvcConfigurerAdapter類spa
@Autowired private LoginInterceptor loginInterceptor;//本身定義的攔截器類 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor).addPathPatterns("攔截URL,能夠不填默認所有請求攔截"); }
3.啓動SpringBoot應用便可。code