springboot 自定义拦截器
时间: 2023-11-03 07:02:39 浏览: 33
在 Spring Boot 中,可以通过实现 HandlerInterceptor 接口来自定义拦截器。下面是一个简单的示例:
1. 创建一个拦截器类,实现 HandlerInterceptor 接口:
```
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求处理之前进行调用(Controller方法调用之前)
System.out.println("MyInterceptor preHandle...");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
System.out.println("MyInterceptor postHandle...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在整个请求处理完毕之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要用于进行资源清理工作)
System.out.println("MyInterceptor afterCompletion...");
}
}
```
2. 在配置文件中注册拦截器:
```
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
```
此处将 MyInterceptor 注册为拦截器,并设置拦截所有的请求("/**")。这样,在每个请求进来之前都会先执行 MyInterceptor 中的 preHandle() 方法,在请求处理完之后会执行 postHandle() 方法和 afterCompletion() 方法。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)