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
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-EL | New Expression Language | <c:forEach var="item" items="${sessionScope.cart.items}" > |
JSTL-RT | Page'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 support | catch |
Flow control | choose |
|
URL management | import |
|
Database http://java.sun.com/jstl/sql sql | SQL | query |
Formatting and Internationalization http://java.sun.com/jstl/fmt fmt | Locale | setLocale |
Message formatting | bundle |
|
Number and date format | formatDate |
|
XML http://java.sun.com/jstl/xml x | Core | out |
Flow control | choose |
|
Transform | transform |
In webAF, if you choose to include the JSTL tag libraries (either by using the New Project Wizard or by selecting File Web Application Properties) then the checked tag libraries will automatically be included in any new JSP files you add to the project. For example:
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.
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:
Name | Description |
---|---|
pageContext | The pageContext object |
pageScope | A Map of page-scoped attribute names to their values |
requestScope | A Map of request-scoped attribute names to their values |
sessionScope | A Map of session-scoped attribute names to their values |
applicationScope | A Map of application-scoped attribute names to their values |
param | A Map of parameter names to a single String parameter value (that is obtained by calling ServletRequest.getParameter(String)) |
paramValues | A Map of parameter names to a String[ ] of all values for that parameter (that is obtained by calling ServletRequest.getParameterValues(String)) |
header | A Map of header names to a single String header value (that is obtained by calling ServletRequest.getheader(String)) |
headerValues | A Map of header names to a String[ ] of all values for that parameter (that is obtained by calling ServletRequest.getHeaders(String)) |
cookie | A Map of cookie names to a single Cookie (that is obtained by calling HttpServletRequest.getCookie(String)) |
initParam | A 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).
The JSTL Core tag library comprises three functional areas:
out, set, remove, catch
)if, forEach, forTokens, choose
)import, url
)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.
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.
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.
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.
The JSTL Formatting and Internationalization (I18N) tag library comprises three functional areas:
setLocale
)bundle, message, setBundle
)formatDate, formatNumber, parseDate, parseNumber,
setTimeZone, timeZone
)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.
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
The JSTL XML tag library comprises three functional areas:
out, parse, set
)choose, if, forEach
)transform
)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:
pageScope:
requestScope:
sessionScope:
applicationScope:
param:
header:
cookie:
initParam:
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.
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.
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.