SpringBoot对静态资源的映射规则

本文探讨了SpringBoot中静态资源的映射规则,包括/webjars/**对应的classpath资源,/**查找的静态文件夹,欢迎页面的设定,以及favicon.ico的处理。通过WebMvcAutoConfiguration的addResourceHandlers方法进行配置。
摘要由CSDN通过智能技术生成

在WebMvcAutoConfiguration类中有相对应的方法addResourceHandlers

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();
       //静态资源的映射是在/webjars/目录下的
         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));
         }
       }
      }

		//配置欢迎页面
		@Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
            WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
            welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
            return welcomePageHandlerMapping;
        }

1)、所有的/webjars/**,都要去classpath:/META-INFO/resources/webjars/目录下找资源;

webjars: 以jar包的方式引入静态资源

例如引入jQuery,直接到webjars官网,复制相关依赖,粘贴到pom.xml中就可以使用jQuery的功能。

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>

在这里插入图片描述

  1. 、/**,当前项目的静态资源放在以下的文件夹中是有效的,SpringBoot会在特定的静态文件夹下找映射

classpath:/META-INf/resources/

classpath: /resources/

classpath:/static

classpath:/public

/: 指的是当前项目的根目录。默认情况下,java是源码的根目录,resources是配置文件的根目录

在这里插入图片描述

3)、欢迎页面其实就是在浏览器中输入localhost:8080/时出现的页面,这个我们都知道是index.html/index.jsp页面,这个就是欢迎页面

4)、所有在静态资源文件夹下被命名为favicon.ico的图片都被作为当前项目的网页图标

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值