如何将属性文件与 jax-rs 一起使用?
我刚刚开始使用在 Tomcat 上运行的 jax-rs 设置 Web 服务。有没有办法将属性文件与我的java项目(在eclipse中)捆绑在一起,以便我可以在运行时从中读取属性?另外,如果可能的话,放置它的最佳位置在哪里(这样就无法通过 url 看到它)、WebContent、WEB-INF 等?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
几个选项:
选项 1:您可以将其放在类路径下(在 Eclipse 中将其放在源文件夹下),这样您就可以通过类加载器访问它:
MyClass.class.getResourceAsStream("myproperties.properites")
注意 MyClass 也必须位于同一个源文件夹中(实际上有点复杂,它必须位于同一个类加载器层次结构中,但来自同一文件夹的任何类都可以完成这项工作)
选项2:放入WEB-INF文件夹中。这是首选选项,因为您不需要处理类路径。您需要一个 ServletContext 来访问它:
javax.servlet.ServletContext.getResourceAsStream("WEB-INF/myproperties.properites")
在 jax-rs 中,您可以使用 @Context 注释来获取 ServletContext任何注册的资源或提供者。
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.
对于 GlassFish 3.1 用户,我能够使 Tarlog 的两个选项正常工作,但我必须使用文件的绝对值小路。对于选项 1,我将文件放在 NetBeans 中的 Source Packages 文件夹中,然后我可以通过以下方式访问该文件夹:
对于选项 2,我将文件放在 WEB-INF 下并使用:
如果没有前导斜杠,结果为 null。华泰
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:
For Option 2 I put the file under WEB-INF and used:
Without the leading slash the result was null. HTH