Spring Boot 对静态资源映射提供了默认配置, 默认将 /** 所有访问映射到以下目录:
classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
classpath 即WEB-INF下面的classes目录,在springboot项目中可能就是src/main/resources目录。
也就是\resources目录下默认上面三个目录:static,public,resources均可以无需任何配置浏览器直接访问到。
正常情况下,我们只需要将我们的静态资源放到src/main/resource/static这个目录下即可正常访问,也不需要额外再去创建其他静态资源目录,但是如果我们想自定义一下目录,则可以在application.properties添加spring.resources.static-locations:来指定位置
spring.resources.static-locations:的默认值是:
classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
如果我们想将html页面资源放在src/main/resource/webapp下,只需设置spring.resources.static-locations=classpath:/webapp/,即可直接访问到,但是会覆盖前面的四条设置。所以直接在后面追加一条即可。
像这样:
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/webapp/
当然你也可以直接指定一个硬盘上的任意目录:
#自定义的属性,指定了一个路径,注意要以/结尾
upload-path=D:/verifies/
#会覆盖默认配置,所以需要将默认的也加上否则static、public等这些默认静态资源路径将不能再被使用
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/webapp/,file:${upload-path}
当然也可以通过代码在java类中指定,一般不推荐,配置文件指定更加简单高效
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(!registry.hasMappingForPattern("/static/**")){
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
super.addResourceHandlers(registry);
}
}