Examples of JSP+XML structured website
Author:Eve Cole
Update Time:2009-07-02 17:11:58
XML (Extensible Markup Language) may look like some kind of W3C standard - it has little practical impact now, and if it does come in handy later, it will be a long time coming. But in fact, it is already being used. So, don't wait until XML is added to your favorite HTML editor to start using it. It can solve various internal problems and B2B system problems now.
At Sparks.com, we use XML to standardize data representation across disparate systems, from Java objects to HTML data displays.
In particular, we've found that data can be shared and manipulated more easily when it's standardized on a very basic XML structure. Along the way, we discovered many effective ways to use XML. The following describes our current application in detail.
Standardize 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. Here we introduce the specific generation steps.
Using XSL as a template language
XSL (Extensible Stylesheet Language) is a good way to define the format for displaying XML data, and it would be more efficient if written as several static templates.
Generate HTML
XML plus XSL equals HTML. This may not sound right, but our HTML pages that users see are actually the result of the combination of XML and XSL.
1. Standardization
The power of XML comes from its flexibility. But unfortunately, it's sometimes so flexible that you're left with a blank page wondering how to solve the problem.
In any XML project, the first step is to create a standard data format. To do this you need to make the following decisions:
&&&
Confirm the data:
Because there is no standard XML format, developers are free to develop their own formats. However, if your format is only recognized by one application, then you can only run that application to use the format. It would obviously be more helpful if there were other programs that could also read your XML format. If an XML format is modified, the system using it may also need to be modified, so you should create the format as complete as possible. Because most systems ignore tags they don't recognize, the safest way to change the format of an XML is to add tags, rather than modify them.
Click here to view XML data format examples
At Sparks.com, we looked at all the product data needed for different product presentations. Although not all pages use all data, we have developed a very complete XML data format suitable for all data. For example, our product details page displays more data than our product browse page. However, we still use the same data format in both cases because each page's XSL template uses only the fields it requires.
Whether to use DTD
At Sparks.com we use well-organized XML rather than just correct XML, as the former does not require a DTD. DTD adds a layer of processing between the user clicking and seeing the page. We found this layer required too much processing. Of course, it's still nice to use DTDs when communicating with other companies in XML format. Because DTD can ensure that the data structure is correct when sending and receiving.
Choosing a Parsing Engine Now, there are several parsing engines that can be used. Which one you choose depends almost entirely on your application needs. If you decide to use a DTD, the parsing engine must enable your XML to be validated by the DTD. You could put the validation into a separate process, but that would impact performance.
SAX and DOM are two basic parsing models. SAX is event based, so when the XML is parsed, events are sent to the engine. Next, the events are 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, XML data can be provided as if determined by an XSL stylesheet. The debate on the SAX model mainly focuses on the excessive memory reduction of the DOM structure and the acceleration of XSL style sheet parsing time.
However, we found that many systems using SAX did not use it to its full capabilities. These systems use it to build the DOM structure and send events through the DOM structure. With this approach, the DOM must be built from the stylesheet before any XML processing, so performance will suffer.
2. Generate dynamic XML
Once the XML format is established, we need a way to dynamically port it from the database.
Generating XML documents is relatively simple because it only requires a system that can handle strings. We built a system using Java Servlets, Enterprise JavaBean server, JDBC and RDBMS (relational database management system).
&&&&
(For additional information on applying XSL, see XSL as a Template Language.)
Example of Generating XML The actual code for creating an XML docstring in Java can be divided into several methods and classes.
The code that starts the XML generation process is placed in the EJB method. This instance 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 following three xml.append() variables themselves are calls to other methods.
Generating the File Header The first additional method calls the XmlUtils class to generate the 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 the XML file header. The <?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 sheet to display the data. The last thing included is the item-level tag (<browse> in this example). At the end of the file, only the <browse> tag needs to be closed.
<?xml version="1.0"?> <?xml-stylesheet href="/browse_find/browse.xsl" type="text/xsl"?> <browse>
After filling in the product information and completing the file header, the control method will call 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 the product node by generating <product> and </product> tags. It then calls internalXML(), which provides the required content for the product XML. internalXML() is a series of StringBuffer.append() calls. The 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(" ");
Pang?
xml.append(" ").append(amount).append(" ");
xml.append(" ").append(vendor).append(" ");
xml.append(" ");
xml.append(" ").append(pubDesc).append(" ");
xml.append(" ").append(venDesc).append(" ";
Pang?
return xml.toString();
}
Finally, the XMLUtils.endDocument() method is called after closing the file. This call closes the XML tag (in this case) and finally completes the structured XML file. The entire StringBuffer from the control method is also converted to a string and returned to the servlet that handled the original HTTP request.
3. Use XSL as a template language
To get HTML output, we combine the generated XML file with an XSL template that controls how the XML data is represented. Our XSL templates consist of carefully organized XSL and HTML tags.
Start building the template The beginning of our XSL template looks similar to the following code. The first line of code is required and defines this file as an XSL style sheet. The xmlns:xsl= attribute refers to the XML namespace used by this file, and the version= attribute defines the version number of the namespace. At the end of the file we close the tag.
The second line of code starting with <xsl:template> determines the pattern of the XSL template. The Match attribute is required and here points to the XML tag <basketPage>. In our system, the <basketPage> tag contains the <product> tag, which allows the XSL template to access product information embedded in the <product> tag. Once again we have to close the <xsl:template> tag at the end of the file.
Next, let's take a look at well-organized HTML. Since it will be processed by an XML parsing engine, it must comply with all the rules of well-organized XML. Essentially, this means that all opening tags must have a corresponding closing tag. For example, a <P> tag that is not normally closed must be closed 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>
Within the body of the template, there are many XSL tags used to provide logic for data presentation. Two commonly used tags are explained below.
Choose
The <xsl:choose> tag is similar to the beginning of an if-then-else structure in traditional programming languages. In XSL, the choose tag indicates that in the part where the code enters, the assignment will trigger the action. The <xsl:when> tag with assigned attributes follows the choose tag. If the assignment is correct, the content between the opening and closing tags of <xsl:when> will be used. If the assignment is wrong, the content between the opening and closing tags of <xsl:otherwise> is used. The entire section ends with </xsl:choose>.
In this example, the when tag checks the XML for the quantity tag. If the quantity tag contains an error attribute with a value of true, the quantity tag will display the table cells listed below. If the attribute's value is not true, XSL will display the content between the tags otherwise. In the example below, if the error attribute is not true, nothing will be displayed.
<xsl:choose>
<xsl:when test="quantity[@error='true']">
<td bgcolor="src=""/></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
The <xsl:for-each> tag can be used to apply the same style sheet to multiple situations of similar XML data. For us, a series of product information can be taken out from the database and formatted uniformly on the Web page. Here's 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 label. This loop will end when the program encounters a label. Once this loop runs, this template will be applied every time the label appears.
4. Generate HTML
At some point in the future, browsers will integrate XML parsing engines. At that point, you can send XML and XSL files directly to the browser, and the browser displays the XML data according to the rules listed in the style sheet. However, until then developers will have to create parsing capabilities in their server-side systems.
At Sparks.com, we have integrated an XML parser into the Java servlet. This parser uses a mechanism called XSLT (XSL Transformation) to add XML data to the XSL template as specified by the XSL tag.
When our Java servlet handles an HTTP request, the servlet retrieves the dynamically generated XML, which is then passed to the parsing engine. Based on the instructions in the XML file, the parsing engine looks for the appropriate XSL stylesheet. The parser creates an HTML file from the DOM structure, and then this file is sent to the user who makes the HTTP request.
If you choose to use the SAX model, the parser reads through the XML source and creates an event for each XML tag. Events correspond to XML data, and the data is ultimately inserted into the style sheet according to XSL tags.