Absolute to relative path (Eclipse, JSP) [duplicate]

↘锁芯ラ 提交于 2019-12-10 15:10:23

问题


I am making a web application in Eclipse (JSP) and use Tomcat as a server (integrated into Eclipse). I have to create the object below and specify the path to configuration file. This absolute path is working great:

Store store = StoreFactory.create("file:///C:/Users/Aliens/workspace/myProject/WebContent/config/sdb.ttl");

However I am wondering why I can't use relative path. Should it be "config/sdb.ttl" right (if the name of the project is a root)? But it cannot locate it this way (NotFoundException).


回答1:


Relative disk file system paths are relative to the current working directory which is dependent on how you started the application (in Eclipse it would be the project folder, in Command console it would be the currently opened folder, in Tomcat manager/service it would be the Tomacat/bin folder, etc). You have no control over this from inside the Java code, so forget about it.

In JSP/Servlet you can use ServletContext#getRealPath() to convert a relative web content path (it has its root in the public webcontent, in your case the /WebContent folder) to an absolute disk file system path. So:

String relativeWebPath = "/config/sdb.ttl";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
Store store = StoreFactory.create(absoluteDiskPath);
// ...

The ServletContext is available in servlets by the inherited getServletContext() method.




回答2:


Right/standard/compatible way is to use http://adderpit.com/jdk/j2eedocs/api/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String)

like

servletContext.getResourceAsStream("config/sdb.ttl");


来源:https://stackoverflow.com/questions/3596501/absolute-to-relative-path-eclipse-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!