| 
 | 
 
第一步:创建并且实现Handlerlnterceptor接口的类。 
 
 
- public class LoginInterceptor implements HandlerInterceptor {
 
  
-     /**
 
 -      *
 
 -      * @param request
 
 -      * @param response
 
 -      * @param handler 被拦截的控制器对象。
 
 -      * @return false:被拦截,true:被放行
 
 -      * @throws Exception
 
 -      */
 
 -     @Override
 
 -     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 
 -     System.out.println("执行了登录拦截器");
 
 -       return true;
 
 -     }
 
 - }
 
 
  复制代码 
 
 
第二步:通过要给config配置类(该类需要实现WebMvcConfigurer接口)添加拦截器到容器中去。 
- @Configuration
 
 - public class MyAppConfig implements WebMvcConfigurer {
 
  
 
-     @Override
 
 -     public void addInterceptors(InterceptorRegistry registry) {
 
  
-         HandlerInterceptor interceptor = new LoginInterceptor();
 
  
-         String path[] = {"/user/**"};  //拦截的路由
 
 -         String excluedePath[] = {"/login"};//放行的路由
 
  
-         registry.addInterceptor(interceptor).addPathPatterns(path).excludePathPatterns(excluedePath);
 
  
-     }
 
 - }
 
  复制代码 
 
 |   
 
 
 
 |