In a POJO inside Java web app, how do I find the path to the root of the running website, so I can read a file there?
Remember, this is in a POJO, so I don't have:
getServletContext()
(like in a servlet)application
(like in a JSP)I've seen recommendations for System.getProperty("user.dir")
, but this doesn't look right (on my laptop, it returns C:\Program Files\eclipse\eclipse
, which is clearly not what I want).
The app will be deployed to Azure, so I won't technically know the path to the app in advance, this means I can't set it as a property or setting either. I need to produce it out of thin air, in real-time.
Other languages have globals:
$_SERVER['DOCUMENT_ROOT']
AppDomain.Current.BaseDirectory
You can then form a path by combining these values with the relative path from the webroot.
What is the equivalent for Java?
I don't think that there is something comparable to the variable in PHP or .NET simply because there might be multiple webroots on a system: One being used for plain connections and the other for TLS connections or if you set up multiple HTTP-server within an application (I'm doing that with Jetty on a regular basis)
So a "global variable" like a system property can't work here.
My idea of solving that is actually saving the ServletContext or whatever is available within a non-POJO-class (like a servlet) to some static member in one of your classes that are part of the webapp, so you can access it from your POJO and get the webroot from it. As mentioned in one of my comments, that root might be inside a WAR-file so you shouldn't expect java.io.File
to actually work.
That should work even if you use the same webapp multiple times within the same server (or across multiple servers in the same VM) because these webapps should use different class loaders so that storage class should be loaded per webapp.