Spring Boot与Web开发-静态资源的映射
使用Spring Boot:
- 创建SpringBoot,选中我们需要的模块
- SpringBoot 默认配置好场景,只需要在配置文件中指定少量配置
- 编写业务代码
对静态资源的映射规则
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
//可以设置缓存有关的参数,缓存等
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
//欢迎页的映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
return welcomePageHandlerMapping;
}
-
所有 /webjars/** 的请求,都去classpath:/META-INF/resources/webjars/找资源;
webjars:以jar包的方式引入静态资源;
eg: META-INF esourceswebjarsjquery3.3.1jquery.js
发送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>
-
“/**” 访问当前项目的任何资源
"classpath:/META-INF/resources/" "classpath:/resources/" "classpath:/static/" "classpath:/public/" "/" //当前项目的根路径
- classpath: 是类路径下的目录:java和resource下
-
首页;静态资源文件夹下的所有index.html页面,被“/**”映射;
localhost:8080/ 找index页面
-
所有的 **/favicon.ico都是在静态资源文件下找;将图片改为favicon.ico,可以自动映射过去,首页图标
-
自定义静态资源文件夹路径:
spring.resources.static-locations=classpath:/hello/