Servlets and XML: Made for Each Other
By Doug Tidwell2005-05-18
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:
- First, change the
DbOwner,DbUserid, andDbPasswdvariables 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"; 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();
}If you want to, change the SQL query. To keep the demo simple, we're simply retrieving all of the XML documents from the
ordercolumn in thesales_order_viewtable.
// 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:
|
To see all the details, check out 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
