classpath:/META-INF/resources/
> classpath:/resources/
> classpath:/static/
> classpath:/public/
web
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; public void setStaticLocations(String[] staticLocations) { this.staticLocations = appendSlashIfNecessary(staticLocations); } private String[] appendSlashIfNecessary(String[] staticLocations) { String[] normalized = new String[staticLocations.length]; for (int i = 0; i < staticLocations.length; i++) { String location = staticLocations[i]; normalized[i] = location.endsWith("/") ? location : location + "/"; } return normalized; } }
方法一:配置文件 spring.resources.static-locations
spring
# windows中2種斜槓均可以,Linux中使用右斜槓。統一使用右斜槓。 spring: resources: #static-locations: classpath:/mybatis/, file:E:\image\account\img static-locations: classpath:/mybatis/, file:E:${server.servlet.context-path}/image/account/img
方法二:實現WebMvcConfigurer接口windows
package com.mozq.boot.upload01.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { /* 注意:結尾必定以斜槓結尾,否則不起效果。 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("file:E:\\mozq\\image\\account\\img\\", "classpath:/static/", "file:e:/mozq/"); } }
# 指定以.txt結尾的url是訪問靜態資源。 spring: mvc: static-path-pattern: /**/*.txt
@ConfigurationProperties(prefix = "spring.mvc") public class WebMvcProperties { private String staticPathPattern = "/**"; }