XMLC vs. JSP

Java Development News:

XMLC vs. JSP

By David H. Young

01 Apr 2002 | TheServerSide.com

Introduction

Seasoned members of the software industry are all familiar with that weird, loss-of-control feeling that settles in during a long Web application development project. The post-mortem that may or may not happen reveals, in large part, what was already known. An affliction common to large corporations, application architects see their mandated design guidelines and best practices selectively ignored or abandoned. If it doesn't happen during the first version, it certainly will during the next. Developer's change roles, new developers enter the picture, new features obliterate the old, and original development processes are delegated to the bit bucket.

In Web application development, the presentation layer is where best practices and schedule often collide. The "vulnerability" that fosters this situation is the awkward marriage of Java and dynamic markup creation. JavaServer Pages and Enhydra XMLC are two purely Java presentation technologies designed specifically to resolve this relationship. Each represent two very different strategies with associated implications for architects, project managers, designers and developers that are important to consider.

This article focuses on where these two technologies are today and what they do to make the long term goals of the application architect achievable. After reviewing JSP, JSP Tag Libraries and XMLC, we'll take up a real world scenario on the use of push versus pull, then speculate on an assessment of how well these two strategies address Web application development today.


Push and Pull Presentation Strategies

The best known Java Web presentation technology, JSP, employs a strategy we'll call a "pull model." Shove some Java fragments into a markup page using JSP tags of scriplets, compile it up into a Java class, then let the Java fetch live content from a data source via a Java Bean, JDBC calls or what have you. JSP continues to evolve, addressing well-sighted areas of awkwardness at the border where designer and developer interact. JSP Tag Libraries were introduced to squarely address how JSP could better support "best practices" not only between designer and developer, but also in terms of achieving the most maintainable presentations possible. The evolving changes in the JSP API, its capabilities in general and the size and scope of the Apache Jakarta effort reflects the sense of need.

XMLC was developed and introduced by Lutris Technologies to the open source Enhydra.org project in early 1999. Having gained early experience with leaving customers in the wake of embedded Java strategies, Lutris architect Mark Diekhans defined the XML compiler, or XMLC as a course correction to avoid the long term limitations of embedded pull model strategies.

Trying to define a natural relationship between designers represented by customer design teams (often represented by out-sourced design houses) and Lutris' Java developers, Mark's goal was to establish a more loosely coupled way to address the problem of maintainability and the interface to the non-technical HTML designer. XMLC assured creative folks that they didn't have to become Java developers to work with our developers. At the same time, Mark wanted to build true object oriented Web applications with Java. To achieve this, XMLC would turn HTML into true Java resources, putting Java, not the mark up language, in control of application flow.

The conclusion was to use a push model to support this type of Java-to-Java resource relationship. By representing pages of HTML or XML markup as Java resources, the application design retained its object oriented integrity and could load markup resources as needed.


JSP Taglibs and Enhydra XMLC

Let's do a little compare and contrast with real code, explaining XMLC for readers who are new to it. The example below is based on the "Iteration Tag" example provided in the Tag Libraries tutorial hosted at java.sun.com. The example builds a simple table with rows containing the names of different departments within a fictional organization.


Using JSP Taglib

The iteration tag populates a table with the names of departments in the organization.


<%@ taglib uri="/tlt" prefix="tlt" %>
<html>
<body bgcolor="white">
<jsp:useBean id="org" class="Organization"/>
<table border=2 cellspacing=3 cellpadding=3>
<tlt:iteration name="departmentName" type="String"
group="<%= org.getDepartmentNames()%>">
<tr>
<td><a href="list.jsp?deptName=
<%= departmentName %>">
<%= departmentName %></a></td>
</tr>
</tlt:iteration>
</table>
</body>
</html>


This is very nifty indeed. As the tutorial states, this example of tag libraries addresses two common JSP issues:

  1. minimizing the amount of Java programming in JSP pages, and

  2. ensuring a common look and feel across applications.

I won't list the supporting Java code that implements the iteration tag. You can view it in the tutorial just below the result screen shot. The steps required to implement tag libraries in your JSP pages require 1) a tag handler and helper classes for the tag and 2) declare the tag in a tag library descriptor.


Using XMLC

XMLC features a compiler and a runtime environment for standard Web application presentation development.


Pre-compile Phase

The compilation phase translates a targeted markup page of HTML or XML into a W3C DOM template, represented by a Java class. Before compilation, the designer and developer identify areas of dynamic content and assign them "names" that are then embedded with id attributes (e.g., <td id="customerName">). These id attributes are the indicators of which elements are in store for dynamic reworking and/or content.

  1. Insert id attributes. The typical thing to do is identify the table, first row and the cells inside the row.
        <table id="DepartmentsTable">
        <tr id="DepartmentRow">
        <td id="DepartmentName">Engineering</td></tr>
    
    This establishes the first row as the template we'll use during servlet run-time to stamp out new rows.

  2. In the other rows, which we'll throw away during compilation, insert class attribute to indicate they are storyboard mock data.
        <tr class="mock">
        <td>Finance</td></tr>
    

