7、SpringBoot:Web开发静态资源处理

SpringBoot静态资源处理与首页配置
本文介绍SpringBoot中静态资源的处理规则,包括webjars的使用、静态资源映射规则及自定义静态资源路径。同时,探讨了首页处理方法及网站图标配置。

6.1、Web开发探究

6.1.1、简介

其实SpringBoot的东西用起来非常简单,因为SpringBoot最大的特点就是自动装配。

使用SpringBoot的步骤:

  1. 创建一个SpringBoot应用,选择我们需要的模块,SpringBoot就会默认将我们的需要的模块自动配置好。
  2. 手动在配置文件中配置部分配置项目就可以运行起来了
  3. 谆嘱编写业务代码,不需要考虑以前那样一大堆的配置了

要熟悉掌握开发,之前学习的自动配置的原理就一定要搞明白!

比如SpringBoot到底帮我们配置了什么?我们能修改哪些配置?我们能不能扩展?

  • 想容器中自动配置组件: ***Autoconfiguration
  • 自动配置类,封装配置文件的内容:***Properties

没事就找找类,看看自动装配原理!

6.2、静态资源处理

6.2.1、静态资源映射规则

首先,我们搭建一个普通的SpringBoot项目,回顾一下HelloWorld程序

写请求非常简单,那我们要引入我们前端的资源,我们项目中有许多的静态资源,比如css,js等文件,这个SpringBoot怎么处理呢?

如果我们是一个web应用,我们的main下会有一个webapp,我们以前都是将所有的页面导到这里面的!但是我们现在的pom呢,打包方式是jar的方式,那么这种方式SpringBoot能不能给我们写页面呢?当然是可以的,但是SpringBoot对于静态资源放置的位置,是有规定的!

我们先来聊聊这个静态资源映射规则:

SpringBoot中,SpringMVC的web配置都在WebMvcAutoConfiguration这个配置类里面;

我们可以区看看WebMvcAutoConfiguratioAdapter中有很多配置方法;

有一个方法,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));
        }

    }
}

读一下源代码:比如所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源;

6.2.2、什么是webjars 呢?

Webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,直接导入即可。

使用SpringBoot需要使用Webjars,我们可以去搜索一下:

网站:https://www.webjars.org

要使用jQuery,我们只要要引入jQuery对应版本的pom依赖即可!

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

导入完毕,查看webjars目录结构,并访问Jquery.js文件!
在这里插入图片描述
访问:只要是静态资源,SpringBoot就会去对应的路径寻找资源,我们这里访问:http://localhost:8080/webjars/jquery/3.5.1/jquery.js
在这里插入图片描述

6.2.3、第二种静态资源映射规则

那我们项目中要是使用自己的静态资源该怎么导入呢?我们看一下代码:;

我们区staticPathPattern发现第二种映射规则:/**,访问当前的项目任意资源,它会去找resourceProperties这个类,我们可以点进去看一下:

    //找到路径
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
    private String[] staticLocations;
    private boolean addMappings;
    private final ResourceProperties.Chain chain;
    private final ResourceProperties.Cache cache;

    public ResourceProperties() {
    	//找到对应的值
        this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
        this.addMappings = true;
        this.chain = new ResourceProperties.Chain();
        this.cache = new ResourceProperties.Cache();
    }

	//进入方法
    public String[] getStaticLocations() {
        return this.staticLocations;
    }

ResourceProperties可以设置和我们静态资源有关的参数;这里指向了它回去寻找资源的文件夹,即上面的数组的内容

所以得出结论,以下四个目录存放的静态资源都可以被我们识别;

"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"

在这里插入图片描述
优先级:resources>static>public

我们可以在resources根目录下新建对应的文件夹,都可以存放我们的静态文件;

比如我们访问 http://localhost:8080/1.js , 他就会去这些文件夹中寻找对应的静态资源文件;

6.2.4、自定义静态资源路径

我们也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置;

spring.resources.static-locations=classpath:/coding/,classpath:/chen/

6.3、首页处理

静态资源文件夹说完后,我们继续向下看源码!可以看到一个欢迎页的映射,这就是我们的首页!

@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));
    welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
    return welcomePageHandlerMapping;
}

我们继续看

private Optional<Resource> getWelcomePage() {
    String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
    //::是java8 中新引入的运算符
    //Class::function的时候function是属于Class的,应该是静态方法。
    //this::function的function是属于这个对象的
    //简而言之,就是一种语法糖而已,是一种简写
    return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}

// 欢迎页就是一个location下的的 index.html 而已
private Resource getIndexHtml(String location) {
    return this.resourceLoader.getResource(location + "index.html");
}

欢迎页,静态资源文件夹下的所有index.html页面;被/**映射。

比如我访问 http://localhost:8080/ ,就会找静态资源文件夹下的 index.html

新建一个 index.html ,在我们上面的3个目录中任意一个;然后访问测试 http://localhost:8080/ 看结果!

关于网站图标说明:

与其他静态资源一样,Spring Boot在配置的静态内容位置中查找 favicon.ico。如果存在这样的文件,它将自动用作应用程序的favicon。

以<version>2.1.7.RELEASE </ version>为例子,高版本已经取消
  1. 关闭SpringBoot默认图标
#关闭默认图标
spring.mvc.favicon.enabled=false
  1. 自己放一个图标在静态资源目录下,我放在 public 目录下
  2. 清除浏览器缓存!刷新网页,发现图标已经变成自己的了!
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值