一.默认静态路径
springboot默认设置了静态资源路径, 默认将 /** 所有访问映射到下面的目录:
classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
classpath 是WEB-INF下面的classes目录,在springboot项目中可能是src/main/resources目录。意思就是springboot项目下的resources下的static,public.resources不用配置就可以直接访问里面的资源文件.如果你自定义了资源映射,那么这些默认配置就会失效.
我们可以在配置文件properties或yml下配置添加资源目录,我这里是yml配置文件.
spring
web:
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/webapp/
这样除了默认的路径新增的resources下的webapp目录下的文件也可以直接访问了.
如果想配置磁盘上的其他目录那么就可以在后面添加file:d:/test/这样D磁盘下的test目录也会作为静态资源文件夹.
配置如下
#自定义的属性,指定了一个路径,注意要以/结尾
upload-path: D:/test/
#会覆盖默认配置,所以加上默认配置,不然static、public等这些默认静态资源路径将不能再被使用
spring
web:
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/webapp/,file:${upload-path}
二.自定义资源映射
一般都是通过直接在端口后访问资源,但是想要在添加一层或多层目录怎么办,可以自定义Java类配置,比如这样就多了一层upload
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/upload/temp/");
super.addResourceHandlers(registry);
}
}
当访问ip:端口/upload/地址时就会映射到D:/upload/temp/
当我要访问D:/upload/temp/img/1.jpg这个文件时我就可以这样访问了.如图