Java Reference
In-Depth Information
<servlet>
<servlet-name>logout</servlet-name>
<servlet-class>com.davidflanagan.examples.servlet.Logout</servlet-class>
</servlet>
ListServlets1.java
includes a
main()
method that uses the JAXP API to obtain a SAX
parser instance. It then tells the parser what to parse and starts the parser running.
The remaining methods of the class are invoked by the parser. Note that
List-
Servlets1
extends the SAX
HandlerBase
class. This superclass provides dummy
implementations of all the SAX event handler methods. The example simply over-
rides the handlers of interest. The parser calls the
startElement()
method when it
reads an XML tag; it calls
endElement()
when it finds a closing tag.
characters()
is invoked when the parser reads a string of plain text with no markup. Finally,
the parser calls
warning()
,
error()
,or
fatalError()
when something goes wrong
in the parsing process. The implementations of these methods are written specifi-
cally to extract the desired information from a
web.xml
file and are based on a
knowledge of the structure of this type of file.
Note that
web.xml
files are somewhat unusual in that they don't rely on attributes
for any of the XML tags. That is, servlet names are defined by a
<servlet-name>
tag nested within a
<servlet>
tag, instead of simply using a
name
attribute of the
<servlet>
tag itself. This fact makes the example program slightly more complex
than it would otherwise be. The
web.xml
file does allow
id
attributes for all its
tags. Although servlet engines are not expected to use these attributes, they may
be useful to a configuration tool that parses and automatically generates
web.xml
files. For completeness, the
startElement()
method in Example 19-1 looks for an
id
attribute of the
<servlet>
tag. The value of that attribute, if it exists, is reported
in the program's output.
Example 19−1: ListServlets1.java
package com.davidflanagan.examples.xml;
import javax.xml.parsers.*;
// The JAXP package
import org.xml.sax.*;
// The main SAX package
import java.io.*;
/**
* Parse a web.xml file using JAXP and SAX1. Print out the names
* and class names of all servlets listed in the file.
*
* This class implements the HandlerBase helper class, which means
* that it defines all the "callback" methods that the SAX parser will
* invoke to notify the application. In this example we override the
* methods that we require.
*
* This example uses full package names in places to help keep the JAXP
* and SAX APIs distinct.
**/
public class ListServlets1 extends org.xml.sax.HandlerBase {
/** The main method sets things up for parsing */
public static void main(String[] args)
throws IOException, SAXException, ParserConfigurationException
{
// Create a JAXP "parser factory" for creating SAX parsers
javax.xml.parsers.SAXParserFactory spf=SAXParserFactory.newInstance();