Java WebApp: Loading resource from .jar located in WEB-INF

和自甴很熟 提交于 2020-01-07 05:05:13

问题


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? Should I use getServletContext().getResourceAsStream(?) for this purpose or the <name-of-known-class>.getResourseAsStream(?), and what path do I need to specify there?

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

回答1:


You should use <name-of-known-class>.getResourseAsStream(?), which loads resources using the "local" classloader. In the case of a webapp, this will use the webapp's classloader.

The getServletContext().getResourceAsStream(?) method will return webapp resources relative to the webapp root, and cannot look inside JAR files.

The javadoc for this method describes the path you need to specify, but essentially you can use paths relative to the known class, e.g.

SomeKnownClass.class.getResourceAsStream("required-file.xml");


来源:https://stackoverflow.com/questions/2584162/java-webapp-loading-resource-from-jar-located-in-web-inf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!