1. 创建自己的拦截器,实现WebMvcConfigurerAdapter,并重写相关方法
public class DemoInterceptor extends HandlerInterceptorAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
LOGGER.info("******");
System.out.print("我的拦截器");
LOGGER.info("******");
}
}
2. 创建配置类,将自己的拦截器通过@Bean注册,并重写WebMvcConfigurerAdapter的addInterceptors方法,将自己的拦截器添加进去,并可以设置拦截的url。
@Configuration
public class DemoWebConfigAdapter extends WebMvcConfigurerAdapter {
@Bean
public DemoInterceptor demoInterceptor(){
DemoInterceptor demoInterceptor = new DemoInterceptor();
return demoInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(demoInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}