springboot指定首页(静态资源导入)

    科技2022-07-16  116

    ResourceProperties小小的源码分析

    1. 静态资源该放在哪里?2. 首页该如何自动展示?

    1. 静态资源该放在哪里?

    springboot 集成了spring-webmvc,这个都是知道的。 该框架的特点是自动装配。

    先看WebMvcAutoConfiguration自动装配类 public void addResourceHandlers(ResourceHandlerRegistry registry) { // 是否手动配置properties或者yaml指定静态资源放置位置 if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); } else { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); // webjar 无需关注 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)); } } }

    这是mvc帮我找到的资源位置 点进出跳到ResourceProperties这个类了 然后在点,找到了它是全局的字符数组,这里看着好像是个空的 再看构造器,赋值了! 数组是这个东西,不就是类路径resouces目录下嘛

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[] {"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

    可以在resources下传教META-INF/resources, static/public/resources这四个文件夹,通过localhost:8080/xxx访问到里面的静态资源。 还有一个没创建。

    优先级 resources > static 默认 > public

    2. 首页该如何自动展示?

    找到首页,在WebMvcAutoConfiguration mvc相关得配置类中寻找 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"); }

    也是同上面放资源得数组一样。放在四个目录下面。 只要是index.html就是识别为首页。便不会404.

    Processed: 0.009, SQL: 8