原因:服务器有文件保护机制,避免直接暴露目录结构,不能使用绝对路径方位静态资源。
解决方案:
添加一个虚拟路径映射到文件的绝对路径。
@RequiredArgsConstructor
@Configuration
public class WebMvcConfig2 implements WebMvcConfigurer {
private static final String templatePath = "/src/main/resources/static/template/";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String realPath = System.getProperty("user.dir") + templatePath;
// URL路径:如localhost:8080/template/a.jpg 映射到本地路径:C:\Users\acer\Desktop\data\项目实训\a.jpg
registry.addResourceHandler("/template/**").addResourceLocations("file:" + realPath);
}
}