开发者

How to get the context root directory in Java EE 6 application from a POJO?

I have a Java EE 6 application with JSF 2 and Tomcat 7. Now I have a POJO. This POJO should read a properties file. The properties file is is located in WEB-INF/classes. The current directory is the users home directory /home/myUser.

How does the POJO get the context's root directory or some similar path, so开发者_高级运维 that it can read the properties file?


The /WEB-INF/classes is just part of the classpath. You could obtain it as classpath resource by ClassLoader#getResourceAsStream(). In a webapplication, the best is to obtain the ClassLoader by Thread#getContextClassLoader() of the current Thread.

So, in a nut:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Properties properties = new Properties();
properties.load(classLoader.getResourceAsStream("filename.properties"));


and one more thing
if you can have a POJO that can read a properties file...
i guess something is wrong in the preliminary design..
the P in POJO stands for Plain...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