1. Java中配置文件的三种配置位置及读取方式
1.1 XML和*.properties(属性文件)/ini
1.2 存放位置
1.2.1 src根目录下
Xxx.class.getResourceAsStream("/config.properties");
1.2.2 与读取配置文件的类在同一包
Xxx.class.getResourceAsStream("config2.properties");
1.2.3 WEB-INF(或其子目录下)
ServletContext application = this.getServletContext();
InputStream is =
application.getResourceAsStream("/WEB-INF/config3.properties");
注1:*.properties文件
key=value
#注释
Properties.load(is)
2. XML的作用
配置
*.properties
*.xml
*.ini
数据交换
xml
webservice
json
3. dom4j+xpath解析xml文件
xpath等同数据库的select语句
document.selectNodes(xpath);//查一组
document.selectSingleNode(xpath);//查单个
DOM由节点组成
Node
元素节点
属性节点
文本节点
xpath
/ 定位路径 在系统中建一个文件叫document/students/student/sid|name
@ 属性
举例:/students/student[@pid='p02']
students.xml
public class Demo {
public static void main(String[] args) throws DocumentException{
InputStream is = Demo.class.getResourceAsStream("/config.xml");
SAXReader sax=new SAXReader();
Document document = sax.read(is);
//获取对应节点的内容
// List<Element> nodes = document.selectNodes("config/action");
Element el =(Element) document.selectSingleNode("config/action");
System.out.println(el.attributeValue("path"));
}
public static void main1(String[] args) throws DocumentException{
//根据指定路径获取对应文件的字节码内容保存到is中
InputStream is = Demo.class.getResourceAsStream("/config.xml");
// Properties properties=new Properties();
// //将is里面的字节码属性内容加载到pro里面了
// properties.load(is);
SAXReader sax=new SAXReader();
Document document = sax.read(is);
//获取对应节点的内容
List<Element> nodes = document.selectNodes("config/action");
// 该节点获取到的是全文的所有forward节点还是第一个action的forward所有节点
// List<Element> nodes = document.selectNodes("config/action/forward");
for (Element element : nodes) {
String path = element.attributeValue("path");
String type = element.attributeValue("type");
System.out.println("path:"+path+",type:"+type);
//获取所有action里面的元素forward
List<Element> forwardElement = element.selectNodes("forward");
for (Element ele : forwardElement) {
String name = ele.attributeValue("name");
String forwardPath = ele.attributeValue("path");
String redirect = ele.attributeValue("redirect");
System.out.println("\tname:"+name+",path:"+forwardPath+",redirect:"+redirect);
}
}
}
}