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

大憨熊 提交于 2019-12-21 06:06:07

问题


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.


回答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.




回答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



来源:https://stackoverflow.com/questions/7903472/how-do-i-use-a-properties-file-with-jax-rs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!