SpringBoot之SpringBoot对静态资源的映射规则

SpringBoot之SpringBoot对静态资源的映射规则

Scroll Down

前言

使用SpringBoot进行web开发的步骤:

1.创建SpringBoot应用,选中我们需要的模块;

2.SpringBoot已经默认讲这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来;

3.自己编写业务代码;

SpringBoot对静态资源的映射规则

在SpringBoot中SpringMVC的相关配置都在WebMVCAutoConfiguration类中,在此类中有一个addResourcesHandler()方法

public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!this.resourceProperties.isAddMappings()) {
		logger.debug("Default resource handling disabled");
		return;
	}
	Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
	CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
	if (!registry.hasMappingForPattern("/webjars/**")) {
		customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
		.addResourceLocations("classpath:/META-INF/resources/webjars/")
		.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
	}
	String staticPathPattern = this.mvcProperties.getStaticPathPattern();
	if (!registry.hasMappingForPattern(staticPathPattern)) {
		customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
			.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
			.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
	}
}

1.所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源;

   **webjars:**以jar包的方式引入静态资源
image.png
例如上面的引入jQuery的webjars后访问jQuery.js只需要访问localhost:8080/webjars/jquery/3.3.1/jquery.js路径即可

2."/**"访问当前项目的任何资源,(静态资源的文件夹)

"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/",
"/"

3.配置欢迎页映射

WebMvcAutoConfiguration类里有配置欢迎页映射的方法

@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
				FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
			WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
			welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
			return welcomePageHandlerMapping;
		}

通过源码可知,静态资源文件夹下的所有index.html页面,被"/**"映射

4.所有的**/favicon.ico都是在静态资源文件夹下,用来设置网页图标