Compile Phase

  1. Use the xmlc compiler to generate a Java class using the Xerces parser to (eventually) construct a DOM representation of a markup page.
    The option -delete-class "mock" automatically discards any rows tagged with class="mock" and elements they contain.

Runtime Phase

From doGet() using the following code and importing the XMLC run-time library, the following code will load, then push changes into the DOM template. Each step is labeled with a [XMLC] or [DOM] to indicate if you're using XMLC or DOM methods to get the job done.

  1. Load the compiled template page, OrgHTML.class, using a DOM factory method [XMLC]
          OrgHTML page = (OrgHTML)xmlc.getXMLCFactory().create(OrgHTML.class)

  2. Grab the table's element node [XMLC]
          Element deptTable = page.getElementDepartmentsTable();

  3. Grab the row that serves as a template [XMLC]
          Element deptRow = page.getElementDepartmentRow();

  4. Set the cell's value using setText [XMLC]
          page.setTextDepartmentName();

  5. Clone the updated row template [DOM]
          Node clonedRow = deptRow.cloneNode(true);

  6. Append the clone to the table [DOM]
          deptTable.appendChild(clonedRow);

  7. If no more rows, remove the template row [DOM], otherwise go to Step #4.

  8. Write the DOM back to the client [XMLC]       xmlc.writeDOM(request, response, page);


This code is typical of an XMLC table building pattern. There are some things to note about the XMLC version of this working example.

  1. No tags are introduced other than typical HTML tags.

  2. There are no "structural" files required, such as a tag library descriptor, other than the automatically generated DOM template.

  3. There's no Java code for the designer to see. The only handshake is the use of id attributes.

  4. We can leave in as much mock data we want as long as we identify it as belonging to a class attribute such as class="mock" or class="delete-me".

  5. The reliance on the DOM API for tree traversal is minimized or completely eliminated by the use of the auto-generated getElement<attributeName> methods that provide direct access to specific nodes in the DOM tree.

Most importantly, the designer can make changes to the design without involving the developer, particularly if the auto-compile xmlc feature is turned on. This feature is key to the next example.


A Real World Application

Before we go any further, let's discuss the impact of using xmlc in a scenario that suggests a real world design requirement.

Messages-R-Us is a manufacturer of a Web application called MRU-SMS for sending SMS messages. In addition to their ASP business, they sell the whole application as a shrink-wrap package. Typically purchased by companies like Pete's Postal Service, MRU-SMS can be integrated into the purchaser's Web site, giving them the ability to make available more value to their customer. Best of all, Pete's Postal Service can completely customize the presentation so that it looks like the MRU-SMS service is coming solely from the Message Board's set of services.

Messages-R-Us had the following requirements for the design and construction of MRU-SMS, supporting a "throw over the wall" product strategy.

  • Instructions to the customer's HTML designers must be brain dead simple.

  • It must be virtually impossible for the designer to do anything that would break the application or cause more support calls than desired, namely zero.

Solution with XMLC:

The XMLC compiler features the "-generate both" option which, instead of generating a single DOM class, generates two files: an interface class and an implementation class. The interface class contains the signature for the methods that are the result of the id attributes discovered in the markup file during compilation. So,


 <form name="SmsForm" method="post" action="SmsApp/processMsg/">
 <input id="SmsMessageText" type="text" name="SmsTextField">
 </form>

 

would generate an interface file


import org.w3c.dom.*;
public interface SmsHTML extends org.enhydra.xml.xmlc.XMLObject,     org.enhydra.xml.xmlc.html.HTMLObject {
    public static final String NAME_SmsForm = "SmsForm";
    public static final String NAME_SmsTextField = "SmsTextField";
    public org.w3c.dom.html.HTMLInputElement getElementSmsMessageText();
}

and the Java class that implements that interface.

The impact? The customer of MRU-SMS could make any change they want to the mark up file, including moving the form and input elements around, adding their corporate look & feel and or even add new elements. BUT, they must ensure that the the id="SmsMessageText" is preserved in order to satisfy the SmsHTML interface. They simply create their new HTML file and run the command:


xmlc -generate implementation -class SmsHTML.class filename.html

Of course, this can all be wrapped and automated to further ensure that the customer builds a legitimate HTML file. Furthermore, taking advantage of XMLC's auto-compilation and auto-class loading features will enable the customer to make changes to markup pages while the application is running. The XMLC's DOMFactory method will detect the change, perform the DOM compilation, and load the new SmsHTML.class.

How you would accomplish this in JSP is left to the reader. If you imagine a more complex dynamic HTML page than the one I have presented, there is a lot that can go wrong in the JSP document, especially if the customer is new to JSP. In theory, the packaging of the application should make it so that no Java knowledge is required whatsoever. Only HTML skills are necessary. In the XMLC example, all they need to know is "don't change the ID attribute name".

On the surface, it seems like JSP Tag Libraries may address the issues we've raised. But the problem is that taglibs are simply a patch on a fundamental problem. The fact is that, in the real world, it's just too easy to start coding in Java in the markup again, especially as the idealism of elegant architectures breakdown and the forces of "are you done yet?" or "can you squeeze in one more feature"? take over.


