 | Level: Intermediate Noel Bergman (noel@jspdevguide.com), CTO, Development Technologies Inc.
01 Dec 2001 JavaServer Pages (JSP) technology is an excellent architecture for delivering Web applications, but one of its most important facilities, custom tag libraries, is often poorly leveraged. The primary reason for the failure to properly exploit the taglib facility is not technological, but linguistic. Tag library producers and consumers are not speaking the same language. JSP expert and consultant Noel J. Bergman exposes the nature of the problem and offers some workable solutions.
It's generally agreed among Web application developers that separating the underlying content model from presentation is a good thing. In most large development projects, programmers implement the back end, and presentation is left to one or more Web page designers. This breakdown ensures a final product that is both technologically solid and well-presented,
but it does require the two teams to communicate and work together effectively. This can be a challenge, given that each team is working from a different knowledge base and attending to a very different set of concerns. Prior to the introduction of custom tag libraries in version 1.1 of the JavaServer Pages (JSP) specification, it was necessary to use JSP scripting elements to provide any custom functionality within a JSP page. The explicit use of scripting elements violated
the separation of model and presentation. It also required Web page designers to have Java coding experience in order to do anything more than retrieve properties from JavaBean components. This led to widespread concern over the use of scripting elements within JSP pages, which in turn led to the development of alternative solutions. One classic solution is the development of Model-View-Controller type usage models. Under such usage models, application intelligence is placed in servlets and beans, and JSP pages simply retrieve content for rendering. Jakarta Struts is a good example of this sort of model. Other development teams have created alternative technologies such as the Velocity content engine or Apache's Cocoon project. While these solutions are worthwhile in their own right, they are generally nonstandard, and they ignore the continued evolution of JSP technology. In this article we'll focus on one of the most underused facilities of JSP technology: custom tag libraries. My goal is to change the way you think about custom tag libraries and, more specifically, tag design. I'll start the discussion by dispelling a few myths about JSP technology and about some of the alternative solutions, and then move on to the central topic. JSP technology: Myths and alternatives
There are quite a few common myths about JSP technology, some of them as daunting to potential users as they are generally outdated. Table 1 looks at the most pervasive myths.
Table 1. JSP: The myths
| Myth | Truth | | JSP pages require the intermingling of code model and presentation, in the form of scripting elements. | As we'll discuss in the next section, tag libraries render this claim false. | | JSP page scripting is really Java programming. | This is only partially true. The JSP specification has allowed for multiple scripting
languages since version 1.0. However, this capability has not been broadly implemented.
IBM WebSphere allows the use of many scripting languages, and the underlying technology
has been released as open source (see the sidebar "An alternative to the alternatives"). Also, the Velocity template language is available through a JSP tag library. | | JSP pages are bad because they allow scripting. | This charge has been addressed in recent changes to the JSP specification. The current
release of the specification introduces a new concept to tag libraries. Tag libraries can
include a validation method to validate any JSP page that wants to use that library.
At the Colorado Software Summit 2001, Mark Kolb presented a simple tag library validator
that validates that JSP pages are entirely script free (see Resources). |
Each of the myths outlined above was at least partially true at one time. However, JSP technology is a major part of the J2EE specification and is widely used. As such, there is a tremendous multivendor effort to evolve and mature JSP technology to resolve user concerns. This is one of the benefits of using a standard technology instead of an ad hoc solution. Nonetheless, a common thread persists among managers responsible for deploying Web applications. Not knowing the truth behind the myths, upon being told that JSP technology intermingles programming with presentation, their first response is to say that they'll find an
alternative to JSP, such as Velocity. So the question is, do solutions such as Velocity really solve the problem? The Velocity documentation states that it "permits anyone to use the simple yet powerful template language to reference objects defined in Java code," and that "the Velocity Template Language (VTL) is meant to provide the easiest, simplest, and cleanest way to incorporate
dynamic content in a Web page. Even a Web page developer with little or no programming experience should soon be capable of using VTL to incorporate dynamic content in a Web site." In other words, Velocity doesn't remove programming from presentation; rather it requires users
to learn a new ad hoc scripting language. By requiring Web page designers to learn the Velocity Template Language, Velocity fails to eliminate the mingling of the content and presentation.  |
An alternative to the alternatives
As with any technology platform, JSP does have limitations. One such limitation is that most containers still require Java as the JSP scripting language. Another is the fact that most tag libraries to date do not address the needs of Web page designers. But the solution isn't investment in alternative architectures. I believe we're better off encouraging vendors to invest resources in enhancing the common platform. For example, the JSP specification has accommodated multiple scripting languages since v1.0. This feature is implemented in IBM
WebSphere. Since IBM has released the underlying Bean Scripting Framework as open source (see Resources), we should expect that BSF eventually will be integrated into the JSP container reference implementation, which is part of Jakarta, as well as other commercial JSP containers.
|
|
Velocity is just one example among a number of template engines on the market, but most of them, like Velocity, require some degree of programming skill on the front end. Another popular alternative to JSP technology is the Cocoon project. Cocoon is a lovely technology that uses XML as its source data format. XSLT transforms are used to render the XML content into formats suitable for the user agent, for example, HTML for a browser. Cocoon has its own dynamic page format called XSP. XSP is a close cousin to JSP, but works within the Cocoon environment. XSP exists in large measure because there was no good way to send XML output from a JSP page through Cocoon on the way to the browser. The servlet chaining
mechanism in early servlet containers was insufficient for the job. Today, however, Sun has introduced a new servlet filter mechanism that is perfectly capable of allowing XML output from any arbitrary servlet to be sent through a series of filters. From that perspective, the need for XSP is dramatically reduced, and the need for the Cocoon project to provide its XSLT transform engine as a servlet filter becomes apparent. The bottom line is that JSP technology is constantly evolving to meet the demands of its users. This means that any evaluation of the technology must involve careful review of
the most recent specification. Reviews and editorials even a few months old can be rendered obsolete by new developments (see Resources).
JSP and custom tag libraries
JSP technology is not a tool, it is a platform: a fundamental dynamic-content architecture upon which tools are built. While it's true that the JSP platform includes scriptlets, declarations, and expressions, and its scripting language is Java by default, other languages are supported by the
specification, and by an increasing number of implementations. In addition, the platform includes a rich architecture for developing tag libraries; anything that can be described by HTML or XML tags can be implemented using the standard JSP technology. The JSP platform's inclusion of scripting elements to connect front-end content presentation to back-end functionality does violate the premise that Web page designers should not have to be programmers. But the good news is that these scripting elements (declarations, scriptlets, and expressions) are only a quick fix, and in fact you don't have to use them at all (see Resources). Scripting elements are good for programmers, and good for rapid prototyping, but they are not the long-term solution. Custom tag libraries are the long-term solution. Scripting elements that are used to prototype solutions should migrate into tag libraries as part of the development process.
Designing a custom tag library
Custom tag libraries were introduced in version 1.1 of the JSP technology specification. The addition of this facility allows programmers to create XML tags that specifically address the needs of Web page designers, while hiding the underlying implementation detail. Taken as a set, a tag library's tags form a language: the syntax is predefined by the JSP specification to be XML, the elements are defined by the tag library's DTD or schema, and the semantics are provided by the library. The most important thing to understand when authoring a tag library is that tag design is language design. The onus is on the library designer to make sure that the language created by the tags is suitable for the front-end page designer, who must be able to understand and use the library's functionality. Unfortunately, the vast majority of tag libraries currently available do not employ semantics appropriate for non-programmers. These tag libraries are good examples of bad language design. They use the wrong semantics and a vocabulary that is ill-suited to their intended use. A better approach to tag design
Part of the problem stems from a basic difference in how programmers and designers think. Most programmers are versed in a procedural programming paradigm. In procedural programming, it is the programmer's job to tell the computer how to accomplish each designated task, detailing each step of the procedure. Web page designers operate under a different paradigm. HTML is a declarative language. The Web page designer does not tell the computer how to lay out the page; rather, the designer tells the computer what is desired: a table, a paragraph, an ordered list, and so on. Web page designers are generally not skilled at procedural programming and are not versed in the procedural mindset. This is one reason, although not the only one, why many JSP practitioners discourage (or outright ban) the use of JSP scripting elements within presentation pages. So, if you're designing a tag library, how should you proceed? If we agree that Web page designers aren't programmers, then we can agree that it is unproductive to provide them with tag libraries whose semantics embody procedural programming. This is an important point, but here's another one that is equally, if not more, important. When we start to consider the most productive approach to Web page designers, we're making a conceptual leap: we're beginning to design our tag library with the end user -- the client -- in mind.
Who's the client?
As I mentioned before, the concept you're working with when it comes to authoring a custom tag library is that tag design is language design. You may be familiar with a
slightly different variation of that expression, which stems from object-oriented programming. It states that library design is language design. A good class library designer creates class libraries that use a vocabulary derived from the problem domain. This is because the problem domain is easily understood by those who will be using the library. In the case of a class library, the library's user, its client, is a programmer by definition. In the case of a tag library, your client is a non-programmer. What this means is that you're designing a product for which you are ultimately not a domain expert. As in any development project, your first step should therefore be to call in one or more domain experts. Interview the domain experts, identify the real problems to be solved and, in concert with the domain experts, design a tag language using the vocabulary appropriate to that domain.  |
DBTags: Designed for programmers
To illustrate the problem of designing a language for the target audience, consider the DBTags tag library, which is under the auspices of the Jakarta project. This library provides a set of custom tags that are used to access an SQL database. These tags provide no abstract notion of database interaction beyond what is provided by JDBC, which means that using the DBTags library requires largely the same set of skills and understandings involved in working with JDBC directly. Are these the correct semantics for Web page designers?
|
|
We are introducing a new skill set required of a tag library author: not proficiency in authoring tag classes, but the ability to author a tag language appropriate to its intended users, who are non-programmers by definition. My own view is that declarative languages work best for non-programmers. Creating declarative tags
Most current tag libraries focus on verbs (actions) and adverbs (parameters) to produce their results, whereas I'd like to see more tag designers working with nouns (the desired result) and adjectives (modifiers). This entails a shift in perspective that may be difficult for many programmers, but it boils down to a very simple directive: focus on the what and hide the how. What, not how
Page design should be a process of describing what you want, rather than how to do it. The partnership between the tag author and his or her client -- the Web page designer -- revolves around the author embedding the how into the tag, so that the client can simply be declarative. This does involve more work for the tag author at the tag library design stage, but the resulting language is far more clean, reusable, and maintainable. Declarative languages also tend to be more compact. For example, consider a page that wants to display a greeting to the viewer based on the time of day. Here is how you might code such a page using a JSP scriptlet: Listing 1. Greeting using a scriptlet
Good
<%
String timeOfDay = (new SimpleDateFormat("aa")).format(new Date());
if (timeOfDay.equals("AM")) {
%>
Morning
<%
}else{
%>
Afternoon
<%
}
%>
|
Another version, using Cocoon, might look as shown in Listing 2. (A version created with Velocity would work similarly.) Listing 2. Greeting using XSP
Good
<xsp:logic>
String timeOfDay = ( new SimpleDateFormat("aa")).format(new Date());
if (timeOfDay.equals("AM")) {
<xsp:content>Morning</xsp:content>
}
else {
<xsp:content>Afternoon</xsp:content>
}
</xsp:logic>
|
Listing 3 shows how a page coded using JSP and declarative tags might look. Listing 3. Greeting using tag attributes
<p>
Good
<xyz:greeting am="Morning" pm="Afternoon" />
</p>
|
We could also choose to expand our JSP tag language to allow for both greater specificity and arbitrary content, as shown in Listing 4. Listing 4. Greeting using child tags
Good
<xyz:greeting>
<xyz:when period="05:00 - 11:59">
Morning
</xyz:when>
<xyz:when period="12:00 - 17:59">
Afternoon
</xyz:when
<xyz:when period="18:00 - 20:59">
Evening
</xyz:when>
<xyz:when period="21:00 - 04:59">
Night
</xyz:when>
</xyz:greeting>
|
A shift in syntax
So, what happens when you start thinking in terms of nouns and adjectives instead of verbs and adverbs? We'll use an example to find out. Listing 5 shows what happens when, rather than using a tag to describe looping, we devise a tag that describes something that is looped. Listing 5. A declarative tag for looping
<xyz:data-table source="iterator" id="beanname">
<tr>
<td><jsp:getProperty name="beanname" property="prop" /></td>
</tr>
</xyz:data-table>
|
The data-table tag used in Listing 5 iterates over the contents provided by an iterator bean previously placed into the page's environment, and applies the body contents. The necessary process may be implied, but the desired result is explicit. The use of an iterator interface allows any kind of iterable data to be handled, including database cursors, through the use of a bridge or adapter pattern. This is just a trivial example to show that iteration can be declarative instead of procedural. There are many elegant extensions that can be created once you understand the basic idea. Again, you should derive the vocabulary from the problem domain, not the solution domain. This will help you to focus on the appropriate nouns and adjectives. Your nouns (tags) are entities from the domain, the adjectives (attributes or possibly child tags) are properties. Clean, clear, and simple are good signs. When you get stuck, think of HTML tags; such constructs as frame sets, tables, and forms are good examples. If you find yourself describing the
process instead of the desired result, take a step back and reconsider. You want to stay focused on what, not how.
Advantages of using JSP custom tags
You'll note from the listings above that there is no implementation specified on pages using custom tags. This is a very important point. The scriptlet and XSP solutions shown in Listing 1 and Listing 2 embed the solution within
the presentation page. The declarative tag language does not. To understand why this is important, consider whose time is being measured. In both of the scripting examples, the time is the server's time. But what if we wanted to change the page to reflect the user's time? A page based on scriptlets or XSP would have to be rewritten. A page based on declarative tags could be tweaked to emit JavaScript. What if we wanted the option of reflecting either the server's time or the client's time? If we built our page using scriptlets, we'd have a mess on our hands. If we used a declarative tag language we could simply extend the tag language to (optionally) allow the following:
<xyz:greeting machine="server or client">
...
</xyz:greeting>
|
When rendering the server's time, the tag would provide the correct greeting. When rendering the client's time, the same tag might instead generate JavaScript to present the correct greeting. Another important advantage to using JSP custom tags arises when we consider presentation logic. People sometimes talk about the separation of presentation from logic, but what they're really talking about is the separation of presentation logic from the content model and business logic. Presentation logic needs to be encoded at the proper level of discourse for view production. For example, a user-agent tag should be easily understandable by a Web page designer. A declarative user-agent tag might allow such constructs as those shown in Listing 6. Listing 6. Sample user-agent tags
<xyz:user-agent agent="opera | ie 5+ | ns 4+">
... include contents only if the user-agent is one of the above ...
</xyz:user-agent>
<xyz:user-agent type="robot">
... include contents only if user-agent is categorized as a robot ...
</xyz:user-agent>
<xyz:user-agent supports="JavaScript">
... include contents only if user-agent supports JavaScript ...
</xyz:user-agent>
|
Another way to accomplish this sort of thing might be to generate XML, and have something like a Cocoon filter apply an XSLT transform based on the user-agent.
Conclusion: Aiming for usability
None of the examples in this article have focused on how the underlying Java technology works, or even whether or not the ultimate implementation occurs on the client or the server. The point, rather, is the usability of the technology for the end user. The nice thing about JSP is that, although ease of use is the goal, we need not sacrifice in the area of implementation. Something visually simple like:
<xyz:input type="text" width="32" validate="[pattern]"/>
|
could emit client-side field validation code. The generated page might incorporate complex JavaScript, but who would know? The underlying complexity would be hidden from the page designer and generated by the tag library. On the other hand, the "pattern" dialect does need to be appropriate for page designers. This means that, for example, regular expressions might not be the best choice of dialect to choose when designing the tag library, despite the fondness most programmers have for them. But the tag library could accept multiple forms for specifying patterns. Weighing the possibilities and making decisions that promote tag usability is the foundation part of designing a custom tag library. I think I have demonstrated that JSP provides considerable choice when it comes to the implementation of your tags; as with any development project, however, your first consideration when designing a custom tag library should be the end user.
Resources - The Jakarta Struts project is a good example of JSP pages in a Model-View-Controller type paradigm. There are problems with some applications of this model, however. For example, I find that with most sites using this
style of interaction, once I am logged in I cannot bookmark any useful content. This is because the only URL presented to the browser is the URL for the controlling servlet. This problem can often be resolved through the use of servlet mapping.
- When it comes to alternative content engines, I'm very impressed with the Cocoon project, but I think it should be recast to perform the XSLT transforms in a servlet filter.
- The WebSphere Application Server implements JSP technology with support for numerous scripting languages.
- See the Jakarta home page to learn more about the Jakarta project and its subprojects such as the DBTags tag library.
- In "JSP
technology -- friend or foe?" (developerWorks, October 2000), Brett McLaughlin takes the opposite stance of my own regarding alternatives to the JSP platform. It is a testament to the evolution of JSP technology, however, that his specific complaints from just one year ago have been rendered obsolete by
enhancements to the specification since then.
- Sue Spielman's "JSP vs. XSP" (OnJava.com, February 2001) is a thorough discussion of the differences between JSP technology and Cocoon. As Spielman observes, XSP was developed in part due to the Servlet platform's failure to provide an effective way to chain from a content generator through a transformer. XSP was developed, in part, to work with
Cocoon's internal chaining mechanism to address that lack. Less than a year later, however, a standard technology known as Servlet Filtering obviates the need for proprietary chaining mechanisms.
- Spielman also offers a technical introduction to creating custom tag libraries (OnJava.com, April 2001).
- If you need it, my recent tutorial "Introduction to JavaServer Pages technology" (developerWorks, August 2001) will get you started with the JSP platform.
- You can find out more about the DBTags tag library (and JSP and JDBC technologies) by reading my article "Dynamic Web-based data access using JSP and JDBC technologies" (developerWorks, September 2001).
- You'll find hundreds of articles about every aspect of Java programming in the IBM developerWorks Java technology
zone.
About the author  | 
|  |
Noel J. Bergman's background in object-oriented programming spans more than 20 years. He participated on the original CORBA and Common Object Services Task Forces and consistently receives high marks as a favored speaker at the Colorado Software Summit, as
well as other industry conferences. Noel provides customized IT consulting and mentoring services based on each client's specific problem domain. He is currently involved in using open source freeware to develop interactive database-backed Web sites. He is also a co-author of GNUJSP, an open source implementation of JSP, and is the originator of the JSP Developer's Guide
Web site. Contact Noel at noel@jspdevguide.com.
|
Rate this page
|  |