[英]Java WebApp: Loading resource from .jar located in WEB-INF
There are a lot of similar questions, but, probably, mine is a little bit different: 有很多类似的问题,但我的可能有点不同:
What is the right way to load resource from inside of .jar
file located in WEB-INF/lib
folder (if I know the jar file name and the name of the class it resource belongs to), while Web Application is running? 在Web应用程序运行时,从位于WEB-INF/lib
文件夹中的.jar
文件内部加载资源的正确方法是什么(如果我知道jar文件名及其资源所属的类的名称)? Should I use getServletContext().getResourceAsStream(?)
for this purpose or the <name-of-known-class>.getResourseAsStream(?)
, and what path do I need to specify there? 为此,我应该使用getServletContext().getResourceAsStream(?)
还是<name-of-known-class>.getResourseAsStream(?)
,我需要在其中指定什么路径?
So, the structure is: 因此,结构为:
/WEB-INF
/classes
/some/package/name
?.class #some Java code or Servlet that tries to read 'required-file.xml'
/lib
/<jar-with-known-name>.jar
/another/package/with/known/name
SomeKnownClass.class
required-file.xml
You should use <name-of-known-class>.getResourseAsStream(?)
, which loads resources using the "local" classloader. 您应该使用<name-of-known-class>.getResourseAsStream(?)
,它使用“本地”类加载器加载资源。 In the case of a webapp, this will use the webapp's classloader. 对于webapp,将使用webapp的类加载器。
The getServletContext().getResourceAsStream(?)
method will return webapp resources relative to the webapp root, and cannot look inside JAR files. getServletContext().getResourceAsStream(?)
方法将返回相对于webapp根的webapp资源,并且无法查看JAR文件内部。
The javadoc for this method describes the path you need to specify, but essentially you can use paths relative to the known class, eg 此方法的Javadoc描述了您需要指定的路径,但实际上您可以使用相对于已知类的路径,例如
SomeKnownClass.class.getResourceAsStream("required-file.xml");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.