当前位置: 首页 > news >正文

SpringBoot的static静态资源访问、参数配置、代码自定义访问规则

目录

  • 1. 静态资源
    • 1.1 默认静态资源
    • 1.2 Controller高优先级
    • 1.3 修改静态资源的URL根路径
    • 1.4 修改静态资源的目录
    • 1.5 访问webjars依赖包的静态资源
    • 1.6 静态资源的关闭
    • 1.7 静态资源在浏览器的缓存
    • 1.8 静态资源实战
    • 1.9 通过代码自定义静态资源访问规则

1. 静态资源

查看源码如下:

package org.springframework.boot.autoconfigure.web.servlet;
......省略部分......
public class WebMvcAutoConfiguration {
......省略部分......public void addResourceHandlers(ResourceHandlerRegistry registry) {if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");} else {// 将静态资源映射,都添加到映射中心this.addResourceHandler(registry, this.mvcProperties.getWebjarsPathPattern(), "classpath:/META-INF/resources/webjars/");this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {registration.addResourceLocations(this.resourceProperties.getStaticLocations());if (this.servletContext != null) {ServletContextResource resource = new ServletContextResource(this.servletContext, "/");registration.addResourceLocations(new Resource[]{resource});}});}}
......省略部分......private void addResourceHandler(ResourceHandlerRegistry registry, String pattern, Consumer<ResourceHandlerRegistration> customizer) {if (!registry.hasMappingForPattern(pattern)) {ResourceHandlerRegistration registration = registry.addResourceHandler(new String[]{pattern});customizer.accept(registration);registration.setCachePeriod(this.getSeconds(this.resourceProperties.getCache().getPeriod()));registration.setCacheControl(this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl());registration.setUseLastModified(this.resourceProperties.getCache().isUseLastModified());this.customizeResourceHandlerRegistration(registration);}}
......省略部分......
}

1.1 默认静态资源

默认的静态资源目录为:resources/META-INF/resources、resources/public、resources/resources、resources/static。一般用于存放图片、视频、css、js文件

默认的访问静态资源的URL根路径为:/**

所以访问resources/META-INF/resources/baidu1.jpg的URL为http://localhost:8080/baidu1.jpg

1.2 Controller高优先级

如果一个Controller的的@RequestMapping定义的访问路径,和静态资源的URL访问路径一样,则返回Controller的内容

1.3 修改静态资源的URL根路径

可以通过配置参数: spring.mvc.static-path-pattern: /static/**,修改静态资源的URL根路径。此时访问resources/META-INF/resources/baidu1.jpg的URL为http://localhost:8080/static/baidu1.jpg

1.4 修改静态资源的目录

可以通过配置参数:spring.web.resources.static-locations: [classpath:/my-resources/],修改静态资源的目录。会使resources/public、resources/resources、resources/static目录失效,但resources/META-INF/resources目录不失效

1.5 访问webjars依赖包的静态资源

会自动将resources/META-INF/resources/webjars/**,作为静态资源目录

这里我们以jquery为例,进行讲解。在pom.xml添加如下依赖

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

org.webjars.jquery的jar包的目录结构如下:
jquery的jar包的目录结构
然后访问http://localhost:8080/static/webjars/jquery/3.6.1/jquery.js。显示如下:

jquery效果
可以使用spring.mvc.webjars-path-pattern=/wj/**修改webjars路径访问前缀,这样需要通过http://localhost:8080/static/wj/jquery/3.6.1/jquery.js进行访问

1.6 静态资源的关闭

可以通过配置参数:spring.web.resources.add-mappings=false,关闭所有静态资源

1.7 静态资源在浏览器的缓存

  • 浏览器会将静态资源缓存,在缓存时间过期前,不会向服务器进行静态资源的请求。通过配置参数进行设置:spring.web.resources.cache.period=3,单位为秒,默认为0秒

  • cacheControl: HTTP缓存控制。参考: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching。通过spring.web.resources.cache.cachecontrol.max-age=7200设置,默认是7200秒,优先级比spring.web.resources.cache.period高。如果没手动设置该参数,但手动设置了spring.web.resources.cache.period,则period参数生效

  • useLastModified:是否使用最后一次修改。配合cacheControl使用。比如如果浏览器访问了一个静态资源index.js,如果服务器这个资源没有发生变化,下次访问的时候就可以直接让浏览器用自己缓存中的东西,而不用给服务器发请求,此时浏览器状态码为304。通过spring.web.resources.cache.use-last-modified=true设置,默认为true

  • 共享缓存和私有缓存。共享缓存: 客户浏览器和代理服务器都会缓存;私有缓存: 只有客户浏览器会缓存。通过spring.web.resources.cache.cachecontrol.cache-public=truespring.web.resources.cache.cachecontrol.cache-private=false设置。默认由浏览器自行决定,但一般是私有缓存

1.8 静态资源实战

Controller中定义了一个@RequestMapping(“/static/baidu1.jpg”)路径,和resources\META-INF\resources\baidu1.jpg静态资源的路径一样。内容如下:

package com.hh.springboottest.myController;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@RequestMapping("/static/baidu1.jpg")public String helloHandle() {return "hello springboot";}
}

resources目录内容如下。分别有resources/META-INF/baidu1.jpg、resources/my-resources/baidu2.jpg、resources/public/baidu3.jpg、resources/resources/baidu4.jpg、resources/static/baidu5.jpg

resources目录内容
application.yaml内容如下。分别定义了静态资源访问URL根路径,和静态资源目录

spring:mvc:static-path-pattern: /static/**web:resources:static-locations: [classpath:/my-resources/]

访问http://localhost:8080/static/baidu1.jpg,效果如下:

访问static/baidu1.jpg
访问http://localhost:8080/static/baidu2.jpg,效果如下:
访问static/baidu2.jpg
http://localhost:8080/static/baidu3.jpg、http://localhost:8080/static/baidu4.jpg、http://localhost:8080/static/baidu5.jpg不能访问

1.9 通过代码自定义静态资源访问规则

如下。添加一个静态资源访问URL,并指定其访问资源路径和缓存时间。其原理是给容器中添加一个WebMvcConfigurer组件,让配置的底层行为都生效

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.concurrent.TimeUnit;// @EnableWebMvc  // 禁用springBoot的默认配置
// 这是一个配置类。给容器中放一个WebMvcConfigurer组件,就能自定义底层。有以下两种方式
//     1. 可以让配置类实现WebMvcConfigurer接口
//     2. 可以在配置类中,将@Bean注解标注在方法上,然后方法返回WebMvcConfigurer
@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {// 默认就会保留以前规则// WebMvcConfigurer.super.addResourceHandlers(registry);// 自己添加新的规则registry.addResourceHandler("/my-static/**").addResourceLocations("classpath:/static1/", "classpath:/static2/").setCacheControl(CacheControl.maxAge(1180, TimeUnit.SECONDS));}
}
http://www.lryc.cn/news/102483.html

相关文章:

  • IO进、线程——线程(线程的创建、线程的退出、线程的回收、线程的分离和多线程并发编程)
  • neo4j教程-Cypher操作
  • 秋招算法备战第31天 | 贪心算法理论基础、455.分发饼干、376. 摆动序列、53. 最大子序和
  • 页面生成图片或PDF node-egg
  • go常用知识点
  • ComPDFKit PDF SDK(支持Web、Android、IOS、Windows、Server、API、跨平台)
  • 使用maven容器打包java项目
  • 超前端相关的学习网站和一些靠谱的小工具
  • uniapp跳转到外部链接
  • 初识DBT以及搭建第一个DBT工程
  • Python基于PyTorch实现卷积神经网络回归模型(CNN回归算法)项目实战
  • (AcWing)集合-Nim游戏
  • ConcurrentHashMap源码详解
  • 医疗流程自动化盛行,RPA成为医疗保健行业的重点应用技术
  • Java 版 spring cloud + spring boot 工程系统管理 工程项目管理系统源码 工程项目各模块及其功能点清单
  • java重试机制实现方案
  • 参数量仅有50KB的超轻量级unet变种网络egeunet【参数和计算量降低494和160倍】医疗图像分割实践
  • Android10 Settings系列(三)根据需求动态添加删除一级菜单、二级菜单的设置项
  • 51单片机——串行口通信
  • 洛谷题单 Part 6.7.1 矩阵
  • Spring中c3p0与dbcp配置
  • Flutter 添加 example流程
  • 数据治理8种方法
  • 大模型成互联网真正蜕变的标志,亦是各种新技术开始衍生的标志
  • 指针进阶详解---C语言
  • 设计模式思考,简单工厂模式和策略模式的区别?
  • Java - sh 脚本启动 jar 包等服务 - sh 脚本模板 - 适用于任何类似的服务启动
  • MySQL高级篇第5章(存储引擎)
  • openssl 命令行国密sm2的签名验签操作
  • 开源代码分享(9)—面向100%清洁能源的发输电系统扩展规划(附matlab代码)