Introduction to the Java Standard Tag Library

In the beginning, there was HTML — and everyone was happy. Then, one day, someone clever decided that they needed to have dynamic content on their Website, invented a scripting language that generated HTML, and all hell broke loose. Within months, Web pages had grown into a jungle of HTML, scripting code, and SQL statements.

At first, Java’s take on all this was the Servlet. Although useful in certain circumstances, it proved cumbersome and unwieldy. The saviour was to come in the form of Java ServerPages. Able to leap across buildings in a single bound, JSPs looked like a scripting language and acted like scripting language, but in actual fact were nothing more than a clever way of writing Servlets! JSPs solved a lot of problems that were inherent within Servlets, but they introduced a number of issues as well.

Pages could easily become a mess of scriptlet code and HTML fragments. Worse still, JSPs allowed you to avoid having to write JavaBeans to take care of your business logic; putting all your site functionality into the Web page itself was a quick fix that, more often than not, would come back and bite you when you least expected it. Finally, the typical front end developer took to JSP scripts like a fish to a bicycle, shying away from the complexities of Vectors, Request objects and null pointer exceptions in favour of simpler pleasures.

Why am I telling you all this? Because, just when it seemed like everything was headed in a downward spiral, there came a solution! Enter stage left, the Java Standard Tag Library.

Meet the JSTL

The Java Standard Tag Library (or JSTL) is nothing more than a Java Tag Library that provides us with a number of Standard functions. Ok, ok — put another way, the JSTL is going to make your quagmire of JSP script and HTML look like regular plain old HTML pages again. And that is a good thing. Your pages will be more readable (no more scriptlets), your code architecture will become a lot cleaner (no more HTML in your JavaBean classes) and, best of all, the front end developers you work with will invite you to the pub at lunchtime like they used to.

Ok, just to whet your appetite before we talk about how to get the thing installed, here’s a fairly typical piece of code you might see in a JSP page:

By now, the HTML developers you work with aren’t just inviting you to the pub, they’re getting the rounds in as well!

Ok, let’s get this thing installed. You will need an application server that adheres to the JSP 1.2 spec. For most people that means Tomcat 4.0+. Once Tomcat is installed, you’ll need to download a copy of the JSTL itself. You can get hold of a copy from the Jakarta Apache site (see Resources at the end of this article). Download the code for this article here.

Create a new Web application in Tomcat (you can just create a new directory under the webapps/ directory). For this article, we’ll call the Web application “jstl_stuff”.

Unpack the JSTL archive.

Create a “WEB-INF” directory within “jstl_stuff”, and a “lib” directory within “WEB-INF”.

Copy everything from the lib directory of your JSTL archive into <Tomcat Home>/webapps/jstl_stuff/WEB-INF/lib.

Restart Tomcat.

To test the installation, create a page entitled index.jsp in the /jstl_stuff directory, and add the following code:

Now try browsing to http://localhost:8080/jstl_stuff. If you see a page that displays “Doh! It’s working!” and nothing else, everything is working perfectly. If you see an explosion of java exceptions, something has gone wrong, and it’s time to start checking your Tomcat configuration.

The Components Explained

I’m going to be referencing the following class (simpsons.Homer) for the examples. You can compile it and place it in <tomcat home>/webapps/WEB-INF/classes/simpsons, or you could write your own.

Note: in the following examples, we need to declare that we’re going to use the Homer class in our JSP pages. Remember to add the following line to the top of your JSP pages after you’ve compiled the class:

<jsp:useBean id="homer" class="simpsons.Homer" scope="page" />

The JSTL is split into 4 components:

Core – The main tags used within the library

XML â€“ A set of XML processing tags

Format â€“ Internationalization and formatting tags

SQL â€“ Tags for accessing an SQL Database

We are going to cover the Core and Format set of tags in this article. If you want to get to grips with either of the others, see the resource links at the end of this article.

In order to inform Tomcat that we are about to use the JSTL core tags in our page, we need to include the following taglib directive in every page in which JSTL tags are used:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

