【问题标题】:Get absolute path of "web content" folder in Java获取 Java 中“Web 内容”文件夹的绝对路径
【发布时间】:2014-11-29 10:16:32
【问题描述】:

我想在源代码中获取Web content 文件夹的绝对路径,这样我就可以检索另一个文件夹来上传文件。

我尝试ServletActionContext.getServletContext().getRealPath("images")获取源代码中的文件夹图像。

预期结果应该是

“C:\Learning\Workspace\Eclipse\boxingsaigon\WebContent\images”。

但它会返回我部署网络的位置:

实际结果是

“C:\Learning\Workspace\Eclipse.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\boxingsaigon\images”。

有什么办法吗?

【问题讨论】:

  • 你需要清楚,这样人们才能理解你得到了什么,你期望什么以及当前有什么问题。
  • 抱歉我编辑了问题
  • 试试这个String path=application.getRealPath("/DBBACKUP/EXPORT/dbexport.sql");这里/DBBACKUP/EXPORT/是我的网络项目中的文件夹
  • 那是因为从外观上看,它是从扩展war文件的地方开始的。
  • @AtulNar 没有应用程序对象。请帮我仔细检查。谢谢

标签: java jsp servlets absolute-path


【解决方案1】:

您获取绝对路径的方法是正确的。您可以通过

获取完整路径
ServletActionContext.getServletContext().getRealPath("images");   

但是你得到的路径C:\Learning\Workspace\Eclipse.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\boxingsaigon\images 是你的实际Web 应用程序部署的路径。

如果您将部署路径更改为 tomcat webapps 目录,它会为您提供该目录的路径。
您可以获得实际源代码所在的路径。

From Doc

 ServletContext.getRealPath() returns the absolute file path on the server's 
 filesystem would be served by a request for
 "http://host/contextPath/index.html", where contextPath is the 
 context path of this ServletContext..

【讨论】:

    【解决方案2】:

    你可以试试这个:

    public String getRealFile(HttpServletRequest request, String path) {
      return request.getSession().getServletContext().getRealPath(path);
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2011-03-13
      • 2015-09-09
      • 2011-08-30
      相关资源
      最近更新 更多