我们都知道静态资源放在resource文件夹中的,那么springboot是怎么找到静态资源的路径,以及我们怎么自定义路径访问,本文将带你一探究竟
只要静态资源放在类路径下: called /static
(or /public
or /resources
or /META-INF/resources
访问 : 当前项目根路径/ + 静态资源名
原理: 静态映射/**。
请求进来,先去找Controller看能不能处理。
如不能处理的所有请求又都交给静态资源处理器。
静态资源也找不到则响应404页面。
改变默认的静态资源路径
spring:
mvc:
#这个叫静态资源访问前缀
static-path-pattern: /res/**
#这个叫静态资源访问路径
resources:
static-locations: [classpath:/haha/]
默认无前缀
spring:
mvc:
static-path-pattern: /res/**
当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找
自动映射 /webjars/**
https://www.webjars.org/
这里是引入的webjars的jquery依赖
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.5.1version>
dependency>
访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径
spring:
# mvc:
# static-path-pattern: /res/** 这个会导致welcome page功能失效
resources:
static-locations: [classpath:/haha/]
Favicon
favicon.ico 放在静态资源目录下即可。
spring:
# mvc:
# static-path-pattern: /res/** 这个会导致 Favicon 功能失效
浏览器会发送/favicon.ico请求获取到图标,整个session期间不再获取
1.SpringBoot启动默认加载 xxxAutoConfiguration 类(在这里加载的是WebMvcAutoConfiguration自动配置类)
这里就使用了自动配置原理,自动配置原理相关文章
2.SpringMVC功能的自动配置类 WebMvcAutoConfiguration,生效
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
//多余代码省略
}
//每一个配置类只有一个有参构造器(这里例子是WebMvcAutoConfigurationAdapter)
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
//@EnableConfigurationProperties
//注解的作用是:让使用了 @ConfigurationProperties 注解的类生效,并且将该类注入到 IOC 容器中,交由 IOC 容器进行管理
//在这里是把WebMvcProperties和WebProperties注入到IOC容器中
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {
//有参构造器所有参数的值都会从容器中确定
public WebMvcAutoConfigurationAdapter(
//ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
ResourceProperties resourceProperties,
//WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
WebMvcProperties mvcProperties,
//ListableBeanFactory beanFactory Spring的beanFactory
ListableBeanFactory beanFactory,
//HttpMessageConverters 找到所有的HttpMessageConverters
ObjectProvider<HttpMessageConverters> messageConvertersProvider,
//ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。
ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
//DispatcherServletPath DispatcherServlet处理的路径
ObjectProvider<DispatcherServletPath> dispatcherServletPath,
//ServletRegistrationBean 给应用注册Servlet.Filter....
ObjectProvider<ServletRegistrationBean<?>> servletRegistrations
)
{
this.resourceProperties = resourceProperties;
this.mvcProperties = mvcProperties;
this.beanFactory = beanFactory;
this.messageConvertersProvider = messageConvertersProvider;
this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
this.dispatcherServletPath = dispatcherServletPath;
this.servletRegistrations = servletRegistrations;
}
}
//配置文件的相关属性和xxx进行了绑定。WebMvcProperties==**spring.mvc**.ResourceProperties==**spring.resources**
@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {
}
//配置文件的相关属性和xxx进行了绑定。WebMvcProperties==**spring.mvc**.ResourceProperties==**spring.resources**
@ConfigurationProperties("spring.web")
public class WebProperties {
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//如果禁用掉静态资源的路径映射,那么下面的资源都不会被处理,对应到显示层面就是所有的静态资源不会被访问
//4.1.1.1.1实现看这里
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
//webjars的规则
if (!registry.hasMappingForPattern("/webjars/**")) {
//映射的是webjars下面的规则
//4.1.1.1.2看这里
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//如果没有配置映射规则,则就进入默认的映射规则
if (!registry.hasMappingForPattern(staticPathPattern)) {
//映射的是staticPathPattern下面的规则
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
4.1.1.1.1在yaml配置文件中规定静态资源是否能访问
spring:
web:
resources:
#如果 add-mappings为true就能访问路径下的所有静态资源
#如果 add-mappings为false就禁用掉访问访问路径下的所有静态资源
add-mappings: true
4.1.1.1.2静态资源访问前缀和映射路径
//webjars默认的静态资源访问前缀的"/webjars/**"
//会映射到的路径:
//"classpath:/META-INF/resources/webjars/"
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/")
//staticPathPattern默认的静态资源访问前缀的"/**"
//会映射到的路径:
//"classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/"
public class WebMvcProperties {
private String staticPathPattern = "/**";
}
public static class Resources {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
}
//HandlerMapping:处理器映射。保存了每一个Handler能处理哪些请求。
@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));
welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
return welcomePageHandlerMapping;
}
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
//欢迎页要存在,并且必须要和/**相等才能进入
if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
//要用欢迎页功能,必须是/**
logger.info("Adding welcome page: " + welcomePage.get());
setRootViewName("forward:index.html");
}
else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
// 调用Controller /index
logger.info("Adding welcome page template: index");
setRootViewName("index");
}
}