Java WebApp:从位于WEB-INF的.jar加载资源 [英] Java WebApp: Loading resource from .jar located in WEB-INF

查看:91
本文介绍了Java WebApp:从位于WEB-INF的.jar加载资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多类似的问题,但是,我的可能有点不同:

There are a lot of similar questions, but, probably, mine is a little bit different:

在运行Web应用程序时,从位于WEB-INF/lib文件夹中的.jar文件内部加载资源的正确方法是什么(如果我知道jar文件名和该资源所属的类的名称)?为此,我应该使用getServletContext().getResourceAsStream(?)还是<name-of-known-class>.getResourseAsStream(?),我需要在其中指定什么路径?

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?

因此,结构为:

/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

推荐答案

您应该使用<name-of-known-class>.getResourseAsStream(?),它使用本地"类加载器加载资源.对于webapp,将使用webapp的类加载器.

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.

getServletContext().getResourceAsStream(?)方法将返回相对于webapp根目录的webapp资源,并且无法查看JAR文件内部.

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");

这篇关于Java WebApp:从位于WEB-INF的.jar加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