在最近的一个MIS项目中,为了避免硬编码,我需要把一些配置信息写在一个配置文件中.考虑到是J2EE项目,J2EE的配置文件
好像都是xml文件了,再用传统ini文件是不是有点落伍了?
ok,就用xml做配置文件吧.
我的配置文件reportenv.xml如下,比较简单:
<?xml version="1.0" encoding="utf-8"?>
<reportenv>
<datasource>
<username>sqlname</username>
<password>password</password>
</datasource>
</reportenv>
现在的问题是我用什么来读取配置信息?
现在流行的是dom4j和sax,我以前一直用dom4j.可是weblogic workshop自带的是sax,我又不想再引入包了,于是就是sax吧.
第一步:ConfigParser.java
/*
* Create Date: 2005-6-13
* Create By: 板桥里人
* purpose:xml配置文件属性读取器
*/
package com.infoearth.report;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import java.util.Properties;
public class ConfigParser extends DefaultHandler {
////定义一个Properties 用来存放属性值
private Properties props;
private String currentSet;
private String currentName;
private StringBuffer currentValue = new StringBuffer();
//构建器初始化props
public ConfigParser() {
this.props = new Properties();
}
public Properties getProps() {
return this.props;
}
//定义开始解析元素的方法. 这里是将<xxx>中的名称xxx提取出来.
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
currentValue.delete(0, currentValue.length());
this.currentName =qName;
}
//这里是将<xxx></xxx>之间的值加入到currentValue
public void characters(char[] ch, int start, int length) throws SAXException {
currentValue.append(ch, start, length);
}
//在遇到</xxx>结束后,将之前的名称和值一一对应保存在props中
public void endElement(String uri, String localName, String qName) throws SAXException {
props.put(qName.toLowerCase(), currentValue.toString().trim());
}
}
第二步:ParseXML.java
/*
* Create Date: 2005-6-13
* Create By: 板桥里人 李春雷修改
* purpose:xml配置文件属性读取器(通用),
*/
package com.infoearth.report;
import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.net.URL;
public class ParseXML{
//定义一个Properties 用来存放属性值






