• SpringBoot——静态资源及原理


    优质博文:IT-BLOG-CN

    一、使用 SpringBoot 的步骤

    【1】创建SpringBoot应用,选中自己需要的模块。
    【2】SpringBoot已经默认将这些场景配置好,只需要在配置文件中指定少量配置就可以运行起来。
    【3】编写业务逻辑代码。

    二、自动配置原理

    我们要了解SpringBoot帮我们配置了什么?能不能修改?能修改那些配置?能不能扩展等等。
    【1】xxxAutoConfiguration:帮我们给容器中自动配置组件。
    【2】xxxProperties:配置来封装配置文件的内容。

    三、SpringBoot 对静态资源的映射规则

    当创建一个jar工程时,想引入css等静态资源时,需要遵守SpringBoot的静态资源映射关系,通过WebMvcAutoConfiguration查看静态配置资源的规则。

    //添加资源映射addResourceHandlers
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if(!this.resourceProperties.isAddMappings()) {
            logger.debug("Default resource handling disabled");
        } else {
            Integer cachePeriod = this.resourceProperties.getCachePeriod();
            if(!registry.hasMappingForPattern("/webjars/**")) {
                this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod));
            }
            // 3中说明
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            if(!registry.hasMappingForPattern(staticPathPattern)) {
                this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    【1】如上配置的/webjars/**可知,所有的获取都去classpath:/META-INF/resources/webjars下找资源。而webjar实际上是以jar包的方式引入静态资源,可以参考官方文档

    ▶ 获取Jqueryjar包依赖:

    <dependency>
        <groupId>org.webjarsgroupId>
        <artifactId>jqueryartifactId>
        <version>3.3.1-1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    ▶ 进入导入的Jqueryjar包中,查看目录结构如下:所有的 /webjars/**,都去classpath:/META‐INF/resources/webjars/找资源。例如:localhost:8080/webjars/jquery/3.3.1/jquery.js(在访问的时候,只需要写webjars下面资源的名称即可)

    【2】同时可以在ResourceProperties设置与静态资源有关的参数,例如缓存时间。

    @ConfigurationProperties(
        prefix = "spring.resources",
        ignoreUnknownFields = false
    )
    public class ResourceProperties implements ResourceLoaderAware, InitializingBean {
    
    • 1
    • 2
    • 3
    • 4
    • 5

    【3】除了/webjars/**,我们看下紧接着的第二个方法获取staticPathPattern路径:最终方法指向 =/**访问当前项目的任何资源(静态资源的文件夹)。

    this.staticPathPattern = "/**";
    
    • 1

    如果没有进行处理,就会从如下路径中进行获取:

    classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" "/":当前项目根路径 ,以上就是静态资源的文件处理。
    
    • 1
    private static final String[] SERVLET_RESOURCE_LOCATIONS = new String[]{"/"};//当前项目根路径
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/",
    "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
    private static final String[] RESOURCE_LOCATIONS;
    static {
        RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length + SERVLET_RESOURCE_LOCATIONS.length];
        System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0, SERVLET_RESOURCE_LOCATIONS.length);
        System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, SERVLET_RESOURCE_LOCATIONS.length,
        CLASSPATH_RESOURCE_LOCATIONS.length);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    【4】获取欢迎页,通过如下代码可知:静态资源文件夹下的所有index.html页面,都被“/**”映射。(localhost:8080——就能够访问首页)

    // 获取欢迎页
    @Bean
    public WebMvcAutoConfiguration.WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {
            return new WebMvcAutoConfiguration.WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
            this.mvcProperties.getStaticPathPattern());
    }
    
    //进入如上的resourceProperties.getWelcomePage()方法,会获取到当前项目路径下的index.html文件。
    private String[] getStaticWelcomePageLocations() {
        String[] result = new String[this.staticLocations.length];
    
        for(int i = 0; i < result.length; ++i) {
            String location = this.staticLocations[i];
            if(!location.endsWith("/")) {
                location = location + "/";
            }
    
            result[i] = location + "index.html";
        }
    
        return result;
    }
    
    //进入如上的this.mvcProperties.getStaticPathPattern()方法,获取映射的路径
    this.staticPathPattern = "/**";
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    【5】所有的**/favicon.ico都是从静态文件中获取一个favicon.ico文件。图标:​

    @Configuration
    @ConditionalOnProperty(
        value = {"spring.mvc.favicon.enabled"},
        matchIfMissing = true
    )
    public static class FaviconConfiguration {
        private final ResourceProperties resourceProperties;
    
        public FaviconConfiguration(ResourceProperties resourceProperties) {
            this.resourceProperties = resourceProperties;
        }
    
        @Bean
        public SimpleUrlHandlerMapping faviconHandlerMapping() {
            SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
            mapping.setOrder(-2147483647);
            //默认获取图标的位置和名称
            mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
            return mapping;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    【6】也可以在application.properties全局配置文件中自定义静态文件:在配置文件中设置如下,那么默认的就不在生效。

    # 配置文件是一个数组,可以用逗号进行分隔
    spring.resources.static-locations=classpath:/hello/,calsspath:/xxx/
    
    • 1
    • 2
  • 相关阅读:
    从源码到成品应用:互联网医院系统与在线问诊APP的开发全解析
    忘机工尺谱 - 快速打谱软件
    HLS学习1:点灯
    NodeJs的模块化和包
    嵌入式PID算法总结
    【数据结构与算法】动态规划法解题20240302
    Coupang走什么物流?Coupang火箭颜色什么意思?——站斧浏览器
    【UE5 Cesium】19-Cesium for Unreal 建立飞行跟踪器(4)
    周末了,不得找个陪玩打游戏?看我用Python怎么找个最好的
    坐标正反算(含高程),把要素内置化(无需改程序文件,即可更换路线,同时存两条线要素
  • 原文地址:https://blog.csdn.net/zhengzhaoyang122/article/details/134520496