///JSP Technology — Friend or Foe?

JSP Technology — Friend or Foe?

A critical look at JavaServer Pages servlets as a viable presentation technology

An old Java technology hand and new Enhydra partisan, the author urges developers to consider alternatives to JavaServer Pages (JSP) servlets when choosing an approach to coding Web applications. JSP technology, part of Sun’s J2EE platform and programming model, serves as a solution to the common dilemma of how to turn drab content into a visually appealing presentation layer. The fact is, Web developers aren’t uniformly happy with JSP technology. Since many variations on the Sun technology are now available, you can choose from a number of presentation technologies. This article takes an in-depth look at JSP coding and explores some attractive alternatives.

Presentation technology was designed to transform plain ol’ raw Web content into content wrapped in an attractive presentation layer. JavaServer Pages (JSP) technology, Sun’s presentation model and part of the J2EE platform, has received significant attention. There are both advantages and disadvantages to using JSP technology, and Web developers should be aware of the good and the bad — and know that they don’t have to be limited to this single technology. In fact, these days a number of presentation technologies are available. This article begins by defining the problems presentation technologies were designed to solve. It then examines the specific strengths and weaknesses of the JSP model. Finally, it introduces some viable alternatives to Sun’s presentation technology.

A bit of history

Before diving into an explanation of presentation technology, it’s helpful to fill in some details on the situation that led to the birth of the technology. Just 10 short years ago, the term thin client was a novelty. We still lived in a world of desktop applications, powered by wimpy 286 microprocessors with 14-inch monitors that we squinted at. Boy, have times changed! Now my desktop does nothing but power a Web browser, while servers from Sun, IBM, HP, Compaq, and the rest churn out computations, business logic, and content. And that little monitor? Replaced by flat-screen, plasma, whopping 21- and 25-inch beauties. Why? So we can see the intricate and complex HTML displays that serve as a front-end to these powerful applications. No longer does a clunky interface suffice; now we expect flashy graphics, moving images, color-coordinated presentations that would look good in any room in the house, and speedy rendering to boot.

The premise

Today, a decade beyond those fledgling Windows applications, we are still dealing with this huge shift in the presentation paradigm. The woeful Visual Basic and C programmers who remain now find themselves working either on back-end systems or Windows-only applications, or they have added a Web-capable language such as the Java language to their toolbox. An application that doesn’t support at least three of four ML-isms — such as HTML, XML, and WML — is considered shabby, if not an outright failure. And, of course, that means we all care very deeply about the ability to easily develop a Web presentation layer.

As it turns out, using the new Internet, and all the languages we have at our disposal — Java, C, Perl, Pascal, and Ada, among others — hasn’t been as easy as we might have hoped. A number of issues creep up when it comes to taking the programming languages everyone used for back-end systems and leveraging them to generate markup language suitable for a client. With the arrival of more options on the browser (DHTML and JavaScript coding, for example), the increase in graphic artist talent in the Web domain, and tools that could create complex interfaces using standard HTML, the demand for fancy user interfaces has grown faster than our ability to develop these front ends to our applications. And this has given rise to presentation technology.

Presentation technology was designed to perform a single task: convert content, namely data without display details, into presentation — meaning the various user interfaces you see on your phone, PalmPilot, or Web browser. What are the problems that these presentation technologies claimed to solve? Let’s take a look.

Segregation vs. integration

The primary purpose of presentation technology is to allow a separation between content and presentation. In other words, business logic units (presumably in some programming language like C or Java) don’t have to generate data in a presentation-specific manner. Data, or content, is returned raw, without formatting. The presentation technology then applies formatting, or presentation, to this content. The result is an amalgam of data surrounded by and intertwined with graphics, formatting, colors, and logos.

Look at the examples in Listing 1 and Listing 2 to see at a glance the difference between raw content and content combined with presentation technology.

Listing 1 shows raw content, with nothing but data, that could be used in a variety of ways.

Russell Crowe

Tom Hanks
Meg Ryan
Mary Stuart Masterson
Alec Baldwin
Ashley Judd
Keanu Reeves

Listing 2, which is much more complex than the one above, shows the same data wrapped in presentation technology and ready for display in an HTML-capable browser.



