Java Reference
In-Depth Information
Example 19−6: WebAppConfig2.java (continued)
// Create the new Element that represents our new servlet
Element newServletName = new Element("servlet-name");
newServletName.setContent(servletName);
Element newServletClass = new Element("servlet-class");
newServletClass.setContent(className);
Element newServlet = new Element("servlet");
newServlet.addChild(newServletName);
newServlet.addChild(newServletClass);
// find the first <servlet> child in the document
Element root = document.getRootElement();
Element firstServlet = root.getChild("servlet");
// Now insert our new servlet tag before the one we just found.
Element parent = firstServlet.getParent();
List children = parent.getChildren();
children.add(children.indexOf(firstServlet), newServlet);
}
/**
* Output the JDOM tree to the specified stream as an XML document.
**/
public void output(OutputStream out) throws IOException {
// JDOM can output JDOM trees in a variety of ways (such as converting
// them to DOM trees or SAX event streams). Here we use an "outputter"
// that converts a JDOM tree to an XML document
XMLOutputter outputter = new XMLOutputter(" ", // indentation
true); // use newlines
outputter.output(document, out);
}
}
Compiling and Running the Example
In order to compile and run Example 19-6, you must download the JDOM distribu-
tion, which is freely available from http://www.jdom.or g/ . This example was devel-
oped using the Beta 4 release of JDOM. Because of the beta status of JDOM, I'm
not going to try to give explicit build instructions here. You need to have the
JDOM classes in your classpath to compile and run the example. Additionally,
since the example relies on the Xerces SAX 2 parser, you need to have the Xerces
JAR file in your classpath to run the example. Xerces is conveniently bundled with
JDOM (at least in the Beta 4 distribution). Finally, note that JDOM is undergoing
rapid development, and the API may change somewhat from the Beta 4 version
used here. If so, you may need to modify the example to get it to compile and
run.
Exercises
19-1. Many of the examples in this chapter were designed to parse the web.xml
files that configure web applications. If you use the Tomcat servlet container
to run your servlets, you may know that Tomcat uses another XML file,
server.xml , for server-level configuration information. In Tomcat 3.1, this file
Search WWH ::




Custom Search