新人新帖,喷后请指正,谢谢
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,完美