拦截器Interceptor

简单介绍了Interceptor的使用以及与Filter的区别

拦截器Interceptor

简单介绍

概念:是一种动态拦截方法调用的机制,类似于过滤器。Spring框架中提供的,主要用来动态拦截控制器方法的执行。

作用:拦截请求,在指定的方法调用前后,根据业务需要执行预先设定的代码。

快速使用

定义拦截器,实现HandlerInterceptor接口,并实现其所有方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@Slf4j
@Component // 由于拦截器是Spring的组件,所以需要交给Spring管理
public class DemoInterceptor implements HandlerInterceptor {
    @Override // 在目标方法执行之前执行,返回true则放行,返回false则拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle……");
        return true;
    }

    @Override // 在目标方法执行之后执行,但在视图渲染之前
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle……");
    }

    @Override // 在视图渲染之后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion……");
    }
}

然后在配置类中注册拦截器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
@Configuration
public class WebConfig implements WebMvcConfigurer {
    // @Autowired
    // private DemoInterceptor demoInterceptor;

    @Autowired
    private TokenInterceptor tokenInterceptor;

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
       // 添加拦截器
       registry.addInterceptor(tokenInterceptor)
               .addPathPatterns("/**") // 指定拦截所有请求
               .excludePathPatterns("/login"); // 指定放行(不拦截)/login请求
   }
}

执行结果:

image-20250920215448574

拦截路径

image-20250920223045670

拦截路径 含义 举例
/* 一级路径 能匹配/depts,/emps,/login,不能匹配 /depts/1
/** 任意级路径 能匹配/depts,/depts/1,/depts/1/2
/depts/* /depts下的一级路径 能匹配/depts/1,不能匹配/depts/1/2,/depts
/depts/** /depts下的任意级路径 能匹配/depts,/depts/1,/depts/1/2,不能匹配/emps/1

执行流程

过滤器(Filter)和拦截器时存在的情况下,会先经过过滤器再经过拦截器,然后执行对应方法后返回拦截器,再返回过滤器

image-20250920224033155

Filter与Interceptor的区别

接口规范不同:过滤器需要实现Filter接口,而拦截器需要实现HandlerInterceptor接口。

拦截范围不同:过滤器Filter会拦截所有的资源,而Interceptor只会拦截Spring环境中的资源。

本站于2025年3月26日建立
使用 Hugo 构建
主题 StackJimmy 设计