写在前面:
环境:Spring Boot版本:1.5.10.RELEASE
文章中相关源码的分析,都是以WebMvcAutoConfiguration
类为起点,在其基础上再进行相关的分析。
一、访问/webjars/**路径
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod));
}
}
}
从源码可知,所有/webjars/**
的请求都会到"classpath:/META-INF/resources/webjars/"
路径下寻找相关的资源。
这里解释一下,所谓的webjars即是以jar包的方式引入静态资源。
开发时,我们所需的一些前端资源可以到webjars官网以maven的方式进行引入。
这里以引入jquery为例进行演示:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
引入jquery依赖后,我们在External Libraries下找到如下的结构图。
我们在浏览器地址栏输入localhost:8080/webjars/jquery/3.3.1/jquery.js
将会看到jquery.js的代码。
温馨提示:如果在application.properties中配置server.context-path=/crud
路径后,我们在访问的时候需要添加/crud,如:http://localhost:8080/crud
/webjars/jquery/3.3.1/jquery.js
二、访问/**路径
经上述分析,/**
访问当前项目的任何资源,都去(静态资源的文件夹
)找映射,如下:
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
现有静态资源放在static目录下,我们可以访问http://localhost:8080/asserts/js/Chart.min.js
三、访问/**路径下的欢迎页
首页(index.html)可以存放的位置为静态资源存放的位置。如下
四、访问**/favicon.ico路径
public static class FaviconConfiguration {
private final ResourceProperties resourceProperties;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(this.resourceProperties.getFaviconLocations());
return requestHandler;
}
}
经上分析,favicon.ico存放的位置依然为静态资源文件的路径下。