java 如何获取任何应用程序上下文根的文件系统路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7460608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:03:52  来源:igfitidea点击:

How to get file system path of the context root of any application

javajspjakarta-eetomcat

提问by Pedantic

I am working on web application.I invoke on my jsp request.getContextPath(), but strangely I got address /streetshop.

我正在开发网络应用程序。我在我的 jsp 上调用request.getContextPath(),但奇怪的是我得到了地址/streetshop

Then I am appending some path as request.getContextPath() + "abc"and create folder.

然后我附加一些路径request.getContextPath() + "abc"并创建文件夹。

Then its creating folder in D://instead of my webapplication folder.

然后它的创建文件夹D://而不是我的 webapplication 文件夹。

Please, tell me, I want to upload an image in put it in my web-application root/images/images.gif.

请告诉我,我想上传一张图片并将其放入我的web-application root/images/images.gif.

回答by home

You mix things up here. HttpServletRequest.getContextPath()returns your web application root path. In your example this is /streetshop, so your URL may look similar to www.myapp.com/streetshop. If you want to access the internal file system path, you must obtain it from the ServletContextusing request.getServletContext().getRealPath("/"). This should return the location of your WAR files' WebContentfolder.

你在这里搞混了。HttpServletRequest.getContextPath()返回您的 Web 应用程序根路径。在您的示例中,这是/streetshop,因此您的 URL 可能类似于www.myapp.com/streetshop. 如果要访问内部文件系统路径,必须从ServletContextusing 中获取request.getServletContext().getRealPath("/")。这应该返回 WAR 文件文件WebContent夹的位置。

Keep in mind that if you modify contents of this path during runtime, you're going to loose everything when redeploying your application.

请记住,如果您在运行时修改此路径的内容,您将在重新部署应用程序时丢失所有内容。