spring boot 2.x静态资源会被拦截器拦截的原因分析及解决
spring boot 2.x静态资源会被拦截器拦截的原因
在spring boot 1.5.x中,resources/static目录下的静态资源可以直接访问,并且访问路径上不用带static,比如静态资源放置位置如下图所示:
那么访问静态资源的路径可以是:
http://localhost:8080/views/demoindex.html
http://localhost:8080/res/js/jquery.min.js
当有配置自定义HandlerInterceptor拦截器时,请求以上静态资源路径不会被拦截。
自定义HandlerInterceptor拦截器源码如下
package com.itopener.demo.config; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /** * @author fuwei.deng * @date 2018年4月13日 下午3:32:26 * @version 1.0.0 */ public class LoginRequiredInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(LoginRequiredInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info(request.getRequestURI()); return super.preHandle(request, response, handler); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.info(request.getRequestURI()); super.afterCompletion(request, response, handler, ex); } }
配置如下
package com.itopener.demo.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * @author fuwei.deng * @date 2018年4月13日 下午3:32:54 * @version 1.0.0 */ @Configuration public class WebMvcConfiguration extends WebMvcConfigurerAdapter { private final Logger logger = LoggerFactory.getLogger(WebMvcConfiguration.class); @Override public void addInterceptors(InterceptorRegistry registry) { logger.info("add interceptors"); registry.addInterceptor(new LoginRequiredInterceptor()); } }
访问静态资源时路径上不用加static目录
当spring boot版本升级为2.x时,访问静态资源就会被HandlerInterceptor拦截
这样对于利用HandlerInterceptor来处理访问权限或其他相关的功能就会受影响,跟踪源码查看原因,是因为spring boot 2.x依赖的spring 5.x版本,相对于spring boot 1.5.x依赖的spring 4.3.x版本而言,针对资源的拦截器初始化时有区别
具体源码在WebMvcConfigurationSupport中,spring 4.3.x源码如下:
/** * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped * resource handlers. To configure resource handling, override * {@link #addResourceHandlers}. */ @Bean public HandlerMapping resourceHandlerMapping() { ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext, this.servletContext, mvcContentNegotiationManager()); addResourceHandlers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); if (handlerMapping != null) { handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); // 此处固定添加了一个Interceptor handlerMapping.setInterceptors(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())); handlerMapping.setCorsConfigurations(getCorsConfigurations()); } else { handlerMapping = new EmptyHandlerMapping(); } return handlerMapping; }
而spring 5.x的源码如下:
/** * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped * resource handlers. To configure resource handling, override * {@link #addResourceHandlers}. */ @Bean public HandlerMapping resourceHandlerMapping() { Assert.state(this.applicationContext != null, "No ApplicationContext set"); Assert.state(this.servletContext != null, "No ServletContext set"); ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext, this.servletContext, mvcContentNegotiationManager(), mvcUrlPathHelper()); addResourceHandlers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); if (handlerMapping != null) { handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); // 此处是将所有的HandlerInterceptor都添加了(包含自定义的HandlerInterceptor) handlerMapping.setInterceptors(getInterceptors()); handlerMapping.setCorsConfigurations(getCorsConfigurations()); } else { handlerMapping = new EmptyHandlerMapping(); } return handlerMapping; } /** * Provide access to the shared handler interceptors used to configure * {@link HandlerMapping} instances with. This method cannot be overridden, * use {@link #addInterceptors(InterceptorRegistry)} instead. */ protected final Object[] getInterceptors() { if (this.interceptors == null) { InterceptorRegistry registry = new InterceptorRegistry(); // 此处传入新new的registry对象,在配置类当中设置自定义的HandlerInterceptor后即可获取到 addInterceptors(registry); registry.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService())); registry.addInterceptor(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())); this.interceptors = registry.getInterceptors(); } return this.interceptors.toArray(); }
从源码当中可以看出,使用spring 5.x时,静态资源也会执行自定义的拦截器,因此在配置拦截器的时候需要指定排除静态资源的访问路径,即配置改为如下即可:
package com.itopener.demo.config; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author fuwei.deng * @date 2018年4月13日 下午3:32:54 * @version 1.0.0 */ @Configuration public class WebMvcConfiguration implements WebMvcConfigurer { private final Logger logger = LoggerFactory.getLogger(WebMvcConfiguration.class); @Override public void addInterceptors(InterceptorRegistry registry) { logger.info("add interceptors"); registry.addInterceptor(new LoginRequiredInterceptor()).excludePathPatterns(Arrays.asList("/views/**", "/res/**")); } }
这样就可以和spring boot 1.5.x一样的方式使用了。
不过从源码当中可以看出,每个静态资源的请求都会被自定义Interceptor拦截,只是通过访问路径判断后不会执行拦截器的内容,所以spring 5.x相对于spring 4.3.x而言,这部分处理的性能会更低一些
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Spring Boot集成Shiro实现动态加载权限的完整步骤
这篇文章主要给大家介绍了关于Spring Boot集成Shiro实现动态加载权限的完整步骤,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring Boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧2019-09-09Springboot中@ConfigurationProperties轻松管理应用程序的配置信息详解
通过@ConfigurationProperties注解,可以将外部配置文件中的属性值注入到JavaBean中,简化了配置属性的读取和管理,这使得SpringBoot应用程序中配置文件的属性值可以映射到POJO类中,实现类型安全的属性访问,此方法避免了手动读取配置文件属性的需要2024-10-10Netty分布式ByteBuf使用subPage级别内存分配剖析
这篇文章主要为大家介绍了Netty分布式ByteBuf使用subPage级别内存分配剖析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-03-03解决Maven项目中 Invalid bound statement 无效的绑定问题
这篇文章主要介绍了解决Maven项目中 Invalid bound statement 无效的绑定问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06Java常用类库Apache Commons工具类说明及使用实例详解
这篇文章主要介绍了Java常用类库Apache Commons工具类说明及使用实例详解,需要的朋友可以参考下2020-02-02
最新评论