springboot3的拦截器配置
时间: 2023-10-15 19:08:03 浏览: 165
Spring Controller拦截器配置
在Spring Boot中配置拦截器,可以通过实现HandlerInterceptor接口来自定义拦截器,并在配置类中进行注册。
首先,创建一个拦截器类,实现HandlerInterceptor接口,并重写其中的方法。例如:
```java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 在请求处理之前进行调用(Controller方法调用之前)
// 返回false将取消当前请求
return true;
}
@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渲染了对应的视图之后执行(主要是用于进行资源清理工作)
}
}
```
然后,在配置类中注册拦截器。例如:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器
registry.addInterceptor(myInterceptor).addPathPatterns("/**"); }
}
```
以上代码中,MyInterceptor是自定义的拦截器类,WebConfig是配置类,通过WebMvcConfigurer接口的addInterceptors()方法注册拦截器,并指定拦截的路径。
阅读全文