springboot内置Tomcat的getServletContext().getRealPath问题

默认情况下springboot中request.getServletContext().getRealPath 返回的是一个临时文件夹的地址

通过查看源代码 位置在

org.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactory#getCommonDocumentRoot
private File getCommonDocumentRoot() {
		for (String commonDocRoot : COMMON_DOC_ROOTS) {
			File root = new File(commonDocRoot);
			if (root.exists() && root.isDirectory()) {
				return root.getAbsoluteFile();
			}
		}
		return null;
	}
private static final String[] COMMON_DOC_ROOTS = { "src/main/webapp", "public",
			"static" };

可以看到springboot 会尝试读取COMMON_DOC_ROOTS 配置里面的路径,所以我们只需要在springboot 所在的jar 或者项目所在的根目录下新建一个public或者static的文件夹,那么通过 request.getServletContext().getRealPath 就会得到public或者static的路径

猜你喜欢

转载自blog.csdn.net/qq_42574277/article/details/89311356