# 一点说明:
使用的SpringBoot版本:SpringBoot2.0X在SpringBoot2.0之前SpringBoot拦截器是不会拦截静态资源的,所以…注意下面我写的注意拦截器目录结构1.编写拦截器
/** * 登录拦截器 */ public class LoginHanderInterceptor implements HandlerInterceptor { //目标方法执行之前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object user = request.getSession().getAttribute("user"); if(user == null || user.equals("") ){ //未登陆,返回登陆页面 request.getRequestDispatcher("/login.html").forward(request,response); return false; }else{ //已登陆,放行请求 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.注册拦截器
@Configuration public class MvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry){ registry.addViewController("/").setViewName("login"); } // 注册拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginHanderInterceptor()).addPathPatterns("/**") // 下面配置的是不进行拦截的路径 .excludePathPatterns("/login.html","/","/user/login","/login","/static/**"); } /** * 所有的 WebMvcConfigurationSupport 组件都会一起起作用 * @return */ @Bean //将所有组件注册在容器 public WebMvcConfigurer webMvcConfigurationSupport(){ WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/login.html").setViewName("login"); registry.addViewController("/login").setViewName("login"); } }; return webMvcConfigurer; } } 注意: 1.首先要在application.yml(或者application.properties中配置静态资源的映射路径) spring.mvc.static-path-pattern: /static/** (具体格式根据自己配置文件进行书写) 2.在排除静态资源拦截的时候,注意路径的书写。我一开始写的是/static/*会报错,之后改为/static/**就可以了 3.如果利用WebJars开发,/wabjars/下的静态资源也要进行配置 3.写完登陆拦截器后别忘了还要进行注册/* 匹配0或者任意数量的字符 (匹配一级,即/js,/css等)
/** 匹配0或者更多的目录 (匹配多级,即/js/*.js,/css/../../*.css等)