A demarcation that never wanders...

Let's return to the original discussion of "what do presentation technologies do to make application architects more successful?" Architects typically point at the "complete separation between markup and programming logic" as the holy grail of maintainable, low-overhead Web presentation technologies. What does this really mean? Here's a swagger based on consulting engagement experiences:

  1. Designers don't have to become Java developers, and can achieve their goals without critical path reliance on the presence or availability of a Java developer.
  2. Java developers don't muck with the designer domain.

  3. Supporting tools, in each environment, can focus on what they do best.

  4. Greater ease of aintainability and upgradeability of Web presentations is achieveable.

  5. Each role can work independently both in terms of project time lines.

  6. Best practices can be achieved with minimum bureaucratic effort and infrastructure.

  7. Design and development teams can be separated by long distances, typical in a consulting or out-sourced scenario, with the fewest possible opportunities for error or inter-dependency of roles.

Given this working list, how well do JSP and XMLC deliver on the promise of markup and programming logic independence?

XMLC draws the line between Java and markup using the DOM API. It guarantees a level of independence at the cost of a little bit of DOM programming, made easier by the auto-generation of accessor methods that key off of the presence of id attributes. The win:

  • No Java code is ever embedded.

  • A natural line is created for loading different implementations of DOM templates that support the same interface. These DOM templates support:

    • localization

    • branding

    • custom look & feel

    • devices (voice, phone, PDA)

    • private, XML application

  • Well-formed resultant XML or HTML documents are guaranteed.

  • No custom tags are produced that may cause problems for HTML design tools.

  • The storyboard markup and the markup used for compilation are one in the same. There's no need for tracking two parallel files.

JSP began with a strategy that was inherently flawed (by supporting embedded Java) when applied to large projects. It has led to a mini-industry of technology strategies in books and columns, such as one that appeared recently in JavaPro magazine entitled "Keep Them Separated," dedicated to spending a lot of time on how to achieve separation of markup and Java. The column ends with a note that "Because your new custom tags aren't a part of the standard set of HTML tags that HTML writers use regularly, don't count on them being able to even able or even inclined to use them without some encouragement." The author is just telling it like it is.

In the Push model of XMLC, there's no reason to worry about figuring out disciplines and layered technologies for maintaining the line between markup and Java. Rather than incorporate a meta layer of Java, all the hard work is isolated to the Java side of the fence in your servlet code. An XMLC book, I can tell you from experience, spends most of its time on the DOM API. To be fair, the DOM concept is ellusive at first, but worth the effort.

With both technologies, reasonably complete separation of markup and programming logic is achievable. But there's a key difference.

With JSP, you must rely on externally-defined and enforced best practices. You must:

  1. Document best practices for developers to follow to maintain that separation, and

  2. Establish, and probably construct, a tag library infrastructure that supports the ability to achieve a complete line of demarcation.

With XMLC, these best practices are built in, no matter what application you are building. Why?

  1. There is no way to embed Java in markup.

  2. That's it.

The serendipity of an XML view

There's one more advantage to the push model that further exemplifies the value of a strong demarcation line between markup and Java. The push model works very nice if the markup language that is supported (XML) happens to become an industry standard as a basis for voice (VoiceXML), graphics (SVG), wireless (WML, cHTML, XHTML) and a lot of in-house proprietary applications. XML was chosen as the basis for the XMLC strategy at a time before XML was "a sure thing." It was a combination of good insight and a certain amount of luck.

In fact, XMLC's basis in XML is so convenient that we're able to say that XMLC supports any XML application without lifting a finger. As long as the XML is well-formed, i.e., parseable, then, worst case, XMLC can convert that markup into a DOM template. The incremental levels of support are:

  • No id attributes, just compile into a DOM template. You're on your own with basic DOM programming, unassisted by auto-generated accessor methods.

  • Add id and, optionally, class DTD definitions, to trigger auto-accessor method creation during xmlc compilation. You now require much less DOM API experience.

  • Support the application-specific DOM API subclass, such as the VoiceXML and XHTML DOM APIs. You now have maximum development convenience, using W3C standards.

But JSP is cool too...

My goal with this article was to introduce a different perspective on making a technology decision. In updating my JSP knowledge by reading Wellington L.S. da Silva's JSP and Tag Libraries for Web Development" from New Riders I realized just how seductive JSP development is. It's fun, full featured and very exciting in terms of the working coming out of JSR-127 and the Jakarta Taglibs effort.

However, if you're an application architect responsible for significantly staffed, long duration Web application projects supporting applications that are going to grow significantly over time, then you're probably concerned with the issues that have cropped up when projects are large, staffed with different players leaving and entering at different points in the project, and doing curious things to get the job done when the RTM date is looming.

There is a simple alternative if you don't want to"fix JSP" fundamental pull model with lots of infrastructure and struts, so to speak. Check out XMLC at xmlc.enhydra.org or Lutris Technologies for commercially supported XMLC developments. For a fully explained, downloadable servlet example of building dynamic tables with XMLC, visit otterpod.com.

David H. Young
http://www.kspar.net
david@kspar.net
Kspar Consulting
Principle