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
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.
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.
1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR!
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");
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With