config.java

来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 52 行

JAVA
52
字号
package persistence;

import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;

public abstract class Config {

    protected Element root;

    protected void init(ServletContext sctx, String xmlFile) throws Exception {
        InputStream is = null;

        // Obtain the root element.
        try {
            is = sctx.getResourceAsStream(xmlFile);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(is));
            root = doc.getDocumentElement();
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    protected void cleanup() {
        root = null;
    }

    protected String getElementText(Element parent, String name) {
        NodeList nodeList = parent.getElementsByTagName(name);
        if (nodeList.getLength() == 0) {
            return null;
        }

        Element element = (Element) nodeList.item(0);
        StringBuffer sb = new StringBuffer();
        for (Node child = element.getFirstChild();
            child != null; child = child.getNextSibling()) {

            if (child.getNodeType() == Node.TEXT_NODE) {
                sb.append(child.getNodeValue());
            }
        }
        return sb.toString().trim();
    }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?