Tomcat 7 到 8.5 升级:getResourceAsStream 抛出 NPE [英] Tomcat 7 to 8.5 upgrade : getResourceAsStream throws NPE
问题描述
我是这项 Dev Ops 工作的新手,所以请原谅我可能忽略的任何简单内容.我正在从 Tomcat 7 升级到 8.5.除了 apache 网站和使用 7 到 8 然后是 8 到 8.5.一切似乎没问题,期待当我启动应用程序并且代码尝试使用以下内容加载信息
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/");
或
getClass().getClassLoader().getResourceAsStream("sql/");
上下文路径正在使用 ROOT.xml 加载,它有一个 docBase 指向位于 ../tomcat/databaseLink
目录中的项目.WEB-INF/classes
文件夹在 ../tomcat/databaseLink
目录下,sql
文件夹在 WEB-INF/classes
文件夹.所以看起来一切正常.
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.
当代码运行时,它看起来像是在 ../tomcat/lib/
目录中寻找 sql
文件夹而不是 ../tomcat/databaseLink/WEB-INF/classes/sql/
目录.我没有对默认的 Tomcat 8 conf 文件进行任何更改.知道为什么会发生这种情况或我错过了什么吗?
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?
推荐答案
ClassLoader#getResourceAsStream
只查找资源,这些资源位于 Web 应用程序类路径上,即:
The method ClassLoader#getResourceAsStream
only finds resources, which are on the web application classpath, i.e.:
- 在文件夹
WEB-INF/classes
或WEB-INF/lib
文件夹内的 JAR 文件中, - 在 Tomcat 的
Shared
、Common
、System
或Bootstrap
类加载器的类路径中(参见 Tomcat 文档).如您所见,默认情况下,Common
类加载器在其类路径中包含目录$CATALINA_HOME/lib
和$CATALINA_BASE/lib
.
- in the folder
WEB-INF/classes
or in a JAR file inside theWEB-INF/lib
folder, - in the classpath of Tomcat's
Shared
,Common
,System
orBootstrap
classloaders (cf. Tomcat documentation). As you noticed, by default theCommon
classloader has the directories$CATALINA_HOME/lib
and$CATALINA_BASE/lib
in its classpath.
您正在寻找的方法是 ServletContext#getResourceAsStream
,在应用目录和WEB中所有JAR的
.所以你应该打电话:META-INF/resources
条目中搜索-INF/lib
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");
这篇关于Tomcat 7 到 8.5 升级:getResourceAsStream 抛出 NPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!