默認(rèn)資源映射
1 springBoot 默認(rèn)為我們提供了靜態(tài)資源處理,使用 WebMvcAutoConfiguration 中的配置各種屬性迅诬。
默認(rèn)配置的/**
映射到 /static (或/public、/resources楼誓、/META-INF/resources)
默認(rèn)配置的 /webjars/**
映射到 classpath:/META-INF/resources/webjars/
PS:上面的 static凡桥、public技羔、resources 等目錄都在 classpath: 下面(如 src/main/resources/static)户辞。
2 如圖泌类,訪問http://localhost:9090/fj.png
Paste_Image.png
自定義資源映射
代碼實現(xiàn)
1 自定義目錄:以增加 /myres/**
映射到 classpath:/myres/**
為例的代碼處理為: 實現(xiàn)類繼承 WebMvcConfigurerAdapter 并重寫方法 addResourceHandlers
@Configuration
public class CustomResourceConfig extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/");
super.addResourceHandlers(registry);
}
// 可以直接使用addResourceLocations 指定磁盤絕對路徑,同樣可以配置多個位置底燎,注意路徑寫法需要加上
//file:registry.addResourceHandler("/myimgs/**").addResourceLocations("file:H:/myimgs/");
}
Paste_Image.png
2 訪問:http://localhost:9090/myres/custom.png
配置文件實現(xiàn)
spring.mvc.static-path-pattern=/myres/**
#classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/myres/
訪問:http://localhost:9090/myres/custom.png
http://localhost:9090/myres/fj.png,之前為http://localhost:9090/fj.png