随笔 - 434,  文章 - 0,  评论 - 463,  阅读 - 46万

步骤 1 彻底搞定静态资源

先找到这个类:WebMvcAutoConfiguration,在这个jar包里面,还是自动配置

WebMvcAutoConfiguration中有一个 addResourceHandlers 方法,这是自动配置静态资源目录的。

public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                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});
                    }

                });
            }
        }

先看这个:

if (!this.resourceProperties.isAddMappings()) {
   logger.debug("Default resource handling disabled");
}

如果isAddMappings为false,就打印默认资源映射路径失效了。isAddMappings方法其实就是返回一个addMappings变量(在WebProperties中)

addMappings的含义就是运行访问静态资源,如果你设置成false,就是禁用所有静态资源映射。

站长在写这篇教程的时候,用的SpringBoot版本为2.5.1,是目前最新的版本。发现和之前的版本比起来,改动还是很大的。翻源码很麻烦,我就直接告诉你结论就行了。

默认的静态资源目录是:

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

这点和以前是一样的,测试一下

image

访问什么路径能返回public.js呢?

在WebMvcProperties中,有一个staticPathPattern属性。

image

默认就是/**,所以,无论你访问什么,都可以被静态资源处理器接受。

启动项目,访问http://localhost:8888/public.js

[图片上传失败…(image-1fcffe-1625294071735)]

成功访问,现在我们手动添加一个静态目录。

spring:
  profiles: test
  resources:
    static-locations: [classpath:/my/]

访问http://localhost:8888/my.txt,也成功了。

最后,把静态资源开关关掉。

spring:
  profiles: test
  resources:
    static-locations: [classpath:/my/]
    add-mappings: false

这样就访问不到任何静态资源了,不过一般来说不用关。

转载自:http://java18.cn/

posted on   剽悍一小兔  阅读(24)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)

< 2025年3月 >
23 24 25 26 27 28 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 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示