17.3 A Tool Application

Java Servlet Programming, 2nd Edition > 17. XMLC > 17.3 A Tool Application

 
< BACKCONTINUE >

17.3 A Tool Application

To conclude our discussion of XMLC, let's look at how the tool application used to demonstrate Tea and WebMacro can be rewritten using XMLC. We'll look first at the HTML template file that represents the common look and feel for our site but has no content relating to our tool listing. It's shown in Example 17-6.

Example 17-6. The Tool Application Template File
<!-- template.html --> <HTML><HEAD><TITLE>Example Title</TITLE></HEAD> <BODY BGCOLOR="#FFFFFF" BACKGROUND="/images/background.gif"       LINK="#003333" ALINK="#669999" VLINK="#333333"> <IMG src="/books/1/318/1/html/2//images/banner.gif" WIDTH=600 HEIGHT=87 BORDER=0><BR> <TABLE> <TR> <TD WIDTH=125 VALIGN=TOP>  <BR><BR><BR>  <FONT FACE="Arial,Helvetica" SIZE="+1" COLOR="#FF0000">  <A HREF="/index.html">Home</A><BR>  <A HREF="/hosting.html">Hosting</A><BR>  <A HREF="/engines.html">Engines</A><BR>  </FONT> </TD> <TD WIDTH=475>   <TABLE CELLPADDING=5><TR><TD WIDTH=600 BGCOLOR="#006699" VALIGN=TOP>   <B><FONT FACE="Arial,Helvetica" SIZE="+2">   <SPAN >Example Title</SPAN>   </FONT></B>   </TD></TR></TABLE>   <B><FONT FACE="Arial,Helvetica" SIZE="+1" COLOR="#003366">   <SPAN >Example Deck</SPAN>   </FONT></B><P>   <P>   <FONT FACE="Arial,Helvetica">   <SPAN >Example Description</SPAN>   <DIV >True content here</DIV>   </FONT> </TD> </TR> <TR> <TD></TD> <TD WIDTH=475 ALIGN=CENTER COLSPAN=3> <HR> <FONT FACE="Arial,Helvetica"> <A HREF="/index.html">Home</A>&nbsp;&nbsp; <A HREF="/hosting.html">Hosting</A>&nbsp;&nbsp; <A HREF="/engines.html">Engines</A>&nbsp;&nbsp;<P> </FONT> <TABLE WIDTH=100%> <TR> <TD WIDTH=260 ALIGN=LEFT VALIGN=TOP> <FONT FACE="Arial,Helvetica"> <A HREF="/copyright.html">Copyright</A> &copy; 2000 Jason Hunter<BR> All Rights Reserved.</TD> <TD WIDTH=5></FONT></TD> <TD WIDTH=230 ALIGN=RIGHT VALIGN=TOP> <FONT FACE="Arial,Helvetica"> Contact: <A HREF="mailto:webmaster@servlets.com">webmaster@servlets.com</a> </FONT></TD> </TR> </TABLE> </TD> </TR> </TABLE> </BODY> </HTML>

Notice the title of the page is a placeholder, and there are three <SPAN> elements named title, deck, and desc holding mock-up text intended for replacement. Also, there's a <DIV> element named content marking the location where the true content for the page should be displayed. The HTML file that will be used to generate the tool application content is shown in Example 17-7.

Example 17-7. The Tool Application Content File
<!-- toolview.html --> <HTML><HEAD><TITLE>Tool Listing</TITLE></HEAD> <BODY BGCOLOR="#FFFFFF" BACKGROUND="/images/background.gif"       LINK="#003333" ALINK="#669999" VLINK="#333333"> <IMG src="/books/1/318/1/html/2//images/banner.gif" WIDTH=600 HEIGHT=87 BORDER=0><BR> <TABLE> <TR> <TD WIDTH=125 VALIGN=TOP>  <BR><BR><BR>  <FONT FACE="Arial,Helvetica" SIZE="+1" COLOR="#FF0000">  <A HREF="/index.html">Home</A><BR>  <A HREF="/hosting.html">Hosting</A><BR>  <A HREF="/engines.html">Engines</A><BR>  </FONT> </TD> <TD WIDTH=475>   <TABLE CELLPADDING=5><TR><TD WIDTH=600 BGCOLOR="#006699" VALIGN=TOP>   <B><FONT FACE="Arial,Helvetica" SIZE="+2">   <SPAN >Tool Listing</SPAN>   </FONT></B>   </TD></TR></TABLE>   <B><FONT FACE="Arial,Helvetica" SIZE="+1" COLOR="#003366">   <SPAN >A list of content creation tools</SPAN>   </FONT></B><P>   <P>   <FONT FACE="Arial,Helvetica">   <SPAN >   Without tools, people are nothing more than animals.  And pretty weak ones   at that.  Here's a list of servlet-based content creation tools you can use   so you won't be a servlet weakling.   </SPAN>   <DIV >     <HR SIZE=2 ALIGN=LEFT>     <FONT FACE="Arial,Helvetica">     <H3>     <SPAN >Some Tool Name</SPAN>     <FONT COLOR=#FF0000><B> <SPAN >(New!)</SPAN> </B></FONT>     </H3>     <A  HREF="http://toolhome.com">http://toolhome.com</A><BR>     <SPAN >        Here go comments for this tool.     </SPAN>     </FONT>   </DIV>   <DIV>     <HR SIZE=2 ALIGN=LEFT>     <FONT FACE="Arial,Helvetica">     <H3>     Another Tool Name     <FONT COLOR=#FF0000><B> (Updated!) </B></FONT>     </H3>     <A HREF="http://toolhome.com">http://toolhome.com</A><BR>        Here go comments for this tool.     </FONT>   </DIV>   </FONT> </TD> </TR> <TR> <TD></TD> <TD WIDTH=475 ALIGN=CENTER COLSPAN=3> <HR> <FONT FACE="Arial,Helvetica"> <A HREF="/index.html">Home</A>&nbsp;&nbsp; <A HREF="/hosting.html">Hosting</A>&nbsp;&nbsp; <A HREF="/engines.html">Engines</A>&nbsp;&nbsp;<P> </FONT> <TABLE WIDTH=100%> <TR> <TD WIDTH=260 ALIGN=LEFT VALIGN=TOP> <FONT FACE="Arial,Helvetica"> <A HREF="/copyright.html">Copyright</A> &copy; 2000 Jason Hunter<BR> All Rights Reserved.</TD> <TD WIDTH=5></FONT></TD> <TD WIDTH=230 ALIGN=RIGHT VALIGN=TOP> <FONT FACE="Arial,Helvetica"> Contact: <A HREF="mailto:webmaster@servlets.com">webmaster@servlets.com</a> </FONT></TD> </TR> </TABLE> </TD> </TR> </TABLE> </BODY> </HTML>

This file looks a lot like the template file, but we have replaced the placeholder values with realistic values and filled in the content area with some prototype tool records. Here's how we'll use this file: we'll programmatically take its key components (its title, deck, description, and prototype record), copy them, and place them into the template file to create the final page.

Why do we need two files? Couldn't we just modify the toolview.html file directly? Yes, we could, but we use the template so that if we update the header, sidebar, or footer in the future, we can update just the template.html file and have that change affect all pages. In other words, the template dictates the overall layout of the page. The toolview.html file is used only for its critical parts.

We run the HTML files through the XMLC compiler using commands like the following. There will be some warnings because the HTML is not valid XML:

% xmlc -class Template -keep -methods template.html % xmlc -class ToolView -keep -methods toolview.html

Then we're ready to write the servlet that acts as the manipulation class. It's listed in Example 17-8.

