1.新建类SystemInit.java
public class SystemInit implements ServletContextListener
{
/**
* 日志
*/
private static final Log log = LogFactory.getLog(SystemInit.class);
/**
* Servlet上下文
*/
private ServletContext context;
private static Configuration config;
/**
* 初始化方法
*/
public void init()
{
log.info("Init System ...... ");
try
{
// Constants.getAbsolutePath() == context.getRealPath("/")
// config.properties路径(例:D:\Program Files\tomcat6.0\webapps\pc\WEB-INF\classes\config.properties)
String configPath = context.getRealPath("/") + "WEB-INF"
+ File.separator + "classes" + File.separator
+ "config.properties";
PropertiesConfiguration properties = new PropertiesConfiguration(
configPath);
config = new Configuration(properties);
// 初始化系统路径
config.setContextPath(context.getContextPath());
// 初始化绝对路径
config.setAbsolutePath(context.getRealPath("/"));
}
catch (Exception ex)
{
log.error("System init fail catch Exception!", ex);
throw new RuntimeException("System init fail,Exception "
+ ex.getClass(), ex);
}
log.info("Init System end ...... ");
}
/**
* 销毁上下文
* @param servletcontextevent
*/
public void contextDestroyed(ServletContextEvent servletcontextevent)
{
}
/**
* 初始化上下文
* @param servletcontextevent
*/
public void contextInitialized(ServletContextEvent servletcontextevent)
{
context = servletcontextevent.getServletContext();
init();
}
/**
* 读取配置
* @return 配置
*/
public static Configuration getConfig()
{
return config;
}
/**
* 重新加载配置文件(对外调用提供更新)
*/
public void reload()
{
init();
}
}
2.新建Configuration.java
/**
* config.properties配置数据对象
*
* @author hpli/025415
* @version [版本号, 2012-3-19]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class Configuration
{
// context path
private String contextPath = "";
// 绝对路径
private String absolutePath = "";
// config配置Map集合
private Map<String, String> configMap;
public Configuration(PropertiesConfiguration properties)
{
// 初始化
configMap = new HashMap<String, String>();
// 获取config.properties所有key
Iterator iterator = properties.getKeys();
// 循环遍历设值
while (iterator.hasNext())
{
String key = (String)iterator.next();
configMap.put(key, properties.getString(key));
}
}
public String getContextPath()
{
return contextPath;
}
public void setContextPath(String contextPath)
{
this.contextPath = contextPath;
}
public String getAbsolutePath()
{
return absolutePath;
}
public void setAbsolutePath(String absolutePath)
{
this.absolutePath = absolutePath;
}
public Map<String, String> getConfigMap()
{
return configMap;
}
public void setConfigMap(Map<String, String> configMap)
{
this.configMap = configMap;
}
}
3.配置web.xml
添加监听
<listener>
<listener-class>com.huawei.virest.common.SystemInit</listener-class>
</listener>