处理 Applet 网页的 DOM

每个网页由一系列嵌套对象组成。这些对象组成文档对象模型(DOM)。 Java applet 可以使用通用 DOM API遍历和修改其父网页的对象。

考虑一个 JavaServlets 的示例,该程序转储其父网页的内容。

为了遍历和操作 DOM 树,必须首先获取对该网页的Document对象的引用。您可以通过使用com.sun.java.browser.plugin2.DOM类中的getDocument方法来实现。这是一个代码段,用于检索对DOMDump applet 的start方法中Document对象的引用。请参阅代码中的内联 注解。

public void start() {
    try {
        // use reflection to get document
        Class c =
          Class.forName("com.sun.java.browser.plugin2.DOM");
        Method m = c.getMethod("getDocument",
          new Class[] { java.applet.Applet.class });
        
        // cast object returned as HTMLDocument;
        // then traverse or modify DOM
        HTMLDocument doc = (HTMLDocument) m.invoke(null,
            new Object[] { this });
        HTMLBodyElement body =
            (HTMLBodyElement) doc.getBody();
        dump(body, INDENT);
    } catch (Exception e) {
        System.out.println("New Java Plug-In not available");
        // In this case, you could fallback to the old
        // bootstrapping mechanism available in the
        // com.sun.java.browser.plugin.dom package
    }
}

现在您已经有了对Document对象的引用,您可以使用 Common DOM API 遍历和修改 DOM 树。 DOMDumpServlets 遍历 DOM 树并将其内容写入 Java 控制台日志。

private void dump(Node root, String prefix) {
    if (root instanceof Element) {
        System.out.println(prefix +
            ((Element) root).getTagName() + 
            " / " + root.getClass().getName());
    } else if (root instanceof CharacterData) {
        String data =
            ((CharacterData) root).getData().trim();
        if (!data.equals("")) {
            System.out.println(prefix +
                "CharacterData: " + data);
        }
    } else {
        System.out.println(prefix +
            root.getClass().getName());
    }
    NamedNodeMap attrs = root.getAttributes();
    if (attrs != null) {
        int len = attrs.getLength();
        for (int i = 0; i < len; i++) {
            Node attr = attrs.item(i);
            System.out.print(prefix + HALF_INDENT +
                "attribute " + i + ": " +
                attr.getNodeName());
            if (attr instanceof Attr) {
                System.out.print(" = " +
                    ((Attr) attr).getValue());
            }
            System.out.println();
        }
    }

    if (root.hasChildNodes()) {
        NodeList children = root.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
                dump(children.item(i), prefix +
                    INDENT);
            }
        }
    }
}

在浏览器中打开AppletPage.html,以查看正在运行的DOMDumpServlets。检查 Java 控制台日志中是否有网页 DOM 树的转储。

Note:

如果看不到 Servlets 正在运行,则需要至少安装Java SE 开发套件(JDK)6 更新 10版本。

Note:

如果看不到示例正在运行,则可能需要在浏览器中启用 JavaScript 解释器,以便 Deployment Toolkit 脚本能够正常运行。

下载源代码用于* DOM Dump *示例,以进行进一步试验。