新人新帖,噴后請指正,謝謝
1.王中王,坑中坑
和很多人一樣,我在springboo自定義配置登錄攔截的時候,寫一個WebConfig類繼承WebMvcConfigureAdapter,重寫AddResourceHandlers,然后樂呵呵的去實現HandlerInterceptor,在preHandle里寫邏輯,然后訪問登錄頁面,然后what a fuck,我登錄頁面的樣式呢?怎么就幾個框框了?滿臉黑人問號?
項目目錄:
properties配置的靜態路徑:spring.mvc.static-path-pattern=/resources/**
WebConfig里的靜態文件配置和攔截配置如下:
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 配置模板資源路徑 registry.addResourceHandler("/templates/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/"); registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/"); } @Override public void addInterceptors(InterceptorRegistry registry) { // InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor()); // 不可以下面方式操作,如果那樣寫是不可以的。這樣等於是創建了多個Interceptor。而不是只有一個Interceptor // addInterceptor.excludePathPatterns("/login"); // addInterceptor.excludePathPatterns("/login/main"); // //攔截所有路徑 // addInterceptor.addPathPatterns("/**"); // addPathPatterns("/**")對所有請求都攔截,但是排除了/login/main和/login請求的攔截 registry.addInterceptor(getSecurityInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/login","/login/main"); } @Bean public MyInterceptor getSecurityInterceptor() { return new MyInterceptor(); }
/** * 在controller之前執行 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("開始檢測是否登錄"); log.info(request.getRequestURL().toString()); // 判斷是否已有該用戶登錄的session if (request.getSession().getAttribute(SESSION_KEY) != null) { log.info("用戶已登錄"); return true; } log.info("用戶尚未登錄"); // 跳轉到登錄頁 response.sendRedirect(request.getContextPath() + "/login"); return false; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { }
打印請求地址輸出后發現(log.info(request.getRequestURL().toString())),static下的靜態頁面都被攔截了,一臉懵逼加問號中。
2.解決辦法
網上查了一大堆資料,都沒有說到點子上的,之道后來發現原因竟然是:版本居然是:
spring boot 2.x已經改為最低支持jdk8版本,而jdk8中的接口允許有默認實現,所以已經廢棄掉WebMvcConfigurerAdapter適配類,而改為直接實現WebMvcConfigurer接口。
以上信息來自==>https://my.oschina.net/dengfuwei/blog/1795346的幫助。
然后 WebConfig implements WebMvcConfigurer,是要實現啊WebMvcConfigurer。。。。。。然后修改一下攔截,注解只留@Configuration。
registry.addInterceptor(getSecurityInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/login","/login/main","/static/**");
重啟項目,訪問:http://localhost:8080/login,完美