Springboot访问静态资源
参考
默认的静态资源位置
classpath:/META-INF/resources/
> classpath:/resources/
> classpath:/static/
> classpath:/public/
@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
# 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接口
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 = "/**";
}