Resources

SAS® AppDev Studio 3.0 Developer's Site

JavaServer Pages Standard Template Library (JSTL)

JSTL (http://java.sun.com/products/jsp/jstl/) is a library of tags that encapsulates functionality commonly needed by Web applications. An implementation of JSTL Version 1 is included with webAF 3.0. JSTL is expected to be included in the forthcoming JSP 2.0 specification.

The information below provides a brief introduction to JSTL library usage; not all tags or attributes are described. The JSTL EL Example Web Application illustrates the use of many of these tags. It includes source code and build directions.

JSTL Libraries
Expression Language
Core Tags
Database Tags
Formatting Tags
XML Tags

JSTL Libraries

There are two versions of the JSTL libraries, which differ only in the way they support the use of runtime expressions for attribute values:

Library name Attribute values evaluated by Example
JSTL-ELNew Expression Language <c:forEach var="item" items="${sessionScope.cart.items}" >
JSTL-RTPage's scripting language (for example, Java) <c:forEach var="item" items="<%= session.getCart().getItems() %>">

You will probably want to use the JSTL-EL library, since the new Expression Language features a syntax that makes it simpler and cleaner to use. Except for the method of evaluating attribute expression values, the two libraries are the same.

Each of the two libraries is actually partitioned into four separate tag libraries:

Library/
TLD uri/
Prefix
Functional
Area
Tags &
Sub-tags

Core

http://java.sun.com/jstl/core

c

Expression Language supportcatch
out
remove
set
Flow controlchoose
  when
  otherwise
if
forEach
forTokens
URL managementimport
  param
  paramredirect
url
  param

Database

http://java.sun.com/jstl/sql

sql

SQLquery
  dateParam
  param
setDataSource
transaction
update
  param
  dateParam

Formatting and Internationalization

http://java.sun.com/jstl/fmt

fmt

LocalesetLocale
Message formattingbundle
message
  param
setBundle
Number and date formatformatDate
formatNumber
parseDate
parseNumber
setTimeZone
timeZone

XML

http://java.sun.com/jstl/xml

x

Coreout
parse
set
Flow controlchoose
  when
  otherwise
forEach
if
Transformtransform
  param

In webAF, if you choose to include the JSTL tag libraries (either by using the New Project Wizard or by selecting File [arrow] Web Application Properties) then the checked tag libraries will automatically be included in any new JSP files you add to the project. For example:

JSTL Options dialog

Selecting the checked options above will add these lines at the top of each new JSP file:

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

The webAF palette will also include drag and drop support for JSTL tags when these options are checked.

Expression Language (EL)

The JSTL EL tags evaluate text inside attribute values bracketed between ${ and } using a simple expression language. Everything in the attribute value that is not bracketed is treated as literal text. You cannot use ordinary JSP expression brackets (<%= and %>) inside attribute values using the EL tag library.

The EL provides a simplified syntax compared to JSP expressions. For example, without EL you would need to write:

   <c:if test="<%= pageContext.getAttribute("isShopping") %>">
      ...
   </c:if>

With EL, you can write the same logic as:

   <c:if test="${isShopping}">
      ...
   </c:if>

A simple identifier (like isShopping) is evaluated as a page-scoped attribute name. If the identifier is not found as a page-scoped attribute, then the request, the session and the application scopes will be searched. If the identifier is still not found, then null will be returned. Implicit objects and nested properties follow a hierarchy using dot notation. For example:

   ${sessionScope.shopCart.itemCount}

evaluates as the value of the itemCount property of the session-scoped attribute shopCart.

The EL defines the following implicit objects:

NameDescription
pageContextThe pageContext object
pageScopeA Map of page-scoped attribute names to their values
requestScopeA Map of request-scoped attribute names to their values
sessionScopeA Map of session-scoped attribute names to their values
applicationScopeA Map of application-scoped attribute names to their values
paramA Map of parameter names to a single String parameter value (that is obtained by calling ServletRequest.getParameter(String))
paramValuesA Map of parameter names to a String[ ] of all values for that parameter (that is obtained by calling ServletRequest.getParameterValues(String))
headerA Map of header names to a single String header value (that is obtained by calling ServletRequest.getheader(String))
headerValuesA Map of header names to a String[ ] of all values for that parameter (that is obtained by calling ServletRequest.getHeaders(String))
cookieA Map of cookie names to a single Cookie (that is obtained by calling HttpServletRequest.getCookie(String))
initParamA Map of parameter names to a single String parameter value (that is obtained by calling ServletRequest.getInitParameter(String))

The EL treats the [ ] operator same way as the dot operator, so ${expressionA[expressionB]} is equivalent to ${expressionA.expressionB}. For example, ${param["myForm.userId"]} will evaluate as the string value of the myForm.userId request parameter.

The EL supports the usual complement of arithmetic, logical and relational operators, plus an empty prefix operator that tests whether a value is null or empty.

JSTL tags frequently collaborate and use nested sub-tags, especially for flow control. For example:

   <c:forEach var="item" items="${sessionScope.shopCart.items}">
      <c:out value="${item.name}"/><br>
   </c:forEach>

The var attribute on the iteration tag specifies the name of the scoped attribute (not a scripting variable) to be used in the nested tag, which outputs the particular item (to the current JSP writer).

Core Tag Library (c prefix)

The JSTL Core tag library comprises three functional areas:

Expression Tags

The out tag is equivalent to the JSP syntax <%= ... %>. For example:

   Summary for account number <c:out value="${myBean.account}"/>

Here myBean is a Java bean that has been exposed with the usual <jsp:useBean ... /> earlier in the page.

The set tag sets an attribute for any JSP scope, defaulting to pageScope. The value can be specified using the value attribute of the tag or by using nested tags. For example:

   <c:set var="userEmail" scope="session" value="${param.email}"/>

This sets the session-scoped attribute userEmail to the value of the request parameter email.

Attributes can be deleted with the remove tag, for example:

   <c:remove var="userEmail" scope="session" />

The catch tag is used as an alternative to a JSP error page to process exceptions.

Flow Control Tags

The if tag executes its body only if its test attribute evaluates as true. For example:

   <c:if test="{!empty param.email}" >
      <c:set var="userEmail" scope="session" value="${param.email}"/>
   </c:if>

This skips execution of the set tag if the email request parameter is null or empty.

Relational expressions are frequently used in flow control tags. For example:

   <c:if test="${myBean.qty < 1}">
      <p><b>Sorry, this item is temporarily out of stock.</b>
   </c:if>

The forEach tag iterates over a collection of objects specified by the items attribute. The current item for the iteration is specified by the var attribute. For example:

   <c:forEach var="withdrawal" items="${sessionScope.curAccount.withdrawals}">
      <tr>
         <td><c:out value="${withdrawal.date}"/></td>
         <td><c:out value="${withdrawal.amount}"/></td>
      </tr>
   </c:forEach>

JSTL can iterate over different kinds of collections, including arrays, java.util.Collection and java.util.Map. Primitive types can be included in the collection. The date and the amount output in the example above could be improved using the formatting tags described later.

As the name suggests, the forToken tag iterates in a similar fashion over tokens in a string, separated by delimiter characters specified by the delims attribute.

The choose tag provides flow control similar to the switch or if/then/else programming constructs, with nested when and otherwise tags. For example:

   <p>Usually ships within
   <c:choose>
     <c:when test="${shipLoc == 'warehouse'}" >
      24 hours
     </c:when>
     <c:when test="${shipLoc == 'depot'}" >
      1-2 days
     </c:when>
     <c:otherwise>
      1-2 weeks
     </c:otherwise>
   </c:choose>

This tests the value of the page-scoped attribute shipLoc and outputs one of three possible shipping time estimates based on the result. In a production Web application you probably would not want to have the shipping estimates hard-coded in your JSP page, since it is business logic, as was shown here for the sake of simplicity.

URL Management Tags

The import tag stores a URL-based resource reference to a scoped attribute value for later use. An example is given in the discussion of XML tags below.

The url tag works with param subtags to build up composite URLs, and to support URL re-writing when cookies are disabled. For example:

   <c:url var="detailsUrl" value="/showDetail.htm" >
      <c:param name="id" value="${curId}"/>
   </c:url>
   <a href="<c:out value='${detailsUrl}'/>">Details</a>

This dynamically constructs a link that includes a query parameter.

Database Library (sql prefix)

The JSTL Database Library provides SQL database access using the setDataSource, query, transaction and update tags.

You probably will not want to use these library tags for a production Web application since this functionality should be encapsulated through Java beans. However, these tags are handy for rapid prototyping.

Formatting and Internationalization Tag Library (fmt prefix)

The JSTL Formatting and Internationalization (I18N) tag library comprises three functional areas:

Locale and Message Formatting Tags

These tags use a resource bundle to output locale-specific information. To show an example, first assume that this is the content of the file AppDevStudioInstallPath\webAF\Projects\MyProject\webapp\WEB-INF\classes\mypkg\messages.properties:

   msg1=There was a problem with your form submission:
   msg2=The required item {0} was not entered.

Now assume that the page-scoped attribute paramName has the value city when this JSP fragment is executed:

   <fmt:bundle basename="mypkg.messages">
      <fmt:message key="msg1"/><br>
      <fmt:message key="msg2">
         <fmt:param value="${paramName}" />
      </fmt:message>
   </fmt:bundle>

This outputs the values substituted from the properties file for the message keys and parameter values. The output would be:

   There was a problem with your form submission:
   The required item city was not entered.

To support output for specific locales, other translated properties files (for example, messages_fr.properties) would be provided.

The setLocale tag can be used to override the default locale. For example:

   <fmt:setLocale value="en_US"/>

This would force the locale to US English.

Number and Date Formatting tags

The formatNumber tag formats dates in a locale-dependent manner. For example:

   The population of <c:out value="${myBean.city}" /> is
         <fmt:formatNumber value="${myBean.population}"/>

Assume that the getPopulation() method of the class for object myBean returns an int. For the locale en_US, this output would include a number with a comma separator, for example:

   The population of Raleigh is 276,093

The formatDate tag formats dates, optionally specifying a style. For example:

   <p><fmt:formatDate value="${myBean.date}" />

Assume that the getDate() method of the class for object myBean returns a java.util.Date. For the locale en_US, this output would be similar to this:

   Aug 15, 2003

XML Tag Library (xml prefix)

The JSTL XML tag library comprises three functional areas:

Core XML Tags

The first step in using the XML tags is to open and parse the desired XML document. This is accomplished with the parse tag. For example:

   <c:import url="/WEB-INF/specialItems.xml" var="xmlDoc" />
   <x:parse xml="${xmlDoc}" var="specialsDoc" scope="application" />

This locates the specialItems.xml file as a URL, parses the document, and saves the root node of the document tree object as an application-scoped attribute specialsDoc. Once this is done, other tags can be used to select nodes and attribute values from the tree.

An important difference between the XML tags and other JSTL-EL tag libraries is that the select attribute is not evaluated using the Expression Language, but as an XPath expression. The XPath expression is written with a leading dollar sign ($) but no curly brackets. For example:

   ... select="$specialsDoc/specials/apparel" ...

This would select all apparel elements under the root element, specials, in the document tree that was previously parsed.

In addition to the usual XPath scope notation, the selection syntax recognizes these prefixes:

These correspond to the EL implicit objects that were previously described.

The out and set tags are equivalent to the corresponding tags in the Core library, except for the XPath select attribute. For example:

   <x:set var="myTie" select="$specialsDoc/specials/apparel/mens/ties[@id=$param:id]"/>
   <x:out select="$myTie/mfg"/> <x:out select="$myTie/description"/>
   NOW ONLY <x:out select="$myTie@price/>!!!

The first line selects the node in the previously parsed document that has an id attribute that equals the value of the id request parameter, from the collection of all ties elements inside mens elements inside apparel elements under the specials element. It saves the node object in the page-scoped attribute myTie. The next two out tags then output the value of the specified sub-nodes of the myTie node object. The final out tag outputs the price attribute of the myTie node.

Flow Control XML Tags

The XML if, forEach and choose tags are equivalent to their counterparts in the Core library, except for the XPath select attribute. For example:

   <ul>
      <x:forEach var="bullet" select="$myTie/bullet">
         <li><x:out value="${bullet}" /></li>
      </x:forEach>
   </ul>

This outputs all the bullet sub-elements for the myTie node that was previously selected.

XML Transform Tags

The transform tag performs an XSLT transformation on a specified XML document (or on the body content of the tag if no xml attribute is specified). The result is saved in the scoped attribute specified by the result attribute, or output if this attribute is omitted from the tag. For example:

   <c:import url="/WEB-INF/convert.xslt" var="xsltDoc" />
   <x:transform xml="${xmlDoc}" xslt="${xsltDoc}" />

This performs the XSLT transformation defined in the convert.xslt file on the XML document URL specified by the previously defined scoped attribute xmlDoc. The result of the transform will be output (to the current JSP writer).

For more information, see the About the JSTL EL Example.