Java Reference
In-Depth Information
There is one complication to this example. Most web.xml files contain a <!DOC-
TYPE> tag that specifies the document type (or DTD). Despite the fact that Exam-
ple 19-1 specifies that the parser should not validate the document, a conforming
XML parser must still read the DTD for any document that has a <!DOCTYPE> decla-
ration. Most web.xml have a declaration like this:
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
In order to read the DTD, the parser must be able to read the specified URL. If
your system is not connected to the Internet when you run the example, it will
hang. One workaround is to replace the DTD URL with the name of a local copy
of the DTD, which is what has been done in the sample web.xml file bundled with
the downloadable examples. Another workaround to this DTD problem is to sim-
ply remove (or comment out) the <!DOCTYPE> declaration from the web.xml file
you process with ListServlets1 .
Parsing with SAX 2
Example 19-1 showed how you can parse an XML document using the SAX 1 API,
which is what is supported by the current version of JAXP (at this writing). The
SAX 1 API is out of date, however. So Example 19-2 shows how you can accom-
plish a similar parsing task using the SAX 2 API and the open-source Xerces parser
available from the Apache Software Foundation.
Example 19-2 is a listing of the program ListServlets2.java . Like the List-
Servlets1.java example, this program reads a specified web.xml file and looks for
<servlet> tags, so it can print out the servlet name-to-servlet class mappings. This
example goes a little further than the last, however, and also looks for <servlet-
mapping> tags, so it can also output the URL patterns that are mapped to named
servlets. The example uses two hashtables to store the information as it accumu-
lates it, then prints out all the information when parsing is complete.
The SAX 2 API is functionally similar to the SAX 1 API, but a number of classes
and interfaces have new names and some methods have new signatures. Many of
the changes were required for the addition of XML namespace support in SAX 2.
As you read through Example 19-2, pay attention to the API differences from
Example 19-1.
Example 19−2: ListServlets2.java
package com.davidflanagan.examples.xml;
import org.xml.sax.*;
// The main SAX package
import org.xml.sax.helpers.*;
// SAX helper classes
import java.io.*;
// For reading the input file
import java.util.*;
// Hashtable, lists, and so on
/**
* Parse a web.xml file using the SAX2 API and the Xerces parser from the
* Apache project.
*
* This class extends DefaultHandler so that instances can serve as SAX2
* event handlers, and can be notified by the parser of parsing events.
Search WWH ::




Custom Search