springboot指定首页(静态资源导入)

1. 静态资源该放在哪里?

springboot 集成了spring-webmvc,这个都是知道的。
该框架的特点是自动装配。

  1. 先看WebMvcAutoConfiguration自动装配类
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
 	 // 是否手动配置properties或者yaml指定静态资源放置位置
     if (!this.resourceProperties.isAddMappings()) {
         logger.debug("Default resource handling disabled");
     } else {
         Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
         CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
		 // webjar 无需关注
         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));
         }

     }
 }

这是mvc帮我找到的资源位置

点进出跳到ResourceProperties这个类了

然后在点,找到了它是全局的字符数组,这里看着好像是个空的

再看构造器,赋值了!

数组是这个东西,不就是类路径resouces目录下嘛

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

可以在resources下传教META-INF/resources, static/public/resources这四个文件夹,通过localhost:8080/xxx访问到里面的静态资源。

还有一个没创建。

  • 优先级
    resources > static 默认 > public

2. 首页该如何自动展示?

  1. 找到首页,在WebMvcAutoConfiguration mvc相关得配置类中寻找
        private Optional<Resource> getWelcomePage() {
        	// 位置同上
            String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
            return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
        }

        private Resource getIndexHtml(String location) {
            return this.resourceLoader.getResource(location + "index.html");
        }

也是同上面放资源得数组一样。放在四个目录下面。

只要是index.html就是识别为首页。便不会404.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值