本文介绍了相对路径的绝对路径(Eclipse,JSP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Eclipse(JSP)中制作一个Web应用程序,并将Tomcat用作服务器(已集成到Eclipse中).我必须在下面创建对象并指定配置文件的路径.此绝对路径非常有效:

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");

但是我想知道为什么我不能使用相对路径.是"config/sdb.ttl"是否正确(如果项目名称是根)?但是它无法以这种方式找到它(NotFoundException).

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).

推荐答案

相对磁盘文件系统路径是相对于当前工作目录的,该目录取决于您启动应用程序的方式(在Eclipse中,它将是Project文件夹,在Command中控制台,它将是当前打开的文件夹,在Tomcat管理器/服务中,它将是Tomacat/bin文件夹,依此类推).您无法从Java代码内部对此进行控制,所以就算了吧.

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.

在JSP/Servlet中,您可以使用 ServletContext#getRealPath() 将相对的Web内容路径(其根位于公共Web内容中,在您的情况下为/WebContent文件夹)转换为绝对磁盘文件系统路径.所以:

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);
// ...

继承的ServletContext ="noreferrer"> getServletContext() 方法.

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

这篇关于相对路径的绝对路径(Eclipse,JSP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 17:49