//自定义拦截器,实现HandlerInterceptor类html
public class loginInterceptor implements HandlerInterceptor {post
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object user = request.getSession().getAttribute("loginUser"); if(user==null) { request.setAttribute("error","没有权限,请登陆"); request.getRequestDispatcher("/index.html").forward(request, response); return false; } return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }
}spa
//注入到容器中 @Configuration必须写上,不然不起做用code
// 1.x.x 以前使用的是 继承 WebMvcConfigurerAdapter,官方不建议使用 能够配置本身定义的配置方式htm
//2.x.x 使用实现WebMvcConfigurer类 这个里面有不少方法,能够配置本身定义的配置方式继承
@Configurationget
public class myConfig implements WebMvcConfigurer {io
public void addInterceptors(InterceptorRegistry registry) { //拦截根目录下的全部的的,排除/index.html / /user/login registry.addInterceptor(new loginInterceptor()).addPathPatterns("/**") .excludePathPatterns("/index.html","/","/user/login"); }
}class