站内搜索: 请输入搜索关键词
当前页面: 图书首页 > XML and Java: Developing Web Applications, Second Edition

XML and Java: Developing Web Applications, Second Edition

[ directory ] Previous Section Next Section

11.6 A Servlet for Accessing a Database

In previous sections, we showed how to map between an XML document and tables and store and search for an XML document. All the programs we showed are standalone programs. As shown in Figure 11.1, a practical three-tier application implements business logic on an application server with Servlet or Enterprise JavaBeans. In this section and the next, we explain how to accomplish such a scenario.

The program XMLDBServlet, shown in Listing 11.11, is a servlet that calls the XMLTableRetriever class, shown in Listing 11.6. The servlet receives an XML document that contains an invoice ID via HTTP, searches the database with the ID, and returns the result document. This class is a subclass of chap10. GenericDOMServlet.java, shown in Listing 10.9 in Chapter 10.

Listing 11.11 A Java servlet to access the database, chap11/XMLDBServlet.java
       package chap11;
       /**
       * XMLDBServlet.java
       *
       */
       import javax.servlet.*;
       import javax.servlet.http.*;
       import java.io.*;
       import java.net.*;
       import java.util.*;

       import org.w3c.dom.Document;
       import org.w3c.dom.Element;
       import org.xml.sax.InputSource;
       import org.apache.xml.serialize.XMLSerializer;
       import org.apache.xml.serialize.OutputFormat;
       import javax.xml.parsers.DocumentBuilderFactory;
       import javax.xml.parsers.DocumentBuilder;
       import chap10.GenericDOMServlet;

       public class XMLDBServlet extends GenericDOMServlet {

           XMLTableRetriever arc;

[25]       public void init() throws ServletException {
       // Gets userid and password
       String userid   = getInitParameter("USERID");
       String password = getInitParameter("PASSWORD");
       // This constructor initiate connection to database
       arc = new XMLTableRetriever(userid, password);
           }

           /**
            * Handle request using GenericDOMServlet
            */
[36]        public Document doProcess(HttpServletRequest req,
                         HttpServletResponse res,
                         Document reqDoc) {
[39]   Document resDoc = null;
       try {
               Element root = reqDoc.getDocumentElement();
               String invoiceID = root.getFirstChild().getNodeValue();
               // Searches for documents with id
               resDoc = arc.searchByDocumentID(invoiceID);
               if (resDoc == null) {
             // Creates an XML document for the error
             DocumentBuilder builder =
                   DocumentBuilderFactory.newInstance().
                   newDocumentBuilder();
               resDoc = builder.newDocument();
               resDoc.appendChild(resDoc.createElement("Error"));
                 }
           } catch (Exception e) {
               e.printStackTrace();
           }
[56]       return resDoc;
           }

           public String getServletInfo() {
               return "A XMLDB servlet";
           }
           public void destroy(){
           }

       }

We described basic Servlet programming in Chapter 10, Section 10.2. We discuss some important points here.

  • Connection to a database is processed in the init() method (line 25). In this method, an XMLTableArchiver object is created, and the connection is initiated. The connection is kept until the servlet is destroyed. If the process is implemented by CGI, the connection process is invoked for each CGI execution. As shown the previous section, a connection pool can be used in the init() method. Some application servers provide a vendor-specific way to connect to a database. Section 10.2.3 shows some things to consider when you use multithreaded programming in servlets.

  • The doProcess() method (line 36) gets two streams for input and output, and a Document object. The class is a subclass of the chap10.GenericDOM Servlet class used to handle the charset and MIME type of the input XML document correctly (see the discussion in Section 10.2.2). The input document is parsed, and an ID for an XML document to be searched is extracted (line 56). The searchByDocumentID() method of the XMLTableArchiver class (see Listing 11.6) is called to submit a query to a database. The retrieved document is returned with the return value of the doProcess() method. By using the chap10.GenericDOMServlet class, you do not care about the handling of the charset and MIME type, and you can keep your program compact and safe.

Assume that this program is registered to an application server or a servlet engine and is accessible with the URL http://demohost:8080/xmlbook2/chap11/XMLDBServlet. The following is an XML document for input named test.xml.

<?xml version="1.0" encoding="UTF-8"?>
<invoiceNo>2001-08-31-12345</invoiceNo>

The program SendXML sends an XML document to a URL and outputs the result. It is also included on the CD-ROM. The program produces the following result.

R:\samples>java chap11.SendXML   < chap11\test.xml
<?xml version="1.0" encoding="UTF-8"?>
<purchaseOrder invoiceNo="2001-08-31-12345"><shipTo country="US">
<name>Alice Smith</name><street>123 Maple Street</street></shipTo>
<items><item qty="2">ThinkPad X21</item><item qty="1">ThinkPad T22
</item></items></purchaseOrder>
    [ directory ] Previous Section Next Section