Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load resource from jar file packaged in a war file? [duplicate]

Tags:

java

servlets

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

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

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

like image 250
Amit Patel Avatar asked Jan 03 '11 15:01

Amit Patel


People also ask

Can we convert JAR file into war file?

You cannot just simply convert a jar file to a war file. A Web archive has a structure to be followed and there is no straight forward way to convert the type. What you can do is, create a web application, import the jar file as dependency and make endpoints in the webapp to trigger calls in the jar you have.

What is the difference between jar and war files?

JAR files allow us to package multiple files in order to use it as a library, plugin, or any kind of application. On the other hand, WAR files are used only for web applications. The structure of the archives is also different. We can create a JAR with any desired structure.

How do I add a resource file to a JAR file?

1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR!


1 Answers

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

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");
// ...
like image 130
BalusC Avatar answered Nov 09 '22 08:11

BalusC