Java Reference
In-Depth Information
Example 19−3: WebAppConfig.java (continued)
// Use the factory to get a JAXP parser object
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
// Tell the parser how to handle errors. Note that in the JAXP API,
// DOM parsers rely on the SAX API for error handling
parser.setErrorHandler(new org.xml.sax.ErrorHandler() {
public void warning(SAXParseException e) {
System.err.println("WARNING: " + e.getMessage());
}
public void error(SAXParseException e) {
System.err.println("ERROR: " + e.getMessage());
}
public void fatalError(SAXParseException e)
throws SAXException {
System.err.println("FATAL: " + e.getMessage());
throw e;
// re-throw the error
}
});
// Finally, use the JAXP parser to parse the file. This call returns
// A Document object. Now that we have this object, the rest of this
// class uses the DOM API to work with it; JAXP is no longer required.
document = parser.parse(configfile);
}
/**
* This method looks for specific Element nodes in the DOM tree in order
* to figure out the classname associated with the specified servlet name
**/
public String getServletClass(String servletName) {
// Find all <servlet> elements and loop through them.
NodeList servletnodes = document.getElementsByTagName("servlet");
int numservlets = servletnodes.getLength();
for(int i = 0; i < numservlets; i++) {
Element servletTag = (Element)servletnodes.item(i);
// Get the first <servlet-name> tag within the <servlet> tag
Element nameTag = (Element)
servletTag.getElementsByTagName("servlet-name").item(0);
if (nameTag == null) continue;
// The <servlet-name> tag should have a single child of type
// Text. Get that child, and extract its text. Use trim()
// to strip whitespace from the beginning and end of it.
String name =((Text)nameTag.getFirstChild()).getData().trim();
// If this <servlet-name> tag has the right name
if (servletName.equals(name)) {
// Get the matching <servlet-class> tag
Element classTag = (Element)
servletTag.getElementsByTagName("servlet-class").item(0);
if (classTag != null) {
// Extract the tag's text as above, and return it
Text classTagContent = (Text)classTag.getFirstChild();
return classTagContent.getNodeValue().trim();
}
}
}
Search WWH ::




Custom Search