SpringBoot mapping rules for static resources, WebMvcAutoConfiguration class source code analysis

SpringBoot's mapping rules for static resources


  1. The default static resource path is configured in this source code
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
    
    

	private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
    
     "classpath:/META-INF/resources/",
			"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
  1. This code configures the externally imported static resource file structure
@Override
		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));
			}
		}

webjars website
https://www.webjars.org/
introduces jQuery dependency

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.5.1</version>
</dependency>

Insert picture description here
This directory is consistent with the mapping path of the source code

http://localhost:8090/webjars/jquery/3.5.1/jquery.js
enter the above website in the browser address bar to access

  1. The wording of "/**": access any resource of the current project
"classpath:/META-INF/resources/",
"classpath:/resources/", 
"classpath:/static/", 
"classpath:/public/"

The classpath is the resource in the figure below, which can be accessed by creating META-INF/resources in this directory
Insert picture description here

localhost:8080/abc === Go to static resources to find abc

  1. Welcome page: all index.html pages under the static resource folder; are mapped to
    localhost:8080/ by "/**" to find the index page

Insert picture description here

  1. Configure static resource location
spring.resources.static-locations=classpath:/suitianshuang/

Guess you like

Origin blog.csdn.net/weixin_43941676/article/details/108612578