Tomcat 7 to 8.5 upgrade : getResourceAsStream throws NPE

Viewed 387

I am new to this Dev Ops work so please forgive anything simple which I may have overlooked. I am in the middle of upgrading from Tomcat 7 to 8.5. There is not much in terms of migration manuals other then the apache website and using the 7 to 8 then the 8 to 8.5. All seems ok, expect for when I start up the application and the code tries to load information using the following

Thread.currentThread().getContextClassLoader().getResourceAsStream("sql/");

or

getClass().getClassLoader().getResourceAsStream("sql/");

The context path is being loaded using ROOT.xml which has a docBase pointing at the project which is in the ../tomcat/databaseLink directory. The WEB-INF/classes folder is in the ../tomcat/databaseLink directory and the sql folder is in the WEB-INF/classes folder. So it all seems to be ok.

When the code is running it looks like it is looking for the sql folder in the ../tomcat/lib/ directory rather then the ../tomcat/databaseLink/WEB-INF/classes/sql/ directory. I have not made any changes to the default Tomcat 8 conf files. Any idea why this is happening or what I have missed?

1 Answers

The method ClassLoader#getResourceAsStream only finds resources, which are on the web application classpath, i.e.:

  • in the folder WEB-INF/classes or in a JAR file inside the WEB-INF/lib folder,
  • in the classpath of Tomcat's Shared, Common, System or Bootstrap classloaders (cf. Tomcat documentation). As you noticed, by default the Common classloader has the directories $CATALINA_HOME/lib and $CATALINA_BASE/lib in its classpath.

The method you are looking for is ServletContext#getResourceAsStream, which searches in the application directory and META-INF/resources entries of all JARs in WEB-INF/lib. So you should call:

servletContext.getResourceAsStream("/WEB-INF/sql/your_file");
Related