Servlet and XML: complementary to each other (i) (turn)

Source: Internet
Author: User
Tags comments http request key object model query
Servlet|xml Download It now!                                                                 [/TR]                                                                                                                               PDF(79.4 KB)
Free Acrobat Reader-->
Servlet and XML: complementing each other
Doug Tidwell
DeveloperWorks Staff
April 2000
content:Our first servlet sample a basic servlet-generated XML segment and database docking brief introduction to reference authors
study how the Java servlet and XML work together to generate XML documents and DOM trees, and how they dock with the database. This article includes several useful techniques: using HTTP parameters to control the processing and generation of a DOM tree without the need for an XML source document.


For Java programmers, Servlet and XML are two of the most exciting technologies. This article is a presentation prepared for the San Francisco City Java user group February 17, 2000. In this article you'll see how to use a servlet to make a simple XML document, build a DOM tree, and display part of the content on the user's screen, and finally you'll see how to generate XML from a database query.
For the example discussed in this article, we will extend the HttpServlet class. The HttpServlet class provides functionality that is typically associated with CGI programs. It supports put and get, and gives your code full access to the HTTP request headers, including the useragent domain. We'll create some simple servlet and show how they handle the information tagged with XML tags. In this process we will also describe some of the methods of the Document Object Model (DOM). These simple applications will give you an idea of what you can do when you combine the servlet and XML.
First servlet Example
As a start, we'll write a 10-line servlet to generate the XML document. When building a servlet that understands XML, we will do the following three steps:
    1. Set the content type to Text/xml.
    2. Create an XML document.
    3. Writes the XML document back to the client.

In most of our Servlet, the main focus is on the second step. We may create an XML document from a database query, or it may be based on an HTTP parameter that is delivered from the customer, or it may be possible to use other types of data retrieval or generation methods. In the example in this article, you will consider HTTP parameters and database queries primarily.
a basic servlet
For the first example, the second step is "create an XML document" is notWhat we care about; we just want to generate a valid XML document. We have hard-coded the document into the source code, as shown in Listing 1. Color-coding our colorful coding[/b]-->
Color Coding
The color coding list is a feature of this article and we are experimenting with DW. To generate our color-coded listings, I'm using some open source tools. First, I load the document (Java, HTML, XML, and so on) into Emacs. Emacs defines the colors for keywords, comments, function names, and other programming language artifacts (about 10 or more). After Emacs loads and adds color to the file, I use the Htmlize package, an open source utility written in the once popular Emacs Lisp language. Htmlize receives a list (the list looks exactly like it does in Emacs) and converts it to HTML. The result will be a fully color-coded file that highlights keywords, comments, function names, and so on.
Please disassemble our thoughts on these new and improved code listings.
If you would like to do so, see the appropriate link in resources.
Listing 1. Xmlfromscratch.java
public class Xmlfromscratch extends HttpServlet {public void service (HttpServletRequest request, Ht    Tpservletresponse response) throws IOException, servletexception {response.setcontenttype ("text/xml");        PrintWriter out = Response.getwriter ();    Out.println ("<?xml version=\" 1.0\ "?>");    Out.println ("<greeting language=\" en_us\ ">");    Out.println ("Hello, world!");  Out.println ("</greeting>"); }}

The results of this exciting code generation are as follows:
the results of Listing 2. Xmlfromscratch.java
<?xml version= "1.0"?><greeting> Hello, world!</greeting>

You can view the HTML view of the full list or view the Java source files directly.
Generate XML Segment
Now, we've created a servlet that generates a simple XML document that doesn't make sense through hard coding. In the next servlet, we build a DOM tree from scratch and then display a portion of the DOM tree on the requestor's screen. Part of the DOM tree sent back to the requestor depends on the HTTP parameters that the servlet receives. This example shows several useful techniques: using HTTP parameters to control the processing and generation of a DOM tree without the need for an XML source document.
Listing 3 shows the code snippet that handles the HTTP parameter:
Listing 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.hasmoreelements ()) {key = (String) keys.nextelement ();    if (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 the parameters from the HTTP request.
After processing these parameters, we need to find the information that the user requested. The information we use constructs the DOM tree from the object, which contains the text of Shakespeare's 14 lines of poetry and other information about the first 14 lines of poetry. We will return a portion of the DOM tree based on the HTTP subtree parameter. Listing 4 shows some of the code to build the DOM tree:
Listing 4. Building 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.setattribute (" 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 that implements the DOM Document interface, and then we ask that node to create a variety of nodes for us. You can easily rewrite the application so that it generates a DOM tree by parsing the XML file. To simplify the example (and reduce my workload), we defined some instance variables to hold the value of the node that was prepared to serve 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 part of the DOM tree to the user. To accomplish this, we use a recursive method, Printdomtree, that handles the node and all its child nodes. Since this method is recursive, it does not matter whether we start at the document root node or from the other nodes in the DOM tree. If the request is one of the nodes we know, you can pass the node to the method Printdomtree. Otherwise, we can pass the Document node. Listing 5 shows this step.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.