欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot对静态资源的映射规则

程序员文章站 2022-07-10 20:00:30
...

SpringBoot对静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resource",ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware{
	//可以设置和静态资源有关的参数,缓存时间等
@Override
	public void addResource(ResourceHandlerRegistry registry){
		if(!this.resourceProperties.isAddMappings()){
			logger.debug("Default resource handing disabled");
			return;
		}
		Integer cachePeriod = this.resourceProperties.getCachePeriod();
		if(!registry.hasMappingForPattern("/webjar/**")){
			customizeResourceHandlerRegistration(
					registry.addResourceHandler("/webjar/**")
							.addResourceLocations(
									"classpath:/META-INF/resources/webjars/")
					.setCachePeriod(cachePeriod));				
		}
		String staticPathPattern = this.mvcProperties.getStaticPathPattern();
		if(!registry.hasMappingForPattern(staticPathPattern)){
			customizeResourceHandlerRegistration(
					registry.addResourceHandler(staticPathPattern)
		                    .addResourceLocations(
		                    		this.resourceProperties.getStaticLocations())
		            .setCachePeriod(cachePeriod));	        		
		}
	}

1)、所有/webjar/**,都去classpath:/META-INF/resources/webjars/找资源;
webjar:以jar包的方式引入静态资源;
https://www.webjars.org/
SpringBoot对静态资源的映射规则SpringBoot对静态资源的映射规则
localhost:8080/webjars/jquery/3.3.1/jquery.js

<!--引入jquery-webjar-->
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>jquery</artifactId>
	<version>3.3.1</version>
</dependency>

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

String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if(!registry.hasMappingForPattern(staticPathPattern)){
	customizeResourceHandlerRegistration(
		registry.addResourceHandler(staticPathPattern)
		         .addResourceLocations(
		              this.resourceProperties.getStaticLocations())
		        .setCachePeriod(cachePeriod));	        		
}
public String getStaticPathPattern() {
	return this.staticPathPattern;
}
private String staticPathPattern = "/**";
public String[] getStaticLocations() {
	return this.staticLocations;
}
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
		"classpath:/META-INF/resources/", "classpath:/resources/",
		"classpath:/static/", "classpath:/public/" };
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
"/":当前项目的根路径