JSTL Gives Web Applications Flexibility
While scripting languages like PHP continue to draw wide appeal, there are downsides. Try JSP tag libraries for a faster approach
by Alan Berg

February 14, 2006

Scripting languages are quick to develop and easy to manipulate. If you want to build a dynamic Web site in a day or make quick changes to CGI-like scripts, then with relatively few learning hours you can apply scripting languages to these tasks. Further, with scripting languages like PHP, a server-side scripting language that is vaguely similar to C, you gain the potential for rapid development cycles. Once you enact a change, the change propagates live.

These are excellent characteristics of PHP, and what's even better is the language has the reputation of running fast. However, on the dark side there are some drawbacks. Without rigid control, code grows unruly and may become costly to maintain and hard to debug. The diffusion of logic and HTML presentation tags can make for pronounced readability issues. The same issue is true for JSP coding. Struts and other high-level Java frameworks that use the Model-View-Controller (MVC) pattern combat the maintenance issues by dividing applications in such a way that Web designers are not bothered with Java coding. Further, Java coders avoid the majority of the interaction design and graphical user interface (GUI) coding.

However, this separation of tasks between the GUI designer and programmer also has a price; the frameworks have a significant learning curve and indirectly expect a team-like infrastructure that is commonly only found in mid-size to large projects. For small companies the learning curve associated with the frameworks sometimes represents an unrealistic barrier. We may need to be better at addressing the needs of the small businesses and small office/home offices (SOHOs). One possibility for rapid application cycles and instant code changes is pure JavaServer Page (JSP) coding, including all the potential readability and growth pains the practice may entail.

Easier Web Apps
The JavaServer Standard Tag Library (JSTL) is a superset of JSP that attempts to encapsulate commonly required functionality within a series of four extra tag libraries. The idea behind it is to allow for easier creation of Web applications without resorting to mixing Java code in with tags so quickly. Common Web application functionality is encapsulated. JSP has an expression language (EL) that allows for easier plumbing to sessions and beans. For example, the expression:

${sessionScope.driver}

obtains the value of the attribute driver from the scope session. Without EL some of the basic JSP coding is verbose. For example, obtaining a property from a bean in EL is similar to ${login.UID}, where as without EL the resulting code is:

<%= ((Login) pageContext.
  getAttribute("login")).getUID 
  () %>

Note that EL is supported by JSTL but can function outside the extra tag libraries as well. The four logically divided JSTL tag libraries are: core, which works with basic programming constructs such as iterations; internationalization and formatting, which allows for the loading and use of resource bundles for internationalization and the general manipulation of string formatting; SQL, which enables connection to databases through data sources as well as the general manipulation of databases; and XML, which is used for generic manipulations. Note here that with up-and-coming technologies such as AJAX that make extensive use of XML, expect to see more use of the XML library.

Take a look at a simplified PHP page (see Listing 1). Specific functionality is separated into pages. The config.php file contains global variables, and connection.php makes a connection to a specific MySQL server and then closes the connection.

As suggested by the name, $query holds the SQL query. If you have queries that may change over time, then it is better to have each query stored in a text file and have the query read in by the fopen() method. Doing so allows your local database guru the opportunity to manipulate queries that are not entangled in the presentation.

The line starting with $result performs the query by calling the mysq_query() method, which is buffered, and rendering of the HTML needs to wait until all the results are returned. An unbuffered version of this method also exists. If the method fails to obtain a connection the text "Sorry the query failed" displays. It would be nicer to redirect the user to a standard error page at the point of failure instead of inconsistent print statements. PHP is a programming language that supports iteration; the while statement iterates through an array of results collected by the Mysql_fetch_array() method. The array indexes in $row are the column names of the Mysql table, and $message holds a string version of the results in HTML format. Mail is the standard method for sending mail within PHP. The preconfigured variables are hidden in the config.php file. The header shown here states that the message sent will be in HTML format:

$headers = 
  "From: $from\nReply-To: 
  $replyto\nContent-Type: 
  text/html; 
  charset=iso-8859-1";

Consider some salient issues here: The Mysql functionality is not enabled by default and needs to be enabled through the php.ini file. The functionality is then globally enabled. Secondly, many PHP Web sites do not use connection pooling, and therefore there is a one-on-one relationship with connections and page load.

