spring中常用拦截器
时间: 2024-06-13 15:07:19 浏览: 13
在Spring中,常用的拦截器有以下几种:
1. HandlerInterceptor:最常见的拦截器,用于拦截来自客户端浏览器等的HTTP请求。
2. ClientHttpRequestInterceptor:用于拦截RestTemplate的请求,也被称为RestTemplate拦截器或Ribbon拦截器。
3. RequestInterceptor:常用于Feign调用,也是一个HTTP拦截器。
下面是HandlerInterceptor的使用方法:
1. 创建一个类并实现HandlerInterceptor接口。
2. 在类上使用@Component注解,将其声明为Spring Bean。
3. 在类上使用@Order注解指定拦截器的执行顺序。
4. 实现HandlerInterceptor接口的三个方法:preHandle、postHandle和afterCompletion。
5. 在配置类中使用addInterceptor方法将拦截器添加到拦截器链中。
下面是一个HandlerInterceptor的示例代码:
```java
@Component
@Order(1)
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求处理之前进行调用(Controller方法调用之前)
return true; // 如果返回false,则请求中断
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作)
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)