转载:https://www.cnblogs.com/magicalSam/p/7189476.html
一、静态资源路径是指系统能够直接访问的路径,且路径下的全部文件都可被用户经过浏览器直接读取。html
二、在Springboot中默认的静态资源路径有:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/web
1、默认静态资源映射
Spring Boot 对静态资源映射提供了默认配置spring
Spring Boot 默认将 /** 全部访问映射到如下目录:
classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources
如:在resources目录下新建 public、resources、static 三个目录,并分别放入 a.jpg b.jpg c.jpg 图片
浏览器分别访问:
http://localhost:8080/a.jpg http://localhost:8080/b.jpg http://localhost:8080/c.jpg
均能正常访问相应的图片资源。那么说明,Spring Boot 默认会挨个从 public resources static 里面找是否存在相应的资源,若是有则直接返回。
2、自定义静态资源映射
在实际开发中,可能须要自定义静态资源访问路径,那么能够继承WebMvcConfigurerAdapter来实现。浏览器
第一种方式:静态资源配置类
package com.sam.demo.conf; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 配置静态资源映射 * @author sam * @since 2017/7/16 */ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //将全部/static/** 访问都映射到classpath:/static/ 目录下 registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } }
重启项目,访问:http://localhost:8080/static/c.jpg 能正常访问static目录下的c.jpg图片资源。
第二种方式:在application.properties配置
在application.properties中添加配置:
spring.mvc.static-path-pattern=/static/**