一、编写一个拦截类
拦截内实现HandlerInterceptor接口,并重写它的拦截方法
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//这里写拦截逻辑
return false;
}
@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 {
//这里写拦截逻辑
}
}
二、把拦截器注册到容器中
拦截器实现WebMvcConfigurer 接口,并重写addInterceptors方法
@Configuration
public class AdminConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry)
{
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**")//所有请求都拦截,包括静态资源
.excludePathPatterns("/","login","/css/**","/fonts/**");//放行的地址
}
}