我需要从jar加载属性文件.jar包含在war文件中.这是结构
ROOT.war
WEB-INF
lib
my.jar
here my.jar has following structure
my.jar
com
test
myservlet.class
WEB-INF
test.property
Run Code Online (Sandbox Code Playgroud)
现在我在我的一个servlet中编写了以下代码,如下所示:
InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/test.properties");
Properties prop = new Properties();
prop.load(stream );
Run Code Online (Sandbox Code Playgroud)
但是上面的代码我得到了流为null.如果我将属性文件放在ROOT.war/WEB-INF中,它可以正常工作.我很清楚,如果getResourceAsStream中的路径以'/'开头,而不是上下文根中的搜索资源.但是如何读取在根应用程序的WEB-INF/lib中再次找到的jar中的资源?
谢谢和问候,阿米特帕特尔
Bal*_*usC 37
将它放在JAR的根目录中,并通过上下文类加载器而不是servletcontext来获取它.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("test.properties");
// ...
Run Code Online (Sandbox Code Playgroud)
该/WEB-INF文件夹中的约定是特定于WAR文件,而不是JAR文件.摆脱它.如果您确实需要一个单独的JAR文件夹作为类路径的一部分,请/META-INF改用.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("META-INF/test.properties");
// ...
Run Code Online (Sandbox Code Playgroud)
您可以从给定实例访问标准类路径上的任何资源
this.getClass().getResourceAsStream("name");
Run Code Online (Sandbox Code Playgroud)
例如来自你的"myservlet"类(错误的命名).
getServletContext().getResourceAsStream() 访问Web应用程序基目录上下文中的内容.
在jar中加入WEB-INF目录似乎很糟糕 - 你会引起混淆.你能找到更好的名字吗?
| 归档时间: |
|
| 查看次数: |
45119 次 |
| 最近记录: |