<HTML>
<HEAD>
<TITLE>Search Results: Actors</TITLE>
</HEAD>
<BODY>
<H2 ALIGN="center">Search Results: Actors</H2>
<CENTER>
<HR width="85%">
<TABLE width="50%" CELLPADDING="3" CELLSPACING="3" border="1"
BGCOLOR="#FFFFCC">
<TR BGCOLOR="#FFCCCC">
<TH width="50%" ALIGN="center">Last Name</TH>
<TH width="50%" ALIGN="center">First Name</TH>
</TR>
<TR>
<TD width="50%">Baldwin</TD>
<TD width="50%">Alec</TD>
</TR>
<TR>
<TD width="50%">Crowe</TD>
<TD width="50%">Russell</TD>
</TR>
<TR>
<TD width="50%">Hanks</TD>
<TD width="50%">Tom</TD>
</TR>
<TR>
<TD width="50%">Judd</TD>
<TD width="50%">Ashley</TD>
</TR>
<TR>
<TD width="50%">Masterson</TD>
<TD width="50%">Mary Stuart</TD>
</TR>
<TR>
<TD width="50%">Reeves</TD>
<TD width="50%">Keanu</TD>
</TR>
<TR>
<TD width="50%">Ryan</TD>
<TD width="50%">Meg</TD>
</TR>
</TABLE>
</CENTER>
</BODY>
</HTML>

While the content in Listing 1 is clear and easy for the uninitiated layperson to both use and understand, the content in Listing 2 is very specific to the task of display in a browser. It is tricky to extract data from it or manipulate it for any other purpose.

This fundamental difference, the process of segregating content from presentation instead of integrating the two (at least until the user needs the information), is the basic premise of any presentation technology, including the JSP technology. Further, any presentation technology that does not accomplish this basic goal does not truly accomplish the goal it was created to achieve.

Work vs. rework

Besides the separation of content and presentation, another measure of a presentation technology’s usefulness is the amount of rework that it eliminates. The divergence of presentation and content enforces a divergence in the roles of those developing the content. A programmer can focus on the raw content presented in the examples above, and a graphic artist or webmaster can attend to the presentation. A slight overlap of roles remains, however, in the process of taking the presentation — or markup — designed by the artist and applying it to the content the programmer’s code delivers.

In the simplest case, the artist supplies the markup, and the developer provides code and also plugs the markup into the presentation technology. The application is "started up," and the content magically becomes a user interface. Of course, as we all know, development rarely ends there. Next come revisions and changes to the interface and new business rules that must be coded. This is where the true test of the presentation technology’s flexibility comes into play. While it is usually simple to update the raw content being fed into the presentation layer, rarely can the graphic artists easily edit their original work. Changes to the presentation layer are common (we’ve all been victim to marketing departments changing this or that). So now a problem arises: what do the designers change to tweak their work? The original markup language page they gave to the developer? Probably not, as that page has most likely had custom tags or code inserted (JSP pages, template engines), converted to a Java servlet, or changed into something totally unrecognizable.

Often the designer must rework the original page and resubmit this page to the developer. Then the developer has to reconvert this page to the specific format needed for use in the presentation technology. Alternatively, the designer has to learn a scripting language or at least know that which areas of the page’s source code from the developer are off limits. Of course, this is an error-prone, dangerous way to operate. Once you’ve determined that a presentation technology allows a clean split between content and presentation, you should try to ensure that a minimum amount of rework is necessary in order to make presentation changes.

The promise of JSP technology

Now, on to the specifics of JSP coding. The promise of JSP technology is to supply the designer and developer the only presentation technology they will ever need. JSP technology is part of the J2EE platform, which is the strongest show of support Sun can give one of its Java products. To give you an idea of how prevalent this solution is, try running a search on ‘JSP’ at amazon.com; you’ll find more books devoted to JSP technology than about almost any other single Java API. Before I dive into the specific problems that JSP technology presents, you need a clear understanding of what it claims to do.

Content vs. presentation

