Search code examples
javatomcatclassloader

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?


Solution

  • 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.