如何从打包在war文件中的jar文件加载资源? [英] How to load resource from jar file packaged in a war file?

查看:28
本文介绍了如何从打包在war文件中的jar文件加载资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 jar 加载一个属性文件.jar 包含在 war 文件中.这是结构

I need to load a property file from the jar. The jar is included in war file. Here is the structure

ROOT.war
  WEB-INF
     lib
       my.jar

here my.jar has following structure

my.jar
  com
    test
      myservlet.class
  WEB-INF
    test.property

现在我在我的一个 servlet 中编写了以下代码,如下所示:

Now I have written following code in one of my servlet as follows:

InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/test.properties");
Properties prop = new Properties();
prop.load(stream );

但上面的代码我得到了流为空.如果我将属性文件放在 ROOT.war/WEB-INF 中,它工作正常.我有一个很好的想法,如果 getResourceAsStream 中的路径以/"开头,那么它会在上下文根中搜索资源.但是如何读取位于根应用程序的 WEB-INF/lib 中的 jar 中的资源?

but above code I got stream as null. If I put the property file in ROOT.war/WEB-INF it works fine. I have fair idea that if path in getResourceAsStream starts with '/' than it search resource in context root. But how can I read resource which lies in a jar which again found in WEB-INF/lib of root application?

谢谢&问候,阿米特·帕特尔

Thanks & Regards, Amit Patel

推荐答案

将它放在 JAR 的根目录中,并通过上下文类加载器而不是 servletcontext 获取它.

Put it in root of the JAR and get it by context classloader instead of servletcontext.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("test.properties");
// ...

/WEB-INF 文件夹约定特定于 WAR 文件,而不是 JAR 文件.摆脱它.如果您确实需要一个单独的 JAR 文件夹作为类路径的一部分,请改用 /META-INF.

The /WEB-INF folder convention is specific to WAR files, not to JAR files. Get rid of it. If you really need a separate JAR folder which is to be part of the classpath, use /META-INF instead.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("META-INF/test.properties");
// ...

这篇关于如何从打包在war文件中的jar文件加载资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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