简体   繁体   English

如何从POJO获取Java EE 6应用程序中的上下文根目录?

[英]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. 我有一个带有JSF 2和Tomcat 7的Java EE 6应用程序。现在我有一个POJO。 This POJO should read a properties file. 该POJO应该读取属性文件。 The properties file is is located in WEB-INF/classes. 属性文件位于WEB-INF / classes中。 The current directory is the users home directory /home/myUser. 当前目录是用户的主目录/ home / myUser。

How does the POJO get the context's root directory or some similar path, so that it can read the properties file? POJO如何获取上下文的根目录或类似路径,以便它可以读取属性文件?

The /WEB-INF/classes is just part of the classpath. /WEB-INF/classes只是类路径的一部分。 You could obtain it as classpath resource by ClassLoader#getResourceAsStream() . 您可以通过ClassLoader#getResourceAsStream()将其作为类路径资源获取。 In a webapplication, the best is to obtain the ClassLoader by Thread#getContextClassLoader() of the current Thread . 在Web应用程序中,最好的方法是通过当前Thread Thread#getContextClassLoader()获得ClassLoader

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... 如果您有一个可以读取属性文件的POJO ...
i guess something is wrong in the preliminary design.. 我想初步设计出了点问题。
the P in POJO stands for Plain... POJO中的P代表Plain ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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