springboot 加拦截器
时间: 2025-02-13 11:21:39 浏览: 38
### 实现和配置Spring Boot拦截器
在Spring Boot中,通过继承`HandlerInterceptor`接口或其子类来创建自定义拦截器。下面是一个基本的实现过程。
#### 创建自定义拦截器
首先,在项目中新建一个Java文件作为拦截器类,并让这个类实现`HandlerInterceptor`接口:
```java
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre Handle method is Calling");
return true; // 如果返回false,则不会继续执行后续的操作;如果返回true则会继续往下执行
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Post Handle method is Calling");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Request and Response are completed");
}
}
```
此代码展示了如何重写三个核心的方法:`preHandle()`、`postHandle()` 和 `afterCompletion()`, 分别对应于请求前处理、视图渲染完成后以及整个请求结束后调用[^4]。
#### 注册拦截器
接着需要注册上述创建好的拦截器至应用程序上下文中。这通常是在配置类中完成,如下所示:
```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 WebConfig implements WebMvcConfigurer {
private final CustomInterceptor customInterceptor;
public WebConfig(CustomInterceptor customInterceptor){
this.customInterceptor = customInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(customInterceptor).addPathPatterns("/api/**"); // 只匹配/api开头的URL模式
}
}
```
这段代码说明了怎样利用`WebMvcConfigurer`接口来自定义MVC配置,并向其中添加已实例化的拦截器对象。这里还指定了要被拦截的具体路径模式[^3]。
以上就是关于如何在Spring Boot中实现和配置拦截器的大致介绍。需要注意的是,实际开发过程中可能还需要考虑更多细节问题,如异常情况下的响应逻辑等。
阅读全文
相关推荐


















