struts2如何读取自己写的配置文件 (转载)

摘抄自:http://www.yuloo.com/news/1010/504497.html

网站上总是需要用到一些自定义的配置, 我把它放在一个Properties文件中, 如: config.properties 此文件放在与Struts.xml相同的文件夹内, 在此我的是src下.

  1. 新建一个工具类PropertiesUtil, 在其定义一个公共的静态的java.util.Properties类的对象pps

  2. 新建一个监听类WebConfigListener并实现ServletContextListener接口

  public void contextInitialized(ServletContextEvent arg0) {

  PropertiesUtil.pps = new Properties();

  try{

  String path = (getClass().getClassLoader().getResource("").toURI()).getPath();

  FileInputStream fis = new FileInputStream(path + "config.properties");

  PropertiesUtil.pps.load(fis);

  }catch (Exception e) {

  e.printStackTrace();

  }

  }

  3. 在WEB.xml中把WebConfigListener添加上去

       com.phonesale.common.WebConfigListener 

  

  4. 在程序中读取配置时使用: PropertiesUtil.pps.getProperty(key);

posted @ 2013-05-21 21:38  walking000  阅读(255)  评论(0)    收藏  举报