Roll Your Own JSP Tag
Rolling your own JSP tag is a straightforward method for encapsulating Java code in JSP that gives you the advantage of reuse and ease of coding. The disadvantage is programming effort and maintenance costs. Imagine the commonly found Java issue of class path conflicts. On one server, your SQL statements are being fully understood. However, on another server an error is thrown that complains about Unicode in the returned query results. In the back of the collective head is the idea that perhaps the database driver versions have somehow misaligned. It would be nice in such a situation to quickly produce a debug screen through the code shown in Listings 2 and 3. To create a functional tag library you will need to follow a couple of steps:

1. Write a tag library definition. The definition explains to the servlet container the allowed syntax of the tag library (see Listing 2). The general properties of the TLD are defined, and then the specific tag. The tag's name is defined by <tag><name>, and the java class is called by <tag><tagclass>.

2. Write the personalized java class. The class mentioned in the TLD can take advantage of the javax.servlet.jsp.tagext.BodyTagSupport class and extend overriding the doStartTag() method to generate output when the tag is called from within the JSP page. Note that different methods are declared at different points in the processing of the information contained in an instance of the tag. However, because we have stated in the TLD that the tag has no content by <bodycontent>empty</bodycontent>, we need to override only one method.

The systemPropertiesAsHTMLTable() method iterates through all the system properties and generates an HTML table stored in a string with the name and value pair of the property. Notice the bad practice of having formatting hard coded inside the method. It is significantly better to mention a style sheet and pass the location of the style sheet as a parameter in the tag. However, the extra complexity doesn't fit within the current story.

It's worth mentioning where to find the TLD in the WEB-INF/web.xml file. If you have placed the TLD in the WEB-INF directory and then in web.xml, you need to add:

<taglib>
  <taglib-uri>article.tld
  </taglib-uri> 
  <taglib-location>
    /WEB-INF/article.tld
    </taglib-location> 
</taglib>

Notice that within the TLD the <taglib-uri> is also mentioned through the <uri> tag. Next, add the tag library to the JSP and call it:

<%@ taglib uri=
  "/WEB-INF/article.tld" prefix=
  "info" %>
<info:debug/>

We can conclude that although it is relatively straightforward to write your own JSP tag libraries for simple functionality, the complexity also increases when moving to slightly more difficult situations. Why bother when JSTL can do most of the heavy lifting?

Time Out
Before moving on to the coding, let's take a moment to discuss bad error handling. How many times have you seen a Server 500 error when you trawl the Internet? Worse still, the full stack trace of the exception on the page is totally alien and meaningless to the average visitor. Or in the case of PHP, an error message with the line number and method call is also not nice, but at least it doesn't fill the page with gibberish. Things happen, Murphy is alive and very active. Infrastructure fails. Sites get too busy. Memory is consumed. Database connections fail.

If you code for run-time errors you may make the code base unwieldy and full of try catch blocks and print statements. Under Tomcat, the tag example we developed previously fails if a security manager is in place because only a limited number of properties are allowed from the standard conf/catalina.policy file. A compromise is to catch all exceptions in the JSP, and redirect them to a second page. In the page you can log all errors or even send mail and so on and then also print out a more intelligible message, which is achieved through setting:

<%@ page errorPage="error.jsp" %> 

at the top of each displayed page and writing an error.jsp page similar to this:

<%@ page isErrorPage="true" %>
<HTML>
<HEAD><TITLE>Error Page
  </TITLE></HEAD>
<BODY>
<H3>Exception Information</H3>
<%= exception %>
<%
Error handling code.
%>
</BODY>
</HTML>

If you feel like challenging yourself, you could write an error-handling tag library that prints pretty exception pages. You can download an extra tag that simply throws an exception (see Resources online at www.javapro.com). If you wish to see how a particular Web application looks on failure to the average user, install the tag library and place the tag on the pages you our interested in, for example:

<%@ page errorPage="error.jsp" %>
<%@ taglib uri=
  "/WEB-INF/article.tld" prefix=
  "info" %>
<info:ExpressError/>

If the same PHP functionality you see in Listing 1 is enacted in JSP alone, then we would need to be able to get configuration information into a JSP, get information out of databases, iterate through the results, and then send an HTML document through SMTP. Further, it would be nice to have an obvious path to migrating to heavier frameworks later as the Web site grows in complexity and popularity.

The Jakarata taglib project is one potential solution. This project is an Apache derivative. The project contains a diverse list of helper tag libraries, which are constantly maintained and improved by a dedicated following of like-minded developers. The taglib project is expanding over time, and it is well worth the effort to visit the project Web site regularly. The two sets of libraries that will be mentioned here are a JSTL implementation and a special mailer tag set that allows for easy e-mailing.

