在springboot的controller加拦截器
时间: 2024-11-23 16:24:51 浏览: 5
在Spring Boot项目中,添加全局控制器拦截器(Controller Interceptor)可以让你在每个HTTP请求进入Controller处理之前或之后执行一些自定义的操作。这种拦截器类似于过滤器,但它更专注于处理Controller层面的动作。以下是添加全局拦截器的基本步骤:
1. 首先,创建一个实现了`HandlerInterceptor`接口的类。这个接口包含两个方法:`preHandle()`和`afterCompletion()`。`preHandle()`会在请求开始前执行,而`afterCompletion()`则是在请求完成后,无论成功与否都会执行。
```java
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class GlobalControllerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 执行你的预处理逻辑,如记录请求日志等
System.out.println("Pre-handling request");
return true; // 如果你想继续处理请求,返回true;如果不想,返回false
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 请求处理完毕后的操作,比如填充模型数据
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 请求完成后的清理工作,无论是否异常
System.out.println("Request completed");
}
}
```
2. 注册拦截器到Spring MVC上下文中。在配置类中,使用`@EnableWebMvc`开启MVC,并通过`addInterceptors()`方法注册你的拦截器。
```java
import org.springframework.beans.factory.annotation.Autowired;
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 GlobalControllerInterceptor globalInterceptor;
@Autowired
public WebConfig(GlobalControllerInterceptor globalInterceptor) {
this.globalInterceptor = globalInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(globalInterceptor);
}
}
```
阅读全文