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

查看:151
本文介绍了如何从战争文件中打包的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 );

但是在代码之上我得到了流为null。如果我将属性文件放在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?

谢谢&此致,
Amit Patel

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

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

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