Naftuli Kay
Naftuli Kay

Reputation: 91630

Resolving the root of a webapp from getResource

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?

Upvotes: 2

Views: 14617

Answers (2)

alf
alf

Reputation: 8513

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.

Upvotes: 3

skaffman
skaffman

Reputation: 403481

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");

Upvotes: 7

Related Questions