简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM