简体   繁体   中英

How to retrieve web application root path in Java

I am coding my Spring MVC based web application (which was deployed with a war file) and trying to get the value of

String rootDir = request.getSession().getServletContext().getRealPath("/");

I am expecting to get

"C:\user\projects\MyApp"

but the actual value is

"C:\user\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\MyApp\"

I tried to change Source Folder Output Location in Eclipse, but after that all my jsp files, web.xml and folder \\WEB-INF are gone. How can I restore them?

The reason I am asking this is that I want my uploaded images to be saved in "MyApp\\webapp\\WEB-INF\\resources\\images\\" folder.

Why are you expecting the path to be "C:\\user\\projects\\MyApp" ?

Your are running your application using Eclipse and Eclipse is deploying it to C:\\user\\projects\\.metadata\\.plugins\\org.eclipse.wst.server.core and not running it from project source folder that is why you get "C:\\user\\projects\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\MyApp\\" from getRealPath() call.

From ServletContext#getRealPath()

Gets the real path corresponding to the given virtual path. For example, if path is equal to /index.html, this method will return the absolute file path on the server's filesystem to which a request of the form http://://index.html would be mapped, where corresponds to the context path of this ServletContext.

The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators.

Resources inside the /META-INF/resources directories of JAR files bundled in the application's /WEB-INF/lib directory must be considered only if the container has unpacked them from their containing JAR file, in which case the path to the unpacked location must be returned.

This method returns null if the servlet container is unable to translate the given virtual path to a real path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM