JSP + XML architecture website instance

Source: Internet
Author: User
Tags xml parser

XML (Extensible Markup Language) may look like a W3C standard-there is no real impact now, even if it can be used in the future, it will be a long time later. But in fact, it is now applied. Therefore, do not use XML until it has been added to your favorite HTML editor. It can now solve various internal and B2B system problems.

In Sparks.com, we use XML to standardize data representation between different systems, such as Java objects and HTML data display.

In particular, we found that data can be shared and operated more easily as long as the standard is implemented with a very basic XML structure. In this process, we found many effective methods to use XML. The following describes our current application in detail.

Standardization
Before using XML, create an XML data format that is different from the information you want to use.

Generate dynamic XML
Generating HTML from a database is not new, but generating XML is fresh. Here we will introduce the specific generation steps.

Using XSL as the template Language
XSL (Extensible style sheet language) is a good way to define the XML data display format. It is more effective if you write several static templates.

Generate HTML
Adding XSL to XML is equivalent to HTML. This sounds wrong, but what we see in the user's HTML page is actually the result of the combination of XML and XSL.

I. Standardization

The XML capability comes from its flexibility. But unfortunately, it is sometimes too flexible, so that you will face a blank page and worry about how to solve the problem.

In any XML project, the first step is to create a standard data format. Therefore, you must make the following decisions:

&&&
Confirm data:
Because there is no standard XML format, developers can develop their own formats freely. However, if your format can only be recognized by one application, you can only run this program to use this format. If there are other programs that can read your XML format, it is obviously more helpful. If an XML format is modified
The system that uses it may also need to be modified. Therefore, you should establish a complete format as much as possible. Because most systems ignore tags that they cannot recognize, the safest way to change an XML format is to add tags instead of modifying tags.

Click here to view the XML data format instance

At Sparks.com, we checked all the product data required for different products. Although not all pages use all data, we have developed a very complete XML data format for all data. For example, our product details page displays more data than the product browsing page. However, we still use the same data format in both cases, because each page's XSL template only uses the fields it requires.

Whether to use DTD
In Sparks.com, we use well-organized XML, not just the correct XML, because the former does not require DTD. The DTD adds a processing layer between the user clicks and the page that appears. We found that this layer requires too much processing. Of course, when you communicate with other companies in XML format, using DTD is quite good. Because DTD can ensure that the data structure is correct when sending and receiving data.

Select resolution Engine
Currently, there are several parsing engines available. Which one to choose depends almost entirely on your application needs. If you decide to use DTD, This parsing engine must make your XML validated by DTD. You can put the verification in another process, but that will affect the performance.

SAX and DOM are two basic parsing models. The event is sent to the engine when the XML is parsed Based on the event. Next, the event is synchronized with the output file. The DOM parsing engine creates a hierarchical tree structure for dynamic XML data and XSL style sheets. By randomly accessing the DOM tree, you can provide XML data, just as determined by the XSL style sheet. The debate on the SAX model mainly focuses on the reduction of memory in the DOM structure and the shortening of the time for parsing the XSL style table.

However, we found that many systems using SAX did not fully utilize its capabilities. These systems use it to create a DOM structure and send events through the DOM structure. In this way, DOM must be created from the style sheet before any XML processing, so the performance will decrease.

Ii. generate dynamic XML

Once the XML format is set up, we need a way to dynamically port it from the database.

Generating an XML document is relatively simple because it only requires a system that can process strings. We have built a system that uses Java Servlet, Enterprise JavaBean server, JDBC, and RDBMS (relational database management system.

&&&&
(For more information about XSL applications, see using XSL as the template language .)

Example of generating XML
The real code for creating XML document strings in Java can be divided into several methods and classes.

The code that starts the XML generation process is put in the EJB method. This routine immediately creates a StringBuffer to store the generated XML string.

StringBuffer xml = new StringBuffer ();
Xml. append (XmlUtils. beginDocument ("/browse_find/browse. xsl", "browse", request ));
Xml. append (product. toXml ());
Xml. append (XmlUtils. endDocument ("browse ");
Out. print (xml. toString ());

The next three xml. append () variables are calls to other methods.
Generate a File Header
The first additional method calls the XmlUtils class to generate an XML file header. The code in our Java Servlet is as follows:

Public static String beginDocument (String stylesheet, String page)
{
StringBuffer xml = new StringBuffer ();
Xml. append ("<? Xml version = "1.0"?> ")
. Append ("<? Xml-stylesheet href = "")
. Append (stylesheet). append (""")
. Append ("type =" text/xsl "?> ");
Xml. append ("<"). append (page). append ("> ");
Return xml. toString ();
}

This code generates an XML file header. <? Xml> tag defines this file as an XML file that supports Version 1.0. The second line of code points to the location of the correct style table used to display data. The last entry is the item-level label (<browse> in this instance ). At the end of the file, only the <browse> label needs to be closed.

<? Xml version = "1.0"?> <? Xml-stylesheet href = "/browse_find/browse. xsl" type = "text/xsl"?> <Browse>

Enter Product Information
After the file header is completed, the control method calls the Java object to generate its XML. In this example, the product object is called. The product object uses two methods to generate its XML Representation. The first method toXML () creates a product node by generating the <product> and </product> labels. It then calls internalXML () to provide the content required for the product XML. InternalXML () is a series of StringBuffer. append () calls. StringBuffer is also converted to a string and returned to the control method.
Public String toXml ()
{
StringBuffer xml = new StringBuffer ("<product> ");
Xml. append (internalXml ());
Xml. append ("</product> ");
Return xml. toString ();
}

Public String internalXml ()
{
StringBuffer xml = new
StringBuffer ("")
. Append (productType). append ("");
Xml. append (""). append (idValue. trim ())
. Append ("");
Xml. append (""). append (idName. trim ())
. Append ("");
Xml. append (""). append (page. trim ())
. Append ("");
Why?
Xml. append (""). append (amount). append ("");
Xml. append (""). append (vendor). append ("");
Xml. append ("");
Xml. append (""). append (pubDesc). append ("");
Xml. append (""). append (venDesc). append ("";
Why?
Return xml. toString ();
}

Close file
Finally, the XMLUtils. endDocument () method is called. This call closes the XML tag (in this example) and finally completes the XML file with a good architecture. The entire StringBuffer from the control method is also converted to a string and returned to the servlet that processes the original HTTP request.

Iii. Using XSL as the template Language

To get html output, we combine the generated XML file with the XSL template that controls how XML data is represented. Our XSL template consists of carefully organized XSL and HTML tags.

Start template Creation
The beginning part of our XSL template is similar to the following code. The first line of code is required. This file is defined as an XSL style sheet. Xmlns: xsl = attribute references the XML namespace used in this file, while version = attribute defines the version number of the namespace. Close the tag at the end of the file.

The second line of code starting with <xsl: template> confirms the mode of the XSL template. The Match attribute is required and points to the XML tag <basketPage>. In our system, the <basketPage> tag contains the <product> tag, which allows the XSL template to access the product information embedded in the <product> tag. Once again, we must close the <xsl: template> tag at the end of the file.

Next, let's take a look at the well-organized HTML. Because it will be processed by the XML parsing engine, it must comply with all the well-organized XML rules. Essentially, this means that all start labels must have corresponding end labels. For example, the <P> label that is usually not terminated must be disabled with </P>.

<Xsl: stylesheet xmlns: xsl = "http://www.w3.org/1999/XSL/Transform"
Version = "1.0">
<Xsl: template match = "basketPage">
<Html>
<Head>
<Title> Shopping Bag/Adjust Quantity </title>
</Head>
<Body bgcolor ="

</Xsl: template>
</Xsl: stylesheet>

Many XSL labels are used in the template body to provide logic for data representation. The following describes two commonly used labels.
Choose
<Xsl: choose> labels are similar to the start part of the if-then-else structure in traditional programming languages. In XSL, the choose label indicates that the assignment will trigger the action in the code entry section. The <xsl: when> tag with the value assignment attribute is behind the choose tag. If the value assignment is correct, the content between the start and end labels of <xsl: when> will be used. If the value assignment is incorrect, use the content between the start and end labels of <xsl: otherwise>. The entire part is ended with </xsl: choose>.

In this example, the when TAG checks the XML for the quantity tag. If the quantity tag contains the error attribute whose value is true, the quantity tag displays the table units listed below. If the attribute value is not true, XSL displays the content between otherwise labels. In the following example, if the error attribute is not true, nothing will be displayed.

<Xsl: choose>
<Xsl: when test = "quantity [@ error = 'true']">
<Td bgcolor = "src =" http://img.sparks.com/Images/I-Catalog/sparks_images/sparks_ui/clearpixel.gif "/> </td>
<Td valign = "top" bgcolor = "<font face =" Verdana, Arial "size =" 1 "color =" <B> * Not enough in stock. your quantity was adjusted accordingly. </B> </font>
</Td>
</Xsl: when>
<Xsl: otherwise>
</Xsl: otherwise>
</Xsl: choose>

For-each
<Xsl: for-each> labels can be used to apply the same style table to multiple situations with similar XML data. For us, we can retrieve a series of product information from the database and format it on the web page. Here is an example:
<Xsl: for-each select = "package">
<Xsl: apply-templates select = "product"/>
</Xsl: for-each>

The for-each loop starts when the program encounters a tag. This loop ends when the program encounters a tag. Once this loop is run, this template will be applied every time the tag appears.

4. Generate HTML

In the future, the browser will integrate the XML parsing engine. At that time, you can directly send XML and XSL files to the browser, while the browser displays XML data according to the rules listed in the style sheet. However, before that, developers will have to create parsing functions in their server-side systems.

At Sparks.com, we have integrated an XML parser in Java servlet. This parser uses a mechanism called XSLT (XSL Transformation) to add XML data to the XSL template according to the description of the XSL tag.

When our Java servlet processes HTTP requests, the servlet retrieves the dynamically generated XML and then transmits the XML to the parsing engine. Based on the instructions in the XML file, the parsing engine looks for the appropriate XSL style sheet. The parser creates an HTML file through the DOM structure, and then transmits the file to the user who sends the HTTP request.

If you choose to use the SAX model, the parser will read the XML source program and create an event for each XML tag. The event corresponds to the XML data, and finally inserts data into the style sheet according to the XSL tag.

Related Article

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.