Knowledge Base
Inicio > Cursos > JSP-Taglibs
JSP taglibs: Better usability by design

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.
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.

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?

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.

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

<%
     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

<xsp:logic>
    String timeOfDay = ( new SimpleDateFormat("aa")).format(new Date());

      if (timeOfDay.equals("AM")) {
      &lt;xsp:content>Morning</xsp:content>
    }
    else {
      &lt;xsp:content>Afternoon</xsp:content>
    }
&lt;/xsp:logic>
				

Listing 3 shows how a page coded using JSP and declarative tags might look.

Listing 3. Greeting using tag attributes

     &lt;xyz:greeting am="Morning" pm="Afternoon" />
				

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

&lt;xyz:greeting>
       &lt;xyz:when period="05:00 - 11:59">
       Morning
       &lt;/xyz:when>
       &lt;xyz:when period="12:00 - 17:59">
       Afternoon
       &lt;/xyz:when
       &lt;xyz:when period="18:00 - 20:59">
       Evening
       &lt;/xyz:when>
       &lt;xyz:when period="21:00 - 04:59">
       Night
       &lt;/xyz:when>
&lt;/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

&lt;xyz:data-table source="iterator" id="beanname">
&lt;tr>
&lt;td><jsp:getProperty name="beanname" property="prop" /></td>
&lt;/tr>
&lt;/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:

&lt;xyz:greeting machine="server or client">
...
&lt;/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

&lt;xyz:user-agent agent="opera | ie 5+ | ns 4+">
... include contents only if the user-agent is one of the above ...
&lt;/xyz:user-agent>

&lt;xyz:user-agent type="robot">
... include contents only if user-agent is categorized as a robot ...
&lt;/xyz:user-agent>

&lt;xyz:user-agent supports="JavaScript">
... include contents only if user-agent supports JavaScript ...
&lt;/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:

&lt;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.