文章目录
静态资源
版本信息:SpringBoot 2.6.1
官方文档
1. 静态资源路径
classpath路径下(也就是 src/main/recources)
- /static
- /public
- /resources
- /META-INF/resources
放在以上四个目录下的静态资源可以通过浏览器直接访问
访问方式: http://localhost:端口/xx.png
如果访问404可以 clean 一下然后重启试一下(根本就不需要去改配置文件,重写addResourceHandlers() 之类的)
2. 修改静态资源访问前缀
spring:
mvc:
static-path-pattern: /res/**
访问方式: http://localhost:端口/res/xx.png
3. 自定义静态资源路径
spring:
web:
resources:
static-locations: classpath:/myres/
4. 欢迎页 index.html
当静态资源路径下有 index.html 时,我们访问 http://localhost:端口/ 时就会展示 index.html
注意: 不能配置 spring.mvc.static-path-pattern,否则会导致 index.html 不能被访问
5. 自定义网站图标
将名为 favicon.ico 的图标放在静态资源目录下,就可以修改如下所示位置的网站图标
6. 源码解析
6.1 默认静态资源路径配置
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#addResourceHandlers
查看getStaticLocations() 方法可以看到源码中 CLASSPATH_RESOURCE_LOCATIONS 数组中定义了静态资源的路径
6.2 为什么配置了静态资源前缀,欢迎页访问会失效
如下所示,源码中判断了前缀必须是 /** ,所以如果我们改成了其他的前缀,欢迎页的默认访问就失效了