Servlet and XML

zhaozj2021-02-08  418

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 ("");

Out.println (""); out.println ("Hello, World!");

Out.println ("");

}

} The result of this exciting code generation is as follows: Listing 2. XMLFromscratch.java results

Hello, World!

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:

Shakespeare

William

British

1564

1616

If the subtree parameter is Title, the result is:

SONNET 130 </ Title></p> <p>You can view the HTML view of your full list or view the Java source file directly.</p> <p>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.</p> <p>However, after installing the database, you need to complete the following three things to work:</p> <p>First, change DBOWNER, DBUSERID and DBPASSWD variables to appropriate values ​​for the system.</p> <p>/</p> <p>/ / Must change these three strings correctly, otherwise //</p> <p>// servlet does not work. //</p> <p>/</p> <p>Dbuserid = "xxxxxxxx";</p> <p>Dbpasswd = "xxxxxxxx";</p> <p>DBOWNER = "xxxxxxxx";</p> <p>Next, use the JDBC driver that is suitable for your system. We are using DB2.</p> <p>Static string jdbcdriver = "com.ibm.db2.jdbc.App.db2driver";</p> <p>...</p> <p>Try</p> <p>{</p> <p>Class.Forname ("com.ibm.db2.jdbc.app.db2driver"). NewInstance ();</p> <p>}</p> <p>Catch (Exception E)</p> <p>{</p> <p>System.out.println ("Can't Get The Driver!"); E.PrintStackTrace ();</p> <p>} 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.</p> <p>/ / We have hardcoded SQL statements here; if you enter</p> <p>// Limit the query, the situation will be more complicated. String query = "select Order from" DBOWNER ".sales_order_view";</p> <p>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:</p> <p>Listing 6. XMLFromDB2.JAVA</p> <p>/ / We have hardcoded SQL statements here; if you enter</p> <p>// Limit the query, the situation will be more complicated. String query = "select Order from" DBOWNER ".sales_order_view";</p> <p>Res.SetContentType ("text / xml");</p> <p>Try</p> <p>{</p> <p>CONINFO INDEX = New Conince ();</p> <p>Connection con = GetCon (index); statement stmt = con.createstatement ();</p> <p>ResultSet RS = Stmt.executeQuery (Query);</p> <p>...</p> <p>// Display result set. We remove the XML document from each line.</p> <p>// Analyze it, then print the DOM tree. RS.NEXT () returns when there is no more rows</p> <p>// false. While (rs.next ())</p> <p>{</p> <p>String nextorder = rs.getstring (1) .trim ();</p> <p>Document Doc = NULL;</p> <p>StringReader SR = New StringReader (NextOrder);</p> <p>InputSource ISRC = New INPUTSOURCE (SR);</p> <p>Try</p> <p>{</p> <p>Parser.Parse (ISRC);</p> <p>Doc = parse.getdocument ();</p> <p>}</p> <p>Catch (Exception E)</p> <p>{</p> <p>System.err.Println ("Sorry, An Error Occurred:" E);</p> <p>}</p> <p>IF (doc! = null)</p> <p>Printdomtree (DOC, OUT);</p> <p>}</p> <p>To learn all details, you can view the HTML view of your full list or view the Java source file directly.</p> <p>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.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-860.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="860" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.041</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'TC_2FW51Ck_2FV71e76Cr4f5K3_2FQnOgBW4oVsX6HkARtrQikxKLgl2LgxY8cDedaD3IlRxsuOymQUJgrP3ji'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>