该回答引用自Deepseek,由本人整理审核 若有帮助,望采纳。
在Spring Boot应用中,session.getServletContext().getRealPath("/") 返回的是一个临时路径,而不是当前项目的路径,这通常是因为Spring Boot应用在运行时使用了嵌入式的Servlet容器(如Tomcat),并且应用被打包成一个可执行的JAR文件。在这种情况下,Servlet容器会将资源文件放在一个临时的文件系统路径中,而不是项目的实际路径。
解决方法
使用 ResourceLoader 获取资源路径
你可以使用Spring的 ResourceLoader 来获取资源文件的路径,而不是依赖于ServletContext的 getRealPath 方法。
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
@Component
public class ResourcePathUtil {
private final ResourceLoader resourceLoader;
public ResourcePathUtil(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public String getResourcePath(String resourceLocation) {
try {
return resourceLoader.getResource(resourceLocation).getFile().getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException("Failed to get resource path", e);
}
}
}
使用时:
String path = resourcePathUtil.getResourcePath("classpath:public/");
使用 application.properties 配置工作目录
你可以在 application.properties 中配置工作目录:
spring.resources.static-locations=classpath:/public/
这样,Spring Boot会自动将 public 目录作为静态资源目录。
检查IDEA的Run/Debug Configurations
由于你的IDEA版本是2024.1.2,可能与2021年的版本有所不同。你可以检查IDEA的Run/Debug Configurations,确保工作目录(Working Directory)设置正确。
- 打开Run/Debug Configurations。
- 选择你的Spring Boot应用配置。
- 在“Configuration”选项卡中,检查“Working directory”是否设置为你的项目根目录。
使用 Path 类获取项目路径
你也可以使用Java的 Path 类来获取项目路径:
import java.nio.file.Paths;
public class ProjectPathUtil {
public static String getProjectPath() {
return Paths.get("").toAbsolutePath().toString();
}
}
使用时:
String projectPath = ProjectPathUtil.getProjectPath();
总结
- 使用
ResourceLoader 获取资源路径是一个更现代和推荐的方法。 - 配置
application.properties 可以确保静态资源路径正确。 - 检查IDEA的Run/Debug Configurations,确保工作目录设置正确。
- 使用
Path 类获取项目路径也是一个可行的方法。
通过这些方法,你应该能够解决 session.getServletContext().getRealPath("/") 返回临时路径的问题。