如何读取放置在战争之外的属性文件? [英] How to read properties file placed outside war?
问题描述
我最近在开发一个网络应用程序.这仅使用 jsps 和 servlet.这是一个小应用程序.现在我已将所有数据源详细信息放在 DAO 实用程序类中.我想把这些细节放在一个可以放在战争之外的属性文件中,这样我们就可以根据环境改变这些值,而不会影响战争.我怎样才能做到这一点?
I'm working on a web application these days. That uses only jsps and servlets. It's a small application. Right now I have placed all the DataSource details in DAO utility class. I want to place these details in a properties file that can be placed outside the war, so that depending on the environment we can change these values, without effecting the war. How can I achieve this?
推荐答案
我是这样做的:
将以下内容添加到 context.xml 文件(conf 文件夹,在 tomcat 安装目录中).您可以更改 name 属性;并在 value 中设置您拥有属性文件的文件夹的路径.
Add the following to context.xml file (conf folder, in tomcat installation dir). you may change the name attribute; and in value set the path of the folder where you have your properties files.
<Environment name="config" value="C:Program filesmy app"
type="java.lang.String" override="false"/>
然后在您的 util 类中,您可以获得这样的文件:(在java:comp/env/config"中,将config"替换为您在 context.xml 中使用的name"属性的值)>
Then in your util class, you can get the file like this: (in "java:comp/env/config" replace 'config' with the value of the "name" attribute you used in context.xml)
String folderName = null;
Properties properties = new Properties();
try {
InitialContext context = new InitialContext();
folderName = (String) context.lookup("java:comp/env/config");
} catch (NamingException ex) {
System.out.println("exception in jndi lookup");
}
if(folderName != null) {
File configFile = new File(folderName + "yourfile.properties");
try {
InputStream is = new FileInputStream(configFile);
properties.load(is);
} catch(IOException ex) {
System.out.println("exception loading properties file");
}
}
希望这对您或其他任何人有帮助.
Hope this helps you or anyone else.
这篇关于如何读取放置在战争之外的属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!