Springboot中自定义拦截器,拦截接口代码示例
时间: 2024-11-30 09:16:30 浏览: 12
在Spring Boot中,你可以通过创建一个实现了`HandlerInterceptor`接口或者实现其默认的子接口如`WebMvcConfigurerAdapter`来自定义全局的HTTP请求拦截器。这里是一个简单的例子:
首先,创建一个名为`MyGlobalInterceptor`的类,它会实现`HandlerInterceptor`接口:
```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 {
// 在请求开始前执行的操作,例如记录日志或者添加全局属性
System.out.println("Pre-handle method called");
return true; // 如果你想继续处理请求,返回true
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在请求处理完成后,但在渲染视图之前执行的操作
System.out.println("Post-handle method called");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 请求完成后的清理工作,无论是否异常都会执行
System.out.println("After-completion method called");
}
}
```
然后,在Spring Boot应用中配置这个拦截器:
```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 {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyGlobalInterceptor());
}
}
```
阅读全文