A Step in the Right Direction

First introduced in 1997, servlets gave developers the ability to write server-side applications in Java. While servlets were great for Common Gateway Interface (CGI) programs and other simple tasks, it soon became evident that producing HTML solely with Java code was cumbersome for all and especially difficult for non-programmers involved in the work.

First introduced in 1997, servlets gave developers the ability to write server-side applications in Java. While servlets were great for Common Gateway Interface (CGI) programs and other simple tasks, it soon became evident that producing HTML solely with Java code was cumbersome for all and especially difficult for non-programmers involved in the work.

Two years later, Sun took a step in the right direction with Java Server Pages (JSP), which made it easy to combine static HTML with dynamic HTML created by Java statements. Using JSP, Java code could be embedded in Web pages amid HTML markup, and programmers could create their own custom JSP tags to interact with custom Java objects.

Unfortunately, the ease with which Java code could be placed on a Java Server Page proved to be a misstep, because it encouraged the bad habit of placing mission-critical application code in a web page, where it’s hard to maintain, is insecure, and is easily bungled by anyone editing the HTML around the Java code.

Servlets and JSP reflected progress, but, in retrospect, both technologies seem like baby steps compared to the leap of progress found in the recent release of the JSP Standard Tag Library, or JSTL. JSTL is a set of custom JSP tags and a new data-access language that enable JSP-based web applications to handle presentation without resorting to Java code. JSTL, which requires a Java servlet container supporting Java Servlet 2.3 and JavaServer Pages 1.2, lives at http://java.sun.com/products/jsp/jstl.

JSTL will eventually be supported natively by servlet containers, but for now, it can be implemented in minutes just by copying several JSTL .jar files to the WEB-INF/lib folder of a web application. A reference implementation of JSTL created by the Apache Jakarta project can be downloaded from http://jakarta.apache.org/taglibs/doc/standard-doc/intro.html. (To differentiate it from other tag libraries offered by Apache Jakarta, JSTL calls it the “standard” library.)

Playing Tag

JSTL consists of two complementary components:

* A set of four, custom JSP tag libraries that provide the core set of features required in web applications: conditional processing, database access, internationalization, and XML processing.

* The JSTL Expression Language, which accesses data at runtime without using JSP expressions or Java statements.

Listing One contains a simple demonstration of JSTL and the Expression Language. hello.jsp is a Java Server Page that uses a parameter called name as part of a greeting. Using the page, the URL http://www.example.com/hello.jsp?name=Sailor produces the response “Hello, Sailor.” Omitting the name parameter produces “Hello, Stranger.” instead.

Listing One: The hello.jsp Java Server Page

<title>Hello Example</title>

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

<c:when test=’${!empty param.name}’>
<h2>Hello, <c:out value=’${param.name}’/>.</h2>
<h2>Hello, stranger.</h2>


The first JSP code in the page is the following directive:

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

Like other tag libraries, a JSTL library must be included on each page that uses it. For example, the directive shown immediately above makes the core library available to the hello. jsp page. By specifying prefix=’c’, all tags from core must be prefaced with the text c followed by the tag’s name, like so:

<c:out value=’${param.name}’/>

JSTL tags are called actions because they generate dynamic web content. The c:out action displays the contents of the local or instance variable indicated by its value attribute.

The variable, such as param.name, is specified using JSTL’s Expression Language, a simple data-access syntax that borrows from ECMAScript (JavaScript) and XPath. Statements that use the language are contained within ${ and }.

By the way, the variable param is one of several, standard Expression Language variables that contain information about the page, the web application, and the servlet container. param is a collection that holds all of the page parameters, each represented as a string.

Like XML elements, actions can stand alone (<tagname/>) or appear as pairs (<tagname></tagname>).

The rest of the page contains three core actions used to create a conditional block:

<c:when test=’${!empty param.name}’>
<h2>Hello, <c:out value=’${param.name}’/>
<h2>Hello, stranger</h2>

The c:choose-c:when-c:otherwise block mirrors the switch-case-default Java statement: it displays the HTML associated with the first c:when action whose test attribute is true. If none of the c:when actions are true, the contents of c:otherwise are displayed.

Code, Pages, Action

JSTL is composed of four tag libraries with 42 actions:

* The core library (prefix c, default URI http://java.sun.com/stl/core) contains general features: output, conditional display of content, looping, variable creation in several scopes, JavaBean access, exception handling, URL imports, and URL redirection.

* The SQL library (prefix sql, default URI http://java.sun.com/jstl/sql) covers database access: data source selection, queries, updates, transactions, and looping through results.

* The internationalization and formatting library (prefix fmt, default URI http://java.sun.com/jstl/fmt) offers locale and resource bundle use, text localization, and number and date formatting.

* The XML processing library (prefix x, default URI http://java.sun.com/jstl/xml) supports XML parsing, XPath access, XSLT transformation, looping through nodes, and conditional processing.

The Expression Language has operators to retrieve information from instance variables (${object.varName}), data structures (${object["name"]}), and indexed arrays or lists (${object[1]}). There also are operators for arithmetic (+, -, *, /, %), comparisons (==, !=, <, <=, >, >=), logic (&&, ||, !), and empty, which detects null objects and empty strings or collections. Parentheses can be used to group subexpressions.

The Expression Language also offers automatic type conversion and five kinds of literals: strings, which are enclosed within single or double quotes; integers; floating-point numbers; boolean values (true or false), and null. There are also nine special variables:

* cookie, a collection of all request cookies, each as a Cookie.instance from the javax.servlet.http package.

* header is a collection of all request headers, each as a string.

* headerValues is a collection of all request headers, each as a string array.

* initParam is a collection of all application initialization parameters, each as a string.

* pageContext is an instance of jspPageContext from the javax.servlet package.

* param is another collection — this one of all request parameters, each as a string.

* paramValues is a collection of all request parameters, each as a string array.

When using one of these collections or other data structures, the c:foreach action makes it easy to loop through each element. The following example displays all of the header variables sent with a JSP page:

<c:forEach items=’${header}’
<li>Name: <c:out
<li>Value: <c:out

Four variables can be used to make explicit references to variable scope:

* applicationScope, a collection of all application scope objects.

* pageScope, a collection of all page scope objects.

* requestScope, a collection of all request scope objects.

* sessionScope, a collection of all session scope objects.

For example, ${sessionScope.price} retrieves an object named price in session scope. If no other scope has an object named price, the expression ${price} also works.

For a more complete reference to JSTL actions and the Expression Language, author Shawn Bayern offers Appendix A of the book JSTL in Action on the Web at http://www.manning.com/bayern/appendixA.pdf. More information on the book is available at http://www.manning.com/bayern.

Let’s look at another example — parsing an RSS news feed — to see some of the power and flexibility of JSTL. RSS, which stands for Really Simple Syndication, is two, similar XML dialects that enable sites to share headlines, links, and other content with each other. JSTL can import and parse XML, HTML, or any other data available at a URL, even if a URL points to a server other than the one hosting the Java Server Page.

Listing Two contains a simplified version of Linux Magazine’s RSS feed. The XML data from this feed can be read into a variable using the <c:import> action from the core library and parsed with the <x:parse> action from the XML library. The parsed data can then be examined, filtered, transformed, and displayed. Listing Three contains a Java Server Page application that uses simple XPath statements to extract and display parts of the XML data.

Listing Two: The lm.rss XML file

<?xml version=”1.0″?>
<rss version=”0.91″>
<title>Linux Magazine</title>
<description>Linux Magazine Online</description>
<title>x86: The Next Generation</title>
<description>Linux Magazine has seen the future, and it looks a
lot like the dual-Opteron-powered Newisys 2100 ECS server. This
revolutionary machine, which goes on sale tomorrow to coincide with
the launch of the AMD Opteron processor, represents the future of
Linux server computing.</description>
<title>Linux’s Perfect Storm</title>

<description>The highly-competitive financial industry has a
history of adopting IT trends ahead of the curve. The Street’s
forecast for Linux? A strong buy.</description>
<title>Java Matters, by Rogers Cadenhead</title>

<description>A Hill of Beans</description>

Is JSTL Right for You?

One likely detractor from JSTL is its Expression Language, which can be disregarded by using versions of the JSTL tag libraries created specifically to be used with JSP’s established syntax for Java statements and expressions. JSTL’s Expression Language is defined as much by what it can’t do as by what it can. There are no assignment operators or conditional logic, encouraging developers to use external Java classes and JSTL actions for these tasks.

Listing Three: The rss.jsp Java Server Page

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<!– Declare the two tag libraries used on this page –>
<%@ taglib uri=’http://java.sun.com/jstl/core‘ prefix=’c’ %>
<%@ taglib uri=’http://java.sun.com/jstl/xml‘ prefix=’x’ %>

<!– Import the RSS feed at the URL specified by feed –>
<!– For example –>
<!– http://example.com/rss.jsp?feed=http://www.linux-mag.com/lm.rss
<c:import url=’${param.feed}’ var=’feedData’/>

<!– Parse the RSS feed –>
<x:parse xml=’${feedData}’ var=’feed’/>

<!– Retrieve the channel element –>
<x:set select=’$feed//rss//channel’ var=’channel’/>

<!– Display the channel element’s title –>
<title><x:out select=’$channel//title’/></title>


<!– Display the channel element’s link and title –>
<p>Headlines from <a href=”<x:out select=’$channel//link’/>”><x:out

<!– Loop through the item elements –>
<x:forEach select=’$feed//rss//channel//item’> <!– Display each
element’s link, title, and description –>
<!– Note that descriptions may contain HTML, so the XML is not
escaped. –>
<li><a href=”<x:out select=’link’/>”><x:out select=’title’/></a>:
<x:out select=’description’ escapeXml=’false’/></li>


However, though some Java programmers may blanch at the thought of learning another language for web applications, the Expression Language is simple enough to be picked up quickly, especially by those who are comfortable with JavaScript.

By keeping Java code out of Java Server Pages, the Expression Language offers considerable benefit towards reusability and reliability. In conjunction with JSTL, it brings JSP much closer to the promise of separating the presentation of a web application from the code required to make it happen. For this reason, it serves as a nice compliment to Jakarta Struts, the open source, web application framework covered in the March and April 2003 issues of Linux Magazine.

Next month’s edition of Java Matters covers another intriguing, open source framework for Java programmers: the JUnit automated test framework.

Rogers Cadenhead is a Web application developer and the coauthor of Teach Yourself Java 2 in 21 Days, Third Edition from Sams Publishing. To contact Cadenhead, visit his weblog at http://www.cadenhead.org/workbench. You can download the code used in this column from http://www.linux-mag.com/downloads/2003-08/java.

Comments are closed.