Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Servlets and XML: Made for each other

Doug Tidwell (dtidwell@us.ibm.com), developerWorks staff, IBM, Software Group
Doug Tidwell is a Senior Programmer at IBM. He has been writing code since the early days of the Reagan administration. Although he swears he has been writing Java code since the late 1950s, the fact that he was born in the mid-1960s has led many to doubt this claim. His job as a Cyber Evangelist is to help customers evaluate and implement new technology. Thanks to a special arrangement with his employer, his salary is now paid entirely in chocolate truffles. Doug can be reached at dtidwell@us.ibm.com.

Summary:  Find out how Java servlets and XML work together to generate an XML document and DOM tree and interface with a database. This article includes a couple of useful techniques: using HTTP parameters to control processing and generating a DOM tree without an XML source document.

Date:  02 May 2000
Level:  Introductory

Comments:  

Servlets and XML rank as two of the most exciting technologies available to Java programmers. In this article, prepared for a presentation given to the City Java users group in San Francisco, February 17, 2000, you'll see how to use servlets to put together a simple XML document, build a DOM tree and print some of it back to the users, and then how to generate XML from a database query.

For the examples we'll discuss here, we'll be extending the HTTPServlet class. The HTTPServlet class provides the functionality normally associated with CGI programs. It supports both put and get, and gives your code complete access to the HTTP request header, including the UserAgent field. We'll create some simple servlets and illustrate how they can work with XML-tagged information. We'll illustrate several methods of the Document Object Model (DOM) along the way. These simple applications will give you some idea of the range of things you can do when you put servlets and XML together.

Our first sample servlet

To get things started, we'll write a 10-line servlet that generates an XML document. As we build our XML-aware servlets, we'll follow three steps:

  1. Set the content type to text/xml.
  2. Create the XML document.
  3. Write the XML document back to the client.

In most of our servlets, most of our effort will be in the second step. We might create an XML document from a database query, we might generate it based on an HTTP parameter passed to us from the client, or we might use some other kind of data retrieval or generation method. In our examples here, we'll focus on HTTP parameters and database queries.


A very basic servlet

For our first example, the middle step of creating the XML document is not our concern; we simply want to generate a valid XML document. We've hardcoded the document into our source code, shown in Listing 1.


Listing 1. xmlfromscratch.java
publicclassxmlfromscratchextendsHttpServlet 
{
  publicvoidservice(HttpServletRequestrequest,
                      HttpServletResponseresponse)
    throwsIOException, ServletException
  {
    response.setContentType("text/xml");
    PrintWriterout = response.getWriter();
    
    out.println("<?xml version=\"1.0\"?>");
    out.println("<greeting language=\"en_US\">");
    out.println("  Hello, World!");
    out.println("</greeting>");
  }
}

The result generated by this exciting piece of code looks like this:


Listing 2. Results from xmlfromscratch.java
<?xml version="1.0"?><greeting>
  Hello, World!
</greeting>


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


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:

<author>
<last-name>Shakespeare</last-name>
<first-name>William</first-name>
<nationality>British</nationality>
<year-of-birth>1564</year-of-birth>
<year-of-death>1616</year-of-death>
</author>

If the subtree parameter is title, the results are:

<title>Sonnet 130</title>

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


Interfacing with a database

Our final example generates XML from a database query. There are many ways of doing this; for this example, we'll use IBM XML Extender for DB2 (see Resources). This free product lets you store XML documents in DB2. Our query extracts those documents from DB2, then passes them on to the user.

If you're using Oracle 8i instead of DB2, you'll find that it boasts similar functions (see Resources). For databases that aren't XML-aware, you could store the XML document as a character large object (CLOB) and retrieve the document as a chunk of text.

However your database is set up, you need to do three things to get this code to work:

  1. First, change the DbOwner, DbUserid, and DbPasswd variables to the correct values for your system.
    ///////////////////////////////////////////////////////////////////////////////
    // Be sure to change these three strings appropriately, or the //
    // servlet won't work. //
    ///////////////////////////////////////////////////////////////////////////////
    DbUserid = "xxxxxxxx";
    DbPasswd = "xxxxxxxx";
    DbOwner = "xxxxxxxx";



  2. Next, use the JDBC driver that works with your system. We're using DB2.

    staticStringJDBCDriver = "COM.ibm.db2.jdbc.app.DB2Driver";
    ...
    try
    {
    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
    }
    catch (Exceptione)
    {
    System.out.println("Can't get the driver!"); e.printStackTrace();
    }



  3. If you want to, change the SQL query. To keep the demo simple, we're simply retrieving all of the XML documents from the order column in the sales_order_view table.

    // We hardcoded the SQL statement here; this would be more
    // sophisticated if we qualified the query based on user input.
    Stringquery = "select order from " + DbOwner + ".sales_order_view";



In the service method, our servlet connects to DB2, executes a query (the results of which are a set of XML documents), parses the query results, and writes the parsed data to the output stream. Listing 6 shows the most relevant sections of the code:


Listing 6. xmlfromdb2.java
// We hardcoded the SQL statement here; this would be more
// sophisticated if we qualified the query based on user input.
Stringquery = "select order from " + DbOwner + ".sales_order_view";

    res.setContentType("text/xml");

    try
      {
        ConInfoindex = newConInfo();
        Connectioncon = getCon(index);
        Statementstmt = con.createStatement();
        ResultSetrs = stmt.executeQuery(query);

        ...

        // Display the result set.  We take the XML doc from each row,
// parse it, then print the DOM tree.  rs.next() returns
// false when there are no more rows.
while (rs.next())
          { 
            StringnextOrder = rs.getString(1).trim();
            Documentdoc = null;
            StringReadersr = newStringReader(nextOrder);
            InputSourceiSrc = newInputSource(sr);
            
            try
              {
                parser.parse(iSrc);
                doc = parser.getDocument();
              }
            catch (Exceptione)
              {
                System.err.println("Sorry, an error occurred: " + e);
              }
            
            if (doc != null)
              printDOMTree(doc, out);
          }


To see all the details, check out the HTML view of the complete listing or view the Java source file directly.


Summary

Although none of the example servlets will change the world, they do illustrate how well XML and servlets work together. Servlets perform as a great mechanism for delivering content to clients, and XML makes a wonderful mechanism for delivering structured data. You can also use servlets to process XML documents on the server and deliver their contents to clients. Best of all, both of these technologies are cross-platform, giving you more flexibility and portability in your applications.


Resources

About the author

Doug Tidwell

Doug Tidwell is a Senior Programmer at IBM. He has been writing code since the early days of the Reagan administration. Although he swears he has been writing Java code since the late 1950s, the fact that he was born in the mid-1960s has led many to doubt this claim. His job as a Cyber Evangelist is to help customers evaluate and implement new technology. Thanks to a special arrangement with his employer, his salary is now paid entirely in chocolate truffles. Doug can be reached at dtidwell@us.ibm.com.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


Forgot your IBM ID?


Forgot your password?
Change your password


By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)


By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Java technology
ArticleID=10449
ArticleTitle=Servlets and XML: Made for each other
publish-date=05022000
author1-email=dtidwell@us.ibm.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).