Above all, JSP technology is about separating content from presentation, foremost in Sun’s published set of goals for JSP pages. In fact, JSP design stemmed directly from the complaints of developers who were tired of typing out.println("<HTML><HEAD><TITLE>" + pageInfo.getTitle() + "</TITLE></HEAD>"); into their servlet code. This mixing of hard-coded content with runtime variables presented a horrible burden on servlet developers. It also made making even minor changes to the presentation layer difficult for the developer.

JSP technology addresses this situation by allowing normal HTML pages (and later, WML or other markup language pages) to be compiled at runtime into a Java servlet, essentially mimicking the out.println() paradigm, without requiring the developer to write this code. And it allows you to insert variables into the page that are not interpreted until runtime.

In a JSP page the HTML snippet shown in Listing 2 could look like the example in Listing 3.

<%@ page import="com.ibm.display.PageUtils" %>

<%@ page import="com.ibm.display.PageInfo" %>
<%
PageInfo pageInfo = (PageInfo)session.getAttribute("PAGE_DATA")
%>
<HTML>
<HEAD>
<TITLE>
<%=pageInfo.getTitle()%>
</TITLE>
</HEAD>
<BODY>
<!-- Other HTML content -->
</BODY>
</HTML>

Judging by these initial principles, then, JSP technology (at least in its stated design) would satisfy the first tenet of a presentation technology, as outlined above: that content be separated from presentation.

Code vs. markup

Second on the JSP technology’s list of features is something that might raise a bit of concern. JSP coding lets you insert Java code directly into a page of markup. To understand why this decision was made, recall that when the JSP specification was being developed, Sun’s competition from Microsoft was at an all-time high, primarily due to the success of Microsoft Active Server Pages (ASP). The similarity of the name JavaServer Pages to Active Server Pages was not merely coincidental. And the ability to mimic many of ASP’s features was also intentional. So JSP authors were given the option to add Java code into their markup.

As an example of Java code being added to markup, the JSP snippet in Listing 4 dynamically adds rows as needed to show each item in the Vector of actors.

<%@ page import="com.ibm.display.PageUtils" %>

<%@ page import="com.ibm.display.PageInfo" %>
<%@ page import="com.ibm.people.Actor" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.Vector" %>
<%
PageInfo pageInfo = (PageInfo)session.getAttribute("PAGE_DATA")
Vector actors = pageInfo.getActors()
%>
<HTML>
<HEAD>
<TITLE>
<%=pageInfo.getTitle()%>
</TITLE>
</HEAD>
<BODY>
<H2 ALIGN="center">Search Results: Actors</H2>
<CENTER>
<HR width="85%">
<TABLE width="50%" CELLPADDING="3" CELLSPACING="3" border="1"
BGCOLOR="#FFFFCC">
<%
for (Iterator i = actors.iterator(); i.hasNext()) {
Actor actor = (Actor)i.next();
%>
<TR BGCOLOR="#FFCCCC">
<TH width="50%" ALIGN="center">
<%=actor.getLastName()%>
</TH>
<TH width="50%" ALIGN="center">
<%=actor.getFirstName()%>
</TH>
</TR>
<%
}
%>
</TABLE>
</CENTER>
</BODY>
</HTML>

Remember that so far I am simply describing the initial design goals of JSP technology; I’ll defer my own judgment about the goals until a later section about the problems of JSP technology. You might be a little suspicious already, however, since embedding code into a JSP page would seem to cause problems with the first goal of JSP technology, separating content from presentation. But really (ahem), I’m not editorializing yet.

Designer vs. developer

A final (and admirable) goal of JSP technology worth mentioning is that it seeks to establish clearly defined roles in the application development process. By ostensibly breaking content from presentation, JSP technology creates a clearer distinction between the designer and developer. The designer creates markup, using only standard HTML, WML, or whatever language is appropriate, and the developer writes code. Of course, many designers today have learned JavaScript, so it should come as no surprise that many of these same designers have begun to learn JSP coding. Often, instead of just doing pure markup, they encode a complete JSP page and hand it over to the developer. Then the usual tweaking takes place, and the developer puts the JSP page into place as a front-end for some portion of the overall application. The key, though, is that many designers do not learn JSP coding, so it must also be workable in that environment.

The problems

I’ve spelled out what a good presentation technology should provide, as well as the specific problems that JSP technology seeks to address. Now, I’m ready to cut to the chase: JSP technology, while built on good ideas, presents quite a few problems. Before you choose to use JSP coding in your applications (which you might still do), you should at least be aware of possible pitfalls.

You should also be aware of a facet of the J2EE programming platform that is often ignored: just because an API comes with the platform doesn’t mean you have to use it. As silly as this sounds, many developers are struggling with the JSP, or EJB, or JMS APIs, thinking if they don’t use these APIs, their applications somehow won’t really be "J2EE applications." In fact, the platform boasts more APIs than most applications need. If you have problems with or doubts about JSP technology, you don’t have to use it! Take a close look at both the positives and the negatives before choosing to use JSP technology in your applications. Let’s take a look at some of the negatives.

Portability vs. language lock-in

JSP technology locks you into a specific language. This point shouldn’t be given too much weight. Java technology for enterprise applications (in my opinion, at least) is the only language choice. And there are no language-independent solutions in this space anyway. Of course, at this stage of the game, I’m disregarding the Microsoft .NET platform for the smoke and mirrors it is. Only time will tell whether that platform will develop into one that is truly language-independent. (I’m more than a bit dubious.)

Still, choosing JSP technology forces you to use the Java language, at least for presentation and content. While CORBA can be used for business logic, JSP coding does necessitate some familiarity with servlets as well as the core Java language. Since many developers come to JSP coding through the J2EE platform, this doesn’t usually present a problem.

Mingling vs. independence

Throughout this article, I’ve come back to the idea of separating content from presentation. You’re probably pretty sick of hearing about this, so now’s the time to determine whether or not JSP actually accomplishes this goal. As I’ve already discussed, JSP claims to have been designed for this separation purpose, and therefore we should assume it achieves its objectives, right? Not necessarily.

Blurring the line between content and presentation

JSP allows Java code to be inserted into the markup language page, and this rather dangerous feature allows content to be intermingled with presentation. Even worse, business logic often makes its way into JSP pages, as shown in Listing 5.

<%@ page import="com.ibm.display.PageUtils" %>

<%@ page import="com.ibm.display.PageInfo" %>
<%@ page import="com.ibm.logic.AdminUtils" %>
<%@ page import="com.ibm.people.Actor" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.Vector" %>
<%
PageInfo pageInfo = (PageInfo)session.getAttribute("PAGE_DATA")
%>
<HTML>
<HEAD>
<TITLE>
<%=pageInfo.getTitle()%>
</TITLE>
</HEAD>
<BODY>
<H2 ALIGN="center">Search Results: Actors</H2>
<CENTER>
<HR width="85%">
<TABLE width="50%" CELLPADDING="3" CELLSPACING="3" border="1"
BGCOLOR="#FFFFCC">
<%
// Based on user's permissions, perform search differently (business logic!)
Vector actors = pageInfo.getActors()
if (pageInfo.getUserInfo().hasPermission("ADMINISTRATOR")) {
actors = AdminUtils.getActors(pageInfo.getSearchCriteria());
} else {
actors = pageInfo.getActors();
}
for (Iterator i = actors.iterator(); i.hasNext()) {
Actor actor = (Actor)i.next();
%>
<TR BGCOLOR="#FFCCCC">
<TH width="50%" ALIGN="center">
<%=actor.getLastName()%>
</TH>
<TH width="50%" ALIGN="center">
<%=actor.getFirstName()%>
</TH>
</TR>
<%
}
%>
</TABLE>
</CENTER>
</BODY>
</HTML>

JSP advocates are quick to let you know that JSP tag libraries can help you avoid this problem. Tag libraries allow custom tags (for example, <AUTHORS />) to be added to a JSP page, which at runtime are resolved into code fragments in, well, tag libraries.

The use of a custom tag and associated tag library would allow the example above to be converted to that shown in Listing 6.

<CENTER>

<TABLE width="50%" CELLPADDING="3" CELLSPACING="3" border="1"
BGCOLOR="#FFFFCC">
<ACTORS />
</TABLE>
</CENTER>

