如何阅读战争外放置的属性文件? [英] How to read properties file placed outside war?
问题描述
这些天我正在开发一个Web应用程序。那只使用jsps和servlet。这是一个小应用程序。现在我已将所有DataSource详细信息放在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安装目录中)。你可以改变名字属性;并在值中设置您拥有属性文件的文件夹的路径。
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 files\my 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屋!