springboot添加拦截器_代码
实现拦截器类
@Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("pre"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("after"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
配置类中注册拦截器:
@Configuration public class MyWebMvcConfigurerAdaptor extends WebMvcConfigurerAdapter { @Bean public WebMvcConfigurerAdapter webMvcConfigurerAdaptor() { WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/hi","hii"); } }; return adapter; } }
访问: http://localhost:8080/hello 拦截器生效
![](https://img2020.cnblogs.com/blog/1517312/202010/1517312-20201020235600306-311266414.png)
注: webMvcConfigurerAdaptor 过时了