In the following snippet:
ServletContext context = request.getServletContext();
String path = context.getRealPath("/");
What does / in the method getRealPath() represent? When should I use it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Introduction
The
ServletContext#getRealPath()is intented to convert a web content path (the path in the expanded WAR folder structure on the server’s disk file system) to an absolute disk file system path.The
"/"represents the web content root. I.e. it represents thewebfolder as in the below project structure:So, passing the
"/"togetRealPath()would return you the absolute disk file system path of the/webfolder of the expanded WAR file of the project. Something like/path/to/server/work/folder/some.war/which you should be able to further use inFileorFileInputStream.Note that most starters don’t seem to see/realize that you can actually pass the whole web content path to it and that they often use
or even
instead of
Don’t ever write files in there
Also note that even though you can write new files into it using
FileOutputStream, all changes (e.g. new files or edited files) will get lost whenever the WAR is redeployed; with the simple reason that all those changes are not contained in the original WAR file. So all starters who are attempting to save uploaded files in there are doing it wrong.Moreover,
getRealPath()will always returnnullor a completely unexpected path when the server isn’t configured to expand the WAR file into the disk file system, but instead into e.g. memory as a virtual file system.getRealPath()is unportable; you’d better never use itUse
getRealPath()carefully. There are actually no sensible real world use cases for it. Based on my 20 years of Java EE experience, there has always been another way which is much better and more portable thangetRealPath().If all you actually need is to get an
InputStreamof the web resource, better useServletContext#getResourceAsStream()instead, this will work regardless of the way how the WAR is expanded. So, if you for example want anInputStreamofindex.jsp, then do not do:But instead do:
Or if you intend to obtain a list of all available web resource paths, use
ServletContext#getResourcePaths()instead.You can obtain an individual resource as
URLviaServletContext#getResource(). This will returnnullwhen the resource does not exist.Or if you intend to save an uploaded file, or create a temporary file, then see the below “See also” links.
See also: