Path to a file in a webapp under GlassFish

Slavko picture Slavko · Jun 2, 2010 · Viewed 13.5k times · Source

How do I specify the path to a file in a web application? I have a folder named 'templates' under WEB-INF, I've been told that under GlassFish v3 the path should look like this:

./WebContent/WEB-INF/templates

but this way I'm getting a file not found exception. What do I have to change in order to make it work?

Answer

Thorbjørn Ravn Andersen picture Thorbjørn Ravn Andersen · Jun 30, 2010

If I understand you correctly, you cannot rely on the current working directory to locate a resource you have deployed. If your resource is physically placed relative to a classpath resource (like inside a jar), you can ask about where that resource is, and then navigate from there.

From How a servlet can get the absolute path to a file outside of the servlet? which in turn is from http://www.exampledepot.com/egs/java.lang/ClassOrigin.html:

Class cls = this.getClass();
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation();  // file:/c:/almanac14/examples/