本文以springboot2.2.x为例,讲述框架如何加载前端默认首页资源index.html。
定位到源码:WebMvcAutoConfiguration,该类负责加载index.html资源,具体负责为:welcomePageHandlerMapping注入bean,可以很清楚的看到最终搜索index资源的方法为getIndexHtml,该方法会默认对五个地址进行资源查看,查找的顺序是 classpath:/META-INF/resources/ ;classpath:/resources/;classpath:/static/;classpath:/public/;/;
@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));
return welcomePageHandlerMapping;
}
private Optional<Resource> getWelcomePage() {
String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}
并且一定要注意项目正常启动后的 项目target(编译好的)文件夹中是否有编译html文件,作者之前因项目中的pom.xml配置build/resources中没有将html资源纳入导致springboot框架找不到页面资源定位了很久原因。以下就是当时定位了很久的pom文件配置,下面的配置把.html资源加在include中即可(或者直接将includes删除也可以达到相同目的)
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>