[英]I can't get the real path from Servlet (Java EE)
When I would like to get a real path in Java EE, using this instructions: 当我想在Java EE中获得真正的路径时,请使用以下说明:
String rootPath = getServletConfig().getServletContext().getRealPath("/");
System.out.println(rootPath);
The result is: C:\\Users\\saad\\Desktop\\pds.metadata.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\Metier\\ 结果是:C:\\ Users \\ saad \\ Desktop \\ pds.metadata.plugins \\ org.eclipse.wst.server.core \\ tmp0 \\ wtpwebapps \\ Metier \\
And normaly, I have to get this result: 而且,我必须得到这个结果:
C:\\Users\\saad\\Desktop\\pds\\Metier\\ C:\\ Users \\用户萨阿德\\桌面\\ PDS \\梅捷\\
Can anyone help me, please? 有人可以帮帮我吗?
This is an excellent example of why the concept of "filesystem path relative to the application" really has no meaning in a servlet. 这是为什么“文件系统路径相对于应用程序”的概念在servlet中没有意义的一个很好的例子。 When a servlet is deployed into a container, there is no guarantee that it resides at a real filesystem location. 将servlet部署到容器中时,无法保证它位于真实的文件系统位置。 The servlet container could choose to execute it directly from the .war file without expanding it, or it could be reading the application code from a URL that is not backed by a traditional file system at all. servlet容器可以选择直接从.war文件执行它而不扩展它,或者它可以从一个完全没有传统文件系统支持的URL读取应用程序代码。
In your case, the long path you got back is exactly where Eclipse deployed your application. 在您的情况下,您获得的长路径正是Eclipse部署应用程序的地方。 That path was 100% correct in that context , because if you look at the filesystem at that location you'll find a copy of your application, but obviously not what you were expecting. 在该上下文中 ,该路径是100%正确的,因为如果您查看该位置的文件系统,您将找到应用程序的副本,但显然不是您所期望的。
In general, it is not possible to portably refer to any file path relative to your application because the path may not exist. 通常,无法以可移植方式引用与应用程序相关的任何文件路径,因为该路径可能不存在。
Path to Tomcat dir (tomcat/bin): Tomcat dir(tomcat / bin)的路径:
File inputFile = new File("file.xml"); // tomcat_dir/bin/file.xml
Path to other Tomcat directories, "webapps" for example: 其他Tomcat目录的路径,例如“webapps”:
File inputFile = new File("../webapps/file.xml"); // tomcat_dir/webapps/file.xml
Good way to get rid of the absolute paths :) 摆脱绝对路径的好方法:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.