At runtime, the code for this tag executes and the correct results are inserted into the page. But this does not solve the problem. The argument against JSP technology is not whether content and presentation can be separated, but whether they must be separated. As long as JSP coding allows inline coding, it is very convenient (especially when deadlines are looming) to make last-minute changes with inline code, rather than converting the code to a tag library. If this doesn’t ring true, consider why the Java language immediately gained popularity over C and C++: Java disallowed many of the features that were problematic in C, such as pointer addition. While you can always argue that you don’t have to perform pointer addition in C or that no good programmer would ever insert code scriptlets, we all know what happens in practice. The Java language is a better language because it mandates that these sorts of bad habits never surface. But JSP in this case is much like C, allowing some very bad practices.

An additional litmus test of the JSP technology’s success in meeting its stated objectives is to see whether or not it is possible to achieve this goal in practice; certainly it isn’t fair to hold JSP to an impossible standard. Most template engines, like FreeMarker and WebMacro, have this same inline coding facility, often with a Perl-analogue language. However, technologies like Enhydra’s XMLC do not allow this type of inline coding. Instead, these technologies take a pure markup language page as input, and generate Java methods. This essentially is changing the program flow; instead of the page (JSP technology) calling logic from the application, the application (Enhydra) uses methods to affect the values of the page. In the specific case of Enhydra, XMLC converts the page into a DOM tree, and uses the DOM’s HTML binding to allow "fields" in the page to be updated. (For more on Enhydra XMLC, check out Resources.)

The point here is that more so than XMLC, JSP technology can achieve its goals, by only allowing tag libraries, for example. But the general tendency in Sun specifications is to always maintain backward compatibility, or at least maintain it for quite a long time. The current version of the JSP spec, 1.1, allows scriptlets, so expect to see code allowed in JSP pages for several years to come. Before diving into JSP coding, be careful of the rather large hole that lies between its ideal, a complete separation of content and presentation, and what it actually provides, which is at best a pseudo-split between your user interface and the code that drives your application.

Single-processing vs. multi-tasking

Ideally, as discussed above, a designer ought to be able to perform a single process, working purely on graphic design, and a developer should be able to focus purely on coding. So the designer should be able to work on a page after it has been converted to an application-suitable format. In the case of a JSP page, that would be after JavaBeans have been imported, inline coding has been inserted, and custom tag libraries have been added to the page. The problem is that some designers use HTML editors, such as HoTMetaL, Macromedia Dreamweaver, or FrontPage, that do not recognize code scriptlets or tag libraries, which means the designer effectively receives only a partial page. Imagine the difficulties when tag libraries or code fragments generate rows of a table, or other formatting details for the page. Designers using the incompatible HTML editors can’t see what those elements look like. When designers can’t easily revise pages after developers finish coding them, instead of clarifying distinct roles, JSP coding can cause them to merge: a developer must multitask, becoming developer, designer, and more.

Unconvinced about the importance of this feature? Then download the J2EE Reference Implementation and load one of the included JSP pages into a WYSIWYG HTML editor, such as Dreamweaver. The page immediately fills with yellow areas letting you know about all the "illegal" markup contained within the page. Of course, the yellow results from the JSP tags and code, rather than any real error in the page.

To date, no JSP-capable WYSIWYG editors exist, and I have not heard of any efforts to build one. While template engines have this same problem, many Java-based solutions, such as my favorite, Enhydra, allow you to supply the markup page as input to the presentation technology. In this case, the designer can make changes as often as needed and resupply the markup page. Running the engine or compiler for the presentation technology converts it to the proper format, and no code changes have to be made (in the typical case). The result is the desired one: designers remain designers, and developers remain developers.

So, be wary of the promise of JSP technology as compared to the reality of what it delivers. In practice, to function in a JSP technology-driven environment you must either have your developers handle a large portion of the markup or have designers learn at least some JSP coding.

HTML vs. XML

