【源码分析】SpringBoot 如何访问工程目录下的静态资源? ​

程序员考拉

共 7728字,需浏览 16分钟

 · 2021-06-24

公众号关注 “GitHub今日热榜
设为 “星标”,带你挖掘更多开发神器!






1、牛刀小试


1.1 图片静态资源的访问


先看官方怎么说,点击链接,打开 SpringBoot官方文档 


文档中明确指出:/static (or /public or /resources or /META-INF/resources) ,这几个目录是SpringBoot放置静态资源的目录,只要把静态资源放到这几个目录下,就能直接访问到。


新建 Spingboot web项目试下,新项目只有 /static 目录 ,手动创建其他几个静态资源文件夹,每个目录添加1张图片


启动项目,分别访问这四张图片:


发现图片均可访问,文档说的对,果然没骗人,由此我们认定 SpringBoot 访问静态资源 :当前项目根路径 + / + 静态资源名


1.2 为静态资源添加访问前缀


By default, resources are mapped on /**, but you can tune that with the spring.mvc.static-path-pattern property. For instance, relocating all resources to /resources/** can be achieved as follows:

PropertiesYaml
spring.mvc.static-path-pattern=/resources/**

[点击并拖拽以移动]


文档又解释了一下,说,默认情况下SpringBoot是帮你映射的路径是 /** ,但是,如果你想加一个前缀也可以,比如  /res/


技术圈有句话:先有业务才有技术,SpringBoot官方考虑到某些网站添加了登录验证,一般需要登录后才能访问项目中的资源,为了登录页样式也能正常显示,方便放行静态资源,直接给所有静态资源添加一个前缀,既可统一拦截,又可统一放开操作:在配置文件application.properties中添加


spring.mvc.static-path-pattern=/res/**


添加完再去访问原来的dog图片链接:http://localhost:8080/dog.jpeg


但是访问:http://localhost:8080/res/dog.jpeg 发现这才可以


1.3  WelCome Page 的奇妙跳转


7.1.6. Welcome Page
Spring Boot supports both static and templated welcome pages. It first looks for an index.html file in the configured static content locations. If one is not found, it then looks for an index template. If either is found, it is automatically used as the welcome page of the application.


文档说把一个名称叫 index.html 的文件放到任意的静态目录下,访问  http://localhost:8080 即可到达,意思就是给你一个首页跳转的快捷方式(注意:需把1.2 的配置路径去掉,否则会导致welcome page功能失效,后面源码分析会说到)


新建html,放到  /static 下,访问:


2、那么,SpringBoot是如何做到的呢?


接下来看源码探究 SpringBoot 静态资源配置原理。


源码位置在:spring-boot-autoconfigure-2.5.1.jar  这个jar里面,具体的目录如下:


/spring-boot-autoconfigure-2.5.1.jar!/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.class


WebMvcAutoConfiguration 类里面找到 addResourceHandlers 方法,顾名思义 添加资源处理器


@Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            // 相当于一个开关去控制静态资源处理器的加载,默认为true,设置为false就会禁止所有规则
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            //第一个就配置webjars的访问规则,规定在类路径的/META-INF/resources/webjars/路径下,感兴趣的同学可以点进方法去,里面还配置了webjars的浏览器端缓存时间,是在application。propertities中的一个配置项 spring.web.resources.cache.period
            addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
            //这里配置了静态资源的四个访问路径
            addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
                registration.addResourceLocations(this.resourceProperties.getStaticLocations());
                if (this.servletContext != null) {
                    ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
                    registration.addResourceLocations(resource);
                }
            });
        }


第一个if判断 this.resourceProperties.isAddMappings()  去配置文件获取

spring.resources 这个属性,默认是 true , 如果设置为false 那么就等于禁用掉所有的静态资源映射功能,不行就试一下


#springapplication.propertities中配置
spring.web.resources.add-mappings=false


重启项目,发现首页无法访问了...


改回 true ,首页就又可以访问了


不要停留,继续看第二个 addResourceHandler 方法,打断点看看这个方法添加了什么规则 



没错,第二个addResourceHandler 方法就表明  / ** 下的所有请求,都在这四个默认的位置去找静态资源映射 ,这四个目录在官方文档中提到过。


另外,访问路径前缀是在 this.mvcProperties.getStaticPathPattern() 获取的,配置上:


spring.mvc.static-path-pattern=/res/**


打断点如下:


注意:所有的请求先去controller控制器找映射,找不到,再来静态资源映射器。

到这里解决了静态资源目录的问题。


马不停蹄,探究  Welcome Page 的事情 


还是在 WebMvcAutoConfiguration 这个类:搜索  “WelcomePage” :


@Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
                FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider)
 
{
            WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
                    new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
                    this.mvcProperties.getStaticPathPattern());
            welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
            welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
            return welcomePageHandlerMapping;
        }


把 WelcomePageHandlerMapping 的有参构造也拿来


WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
            ApplicationContext applicationContext, Resource welcomePage, String staticPathPattern) {
        if (welcomePage != null && "/**".equals(staticPathPattern)) {
            logger.info("Adding welcome page: " + welcomePage);
            setRootViewName("forward:index.html");
        }
        else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
            logger.info("Adding welcome page template: index");
            setRootViewName("index");
        }
    }


根据有参构造可以看出来,只有 欢迎页这个资源存在,并且 静态资源访问路径是 /** ,才能重定向到indes.html ,否则就会去找 Controller 处理。


这就解释了,上面为什么配置了静态资源访问路径 为/res/** 后导致首页无法访问到的问题。



作者:Dkwestworld

出处:cnblogs.com/dk1024/p/14920522.html









关注GitHub今日热榜,专注挖掘好用的开发工具,致力于分享优质高效的工具、资源、插件等,助力开发者成长!






点个在看,你最好看


浏览 20
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报