Developer

Extend the power of JSP with JSTL

JSTL is a specification for custom tag libraries, providing tags for conditional structures, iterating, internationalization, and manipulating HTTP, XML, and SQL. Learn how this emerging standard will affect the next version of Java Server Page.


Java Server Page (JSP) has been the cornerstone of Sun's Web presentation architecture for the last three years. The goal of JSP always has been to get the Web designer—not the Java developer—to do the JSP work. The addition of custom tag libraries, or taglibs, enabled Java developers to create custom tags for their Web designers, simplifying the code to ensure someone is allowed to be logged in, for example, via an <int:checkLogIn/> tag.

Custom taglibs have been a success, with many taglib repositories cropping up around the Internet, many of them doing pretty much the same thing. The first tag I remember writing was an include tag that worked a bit more nicely than the standard JSP counterpart. The next tag was a simple log tag to wrap a logging API. These types of tags can be found all over the place, and in recognition of this fact the JSR-52 has created the JSP Standard Tag Library (JSTL) specification.

JSTL is a specification for a set of custom tag libraries that provide tags for conditional structures, iterating, internationalization, and manipulating HTTP, XML, and SQL. It was originally hosted at the Jakarta project, the Apache Foundation's Web-based Java community, for a couple of reasons. First, Tomcat, Jakarta's flagship product, is the reference version of the Java Web Server specification. Second, Jakarta has one of the most well-known and mature custom taglib repositories around; in fact, JSTL borrows quite a few established Jakarta taglibs. Upon release, Sun put out its own implementation of the JSTL, making available two very similar versions—Jakarta and Sun.

Since JSTL is a specification, there likely will be many implementations, similar to all the implementations of JSP and servlets. When the next major version of your favorite Web server is released at the end of the year, you can expect a JSTL implementation as standard.

JSTL components
JSTL has three major areas for Web designers.
  • Core tag libraries—There's a core taglib that supplies standard programming constructs, such as forEach and if/else, and other tags such as try/catch handling and an improved include tag.
  • Additional tag libraries—A series of additional taglibs deals with SQL, XML, and formatting, including internationalization.
  • The expression language—Original buzz suggested that many expression languages, such as XPath, BeanShell, and EcmaScript, would be allowed, but in the end the JSR-52 chose a simple bean manipulation language. As an alternative to using the expression language, a version of the JSTL taglib simply uses rtexpr values.

Core taglib and expression language
The center of JSTL is the core taglib. This can be split into five areas:
  • Expression
  • Iteration
  • Traditional
  • Include
  • Try/Catch

Let’s take a closer look at each area, beginning with the expression tags.

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

The code to set up the person bean is as follows:
 
<c:out value="${person.name}" default="n/a"/>
<c:set var="person" scope="application">
 

The out tag outputs a value; the set tag puts a value into a scope.

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

The code to set up a people collection is as follows:
 
<c:forEach var="person" items="${people}">
<c:out value="${person.name}"/>
</c:forEach>
<c:forTokens var="token" items="one,two,three" delims=",">
<c:out value="${token}"/>
</c:forTokens>
 

Here, the forEach tag will loop over the people variable and a list or array, and output each one's name. The forToken tag splits the one,two,three string and prints out each one.

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

The code to set up a country bean is as follows:
 
<c:if test="${country.continent == 'Africa'}">
<c:out value="${country}"/>
</c:if>
<c:choose>
<c:when test="${country.continent == 'Africa'}">
<font color="red">
</c:when>
<c:when test="${country.continent == 'Asia'}">
<font color="blue">
</c:when>
<c:otherwise>
<font color="green">
</c:otherwise>
</c:choose>
 

If the country.getContinent() method is equivalent to 'Africa', it is printed out in the if tag. The choose/when/otherwise tag is an improved-upon case/switch statement. It can handle strings happily and has a nice syntax.

Include tags 
<c:import url="http://www.cnn.com/cnn.rss"/>
<c:import url="LocalSample.jsp" var="sample"/>
<c:import url="ftp://ftp.gnu.org/README"/>
<c:url value="http://www.generationjava.com" var="anchor">
<c:param name="name" value="Fred Flintstone"/>
</c:url>
<a href='<c:out value="${anchor}"/>'>Login</a>
 

The JSTL import tag is more powerful than earlier JSP include functions. It allows you to include data directly from another Web site, as in the cnn.com example above. It allows you to get data from other sources, such as FTP sites, and it lets you place the obtained data directly into a variable, as defined by the var attribute, and not print it out on the screen (this is a common feature in the JSTL).

The url tag is a nice way in which to build links to other sites without having to handle the HTTP encoding yourself. Should a space be %20 or %32? Let the url tag take care of it for you. The Flintstone example above shows an easy usage.

Try/Catch tags 
<c:catch var="ex">
... untrusted code ...
</c:catch>
<c:if test="${not empty ex}">
Error: <c:out value="${ex.message}/>
</c:if>

JSTL also provides a simple try/catch mechanism. There's no way to specify which particular throwable you wish to catch, but you can put in a big any exception error handling block to protect your code.

Additional tag libraries
The JSTL tag library is more than the Core library; it also contains SQL, XML, and formatting libraries.

The SQL library may be used to put values in the database or perform queries on the database. It acts upon a datasource, usually a default one named javax.servlet.jsp.jstl.sql.dataSource. An example query tag using the default dataSource to list all users in a database would be:
 
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
<sql:query var="result">
SELECT * FROM USERS
</sql:query>
<ul>
<c:forEach items="${result.rows}" var="row">
<li><c:out value="${row.TITLE}"/>. <c:out value="${row.FIRST_NAME}"/> <c:out value="${row.LAST_NAME}"/></li>
</c:forEach>
</ul>

The recommended namespace for the SQL tag library is, rather originally, sql. The XML tag library allows XPath notation to be used on XML. Simple usages would be grabbing RDF feeds from Weblogs and showing the titles on another Web site. For this tag library, x is recommended as the namespace.
 
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
<c:import url="http://weblogs.flamefew.net/bayard/index.rdf">
<x:parse var="weblog"/>
</c:import>
<x:forEach select="$weblog//item">
<x:out select="title"/><br/>
</x:forEach>
 

Lastly we have the formatting taglib, namespace fmt. A classic use of the formatting taglib would be to output a date variable.
 
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:parseDate value="09 18 1998" var="date" pattern="MM dd yyyy"/>
<fmt:formatDate type="date" value="${date}"/>
 

This is obviously not an exhaustive look into these three taglibs, but it provides a basic sampler.

Expression language
The simple expression language used in JSTL allows bean reflection to occur easily; it also handles some simple operations and array lookup. It is used throughout the most popular variant of JSTL, and will become a core feature in JSP 2.0. So get used to it now, and you'll be ready for the next big thing.

The JSTL-EL is used wherever you see the usage of the ${..} notation in a tag attribute. In the formatDate example above, the JSTL-EL was used to specify the value for the fmt:formatDate tag.

Closing tag
JSTL is a JSP 1.2 tag library. While many JSP containers support this version now, a lot of us are still on the JSP 1.1 version. There are hosts of taglibs at Jakarta Taglibs, which can support some parts of the JSTL's functionality, and a JSP 1.1 version of the JSTL may be released. After all, there's an open source implementation already.

Using JSTL adds a host of powerful standard tags to the JSP developer's toolkit. And it prepares the developer for JSP 2.0 without involving a server upgrade.

Editor's Picks

Free Newsletters, In your Inbox