springboot 拦截器 request 如何获取controller
时间: 2023-10-18 14:10:02 浏览: 135
在 Spring Boot 中,我们可以使用拦截器来对请求进行处理和过滤,在拦截器中获取 Controller 的方式有多种。这里介绍几种比较常见的方式:
1. 实现 HandlerInterceptor 接口,在 preHandle 方法中获取 Controller:
```java
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Object bean = handlerMethod.getBean();
if (bean instanceof YourController) {
YourController controller = (YourController) bean;
// TODO: 对 controller 进行操作
}
}
return true;
}
}
```
2. 继承 HandlerInterceptorAdapter 类,在 preHandle 方法中获取 Controller:
```java
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Object bean = handlerMethod.getBean();
if (bean instanceof YourController) {
YourController controller = (YourController) bean;
// TODO: 对 controller 进行操作
}
}
return true;
}
}
```
3. 在拦截器中使用 AOP 的后置通知,在方法执行完毕后获取 Controller:
```java
public class MyInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Object bean = handlerMethod.getBean();
if (bean instanceof YourController) {
YourController controller = (YourController) bean;
// TODO: 对 controller 进行操作
}
}
}
}
```
需要注意的是,如果拦截器链中有多个拦截器,那么需要确保拦截器的执行顺序,否则可能会导致获取到的 Controller 不正确。
阅读全文