Resolving the root of a webapp from getResource
Solution 1
Well, first of all, this.getClass().getResource
should not work (though I didn't try). It's not a classpath, it's a ServletContext, so you need to use ServletContext.getResource
.
Problem is, it is not necessary a file: it can be an entry in a WAR archive. So depending on what exactly you know, the answer may be different.
We use a Spring utility class which handles both files (via ServletContext.getResourcePaths
if available) and WARs (via ServletContext.getResource
). If you use Spring, that may be the best way. If you don't, you'll probably need to re-implement the solution.
Alternatively, you cal simply use ServletContext.getResourceAsStream
—it doesn't care where exactly the resource is stored. So as long as you need its content and not the path, you should be fine.
Solution 2
No, it won't resolve. Class.getResource
loads resources from the classpath, and the webapp's root directory is not itself on the classpath.
In order to get hold of that resource, you'll need to get hold of the ServletContext
, on which you can then call ServletContext.getResource("/WEB-INF/reports/info.txt")
. That should work.
You can obtain the ServletContext
using Servlet.getServletConfig().getServletContext()
.
Alternatively, move your reports
directory under the /WEB-INF/classes
directory (which is on the classpath). You can then get your file using
getClass().getResource("reports/info.txt");
Naftuli Kay
Updated on June 14, 2022Comments
-
Naftuli Kay almost 2 years
I have a file structure like this in my webapp:
webapp/ ├── META-INF └── WEB-INF ├── reports │ └── info.txt └── web.xml 3 directories, 2 files
I need to get
/WEB-INF/reports/info.txt
from a class like so:this.getClass().getResource("/WEB-INF/reports/info.txt");
Will this resolve? I'm going to test it, but I'm not sure how Tomcat's classloader resolves things. If this doesn't work, how can I get the file?
-
Naftuli Kay over 12 yearsYeah, so the thing is that I need this to work inside of and outside of a servlet container. I need a pretty standard API which will let me get a given path whether I'm in Tomcat or in Eclipse's jUnit classpath. What's this API you're using? I'm using Spring 3.
-
alf over 12 yearsIf you need it outside the container, keep resources in the classpath, and do not touch the Servlet API.
-
Naftuli Kay over 12 yearsUsing Spring's
ResourceLoader
/ApplicationContext
to load files. Awesomeness :)