0
点赞
收藏
分享

微信扫一扫

【SpringBoot】7、静态资源处理【狂神篇】

1、源码分析

@Configuration
...
public class WebMvcAutoConfiguration {
    @Configuration
    ...
    // 静态内部类    
    public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {
        // 添加资源处理
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            // 判断是否有自定义资源路径
            if (!this.resourceProperties.isAddMappings()) {
                // 如果有自定义资源路径,则默认资源失效
                logger.debug("Default resource handling disabled");
            } else {
                // 没有自定义资源路径,就在默认路径下查找
                // 方式一:webjars
                this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
                // 方式二:四个固定路径
                this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
                    registration.addResourceLocations(this.resourceProperties.getStaticLocations());
                    if (this.servletContext != null) {
                        ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                        registration.addResourceLocations(new Resource[]{resource});
                    }

                });
            }
        }
    }    
}
  • this.resourceProperties.getStaticLocations()
@ConfigurationProperties
...
public class WebProperties {
    ...
    // 静态内部类
    public static class Resources {
        // 四个默认路径
        private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
        private String[] staticLocations;
        
        ...
        
        public String[] getStaticLocations() {
            return this.staticLocations;
        }
    }     
}     

2、方式一:webjars

Webjars本质就是以jar包的方式引入静态资源

官网:https://www.webjars.org

  • 导jar包
<!--导入jar包-->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>

在这里插入图片描述

  • 页面使用

在这里插入图片描述

  • 省略版本号

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>webjars-locator</artifactId>
        <version>0.42</version>
    </dependency>
    

在这里插入图片描述

3、方式二:4个固定路径

// 四个默认路径:优先级从前向后,由高到低
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{
    "classpath:/META-INF/resources/",                                                     "classpath:/resources/",                                                               "classpath:/static/",                                                                 "classpath:/public/"
};

在这里插入图片描述

4、方式三:自定义路径

  • application.yml
spring:
  web:
    resources:
      static-locations:
       - classpath:/js/
       - classpath:/css/

在这里插入图片描述

举报

相关推荐

0 条评论