Springboot中自定义拦截器,拦截特定接口
时间: 2024-11-30 07:15:56 浏览: 44
在Spring Boot中,自定义拦截器(Interceptor)允许你在请求特定接口或URL之前、之后甚至在异常发生时添加额外的功能。Spring MVC框架提供了一个强大的拦截器体系,可以通过`@WebMvcConfigurer`或实现`HandlerInterceptor`接口来创建。
**步骤1:创建自定义拦截器**
首先,创建一个实现了`HandlerInterceptor`接口或者扩展了`AbstractHandlerInterceptorAdapter`的类,比如`MyGlobalInterceptor`:
```java
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyGlobalInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求处理前的操作,如日志记录或权限检查等
return true; // 如果返回true,请求继续;false则中断
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 请求处理后的操作,例如填充Model数据
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 异常处理或清理资源
}
}
```
**步骤2:注册拦截器**
然后在`WebMvcConfigurer`中注册你的拦截器:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AppConfig implements WebMvcConfigurer {
private final MyGlobalInterceptor myGlobalInterceptor;
public AppConfig(MyGlobalInterceptor myGlobalInterceptor) {
this.myGlobalInterceptor = myGlobalInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myGlobalInterceptor).addPathPatterns("/api/**"); // 拦截所有以/api开头的接口
}
}
```
在这里,`addPathPatterns()`方法指定了拦截器应该拦截哪些接口或路径模式。你可以替换`/api/**`为实际需要拦截的接口路径。
阅读全文
相关推荐


















