技术笔记|SpringBoot 静态资源访问

SpringBoot 静态资源访问 1. 默认静态资源路径
在 resources 目录下创建 static 或者 public 目录用于存放 images、js、css 等静态资源文件。原因是 SpringBoot 默认的静态资源路径是 {"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"}
技术笔记|SpringBoot 静态资源访问
文章图片

说明:resources 资源目录下包括 static、templates、application.yml 三个子文件,其中 static 里面主要存放 Web 开发过程中需要的静态资源(比如:images、js、css等),而 templates 模板目录存放 HTML 文件,application.yml 是项目的全局配置文件。
由于 classpath:/static/ 是 SpringBoot 默认的资源路径,所以项目启动时,我们可以通过地址栏路径访问到这些资源。
技术笔记|SpringBoot 静态资源访问
文章图片
技术笔记|SpringBoot 静态资源访问
文章图片

那么我们如何在 HTML 文件中访问这些静态资源呢?

静态资源访问type="text/javascript" src="https://www.it610.com/js/index.js"> Hello World!技术笔记|SpringBoot 静态资源访问
文章图片

注:在上面访问 CSS 样式资源文件时,我们添加的路径是 /css/index.css,前面的斜杠 / 表示的是 http://localhost:8181/,所以拼接起来表示的是 http://localhost:8181/css/index.css
技术笔记|SpringBoot 静态资源访问
文章图片

2. 自定义静态资源路径
如果我们不想用 static 和 public 作为静态资源文件名,就需要自己在 application.yml 中定义静态资源路径。
比如我们想将静态资源目录命名为 os,则:
技术笔记|SpringBoot 静态资源访问
文章图片

spring: # 设置静态资源的默认访问路径,多个路径之间用逗号隔开 resources: static-locations: classpath:/static/,classpath:/public/,classpath:/os/

添加上面这个配置可以自定义静态资源路径。一般地,我们还会添加 spring-mvc-static-path-pattern 来增强程序的可读性,即表示在某某静态文件下的某某资源文件。
spring: mvc: static-path-pattern: /os/**

spring boot 项目中的静态资源文件存放在 os 文件下面,当通过浏览器访问这些静态文件时,发现必须要添加 os 作为前缀才能访问。
技术笔记|SpringBoot 静态资源访问
文章图片

【技术笔记|SpringBoot 静态资源访问】当然,一般我们创建 SpringBoot 项目时,会默认在 resources 目录下创建 static 存放静态资源文件,我们直接使用即可。

    推荐阅读