从java类文件中获取apache webcontents文件夹的绝对路径 [英] get absolute path to apache webcontents folder from a java class file

查看:369
本文介绍了从java类文件中获取apache webcontents文件夹的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要在动态Web应用程序内的java类文件中获取绝对路径...

Need to get absolute path in java class file, inside a dynamic web application...


  • 实际上我需要获取apache webapps文件夹的路径...部署webapps的位置

  • Actually i need to get path of apache webapps folder... where the webapps are deployed

例如 /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg

需要获取此信息一个java类文件,不在jsp页面或任何视图页面上......

Need to get this in a java class file, not on jsp page or any view page...

任何想法?

推荐答案


其实我需要获取apache webapps文件夹的路径...部署webapps的位置

例如/apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg

如上所述许多其他答案,你可以使用 ServletContext#getRealPath() 将相对Web内容路径转换为绝对磁盘文件系统路径,以便您可以在文件 FileInputStream ServletContext 位于servlet可用的继承 getServletContext() 方法:

As mentioned by many other answers, you can just use ServletContext#getRealPath() to convert a relative web content path to an absolute disk file system path, so that you could use it further in File or FileInputStream. The ServletContext is in servlets available by the inherited getServletContext() method:

String relativeWebPath = "/images";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath, "imagetosave.jpg");
// ...

但是,文件名 imagetosave.jpg表示您尝试按 FileOutputStream 存储上传的图像。公共webcontent文件夹是存储上传图像的错误位置!无论何时重新部署webapp,或者甚至在服务器重新启动并进行清理时,它们都会丢失。原因很简单,上传的图像根本不包含在待部署的WAR文件中。

However, the filename "imagetosave.jpg" indicates that you're attempting to store an uploaded image by FileOutputStream. The public webcontent folder is the wrong place to store uploaded images! They will all get lost whenever the webapp get redeployed or even when the server get restarted with a cleanup. The simple reason is that the uploaded images are not contained in the to-be-deployed WAR file at all.

您一定要在外面寻找另一个位置将webapp部署文件夹作为上传图像的更永久存储,以便在多个部署/重新启动时保持完整。最好的方法是准备一个固定的本地磁盘文件系统文件夹,例如 / var / webapp / uploads ,并将其作为一些配置设置提供。最后只需将图像存储在那里。

You should definitely look for another location outside the webapp deploy folder as a more permanent storage of uploaded images, so that it will remain intact across multiple deployments/restarts. Best way is to prepare a fixed local disk file system folder such as /var/webapp/uploads and provide this as some configuration setting. Finally just store the image in there.

String uploadsFolder = getItFromConfigurationFileSomehow(); // "/var/webapp/uploads"
File file = new File(uploadsFolder, "imagetosave.jpg");
// ...



参见:



查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