SpringBoot静态资源导入探究

我们通过IDEA新建一个SpringBoot项目后,目录结构如下

在这里插入图片描述

通过Shift+Ctrl+N快捷键搜索WebMvcAutoConfiguration.class文件,进入此文件。我们在这个文件中找到一个名为WebMvcAutoConfigurationAdapter的静态类,找到此类下的addResourceHandlers(ResourceHandlerRegistry registry)方法,
代码如下:


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

            }
        }

方法的开始使用if语句判断是否有自定义配置,如果有则在日志输出**“默认资源配置失效”**。如果没有则继续下面的操作。下面的代码为我们提供了两种途径处理静态资源:

  1. webjars 访问方式为 localhost:8080/webjars/
  2. public,static,/**,resources 访问方式为localhost:8080/

优先级顺序为:META-INF/resources > resources > static > public。

	我们可以通过在配置文件中修改spring.mvc.static-path-pattern来修改默认的映射路径,例如我修改为/hong/**,运行的时候访问 http://localhost:8080/hong/index.html 才会对应到index.html的页面。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值