As I mentioned earlier, the idea behind the JSTL is to provide a basic level of functionality to the programmer, so that JSP scriptlets are no longer needed. For example, if we want to assign a value to a variable, we can use the set action:

<c:set var="homer" value="Doh!" />

To output something to HTML, we can use the out action:

<c:set var="homer" value="Doh!" />
<c:out value="${homer}" />

Running this should provide us with a single “Doh!”

You can set the property of a JavaBean as well. For example, if wanted to set homer‘s IQ property we could do:

<c:set target="${homer}" property="iq" value="34"/>

Veteran JSP coders will probably be scratching their heads at this point. This part of code might look unusual:

${homer}

Welcome to the JSTL Expression Language (or EL)! The EL is a method of accessing Java variables in a much simpler way than the old “JSP-style” involved. The EL is both simple and powerful. Using it, we can access the variables of an object in a wide variety of ways:

${homer.iq}

The above would access the homer object’s iq property.

${homer.braincell[1]}

The above would return the second element of the homer object’s braincell collection. Note that we don’t need to know (and, indeed, don’t care) whether the braincell property of the homer object is an array or a Vector (or anything else that implements the List interface); the EL does all the work for us.

We can also use the EL to evaluate expressions. So, for example, the following would evaluate to true:

${homer.iq < 50}

We can now start to use the EL and the JSTL tags to radically simplify our JSP pages.

Conditional and Iterative Operations

Most of the time, JSP scriptlets are used to perform conditional (if..else) or iterative (for, while) tasks. The JSTL core tags provide this functionality without having to resort to scriptlets. The <c:if ...> and <c:choose ...> tags provide the basic conditional operations. For example, a simple if statement would read:

Here we've used the begin and end parameters to define where the loop will start and terminate. We also use the varStatus object. This object provides an interface into the state of the loop. Check the resources at the end for further information.

JSTL and URL Generation

The JSTL also provides tags to help us tidy up URL generation. Scriptlet code is often used to construct URLs that pass parameters to other pages, and can get messy very quickly. With the JSTL we can construct URLs in a much neater fashion. For example:

Notice how the JSTL has encoded the checkAgainst parameter for use in the URL, replacing the space with a +. No more worrying about invalid URLs! One extra bonus of using the url tag is to aid those surfing without session cookies enabled in their browser. The JSTL will check and automatically add a sessionId to the link if session cookies have been disabled.

Finally, a quick mention of the format tags. These are separate from the core tags, and have to be imported with the statement thus:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>

The above appears at the top of the JSP page. The format tags provide powerful text formatting functions. Just as a brief experiment, try running the following in a JSP page:

What's the Big Deal?

As you can see, the JSTL is a large topic. We have only covered a small part of the core and format libraries here; there are also libraries for dealing with XML as well as a set of tags for JDBC access.

By now you're probably thinking one of two things; either you're thinking, "That's great, my pages will stop looking like a mess of scriptlets," or, "What's the point? I have to learn all this stuff and I don't really get any extra functionality."

As I mentioned at the start of this article, the JSTL is really all about making your life easier in the long run. Using the JSTL helps in a number of areas:

It allows non-Java developers to write Java code without having to touch any Java.

It will tidy up and simplify your JSP files and stop them looking like a spaghetti of scriptlets.

When you start using the JSTL you will notice it enforces you to write better, cleaner code. It's a subtle change at first, but as you get more comfortable with the tags, you'll find it IS faster than developing with scriptlets.

There is a fourth reason for looking into using JSTL in your own projects, and it's a biggie: Java Server Faces. Sometime next year (2004) will see the arrival of application servers that conform to the JSP 2.0 specification, allowing developers to start using Sun's much-ballyhooed Java Server Faces framework. It's an exciting development, and one that JSTL developers will have a head start on; the JSF will make heavy use of the Expression Language as well as the JSTL tags themselves. Making use of the JSTL now will not only help with your projects today, it'll give you a head start when the JSF servers start coming out in 2004.

Ben is Co-Director of Solid State Group, a content management and web development firm based in London. When not pressing keys on a keyboard, he enjoys the vices of obscure Eastern European lager and Ipswich Town FC.