Java Reference
In-Depth Information
Example 19−6: WebAppConfig2.java (continued)
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(System.out);
}
/**
* This field holds the parsed JDOM tree. Note that this is a JDOM
* Document, not a DOM Document.
**/
protected org.jdom.Document document;
/**
* Read the specified File and parse it to create a JDOM tree
**/
public WebAppConfig2(File configfile) throws IOException, JDOMException {
// JDOM can build JDOM trees from a variety of input sources. One
// of those input sources is a SAX parser.
SAXBuilder builder =
new SAXBuilder("org.apache.xerces.parsers.SAXParser");
// Parse the specified file and convert it to a JDOM document
document = builder.build(configfile);
}
/**
* This method looks for specific Element nodes in the JDOM tree in order
* to figure out the classname associated with the specified servlet name
**/
public String getServletClass(String servletName) throws JDOMException {
// Get the root element of the document.
Element root = document.getRootElement();
// Find all <servlet> elements in the document, and loop through them
// to find one with the specified name. Note the use of java.util.List
// instead of org.w3c.dom.NodeList.
List servlets = root.getChildren("servlet");
for(Iterator i = servlets.iterator(); i.hasNext(); ) {
Element servlet = (Element) i.next();
// Get the text of the <servlet-name> tag within the <servlet> tag
String name = servlet.getChild("servlet-name").getContent();
if (name.equals(servletName)) {
// If the names match, return the text of the <servlet-class>
return servlet.getChild("servlet-class").getContent();
}
}
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)
throws JDOMException
{
Search WWH ::




Custom Search