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

时间:2019-11-07
本文章向大家介绍springboot(7)——访问静态资源&WebJars&图标&欢迎页面,主要包括springboot(7)——访问静态资源&WebJars&图标&欢迎页面使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

目录

概述

 1.访问WebJar资源

2.访问静态资源

3.favicon.ico图标

4.欢迎页面


概述

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

 1.访问WebJar资源

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

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

直接访问

原理过程:

查看引入的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一号

原文地址:https://www.cnblogs.com/javayihao/p/11812575.html