Note that the TLDs are stored in the downloaded JAR files and do not have to be mentioned in web.xml.

A Piece of the Configuration
The first part of the puzzle to solve is how to pass configuration information. As we see in the PHP application, global constants may be kept in a separate page. This functional separation has the advantage (for PHP) of keeping the code and configuration separate. Of course, you can keep configuration in many places including property files, web.xml files, database files, and so on, but for the sake of comparison we will use a similar methodology. This code snippet uses the core library to set up an attribute named url that has session scope:

<%@ page errorPage="error.jsp" %>
<%@ taglib prefix="c" uri=
  "http://java.sun.com/jsp/jstl/
  core" %>
<c:set var="url" value=
  "jdbc:mysql://localhost:3306/
  orders" scope="session"/>

By including the relevant file that contains this code snippet, the first page the user visits through:

<%@ include file="config.jsp" %> 

guarantees that the session is fully populated. Line 5 in the core application (see Listing 4) loads in configuration information. Lines 9–14, starting with <sql:setDataSource, use the configuration information to define a datasource for connecting to the database. In the case of the included project the datasource is a single JDBC connection. However, you may link in JNDI resources through this tag as well. One issue with the tag is that at the top of the web.xml file you need to have JSP version 2.4 defined, and absolutely no version lower or the current core taglibrary will fail to function correctly.

The <sql:query lines (14–16) perform a query using the default datasource. The resultset is stored in the attribute answer ready for manipulation. The <mt:mail> lines (18–37) are quite long because the message is being generated by iterating through the resultset, referenced in the answer attribute. The global properties are defined such as the host and from address. The message type may be either text or HTML.

Within the <mt:message> tag (lines 23–30) the database results are iterated through by the core tag library, and the results are written through a combination of plain HTML and c:out. If an error occurs, then lines 33–35 will print an error message.

We've put together well-known tag libraries to mimic similar work that was enacted by a simple PHP application. The most complex part of the page is the iterating through the database resultset. The method of generating the message string is a mater of taste. For example, you could include Java to populate a string, and place the result through <c:out in the message. This extra coding complexity is part of the JSTL learning curve.

Being agile and able to achieve rapid application cycles and modifications of standard Web sites on the fly requires rapid build cycles. JSP, Active Server Pages (ASP), and PHP are competing head to head. By working with the JSTL and other well-known tag libraries, rapid application development (RAD) is supported. Important side issues in the competition include the quality of the integrated development environment (IDE) and the simplicity of setting up the application servers.

The popular Eclipse environment doesn't provide out-of-the-box support for JSP, but this situation may change soon. Currently there are commercial and noncommercial Eclipse plug-ins. MyEclipse or Nitrox, for example, support JSP editing. Linux, Apache, MySQL, and PHP (LAMP) servers are relatively easy to set up and understand. Infrastructure based on JBoss or Tomcat has that potential for simplicity. However, IIS6 servers win on ease of installation. If Java is to be king in this field, then that is where the focus may need to turn.

Exit This Way
Arguably, where Java wins is in terms of escape routes. Java is mature and built for use in the enterprise. Many frameworks exist that are helpful for scaling up. Success does happen. Teams get bigger; effort starts to get divided. Then the full story of dividing responsibility comes to the fore. Frameworks such as JavaServer Faces (JSF) and Struts can be migrated too without extreme fuss. The use of managed beans in JSF, where you can define bean creation and scope within XML files, can take away some of the drudgery and repetition of code. You may even get to play with their cool tag libraries. For future reference, yet another Apache project is Myfaces, which is an implementation of JSF. The project includes some nice tags such as master view tables and is even expanding into the AJAX arena.

We've taken a whirlwind tour of the possibilities for making a basic Web application rapidly. JSTL in combination with other tag libraries is well suited for this task. It can be argued that iteration in the core tag library requires a small learning curve. Further, if later the functionality is expanded and larger team groupings occur, there are escape routes to more monolithic frameworks such as JSF, spring, and Struts.

About the Author
Alan Berg, Bsc., MSc,.PGCE, has been a lead developer at the Central Computer Services at the University of Amsterdam for the last seven years. In his spare time he writes computer articles. He has a degree, two masters, and a teaching qualification. In previous incarnations he was a technical writer, an Internet/Linux course writer, and a science teacher. Contact Alan at .