Java Reference
In-Depth Information
the other methods of the class. The class also includes a main() method that
invokes these other methods.
The getServletClass() method looks for <servlet-name> tags and returns the
text of the associated <servlet-class> tags. (These tags always come in pairs in a
web.xml file.) This method demonstrates a number of features of the DOM parse
tree, notably the getElementsByTagName() method. The addServlet() method
inserts a new <servlet> tag into the parse tree. It demonstrates how to construct
new DOM nodes and add them to an existing parse tree. Finally, the output()
method uses an XMLDocumentWriter to traverse all the nodes of the parse tree and
convert them back into XML format. The XMLDocumentWriter class is covered in
the next section and listed in Example 19-4.
Example 19−3: WebAppConfig.java
package com.davidflanagan.examples.xml;
import javax.xml.parsers.*;
// JAXP classes for parsing
import org.w3c.dom.*;
// W3C DOM classes for traversing the document
import org.xml.sax.*;
// SAX classes used for error handling by JAXP
import java.io.*;
// For reading the input file
/**
* A WebAppConfig object is a wrapper around a DOM tree for a web.xml
* file. The methods of the class use the DOM API to work with the
* tree in various ways.
**/
public class WebAppConfig {
/** The main method creates and demonstrates a WebAppConfig object */
public static void main(String[] args)
throws IOException, SAXException, ParserConfigurationException
{
// Create a new WebAppConfig object that represents the web.xml
// file specified by the first command-line argument
WebAppConfig config = new WebAppConfig(new File(args[0]));
// Query the tree for the class name associated with the specified
// servlet name
System.out.println("Class for servlet " + args[1] + " is " +
config.getServletClass(args[1]));
// Add a new servlet name-to-class mapping to the DOM tree
config.addServlet("foo", "bar");
// And write out an XML version of the DOM tree to standard out
config.output(new PrintWriter(new OutputStreamWriter(System.out)));
}
org.w3c.dom.Document document; // This field holds the parsed DOM tree
/**
* This constructor method is passed an XML file. It uses the JAXP API to
* obtain a DOM parser, and to parse the file into a DOM Document object,
* which is used by the remaining methods of the class.
**/
public WebAppConfig(File configfile)
throws IOException, SAXException, ParserConfigurationException
{
// Get a JAXP parser factory object
javax.xml.parsers.DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
// Tell the factory what kind of parser we want
dbf.setValidating(false);
Search WWH ::




Custom Search