(1)引入静态资源时,错误解决方法
在做SpringBoot访问静态资源文件(css、js、images)时候,发现总是报错:
以为是路径中没有添加static,所以路径又添加static,再次访问如下:
额哦,还是一样的错误,看来不是这个问题。继续查找原因,发现是在springboot的配置文件中,配置访问静态资源的路径错误:
spring: mvc:static-path-pattern: /**resources:static-locations: classpath:/static/**
上面配置中的static-locations路径配置有误,不应该是写/**。直接写成:classpath:/static/即可,如下代码所示。
spring: mvc:static-path-pattern: /**resources:static-locations: classpath:/static/
再次访问,即可成功访问到静态资源:
(2)SpringBoot静态资源配置
springboot项目中,访问静态资源,需要在application.yml配置文件中进行路径的配置。即:配置静态资源放在哪个路径目录下面。
springboot默认的四种静态资源路径
classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/
springboot默认会去上面四个目录中,寻找静态资源文件,找不到则返回错误页面。
也可以自定义静态资源目录文件,在【application.yml】配置文件中,添加如下配置:
spring:mvc:static-path-pattern: /**resources:static-locations: classpath:/这里写自定义的静态资源文件目录名称/
spring.mvc.static-path-pattern属性
告诉springboot以什么样的路径来访问静态资源。因为,只有当静态资源满足什么样的匹配条件时候,springboot才会知道根据什么条件去处理静态资源请求。例如: 当配置static-path-pattern=/static/**时候,只有当访问路径中包含/static时候,才能作为静态资源文件处理。
spring.resources.static-locations属性
前面配置好了静态资源匹配处理方式,这里就需要配置静态资源目录在哪里了static-locations属性告诉springboot,静态资源都在都放在这个目录之下,springboot就会去该目录下查找静态资源文件。
注意:static-locations属性值,不要添加/**,否则识别不到,我就是添加了/**,才没有访问到资源文件。