快速配置一个拦截器
配置代码
@Configuration
public class MvcConfig implements WebMvcConfigurer {
//重写连接器配置
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
addInterceptor 添加拦截器
addPathPatterns 拦截哪些路径
excludePathPatterns 跳过哪些路径
*/
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/hello","等等","等等");
}
}
拦截器代码
public class LoginInterceptor implements HandlerInterceptor {
// 在业务处理器处理请求之前被调用
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//这里面写逻辑代码 返回false会被拦截
return false;
}
// 在业务处理器处理请求完成之后,生成视图之前执行
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
// 在DispatcherServlet完全处理完请求之后被调用,可用于清理资源
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}