Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Servlets and XML: Made for Each Other

By Doug Tidwell
2005-05-18


Generating XML fragments

Well, we've created a servlet that is hardcoded to generate a simple, useless XML document. In this next servlet, we build a DOM tree from scratch, then we print some of the DOM tree back to the requestor. The part of the DOM tree that gets sent back to the requestor depends on the HTTP parameters our servlet receives. This example illustrates a couple of useful techniques: using HTTP parameters to control processing and generating a DOM tree without an XML source document.

Listing 3 shows the section of the code that processes the HTTP parameters:

Listing 3. xmlfromdom.java


publicvoidservice(HttpServletRequestrequest,
HttpServletResponseresponse)
throwsIOException, ServletException
{
response.setContentType("text/xml");
PrintWriterout = response.getWriter();

Enumerationkeys;
Stringkey;
StringrequestedSubtree = "";

keys = request.getParameterNames();
while (keys.hasMoreElements())
{
key = (String) keys.nextElement();
if (key.equalsIgnoreCase("subtree"))
requestedSubtree = request.getParameter(key);
}

As in our earlier example, we set the content type to text/xml. Once that's done, we use the HttpServletRequest.getParameterNames method to retrieve all the parameters from the HTTP request.

After we've processed the parameters, we need to find the information the user requested. The information we're using builds a DOM tree from objects; that DOM tree contains the text of a Shakespearean sonnet, along with other information about the sonnet. We'll return a portion of the DOM tree based on the HTTP subtree parameter. Listing 4 shows some of the code that builds the DOM tree:

Listing 4. Build the DOM tree


Documentdoc = null;
Elementauthor = null;
Elementlines = null;
Elementtitle = null;

publicvoidinitialize()
{
doc = (Document)Class.
forName("org.apache.xerces.dom.DocumentImpl").
newInstance();

if (doc != null)
{
Elementroot = doc.createElement("sonnet");
root.setAttribute("type", "Shakespearean");

author = doc.createElement("author");

ElementlastName = doc.createElement("last-name");
lastName.appendChild(doc.createTextNode("Shakespeare"));
author.appendChild(lastName);

We create an instance of the Java class that implements the DOM Document interface, then we ask that node to create various nodes for us. You could easily rewrite this application to generate the DOM tree by parsing an XML file. To simplify the example (and to lighten my workload) we've defined instance variables that hold the values of the nodes we intend to serve. These values are declared at the top of the class declaration, and are initialized in the initialize method.

Our last step is to deliver the requested part of the DOM tree back to the user. To do this, we use a recursive method, printDOMTree, that processes a node and all of its children. Because the method is recursive, it doesn't matter if we start at the root node of the document or anywhere else in the DOM tree. If the request is for one of the nodes we know about, we pass that node to the printDOMTree method. Otherwise, we pass the Document node. Listing 5 shows this step.

Listing 5. printDOMTree


if (requestedSubtree.equalsIgnoreCase("author"))
printDOMTree(author, out);
elseif (requestedSubtree.equalsIgnoreCase("lines"))
printDOMTree(lines, out);
elseif (requestedSubtree.equalsIgnoreCase("title"))
printDOMTree(title, out);
else
printDOMTree(doc, out);

If the subtree parameter is author, the results are:




Shakespeare
William
British
1564
1616

If the subtree parameter is title, the results are:

 

You can see the HTML view of the complete listing or view the Java source file directly.



Tutorial Pages:
» Our first sample servlet
» A very basic servlet
» Generating XML fragments
» Interfacing with a database
» Summary
» Resources


First published by IBM DeveloperWorks


 | Bookmark
Related Tutorials:
» Starting with XML
» Performing Client-Side XSL Transformations
» Create a Google Sitemap for your Web Site
» XML and Scripting Languages
» Parsing Comma-Separated Values
» XML Security Suite: Increasing the Security of E-Business