Example 17-8. The Tool Application Manipulation Class
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.w3c.dom.*; import org.w3c.dom.html.*; import org.enhydra.xml.io.DOMFormatter; public class ToolViewServlet extends HttpServlet {   private Tool[] tools;   public void init() throws ServletException {     // Load the tool data in our init for simplicity     String toolsFile = getInitParameter("toolsFile"); // from web.xml     if (toolsFile == null) {       throw new ServletException(         "A tools data file must be specified as the toolsFile init parameter");     }     log("Loading tools from " + toolsFile);     try {       tools = Tool.loadTools(toolsFile);       if (tools.length == 0) {         log("No tools found in " + toolsFile);       }       else {         log(tools.length + " tools found in " + toolsFile);       }     }     catch (Exception e) {       throw new ServletException(e);     }   }   public void doGet(HttpServletRequest req, HttpServletResponse res)                                throws ServletException, IOException {     res.setContentType("text/html");     PrintWriter out = res.getWriter();     // Create the DOM tree for the full document     Template template = new Template();     // Create the DOM Tree that contains the internal content     ToolView toolview = new ToolView();     // Get the prototype tool view record     HTMLDivElement record = toolview.getElementRecord();     // Get a reference to the insertion point for the tool list     HTMLDivElement insertionPoint = template.getElementContent();     Node insertionParent = insertionPoint.getParentNode();     // Set the template title, deck, and desc     // Pull the data from the toolview.html file     String title = ((Text)toolview.getElementTitle().getFirstChild()).getData();     String deck = ((Text)toolview.getElementDeck().getFirstChild()).getData();     String desc = ((Text)toolview.getElementDesc().getFirstChild()).getData();     template.setTitle(title);     // the page title     template.setTextTitle(title); // the element marked "title"     template.setTextDeck(deck);   // the element marked "deck"     template.setTextDesc(desc);   // the element marked "desc"     // Loop over the tools adding a record for each     for (int i = 0; i < tools.length; i++) {       Tool tool = tools[i];       toolview.setTextToolName(tool.name);       toolview.setTextToolComments(tool.comments);       if (tool.isNewWithin(45)) {         toolview.setTextToolStatus(" (New!) ");       }       else if (tool.isUpdatedWithin(45)) {         toolview.setTextToolStatus(" (Updated!) ");       }       else {         toolview.setTextToolStatus("");       }       HTMLAnchorElement link = toolview.getElementToolLink();       link.setHref(tool.homeURL);       Text linkText = toolview.createTextNode(tool.homeURL);       link.replaceChild(linkText, link.getLastChild());       // importNode() is DOM Level 2       insertionParent.insertBefore(template.importNode(record, true), null);     }     // Remove insertion placeholder     insertionParent.removeChild(insertionPoint);     // Output the document     DOMFormatter formatter = new DOMFormatter();  // can be heavily tweaked     formatter.write(template, out);   } }

The init( ) method of the servlet loads the tool data from the file specified in the toolsFile init parameter, using the Tool class from Chapter 14. In the doGet( ) method we do the interesting work. We create an instance of the Template document and an instance of the ToolView document. Then we locate the prototype tool record in the ToolView and the insertion point for tool records in the Template. Next we retrieve the title, deck, and description from the ToolView document and copy over those values to the Template.

In the for loop we handle the task of creating the list of tool records. For each tool, we assign appropriate values to the prototype record: first the name and comments, then the status, and finally the link. After the record has been modified, we add the record to the template at the insertion point. In DOM, nodes are tied to the document that created them, so we use the importNode( ) method to enable the record to move from the ToolView document to the Template. The importNode( ) method performs a deep copy (because we passed true as the second argument) so each iteration of the for loop adds a different copy of the record contents. After the for loop we remove the insertion point from the template and output the document to the client.

When running this servlet be aware that the importNode( ) method is new in DOM Level 2, so for this servlet to execute, your server must have a classpath that includes the DOM Level 2 classes before any DOM Level 1 classes. The xmlc.jar archive contains DOM Level 2, so you wouldn't think this would be a problem, but some servers (including Tomcat 3.2) have a DOM Level 1 implementation in their default classpath to help them read web.xml files. For this servlet to work on such servers you must edit the server classpath to ensure XMLC's xmlc.jar is located before the server's own XML libraries. (Tomcat 3.2 autoloads JAR files in alphabetical order, so you may need to rename JAR files.)

One problem inherent to XMLC shown by this example is that conditionally included blocks of text whose contents vary, like the (New! ) and (Updated! ) remarks, can be difficult to incorporate into pages because the template can declare only one possible block of text for inclusion. In this example it's clear the Java code knows more than it should about the rendering of the remarks.

A nice perk of XMLC is that any special characters in the included element content like <, >, and & are automatically escaped as they're sent to the client, because the formatter outputting the document can easily recognize what's structure and what's content. This knowledge of document structure also makes it possible for the formatter to perform advanced tasks like modifying all links to encode session IDs, although that particular feature hasn't yet been implemented.

The page generated by this servlet looks the same as the page generated by the Tea and WebMacro examples.


Last updated on 3/20/2003
Java Servlet Programming, 2nd Edition, © 2001 O'Reilly

< BACKCONTINUE >


Java servlet programming
Java Servlet Programming (Java Series)
ISBN: 0596000405
EAN: 2147483647
Year: 2000
Pages: 223

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net