One of the most significant disadvantages of JSP technology, and one of the most overlooked, is its incompatibility with XML. More precisely, and particularly in the HTML realm, JSP pages are not required to be XHTML-compatible. XHTML is a World Wide Web Consortium (W3C) specification that is now replacing HTML 4.0. XHTML defines the HTML tagset in terms of a well-formed XML document. For example, the <br> tag must be converted to <br/> to ensure XML compliance. (If this doesn’t make much sense, you can check out the XML specification and the developerWorks article about XHTML, listed in Resources.) Similar rules are applied to image tags, and in XHTML 1.1 (recently coming of age) most font properties and other styling move into CSS stylesheets. Still, most standard HTML documents convert easily to XHTML 1.0, which means they can be read directly with any XML-compliant parser, such as Apache Xerces, and manipulated as XML.

"What’s the big deal?" you ask. The big deal is that XML quickly is becoming the global standard for inter- and intra-application communication. Passing data around in an XML format lets any other application that employs basic XML data-handling facilities use your application’s data easily. Imagine being able to communicate with credit card companies for e-commerce simply by moving your data into an XML format! Many times, your presentation of data needs to be exchanged with other companies as well. The most common case is the portal application, which receives content from a variety of providers (weather, stock quotes, and news, for example), often with branding from the provider. JSP pages, however, with their mix of code and custom tag libraries, cannot function well in this environment.

JSP pages are rarely well-formed XML documents, never mind conforming to XHTML, a markup language that doesn’t allow the various JSP custom tag libraries. More important, though, is that the code snippets inserted in JSP pages are not any form of markup and will create loads of parser errors once they are processed by another application.

Before you go quoting me on this, let’s get the whole story out there. If the application were to allow the JSP page to be evaluated by the original client, the result would be pure HTML (or WML, VoXML, and so on). Most applications that request this data, however, employ some form of caching, as network round-trips are very expensive. In these cases, the cached page returns stale data. In those cases, then, you’d probably prefer to return pure XML-compliant results, preferably in a static form. And it is in those cases that JSP technology cannot help; JSP pages must always be evaluated at runtime to remove the JSP code scriptlets and tag libraries.

Apply the litmus test: Can some other presentation technology do this? The answer is yes. The decided leader in this arena is the Apache Cocoon project, which is based entirely on XML and an application of XSLT stylesheets (which can be applied either at runtime or statically). Because XML Server Pages (called XSP in the Cocoon framework) are actually XML documents, they are always XML-conformant. Other technologies like Tea and Enhydra XMLC that allow the input of a pure markup language page also allow this, although they do not mandate it. In these cases, the user can use XHTML or standard HTML. Still, this is better than the JSP case, where well-formed XML cannot be accomplished statically.

Summary

I hope that I have opened your eyes a bit about the advantages and disadvantages of JSP technology and that now you can look at JSP coding as one alternative among many presentation technologies. At this point, you might also be a bit skeptical about the entire J2EE programming model. If you’re convinced to further investigate the platform options, look for alternatives to JSP coding in Apache Cocoon, Enhydra, and the various templating engines.

Finally, keep in mind that, despite all appearances to the contrary, this article isn’t about recommending you use JSP or that you avoid it. I do intend to encourage you to peel back the layers of any technology to make sure it’s right for you. Programming models are like examples; sometimes they make sense, and sometimes they don’t. Look around, find out what works best for you, and make the informed decision, rather than the quick one.

Have fun, and see you on the Web!

Resources

  • Read the current JSP specification, and get the whole story.
  • Get ahead of the game by checking out what’s coming up in JSP 1.2.
  • Worried about XML compatibility? You can get all the details on XML by reading the specification and Molly Holzschlag’s article for developerWorks on getting up to speed with XHTML.
  • Get the XML view of styling documents at the W3C Style Center.
  • Want a J2EE solution that provides more than JSP, and is open source, too? Read about Enhydra today.
  • Come out of your shell and check out Apache Cocoon, an open source alternative for handling dynamic content using XSLT.
  • If you don’t mind jumping out of Java, template engines can save the day! Two worth taking a look at are WebMacro and FreeMarker.
  • 2010-05-26T17:17:42+00:00 March 7th, 2003|Java|0 Comments

    About the Author:

    Brett McLaughlin has been working in computers since the Logo days ( remember the little triangle?). He currently specializes in building application infrastructure using the Java language and Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom, Inc. Brett is one of the co-founders of the Java Apache project Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine.

    Leave A Comment