SpringBoot(6)web开发之静态资源导入

    技术2024-12-26  29

    静态资源

    1.找到自动装配的WebMvcAutoConfiguration.calss 2.找到方法addResourceHandlers:加载资源处理器

    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(); //webjars可以访问静态资源 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(); //WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())):找resourceProperties if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } }

    resourceProperties中定义了CLASSPATH_RESOURCE_LOCATIONS,此处的静态资源可以访问

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

    3.在resources目录下新建这几个文件,访问其中的静态资源。

    Processed: 0.009, SQL: 9