下面是配置拦截器的代码:
@SuppressWarnings("deprecation") @Configuration public class GlobleConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterpter()).excludePathPatterns("/index.html","/","/user/login") //.addPathPatterns("/main","/dashboard"); .addPathPatterns("/**"); }
}
下面是我写的自己的拦截器
public class MyInterpter implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("---MyInterpter"); Object name= request.getSession().getAttribute("loginUser"); if(name==null){ request.getSession().setAttribute("msg", "你还没有登录,请登录后在访问"); request.setAttribute("msg", "你还没有登录,请登录后在访问"); request.getRequestDispatcher("/index.html").forward(request, response); return false; } 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 { } }
当我访问:http://localhost:8001/index.html,还是会被拦截器拦截,excludePathPatterns的配置失效了,求大神帮忙看一下,
下面有一种说法:(我不这样认为)
https://blog.csdn.net/myth_g/article/details/80547608
下面这个是一种解答:
我也纠结了很久,然后发现自己智障了,其实是有效的,但是当你访问http://localhost:8001/index.html的时候,可能index.html不存在,然后spring报错,自动跳到/error显示错误,但是这个路径会被自己的拦截器拦截,这就给人一种拦截器的exclude不起作用的错觉,其实是起了作用的,所以要想拦截器正常工作,只需把/error路径也exclude一下