SpringBoot中访问静态资源

场景

在SpringBoot中加载静态资源和在普通的web应用中不一样。

默认情况下:

SpringBoot从classpath的/static,/public或者

/META-INF/resource文件夹

或者

从ServletContext根目录提供静态内容。

实现

使用默认的静态资源访问

因为是默认目录,所以直接输入文件名,不用输入上级目录名。

在项目下resource下新建目录以及静态资源如下:

SpringBoot中访问静态资源SpringBoot中访问静态资源

其中public.js

SpringBoot中访问静态资源SpringBoot中访问静态资源

其中static.js

SpringBoot中访问静态资源SpringBoot中访问静态资源

运行项目打开浏览器输入:

http://localhost:8080/public.js

SpringBoot中访问静态资源SpringBoot中访问静态资源

再输入:

http://localhost:8080/static.js

SpringBoot中访问静态资源SpringBoot中访问静态资源

同理访问图片资源

输入:

http://localhost:8080/qrstatic.gif

SpringBoot中访问静态资源SpringBoot中访问静态资源

再输入:

http://localhost:8080/qrpublic.gif

SpringBoot中访问静态资源SpringBoot中访问静态资源

 

不使用默认的静态资源访问路径

打开application.properties配置文件

#修改默认的静态资源访问路径
spring.resources.static-locations=classpath:/static/

此时只能访问static目录下,再访问public目录下就会提示404

SpringBoot中访问静态资源SpringBoot中访问静态资源

源码下载

https://download.****.net/download/badao_liumang_qizhi/11072980