springboot对静态资源的映射规则

SpringBoot对css等静态文件的存放位置有规定。而SpringBoot把Spring MVC的相关配置全都放在了WebMvcAutoConfiguration.java里面。在该文件里面有一个添加资源映射的方法。其代码如下:

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();

                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();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
			this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }
            }
        }

下面是springboot的四条映射规则

  1. 所有的/webjars/**都去classpath:/META-INF/resources/webjars/找资源,webjars意思是以jar包的方式引入静态资源。
    以引入jquery为例,我们进入www.webjars.org网站,网站页面如图所示:
    www.webjars.org

如上图所示,我们点击箭头所指的Maven选项,网站就会显示对应引入文件的依赖代码。如图所示:
在这里插入图片描述
我们还可以在左边选择jquery的版本,选择好后,复制红框里面的代码,将代码粘贴在pom.xml文件中,到此,我们顺利的引入jquery-webjar,然后idea会自动帮我们下载jqueryjar包。下载好的jquery包在External Libraries下,其具体结果如下图:
在这里插入图片描述
下载好之后,我们可以在浏览器中访问jquery.js文件 ,我们在浏览器输入http://localhost:8080/webjars/jquery/3.5.1/jquery.js就可以访问jquery.js文件,文件内容部分截图如下:
在这里插入图片描述

  1. "/**"访问当前项目的任何资源(静态资源的文件夹),我们可以将静态文件存放在以下的几个路径的文件夹。
"classpath:/META-INF/resources/",
 "classpath:/resources/",
 "classpath:/static/",
 "classpath:/public/"
 "/":当前项目的根路径

localhost:8080/abc 去静态资源文件夹里面找abc

  1. 欢迎页,静态资源文件夹下的所有index.html页面被“/**”映射。在浏览器中输入localhost:8080/,系统会找到你所编写的index.html文件。
  2. 所有的**/favicon.ico(页面的图标)都是在静态资源文件下找 。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值