springboot自定义拦截器
时间: 2023-10-12 10:13:33 浏览: 53
在 Spring Boot 中自定义拦截器可以通过实现 `HandlerInterceptor` 接口来实现。下面是一个简单的例子:
首先创建一个拦截器类 `MyInterceptor`,实现 `HandlerInterceptor` 接口:
```java
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Before handling the request");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("After handling the request and rendering the view");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("After completion of the request");
}
}
```
然后在配置类中注册拦截器:
```java
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
```
在上面的例子中,我们在 `addInterceptors` 方法中注册了自定义的拦截器,并通过调用 `addPathPatterns` 方法指定了需要拦截的 URL 模式。这里我们使用了 `/**`,表示匹配所有的 URL。
当请求被拦截时,`preHandle` 方法会在请求处理之前被调用,`postHandle` 方法会在请求处理完成之后被调用,而 `afterCompletion` 方法会在响应已经被发送给客户端后被调用。我们可以在这些方法中添加自己的逻辑,例如记录日志、验证用户权限等。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)