springboot(7)——访问静态资源&WebJars&图标&欢迎页面

目录html

 

概述前端

 1.访问WebJar资源java

2.访问静态资源jquery

3.favicon.ico图标web

4.欢迎页面spring


概述

使用Springboot进行web开发时,boot底层实际用的就是springmvc,项目中加入spring-boot-starter-web依赖,就会提供嵌入的tomcat以及mvc依赖,能够查看依赖树编程

 1.访问WebJar资源

Web前端使用了愈来愈多的JS或CSS,如jQuery, Backbone.js 和Bootstrap。通常状况下,咱们是将这些Web资源拷贝到Java的目录下,经过手工进行管理,这种通方式容易致使文件混乱、版本不一致等问题。tomcat

WebJars是将这些通用的Web前端资源打包成Java的Jar包,而后借助Maven工具对其管理,保证这些Web资源版本惟一性,升级也比较容易。关于webjars资源,有一个专门的网站https://www.webjars.org/,咱们能够到这个网站上找到本身须要的资源,在本身的工程中添加入maven依赖,便可直接使用这些资源了。mvc

直接访问app

 

原理过程:

查看引入的jar包

SpringBoot将对/webjars/**的访问重定向到classpath:/META-INF/resources/webjars/**

源码以下

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

            }
        }

因此可以使用目录 localhost:8080/webjars/jquery/3.3.1/jquery.js访问静态资源

2.访问静态资源

SpringBoot默认配置下,提供了如下几个静态资源目录:

/static:classpath:/static/

/public:classpath:/public/

/resources:classpath:/resources/

/META-INF/resources:classpath:/META-INF/resources/

固然,能够经过spring.resources.static-locations配置指定静态文件的位置。

#配置静态资源
    spring:
      resources:
        #指定静态资源目录
        static-locations: classpath:/mystatic/

 

3.favicon.ico图标

若是在配置的静态资源目录中有favicon.ico文件,SpringBoot会自动将其设置为应用图标。

在Spring Boot的配置文件application.properites中能够添加配置项spring.mvc.favicon.enabled=false关闭默认的favicon,

4.欢迎页面

SpringBoot支持静态和模板欢迎页,它首先在静态资源目录查看index.html文件作为首页,被/**映射

                         公众号 java一号 更多java实战项目资料、技术干活。更重要的是小猿愿成为你编程路上的一个朋友!

文章首发地址: www.javayihao.top

首发公众号: java一号

相关文章
相关标签/搜索