场景:
需要通过url访问服务器上的资源,可以通过nginx进行资源映射(见 nginx映射资源文件),也可以通过Spring Boot进行映射。
代码:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class FileWebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resource/**")
// .addResourceLocations("file:" + "D:/web/resource/", "file:" + "D:/web2/resource/"); // 也可以使用这种写法
.addResourceLocations("file:" + "D:/web/resource/")
.addResourceLocations("file:" + "D:/web2/resource/");
}
}
说明:
1.映射规则为:addResourceHandler参数中**匹配到的字符串(不含分隔符/),拼接到addResourceLocations的参数后面,即为本地资源文件
如:http://localhost:8080/resource/image/1.jpg 被**匹配的字符串为 image/1.jpg,拼接后的url为:D:/web/resource/image/1.jpg 和 D:/web2/resource/image/1.jpg
2.addResourceLocations添加了多个本地路径时,会按照添加顺序依次拼接路径进行查找,直到查找到配置的资源,或者查找完所有路径为止(是把本地路径添加到了locationValues这个List中,所以查找顺序和添加顺序一致)
3.添加addResourceHandler中的参数时,server.servlet.context-path的值不会被匹配(可以认为,进入服务后,server.servlet.context-path对应的值就不存在于路径中了),所以如果一直404,请检查/resources下所有的配置文件是否有配置server.servlet.context-path