springboot拦截器实现代码实现
时间: 2023-07-07 21:45:42 浏览: 63
好的,以下是一个简单的 Spring Boot 拦截器实现示例:
1. 创建一个拦截器类
```java
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求处理之前进行调用(Controller方法调用之前)
System.out.println("请求处理之前执行");
return true; // 只有返回 true 才会继续向下执行,返回 false取消当前请求
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
System.out.println("请求处理之后执行,视图渲染之前");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在整个请求处理之后进行调用,视图渲染之后(主要是用于进行资源清理工作)
System.out.println("请求处理之后执行,视图渲染之后");
}
}
```
2. 注册拦截器
```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
```
3. 测试
启动应用程序并尝试访问任何 URL,您应该在控制台输出中看到类似以下内容的消息:
```
请求处理之前执行
请求处理之后执行,视图渲染之前
请求处理之后执行,视图渲染之后
```
上述示例对所有 URL 路径执行拦截器。如果您只想对特定 URL 路径执行拦截器,则可以使用 addPathPatterns 方法。例如:
```java
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/home");
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)