自己解析hibernate.cfg.xml 的问题

本文介绍了一种使用SAXReader解析hibernate.cfg.xml文件的方法,该方法能够避免因网络问题导致的DTD查找失败,并成功获取数据库连接所需的用户名、URL及密码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目需要自动解析出hibernate.cfg.xml中数据库名用户名和密码。

直接使用以下方法解析,红色代码代表不是用hibernate.cfg.xml中指定的dtd,

不添加红色代码出现的问题是:自动查找hibernate.cfg.xml中指定的dtd,一般是从网上查找。当文件找不到时会报异常。

hibernate框架在不联网的情况下也可是正常使用,是因为框架本身使用自带的dtd不使用hibernate.cfg.xml中指定的dtd,只有Jar包中找不到dtd时,才会到网上查找。


 public static Void getCon() {  
   
        // 得到sax解析器  
        SAXReader read = new SAXReader();  
        //防止到网络上查找DTD
        read.setEntityResolver(new DTDEntityResolver());
        // 通过文件得到输入流  
        InputStream is=null;
try {
// is = new FileInputStream(new File("D:/spaces/.metadata/.me_tcat/webapps/Doraemon/WEB-INF/classes/hibernate.cfg.xml"));
//is = new FileInputStream(new File("D:/struts.xml"));
is = new FileInputStream(new File("D:/hibernate.cfg.xml"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
        //在非静态的方法中可以直接用this.getclass.getResourceAsStream("/hibernate.cfg.xml");  
        try {  
            // 得到xml文档对象  
            Document doc = read.read(is);  
            //得到根元素  
            Element root=doc.getRootElement();  
            // xpath得到session-factory中的内容  
            Element e = (Element) root.selectSingleNode("session-factory");  
            // 得到root下面的集合,通过迭代器输出  
            Iterator it = e.elementIterator();  
            int i=0;
            while (it.hasNext()) {
            if(i==3)break;
                Element ee = (Element) it.next();  
                // 得到属性name中的值  
                String key = ee.attributeValue("name");  
                // 得到文本框中的内容  
                String value = ee.getText();  
                //进行相应的匹配并且赋值  
                if (key.equals("hibernate.connection.username")) {  
                    username = value;  
                    i++;
                    continue;
                } else if (key.equals("connection.url")) {  
                    url = value;  
                    i++;
                    continue;
                } else if (key.equals("hibernate.connection.password")) {  
                    password = value;  
                    i++;
                    continue;                    
                }   
            }  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值