1.创建自定义的拦截器
创建一个自定义的interceptor继承至HandlerInterceptor
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("在这里进行拦截器的操作");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2.添加拦截器到配置文件
创建一个config类继承至WebMvcConfigurer 实现如下方法
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private MyInterceptor myInterceptor ;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**")//添加拦截器到所有路径
.excludePathPatterns("/login");//排除/login
}
}