Tuesday, September 24, 2002 11:07 PM
While there is a
getResourceAsStream(String) method defined in the
ServletContext interface, remember that servlets are not constrained to simply using classes/interfaces defined in the Servlets API--you have full access to the Java 2 API. That means that you could use the
getResourceAsStream(String) method in the
So why are there two methods? The primary reason is to allow a servlet container, via its
ServletContext, to provide access to resources that normally wouldn't be seen by a class loader--for example, files that are not in the
CLASSPATH, database resources, or just about anything else the servlet container vendor can think of. The method provided by
Class, on the other hand, only has access to resources that can be located within the
CLASSPATH (minor simplification).
In your case, you are trying to load an XML file that exists within the WAR file that contains your web application. Since the WAR file is treated by the class loader like a JAR file, it's "root" directory is in the CLASSPATH. That means you just need to find a class that was loaded by an appropriate class loader (based on your description of the problem, we can pretty much assume that any of the classes you are working with will work). Then, call the
getClass() method inherited from
Object on an object of that class, and call the
getResourceAsStream(String) method with an appropriate path to the XML file (i.e. "/WEB-INF/myxmlfile.xml").