For Java programmers, servlet and XML are the most exciting two techniques. This article is a presentation prepared for the San Francisco City Java User Group on February 17, 2000. In this article, you will see how to use the servlet to build a simple XML document, build a DOM tree, and display some content on the user screen, and finally you will see how to generate XML from a database query.
For the examples discussed in this article, we will extend the HTTPSERVLET class. The HTTPServlet class provides features that are usually related to the CGI program. It supports PUT and GET, and allows your code to have full access to the HTTP request header, including the useERAGENT domain. We will create some simple servlets and explain how they handle information with XML tag tags. In this process we will also explain some of the methods of document object model (DOM). These simple applications will enable you to know what you can do when you combine servlets and XML.
The first servlet example acts as a beginning, we will write a 10-line servlet used to generate an XML document. When constructing a servlet that understands XML, we will perform in the following three steps:
Set the content type to Text / XML. Create an XML document. Write the XML document back to the client. In most servlets, main energy is placed in the second step. We may create an XML document based on the database query, or may generate it based on the HTTP parameter transmitted from the customer, or may also use other types of data retrieval or generating methods. In the examples herein, the HTTP parameters and database queries will be mainly considered.
A basic servlet For the first example, the second step "Create XML Document" is not what we care about; we just want to generate an effective XML document. We have hardcoded documents into source code, as shown in Listing 1.
Color Code Color Code List is a feature of this article, we are experimenting with DW. In order to generate our color coding list, I am using some tools for open source. First, I load the document (Java, HTML, XML, etc.) into the EMACS. Emacs defines the colors of keywords, comments, function names, and other programming language components (about more than ten kinds). After Emacs load files and adds colors, I use HTMLize package, which is an open source utility written in Emacs Lisp language. Htmlize receives a list (this list looks exactly the same as in Emacs) and then converts it to HTML. The result will be a fully colored code that highlights keywords, comments, and function names. Please take the idea of our new, improved code list. If you want to do this, see the corresponding link in the reference.
Listing 1. XMLFromscratch.java
Public Class Xmlfromscratch Extends Httpservlet
{
Public void service (httpservletRequest Request,
Httpservletresponse response
THROWS IOEXCEPTION, ServletException
{
Response.setContentType (Text / XML ");
PrintWriter out = response.getwriter ();
Out.println (" XML Version = /" 1.0 / "?>");
Out.println ("
Out.println (" Greeting>");
}
} The result of this exciting code generation is as follows: Listing 2. XMLFromscratch.java results
XML Version = "1.0"?>
Hello, World!
greeting>
You can view the HTML view of your full list or view the Java source file directly.
Generating an XML section Now, we have created a servlet, which generates a simplex XML document with unambiguous. In the next servlet, we generate a DOM tree from zero and then display a part of the DOM tree on the requester's screen. The DOM tree part sent back to the requester depends on the HTTP parameter received by the servlet. This example shows several useful techniques: using the HTTP parameter to control the processing and generation of the DOM tree without the XML source document. Listing 3 shows the code segment for processing HTTP parameters: List 3. XmlfromDom.java
Public void service (httpservletRequest Request,
Httpservletresponse response
THROWS IOEXCEPTION, ServletException
{
Response.setContentType (Text / XML ");
PrintWriter out = response.getwriter ();
ENUMERATION Keys;
String Key;
String RequestedSubtree = ""
Keys = Request.getParameterNames ();
While (keys.hasmorelements ())
{
Key = (string) keys.nextelement ();
Key.Equalsignorecase ("subtree"))
RequestedSubtree = Request.getParameter (key);
} As in the previous example, we set the content type to Text / XML. After that, we use the httpservletRequest.getParameterNames method to retrieve all parameters from the HTTP request. After processing these parameters, we need to find the information requested by the user. We use the information to build a DOM tree from the object; the DOM tree contains the text of Shakespeare's fourteen poems, and other information about this fourteen poem. We will return a part of the DOM tree according to the HTTP Subtree parameters. Listing 4 shows some of the code to build a DOM tree: Listing 4. Build a DOM tree
Document Doc = NULL;
ELEMENT Author = NULL;
ELEMENT LINES = NULL;
ELEMENT TITLE = NULL;
Public void initialize ()
{
DOC = (document) Class.
Forname ("Org.Apache.xerces.Dom.DocumentImpl").
NEWINSTANCE ();
IF (doc! = null)
{
Element root = doc.createElement ("SONNET"); root.setttribute ("type", "shakespearean);
Author = doc.createElement ("author");
Element lastname = doc.createElement ("Last-name");
Lastname.Appendchild (Doc.createTextNode ("Shakespeare");
Author.Appendchild (LastName); We created an instance of a Java class, which implements the Dom Document interface, and then we ask that node to create a variety of nodes for us. You easily rewrite this application so that it generates a DOM tree by analyzing the XML file. To simplify this example (and reduce my workload), we define some instance variables to save the value of the node that is prepared for it. These values are declared at the top of the class declaration and initialized in the Initialize method. The final step is to send the requested DOM tree part to the user. To achieve this task, we use a recursive method, PrintDomtree, which handles nodes and all of them. Because this method is recursive, we are not important to start from the root node of the document or other nodes from the DOM tree. If the requested is a node we know, this node can be passed to the method PrintDomtree. Otherwise, we can pass the Document node. Listing 5 shows this step. Listing 5. PrintDomtree
RequestedSubtree.equalsignoreCase ("Author"))
Printdomtree (Author, Out);
Else IF (RequestedSubtree.equalsignorecase ("Lines"))
Printdomtree (Lines, Out);
Else IF (RequestedSubtree.equalsignoreCase ("Title"))
Printdomtree (title, out);
Else
PrintDomtree (DOC, OUT); if the subtree parameter is Author, the result is:
author> If the subtree parameter is Title, the result is:
You can view the HTML view of your full list or view the Java source file directly.
The last example of docking with the database is based on the database query generates XML. There are many ways to do this (see the article Generating XML from a data store); For this example, we will use IBM XML Extender For DB2 (see Resources). This free product enables you to store XML documents in DB2. Our query extracts these documents from DB2 and transfer it to the user. If you use Oracle 8i instead of DB2, you will find that it claims to have similar features (see Resources). For databases that don't understand XML, you can store the XML document as a character large object (CLOB) and retrieve documents in a text block.
However, after installing the database, you need to complete the following three things to work:
First, change DBOWNER, DBUSERID and DBPASSWD variables to appropriate values for the system.
/
/ / Must change these three strings correctly, otherwise //
// servlet does not work. //
/
Dbuserid = "xxxxxxxx";
Dbpasswd = "xxxxxxxx";
DBOWNER = "xxxxxxxx";
Next, use the JDBC driver that is suitable for your system. We are using DB2.
Static string jdbcdriver = "com.ibm.db2.jdbc.App.db2driver";
...
Try
{
Class.Forname ("com.ibm.db2.jdbc.app.db2driver"). NewInstance ();
}
Catch (Exception E)
{
System.out.println ("Can't Get The Driver!"); E.PrintStackTrace ();
} If you like, you can change the following SQL query statement. To simplify the example, you only retrieve all XML documents in the Order column of the Sales_Order_View table.
/ / We have hardcoded SQL statements here; if you enter
// Limit the query, the situation will be more complicated. String query = "select Order from" DBOWNER ".sales_order_view";
In the service method, our servlet connection DB2, performs a query (its result is a set of XML documents), analyzes the results of the query, and writes the analyzed data to the output stream. Listing 6 shows the code part that is the most closely related to this relationship:
Listing 6. XMLFromDB2.JAVA
/ / We have hardcoded SQL statements here; if you enter
// Limit the query, the situation will be more complicated. String query = "select Order from" DBOWNER ".sales_order_view";
Res.SetContentType ("text / xml");
Try
{
CONINFO INDEX = New Conince ();
Connection con = GetCon (index); statement stmt = con.createstatement ();
ResultSet RS = Stmt.executeQuery (Query);
...
// Display result set. We remove the XML document from each line.
// Analyze it, then print the DOM tree. RS.NEXT () returns when there is no more rows
// false. While (rs.next ())
{
String nextorder = rs.getstring (1) .trim ();
Document Doc = NULL;
StringReader SR = New StringReader (NextOrder);
InputSource ISRC = New INPUTSOURCE (SR);
Try
{
Parser.Parse (ISRC);
Doc = parse.getdocument ();
}
Catch (Exception E)
{
System.err.Println ("Sorry, An Error Occurred:" E);
}
IF (doc! = null)
Printdomtree (DOC, OUT);
}
To learn all details, you can view the HTML view of your full list or view the Java source file directly.
Summary Although there is no such servlet example to change the world, but they do show how good the XML and Servlet works. Servlet is a great mechanism to send content to customers, while XML is a perfect mechanism for transmitting structured data. You can also use the XML document on the Servlet handling the server and send their content to the client. Most importantly, these two technologies are cross-platform technology, which can bring greater flexibility and variability for your application.