springboot 请求拦截
时间: 2025-07-05 08:09:34 浏览: 12
### Spring Boot 中实现请求拦截的方法
#### 创建自定义拦截器
为了创建一个自定义的拦截器,在Spring Boot中通常会继承`HandlerInterceptorAdapter`类或实现`HandlerInterceptor`接口。通过重写其中的方法来定制逻辑,比如在请求到达控制器前验证用户身份、记录日志等。
```java
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyCustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Before handling the request.");
// 可在此处添加业务逻辑判断
return true; // 返回false表示中断后续操作;返回true则继续执行下一个拦截器或目标方法
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("After handling but before rendering view.");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("After completing all operations including view rendering.");
}
}
```
#### 配置并注册拦截器
接着需要将这个自定义的拦截器注册到应用程序上下文中,这可以通过扩展`WebMvcConfigurer`接口完成,并覆盖其`addInterceptors()`方法[^2]。
```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 MyCustomInterceptor myCustomInterceptor;
public WebConfig(MyCustomInterceptor myCustomInterceptor){
this.myCustomInterceptor = myCustomInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myCustomInterceptor).addPathPatterns("/api/**"); // 设置要被拦截的URL模式
}
}
```
上述代码片段展示了如何设置特定路径下的API调用会被指定的拦截器所捕获。这里选择了以`/api/`开头的所有路由作为例子[^4]。
#### 应用启动类
最后确认项目中的入口文件已经正确配置了@SpringBootApplication注解以便自动扫描组件和服务:
```java
package com.jiyongliang.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBoot3CustomInterceptorApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot3CustomInterceptorApplication.class, args);
}
}
```
此部分确保整个框架能够正常工作并且识别出所有的Bean实例化对象以及配置项。
阅读全文
相关推荐




















