Java Reference
In-Depth Information
Example 19−3: WebAppConfig.java (continued)
// If we get here, no matching servlet name was found
return null;
}
/**
* This method adds a new name-to-class mapping in in the form of
* a <servlet> sub-tree to the document.
**/
public void addServlet(String servletName, String className) {
// Create the <servlet> tag
Element newNode = document.createElement("servlet");
// Create the <servlet-name> and <servlet-class> tags
Element nameNode = document.createElement("servlet-name");
Element classNode = document.createElement("servlet-class");
// Add the name and classname text to those tags
nameNode.appendChild(document.createTextNode(servletName));
classNode.appendChild(document.createTextNode(className));
// And add those tags to the servlet tag
newNode.appendChild(nameNode);
newNode.appendChild(classNode);
// Now that we've created the new sub-tree, figure out where to put
// it. This code looks for another servlet tag and inserts the new
// one right before it. Note that this code will fail if the document
// does not already contain at least one <servlet> tag.
NodeList servletnodes = document.getElementsByTagName("servlet");
Element firstServlet = (Element)servletnodes.item(0);
// Insert the new node before the first servlet node
firstServlet.getParentNode().insertBefore(newNode, firstServlet);
}
/**
* Output the DOM tree to the specified stream as an XML document.
* See the XMLDocumentWriter example for the details.
**/
public void output(PrintWriter out) {
XMLDocumentWriter docwriter = new XMLDocumentWriter(out);
docwriter.write(document);
docwriter.close();
}
}
Compiling and Running the Example
The WebAppConfig class uses the JAXP and DOM APIs, so you must have the
jaxp.jar and parser.jar files from the JAXP distribution in your classpath. You
should avoid having the Xerces JAR file in your classpath at the same time, or you
may run into version mismatch problems between the DOM Level 1 parser of
JAXP 1.0 and the DOM Level 2 parser of Xerces. Compile WebAppConfig.java in
the normal way. To run the program, specify the name of a web.xml file to parse
as the first command-line argument and provide a servlet name as the second
argument. When you run the program, it prints the class name (if any) that is
mapped to the specified servlet name. Then it inserts a dummy <servlet> tag into
the parse tree and prints out the modified parse tree in XML format to standard
Search WWH ::




Custom Search