How do I use a properties file with jax-rs?

10,841

Solution 1

Several options:

Option 1: You can put it under your classpath (in Eclipse put it under and source folder), so you can access it via the Classloader: MyClass.class.getResourceAsStream("myproperties.properites")

Pay attention that MyClass must also be in the same source folder (actually it's a bit more complex, it must be in the same classloader hierarchy, but any class from the same folder will do the job)

Option 2: Put it in WEB-INF folder. It's a preferred option, since you don't need to deal with the classpath. You'll need a ServletContext to access it: javax.servlet.ServletContext.getResourceAsStream("WEB-INF/myproperties.properites")

In jax-rs you can obtain the ServletContext using the @Context annotation in any registered resource or provider.

Solution 2

For GlassFish 3.1 users, I was able to get both of Tarlog's options working, but I had to use the file's absolute path. For Option 1 I put the file in the Source Packages folder in NetBeans, which I could then access via:

InputStream is = TestResource.class.getResourceAsStream("/test_model.js");

For Option 2 I put the file under WEB-INF and used:

@Context ServletContext servletContext;
InputStream is = servletContext.getResourceAsStream("/WEB-INF/test_model.js");

Without the leading slash the result was null. HTH

Share:
10,841
Blaskovicz
Author by

Blaskovicz

I'm an avid web site/service programmer with a knowledge of golang, javascript, ruby, unix, html, css, scss, perl, and a passion for automation.

Updated on June 05, 2022

Comments

  • Blaskovicz
    Blaskovicz almost 2 years

    I've just been getting started setting up a web service with jax-rs running on Tomcat. Is there a way to bundle a properties file with my java project (in eclipse) so that I can read properties out of it at runtime? Also if it's possible, where would be the best location to put it (so that it couldn't be seen via a url), WebContent, WEB-INF, etc?

    Thanks.