You are on page 1of 13

Object Description Operator Description

JSTL Quick Reference headerValues Map of request header name to a String


array of values
! (not) True if operand is false; false, otherwise.

Copyright 2003 Bill Siggelkow


cookie Map of cookie name to a Cookie object Other Operators
initParam Map of context initialization parameter Operator Description
name to a String parameter value (set in
Expressions (EL) web.xml) empty True if the operand is null, an empty String,
empty array, empty Map, or empty List; false,
otherwise.
Arithmetic Operators
In Attribute Values () Paranthesis for changing operator
• <a:tag value="${expr}"/> Operator Description precedence.
• <a:tag value="me${expr} ${expr}"/>
+ Addition
EL Functions (JSTL 1.1)
Bean Property Access - Subtraction Note: All functions treat null Strings as empty Strings.
bean.name
bean["name"] * Multiplication <%@ taglib prefix="fn"
uri="http://java.sun.com/jstl/functions" %>

Indexed Property Access / (div) Division


Usage: ${fn:function(arg0, ...)}
bean.property[index] % (mod) Remainder (modulus)

Map Property Access <p>We offer ${fn:length(flavorSet)} ice cream


flavors.</p>
bean.property["key"] Relational Operators
Operator Description
Implicit Objects (maps) Function Description

Object Description == (eq) Equality


fn:contains Returns true if substring is contained
in string; false, otherwise.
pageContext JSP Page Context object != (ne) Inequality (string, substring) :
boolean
pageScope Page-scoped variables (valid only on a < (lt) Less than
given JSP page) fn:containsIgnoreCase Returns true if substring is contained
> (gt) Greater than in string regardless of case; false,
(string, substring) : otherwise.
requestScope Request-scoped variables (valid for a given boolean
request) <= (le) Less than or equal to
fn:endsWith Returns true if string ends with the
sessionScope Session-scoped variables (valid for the >= (ge) Greater than or equal to specified suffix; false, otherwise.
user's session) (string, suffix) :
<= (le) Less than or equal to boolean
applicationScope Application-scoped variables (valid for a
given application context) fn:escapeXml Escapes characters (e.g changing “<”
to “&lt;”) that could be interpreted as
Logical Operators (string) : String XML (including HTML) markup.
param Map of request parameter name to a String Operator Description
parameter value
fn:indexOf Returns an integer representing the 0-
&& (and) True if both operands are true; false, based index within string of the first
paramValues Map of request parameter name to a String (string, substring) : int occurrence of substring. If substring is
otherwise.
array of parameter values empty, 0 is returned.
|| (or) True if either or both operands are true; false,
header Map of request header name to a header
otherwise.
String value
Function Description <c:remove var="dogAge" scope="page"/>
Core Tag Library
fn:join Joins all elements of the string array
into a single string. Separator Attribute Description Rqd Default
(string[], separator) : separates each element in the
String resulting string. If separator is an <%@ taglib prefix="c" var Name of variable to delete Yes None
empty string, the elements are joined uri="http://java.sun.com/jstl/core" %>
without a separator. scope Scope of variable No All
General-Purpose Actions scopes
fn:length If a collection or array is passed, the
size of the collection or array is
Actions for rendering data, creating and
(collection or string) : modifying scoped variables, and catching <c:catch> - traps all exceptions or errors from the
returned; If a string is passed, the
int number of characters in the string is exceptions. enclosed body.
returned.
<c:catch var="err">
<c:out> - renders data to the page <c:import value="http://java.sun.com"/>
fn:replace Replaces in inputString, every
</c:catch>
occurrence of beforeString with <h2>Welcome, <c:out value="${user.name}" <c:if test="${not empty err}">
(inputString, afterString. An empty string is
beforeSubstring, default="Guest"/></h2> Could not connect to Java web site.
returned if either inputString or </c:if>
afterSubstring) : String beforeString is empty. If afterString is
empty, all occurences of the
beforeString are removed. Attribute Description Rqd Default
Attribute Description Rqd Default
fn:split Splits string into a string array using value Data to output Yes None
var Name of variable to hold the No None
the given set of delimiter characters.
(string, delimiters) : default Fallback data to output if No Body thrown exception, if any.
The delimiter characters are not
String[] value is empty Variable will be of type
included in any returned tokens.
java.lang.Throwable.
fn:startsWith Returns true if string starts with the escapeXml true to escape special No true
specified prefix; false, otherwise. characters
(string, prefix) : Returns true if prefix is empty. Conditional Actions
boolean Actions for processing markup based on logical
conditions.
fn:substring Returns a subset of string using the
zero-based indices – inclusive of the <c:set> - saves data to a scoped variable
(string, beginIndex, begin index, but exclusive of the end <c:if> - processes the body if test is true
endIndex) : String index. <c:set var="dogAge" value="${age div 7}"/>
You are <c:out value="${dogAge}"/> in dog <c:if test="${user.age ge 40}">
fn:substringAfter Returns the subset of string following years. You are over the hill.
the given substring. </c:if>
(string, substring) :
String Attribute Description Rqd Default
Attribute Description Rqd Default
fn:substringBefore Returns the subset of string that value Data to save No Body
procedes the given substring. test Condition to evaluate Yes None
(string, substring) :
String target Name of variable to modify No None
var Name of variable to store No None
fn:toLowerCase Converts all characters of a string to property Property of target to modify No None test condition's result
lowercase.
(string) : String scope Scope of variable No page
var Name of variable to store No None
data
fn:toUpperCase Converts all characters of a string to
uppercase.
(string) : String scope Scope of variable No page
<c:choose> - multiple conditions – processes the
fn:trim Removes whitespace from both ends
body of the first enclosed when tag where the test
of a string. condition is true. If none match then the body of the
(string) : String <c:remove> - deletes a scoped variable
otherwise tag (if present) is processed.
<c:choose>
<c:when test="${a boolean expr}"> Attribute Description Rqd Default Attribute Description Rqd Default
// do something
</c:when>
varStatus Name of variable to hold the No None var Name of variable to hold No None
<c:when test="${another boolean expr}"> loop status with the following the current token. This
// do something else properties: variable has only nested
</c:when> visibility.
<c:otherwise> • index – position of the
// do this when nothing else is true current item items String of tokens to loop Yes None
</c:otherwise> over.
</c:choose> • count – number of times
through the loop (starting
with 1) delims Set of characters that Yes None
The choose tag accepts no attributes and can only separate the tokens (e.g.
contain when tag(s) and an optional otherwise tag. • first – boolean delims=”,;” will tokenize a
indicator if this is the first string separated by
iteration commas or semi-colons).
<c:when> - processes the body if test is true and no
other previous <c:when> tags evaluated to true. • last – boolean indicator
if this is the last iteration
URL Related Actions
Attribute Description Rqd Default
Actions for importing content from URLs, building
test Condition to evaluate Yes None
URLs, and redirecting.
<c:forEach> - repeats the nested body content
over a collection or for a fixed number of times. <c:import> - imports the content of a URL-based
resource. Action may include nested <c:param>
<c:otherwise> - processes the body if no other <c:forEach items="${user.languages}"
tags to specify the query string (unless the
previous <c:when> condition matched. This tag var="lang" varStatus="status">
<c:if test="${status.first}"> varReader attribute is specified).
accepts no attributes and, if present, must be the last You speak these languages:<br><ul>
tag in the <c:choose> body. </c:if> <c:import url="includes/header.jsp">
<li><c:out value="${lang}"/></li> <c:param name="title">Hello World</c:param>
Iterator Actions <c:if test="${status.last}"></ul></c:if> </c:import>
Actions that loop over collections, for a fixed number </c:forEach>
of times, or over a set of string tokens. These
actions share the following attributes for iterating over Attribute Description Rqd Default
Attribute Description Rqd Default
a subset of elements.
url URL of the resource to Yes None
var Name of variable to hold No None import.
Attribute Description Rqd Default the current item. This
variable has only nested
visibility. context Name of the context No Current
begin Zero-based index of first item No 0 (beginning with a /) of some context
to process, inclusive. other local web application to
items Collection, iterator, map, or No None import the resource from.
array to loop over.
end Zero-based index of last item No Last item
to process, inclusive. var Name of the variable to hold No None
the imported content as a
step Process every stepth element No 1 <c:forTokens> - repeats the nested body String.
(e.g 2 = every second content for each token of a delimited string.
element). scope Scope of the var variable No page
<c:set var="users">Fred,Joe,Mary<c:set>
<c:forTokens var="name" items="${users}" varReader Name of the variable to hold No None
delims=","> the imported content as a
<c:out value="${name}"/><br/> Reader. This variable has
</c:forTokens> only nested visibility so that
the reader will always be
closed.
Attribute Description Rqd Default
<c:url> - builds a URL with the proper rewriting rules <c:redirect> - sends the client a response to
applied (only relative URLs are rewritten). Action redirect to the specified URL. This action will
abort processing of the current page. Action may
Formatting Tag Library
may include nested <c:param> tags to specify
the query string. include nested <c:param> tags to specify the
query string. <%@ taglib prefix="fmt"
<c:url="editProfile.do" var="profileLnk">
uri="http://java.sun.com/jstl/fmt" %>
<c:param name="id" value="${user.id}"/> <c:if test="${empty user}">
</c:url> <c:redirect url="login.do"/>
<a href='<c:out value="${profileLnk}"/>'> </c:if> Internationalization (I18N) Actions
Edit Profile
</a>
Actions that establish localization (l10n) contexts,
specify resource bundles, and format messages.
Attribute Description Rqd Default

Attribute Description Rqd Default url URL of the resource to Yes None
<fmt:setLocale> - Sets the default locale for the
redirect to. specified scope. This will override the browser-
value URL to be processed. Yes None based locale.
context Name of the context No Current
context Name of the context No Current (beginning with a /) of some context <fmt:setLocale scope="session"
(beginning with a /) of some context other local web application. value="fr_CA">
other local web application.

var Name of the variable to hold No None Attribute Description Rqd Default
the URL as a String. <c:param> - adds request parameters to a URL.
This action can only be nested within value String representation of a Yes None
scope Scope of the var variable No page <c:import>, <c:url>, or locale (e.g. en_US) or an
actual java.util.Locale object.
<c:redirect>.
variant Locale variant (as a String) to No None
Attribute Description Rqd Default specify in conjunction with the
locale (language and country).
name Name of the query string Yes None
parameter. scope Scope to set the default locale No page
for.
value Value of the parameter. If not No Body
specified, value is taken from
the tag body.
<fmt:bundle> - Sets the localization context, based
on the specified resource bundle, to be used within
the body content of this tag.
<fmt:bundle basename="resources"
prefix="label.">
<fmt:message key="userId"/>
<fmt:bundle>

Attribute Description Rqd Default

basename Fully-qualified name of the Yes None


base bundle without a file type
(such as “.properties”).

prefix String prefix to be prepended No None


to the value of the message
key. Note that the prefix
must include all characters –
a separator character (e.g. “.”)
is not assumed.
<fmt:message key="fieldRequired">
<fmt:setBundle> - Creates and stores in a scoped <fmt:param value="User ID"/>
</fmt:message> <fmt:setTimeZone> - Sets the specified time zone
variable, a localization context based on the specified
in a named scoped variable or using the default time
resource bundle.
zone name if var is not specified.
<fmt:setBundle Attribute Description Rqd Default
basename="ApplicationResources” <fmt:setTimeZone var="mtnTime"
var="strutsMessages" value="America/Denver"/>
value Value used for parametric No Body Mountain Time: <fmt:formatDate
scope="application"/>
message format substitution. type="time" timeStyle="short"
value="${now}" timeZone="${mtnTime}"/>
Attribute Description Rqd Default

basename Fully-qualified name of the Yes None <fmt:requestEncoding> - Instructs JSTL to use
Attribute Description Rq Default
base bundle without a file type a specific character encoding (see d
(such as “.properties”). http://www.iana.org/assignments/character-sets)
to decode request parameters. Omitting a value value String representation of a time Yes None
var Name of the variable to hold No Default indicates to use automatic detection of the proper zone (such as
the localization context. l10n
context
encoding. “America/New_York”, “GMT-
5”, or “EST”) or an actual
(see java.util.TimeZone object.
“Configu <fmt:requestEncoding key="ISO-8859-1"/>
ration”)
var Name of the variable to store No Default
Attribute Description Rqd Default the time zone. time zone
scope Scope of the var variable No page (see
“Configur
value Character encoding (e.g. “UTF- No Automatic ation”)
8”) to use.
<fmt:message> - Looks up a localized message in a
resource bundle. This tag can contain nested scope Scope of the var variable No page
<fmt:param> tags to specify message format Formatting Actions
substitution values. The resultant message is printed Actions that format and parse numbers,
or stored in a scoped variable. currencies, percentages, dates and times. <fmt:formatNumber> - Formats a number,
<fmt:message key="title"
currency, or percentage in a locale-sensitive manner.
bundle="${strutsResources}"/> <fmt:timeZone> - Sets the specified time zone The formatted value is printed or stored in a scoped
to be applied to the nested body content. The variable.
following example demonstrates that the time
Attribute Description Rqd Default <fmt:formatNumber type="currency"
zone by this action has only nested visibility. value="3.977">
key Message key to be looked up. No Body <jsp:useBean id="now"
class="java.util.Date"/>
<fmt:timeZone Attribute Description Rqd Default
bundle Localization context (set by prio No Default
configuration, <fmt:bundle>, or l10n value="America/Los_Angeles">
<fmt:setBundle>, which specifies context Pacific Time:<fmt:formatDate value Numeric value to No Body
the resource bundle the message type="time" timeStyle="short" format.
key is to be looked up in. value="${now}"/>
</fmt:timeZone>
type Specifies the type of No number
<br/>
var Variable to hold the message. No Local Time:<fmt:formatDate type="time" value. Valid values are:
timeStyle="short" value="${now}"/>
• number
scope Scope of the var variable. No page
• currency
Attribute Description Rqd Default • percentage

<fmt:param> - Supplies a parameter for message pattern Custom formatting No None


value String representation of a time Yes None pattern (overrides other
format substitution in a containing <fmt:message> formatting options
zone (such as
tag. Parameters are substituted in sequential order. “America/New_York”, “GMT-5”, including type – see
or “EST”) or an actual java.text.DecimalFormat
java.util.TimeZone object. )
Attribute Description Rqd Default Attribute Description Rqd Default Attribute Description Rqd Default

currencyCode Currency code (ISO No Based value Value to parse. No Body timeStyle Predefined formatting style for a No default
4217) used for on time (ignored if type=”date”) -- see
formatting currencies. default type Specifies the type of No number java.text.DateFormat.
Such as “USD” (US locale value. Valid values are:
dollars) or “EUR” (euro). Valid values are:
• number • default (2:51:16 PM)
currencySymbol Currency symbol used No Based • currency • short (2:51 PM)
when formatting on • percentage • medium (2:51:16 PM)
currencies. Such as default • long (2:51:16 PM EDT)
“$” for US dollars, or “F” locale pattern Custom parsing pattern No None
for Francs. (overrides type – see • full (2:51:16 PM EDT)
java.text.DecimalFormat) pattern Custom formatting style (overrides No None
groupingUsed Specifies if grouping No true type, dateStyle, and
separators will be used parseLocale String representation of a No Default timeStyle) – see
(for example – locale (e.g. en_US) or an locale java.text.SimpleDateFormat.
formatting “23890” as actual java.util.Locale
“23,890”). object used for parsing. timeZone String representation of a time No Default
zone or an actual time
maxIntegerDigits Maximum number of No None integerOnly Specifies if only the No false java.util.TimeZone object. zone
digits to print in the integer portion of the
integer part of the value should be parsed.
number.
var Variable to store the No None <fmt:formatDate> - Formats a date and/or time in a
minIntegerDigits Minimum number of No None formatted number. locale-sensitive manner. The formatted value is
digits to print in the
integer part of the
printed or stored in a scoped variable.
scope Scope of the var variable No page
number.
<fmt:formatDate value="${now}"
pattern="yy-MMM-dd"/>
maxFractionDigit Maximum number of No None
s digits to print in the Formatting Dates
fractional part of the
Attribute Description Rqd Default
number. Dates are formatted and parsed using the
<fmt:formatDate> and <fmt:parseDate>
minFractionDigit Minimum number of No None value Date value to format. Value No None
actions which share the following common must be a java.util.Date
s digits to print in the
fractional part of the attributes. object.
number.
Attribute Description Rqd Default var Variable to store the No None
var Variable to store the No None formatted number.
formatted number. type Specifies the type of value. Valid No date
values are: scope Scope of the var variable No page
scope Scope of the var No page
• time (time only)
variable
• date (date only)
• both (date and time) <fmt:parseDate> - Parses a string representing a
dateStyle Predefined formatting style for a No default date and/or time in a locale-sensitive manner. The
<fmt:parseNumber> - Parses a String representing date (ignored if type=”time”) -- see parsed value is printed or stored in a scoped
a number, currency, or percentage in a locale- java.text.DateFormat. variable.
sensitive manner. The parsed value is printed or Valid values are:
stored in a scoped variable. • default (Jul 19, 2003)
<fmt:parseDate var="bday"
pattern="MM/dd/yy"
<fmt:parseNumber var="num" type="number"
• short (7/19/03) value="05/10/63"/>
pattern="#,###" value="2,447"/> • medium (Jul 19, 2003) <fmt:formatDate value="${bday}"
<c:out value="${num}"/> • long (July 19, 2003) dateStyle="full"/>
• full (Saturday, July 19,
2003)
Attribute Description Rqd Default Attribute Description Rqd Default
SQL Tag Library
value Date/time string to parse. No None scope Scope of the variable var. No page

parseLocale String representation of a No Default


<%@ taglib prefix="sql"
locale (e.g. en_US) or an locale
uri="http://java.sun.com/jstl/sql" %>
actual java.util.Locale object <sql:update> - Performs a database insert, update,
used for parsing. delete or other statement (such as a DDL statement)
The SQL tag library provides actions to perform that does not return any results. This action may
var Variable to store the parsed No None transactional database queries and updates and include body content containing the actual update
value as a java.util.Date. easily access query results. string as well as <sql:param> tags for parameter
scope Scope of the var variable No page substitution. Like <sql:query>, the <sql:param>
<sql:query> - Performs a database query (e.g. tags must occur after the sql statement if it is
select statement). The query should be expected contained in the <sql:update> tag body.
to return a ResultSet. This action may include
body content containing the actual query string as <sql:update var="updateCount">
well as <sql:param> and <sql:dateParam> UPDATE users SET first_name="William" WHERE
tags for parameter substitution. If the body first_name = "Bill"
contains the SQL query, it must appear before </sql:update>
<c:out value="${updateCount} rows updated."/>
any nested parameter tags.
<sql:query var="users">
Attribute Description Rqd Default
SELECT * FROM users WHERE
last_name = "Burdell"
</sql:query> sql SQL statement to execute. No Body
<c:forEach var="user"items="${users.rows}">
<c:out value="${users.user_name}"/><br/> dataSource Database connection to use. No Default
</c:forEach> A javax.sql.DataSource data
object, or a String source
representing a JNDI resource
Attribute Description Rqd Default or the parameters for
java.sql.DriverManager. If
sql SQL query to execute. No Body specified, this action cannot
be nested in
<sql:transaction>.
dataSource Database connection to use. A No Default
javax.sql.DataSource object, or a data
String representing a JNDI var Name of the variable to store No None
source
resource or the parameters for the query results as a
java.sql.DriverManager. If java.lang.Integer object (e.g.
specified, this action cannot be SQL update statements return
nested in <sql:transaction>. the number of rows affected).

maxRows Maximum number of rows to No Default scope Scope of the variable var. No page
return in the result. If not maxRows
specified or set to -1, no limit is (see
enforced. “Configur
ation”) <sql:transaction> - Establishes a database
transaction for <sql:query> and <sql:update>
startRow Returned results include rows No 0 tags contained in this tag's body. That is, all SQL
starting at this index. The first actions contained in the body of this tag will be
row is row 0.
treated as a single atomic transaction. The
var Name of the variable to store the Yes None
transaction will be committed only if all statements
query results. Returned rows are succeed. If any of the contained SQL actions cause
accessible via the rows property an exception, the transaction will be rolled back.
of this object.
Note: this action will reinstate the prior “auto commit”
setting after completion.
<sql:transaction> Attribute Description Rqd Default Attribute Description Rqd Default
<sql:update sql="DELETE users WHERE
user_name='bsiggelkow'"/> user Database user's username No None value Value of the parameter. Yes None
<sql:update sql="INSERT INTO users Must be a java.util.Date
VALUES ('billsigg','Bill','Siggy')"/> object.
</sql:transaction> password Database user's password No None

var Name of the variable to No Default type Indicates how the database No timestamp
hold the data source. data should interpret the value.
Attribute Description Rqd Default
source Valid values are:
name
dataSource Database connection to No Default (see
• date
use. A data “Configur • time
javax.sql.DataSource source ation”) • timestamp
object, or a String (see
representing a JNDI “Configu
resource or the parameters ration”) scope Scope of the variable var. No page
for java.sql.DriverManager.
<sql:param> - Substitutes parameters into SQL
isolation Transaction isolation level. No Databas prepared statement placeholders (“?”). This
Valid values are:
e 's action can only be nested within
default
• read_committed <sql:query> or <sql:update> tags.
• read_uncommitted If the enclosing tag specifies the SQL in the body,
• repeatable_read any <sql:param> tags must appear after the SQL.
• serializable Parameters are substituted in sequential order.
<c:set var="firstName">Bill</c:set>
<sql:query var="users">
<sql:setDataSource> - Creates and stores in a SELECT user_name, last_name
scoped variable an SQL data source. This tag FROM users WHERE first_name = ?
cannot have a body. Either the dataSource or url <sql:param value="${firstName}"/>
</sql:query>
attribute must be specified.
<sql:setDataSource var="testDB"
Attribute Description Rqd Default
url="jdbc:mysql://localhost/test,
com.mysql.jdbc.Driver"/>
<sql:query var="users" value Value of the parameter. If not No Body
dataSource="${testDB}"> specified, value is taken from
SELECT * FROM users the tag body.
</sql:query>

<sql:dateParam> - Substitutes time, date, or


Attribute Description Rqd Default timestamp parameters into SQL prepared
statement placeholders. This action can only be
dataSource Database connection to No None
use or create. A nested within <sql:query> or
javax.sql.DataSource <sql:update> tags. Parameters are
object, or a String
representing a JNDI
substituted in sequential order.
resource or the parameters
for <fmt:parseDate var="ww2End"
java.sql.DriverManager. pattern="yyyy-MM-dd"
value="1945-09-02"/>
<sql:query var="postWarBabies">
driver Name of the JDBC driver No None SELECT user_name FROM user_profile
class. WHERE birth_date > ?
<sql:dateParam value="${ww2End}"
url URL for the JDBC No None type="date"/>
database connection. </sql:query>
scope="page"/>
Function Description
XML Tag Library <%-- Find the user with matching ID --%>
<x:set var="user" contains Returns true if string1 contains string2;
select="$doc//users/user[@id=$pageScope:user false, otherwise. Non-string arguments are
Id]"/> (string1, string2): converted to strings as if by the string()
<%@ taglib prefix="x" function.
<%-- Say Hi to the user --%> boolean
uri="http://java.sun.com/jstl/xml" %>
Hi <x:out select="$user/first-name"/> !
count Returns the number of nodes in the node
The XML tag library supports parsing of XML set.
documents, selection of XML fragments, conditional XPath Abbreviated Syntax (node-set):
and iterative processing based on XML content, and number
Abbr. XPath Axis Example
XSLT transformations.
// descendant $doc//first-name floor Returns the greatest integer less than or
A common pattern for using the XML tags is as (number or
equal to number or object (as converted as
follows: if by the number() function).
. self $doc/users/user/. object):
1. Use <x:parse> to parse XML into a scoped
number
variable. The XML can come from the body .. parent $doc//[first-
literally, from the body via <c:import>, or from the name='George']/../last-
last(): Returns the number of nodes in the context
name
value attribute which may refer to any XML node.
source. number
@ attribute $doc//user[@id="997"]/firs
<x:parse var="varName" ...> t-name
local-name Returns the part of the element name after
the colon (:) when namespaces are used. If
2. Use the scoped variable from <x:parse> to specify child $doc/users/user[last- (node-set): node set is not specified the function is
the XML document to use in XPath expressions. (blank)
name='Burdell']
string applied to the context node.
<x:out select="$varName/XPath
expression"/> * (matches any $doc//*[local- name Returns the qualified element name, that is,
namespace) name()='users']/user prefix:local-name, when namespaces are
(node-set):
Using JSTL Data as XPath Variables used. If node set is not specified the
Scoped variables can be used in XPath expressions string function is applied to the context node.
($implicitObject:variableName) similar to how they
Useful XPath Functions namespace-uri Returns the uri of the namespace of the
are used in EL (${implicitObject.variableName}). If
Following are some useful XPath functions that given node set. If node set is not specified
the implicit object is omitted, scopes will be searched (node-set):
can be used in XPath expressions. This list does the function is applied to the context node.
in standard order. Note that the “.” and “[]” not include all XPath functions – just those string
notations cannot be used for accessing bean deemed particularly useful when using the JSTL
properties. XML tags. not Returns the logical inversion of the supplied
argument. That is, if the argument is true,
(boolean or
The following example demonstrates the above object):
false is returned; if argument is false, true is
techniques. Function Description returned.
boolean
ceiling Returns the smallest integer greater than or
<%-- Create the XML --%> equal to number or object (as converted as
<x:parse var="doc"> (number or number Converts object (or the current node if
if by the number() function). object is not specifed) to a number. True is
<users> object): (object):
<user id="997"> converted to 1, and false to 0. If the number
<first-name>George</first-name> number number cannot be converted NaN is returned.
<last-name>Burdell</last-name>
</user> concat Concatenates the arguments in order from
<user id="998"> position(): Returns the position of the current node in
left to right. Non-string arguments are the current context node set. The first
<first-name>Joseph</first-name> (string1, string 2, converted to strings as if by the string() number
<last-name>Blough</last-name> ...): position is 1.
function.
</user>
</users> string
</x:parse>

<%-- Define a variable holding user ID --%>


<c:set var="userId" value="${user.id}"
Function Description <title>feed title</title> expression as a string.
<link>source url</link>
<description>feed desc</description> RSS Channel:
round Returns the closest integer to number or <x:out select="$news//channel/title"/>
<item>
object (as converted as if by the number()
(number or <title>article title</title>
function). If two integers are equally close,
object): <link>article url</link>
the value closer to positive infinity is
<description>article
number chosen. (e.g. round(3.5) returns 4, round(- Attribute Description Rqd Default
desc</description>
3.5) returns -3).
</item>
<item> select XPath expression. Yes None
starts-with Returns true if string1 starts with string2; <title>article title</title>
false, otherwise. <link>article url</link>
(string1,string2): escapeXml true to escape special No true
<description>article
boolean desc</description> characters
</item>
</channel>
string Converts the object, or the current node if </rss>
object is not specifed, to a string.
(object): Generally, this function will output the body <x:set> - Saves the result of the select XPath
string of the elements (e.g. string(<a>b</a>) <x:parse> - Parses XML content, provided by the expression to a scoped variable. Returned value
returns “b”). may be a node set (XML fragment), boolean, string,
value attribute or the tags body, into a scoped
variable(s). This variable can then be used for or number.
string-length Number of characters in the string. If object
is not a string it is first converted to a string subsequent processing by other XML tags.
(object): <x:set select="$news//channel/item"
as if by the string() function. var="newsItems"/>
<c:import var="rss"
number url="http://servlet.java.sun.com/syndication
/rss_java_highlights-PARTNER-20.xml"/>
substring Returns a substring of string starting at <x:parse var="news" xml="${rss}"/>
index and continuing for length characters. Attribute Description Rqd Default
(string, index, The first character is position 1, not
length): position 0 as in Java and JavaScript. select XPath expression. No None
string Attribute Description Rqd Default
var Name of variable to store No None
substring-after Returns the substring in string1 following the doc (JSTL 1.1) Text of the document No Body results. The variable type is
first of occurrence of string2 in string1. to a parse as a String or Reader. equal to whatever is returned
(string1, string2): by the select expression.
string xml (JSTL 1.0 – deprecated in 1.1) No Body
Same as doc attribute. • Boolean –
substring-before Returns the substring in string1 preceding java.lang.Boolean
the first of occurrence of string2 in string1. systemId URI of the original document, No None
(string1, string2): • Number –
string used for entity resolution. java.lang.Number

filter XML filter to apply. Value should No None • Node or node set –
sum Converts each node in the set to a number,
be of type org.xml.sax.XMLFilter. implementation-
as if by the number() function, adds up the
(node-set): dependent type
numbers and returns the sum.
number var Name of the variable to store the Yes None
results – may be an scope Scope of variable var. No page
implementation-specific object.

General XML Actions scope Scope of the variable var. No page Flow Control Actions
Actions for parsing XML, outputting to the page, and
varDom Name of the variable to store the Yes None Actions for processing markup based on logical and
selecting XML fragments. The examples that follow result – stored as a DOM object. iterative conditions.
demonstrate use of the XML tags for processing Rich
Site Summary (RSS) feeds. RSS has more or less scopeDom Scope to store variable varDOM No page
the following format: in.
<x:if> - Processes the body if select XPath evaluates
to true (following the rules of the boolean() XPath
<?xml version="1.0"?> function).
<rss version="0.91">
<channel> <x:out> - Prints the result of the XPath <x:if select=
"$news//item[contains(description,'Linux')]"> <x:choose> -- Processes the body of the first Attribute Description Rqd Default
Linux is in the news today! enclosed <x:when> tag where the select XPath
</x:if>
expression evaluates to true. If none match then var Name of variable to hold No None
the body of the <x:otherwise> tag (if present) the current item. This
variable has only nested
Attribute Description Rqd Default is processed. visibility.

select Test condition as an XPath Yes None <x:choose>


<x:when select="$news//item"> Transformation Actions
expression. Body content is
processed if the condition is We've got news :)
</x:when> JSTL provides an <x:transform> tag for
true.
<x:otherwise> performing XSLT transformations. The <x:param>
var Name of variable to store test No None
No news today :( tag can be nested in the <x:transform> tag to set
</x:otherwise>
condition's result </x:choose> a parameter that is used in the stylesheet.

scope Scope of variable No page


<x:transform> - Conducts an XSLT transformation
The choose tag accepts no attributes and can on source XML. The source XML is provided by the
only contain <x:when> tag(s) and an optional doc attribute or the body of the tag. The XSL
<x:otherwise> tag. stylesheet is specified by the xslt attribute. While in
most cases, the stylesheet will be set up by back-end
<x:when> - Represents an alternative in an code – it is possible to define the stylesheet inline
<x:choose> tag. Processes the body if the and make it available with <c:set> as in the
select expression evaluates to true and no other following example:
previous <x:when> tags in the <x:choose>
matched.
<c:set var="xsl">
<?xml version="1.0" encoding="UTF-8"?>
Attribute Description Rqd Default <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform
select Test condition as an XPath Yes None ">
expression. <xsl:template match="item">
<li>
<xsl:value-of select="title"/>
</li>
</xsl:template>
<x:otherwise> - Processes the body if no other <xsl:template match="/">
previous <x:when> condition in the <ol>
<x:choose> matched. This tag accepts no <xsl:apply-templates
select="//item"/>
attributes and, if present, must be the last tag in </ol>
<x:choose> body. </xsl:template>
</xsl:stylesheet>
<x:forEach> - Repeats the nested body content </c:set>
over a node set determined by an XPath <x:transform xml="${news}"
expression, setting the context node to each xslt="${xsl}"/>
element in the iteration.
<x:forEach select="$news//item"> Attribute Description Rqd Default
<a href='<x:out select="link"/>'>
<x:out select="title"/></a><br/>
</x:forEach> doc (JSTL 1.1) Source XML No Body
document for the
transformation. Value can
be a String, Reader,
Attribute Description Rqd Default javax.xml.transform.Source
, org.w3c.dom.Document,
select Name of variable to hold No None or any value exported
the current item. This <x:parse> or <x:set>. If the
variable has only nested value comes from <x:set> it
visibility. cannot be a partial
document.
Attribute Description Rqd Default Attribute Description Rqd Default
JSTL Configuration
xml (JSTL 1.0 – deprecated in No Body name Name of the parameter as a Yes None
1.1) Same as doc attribute. String. This name must
match the name in the
docSystemId (JSTL 1.1) URI of the No None corresponding <xsl:param> JSTL can utilize configuration parameters for setting
source XML to used to XSLT tag. such things as a default application resource bundle,
resolve entity references. time zone, and data source. These values can be
value Value of the parameter. If not No Body established using (1) setVariable-like tags (e.g.
xmlSystemId (JSTL 1.0 – deprecated in No None specified, value is taken from
the tag body. <fmt:setLocale>, <sql:setDataSource>), (2)
1.1) Same as
docSystemId.
programmatically using the JSTL Config API or by (3)
the web container itself via context initialization
xslt XSLT stylesheet to use. Yes None parameters set in the application's web.xml file.
The value must be a String,
Reader or an 1. Set by a JSTL action – this allows specification
javax.xml.transform.Source
object.
of scope by the scope attribute.

xsltSystemId URI of the stylesheet to No None <fmt:setLocale value="en_US" scope="session"/>


use to resolve entity
references.
2. Set Programmatically – allows specification of
var Variable to hold the result No Non e scope via the Config API.
as a
org.w3c.doc.Document import javax.servlet.jst.jstl.core.Config;
object. ...
Config.set( session,
scope Scope of the variable var. Config.FMT_LOCALE,
new java.util.Locale(“en_US") );
result javax.xml.transform.Result No None
object that holds or
processes the transformed
3. Set by Context Initialization Parameters –
XML. specifies value used if setting not found in any of
the standard scopes.

<web-app>
<x:param> - Sets a transformation parameter that ...
will be passed to stylesheet which declares
parameters using the <xsl:param> tag. The <context-param>
<param-name>
<x:param> tag can only be nested within an javax.servlet.jsp.jstl.fmt.locale
<x:transform> tag. Any <x:param> tags must </param-name>
come after the XML body content of the <param-value>
en_US
<x:transform> tag, if present. </param-value>
</context-param>
...
<x:transform xml="${news}"
</web-app>
xslt="${searchXsl}"/>
<x:param name="searchParam">
Web Services
</x:param>
</x:transform>

Attribute Description Rqd Default


Locale Variable Name javax.servlet.jsp.jstl.fmt.timeZone Data Source
Specifies the default locale to be used by the Specifies the data source to be accessed by the SQL
formatting tags. This variable sets an application- Java Constant Config.FMT_TIMEZONE tags. The value can be specified as a
based locale and has priority over any browser-based javax.sql.DataSource object, as a string representing
locales. Type String (e.g. “America/Los_Angeles”) or a JNDI relatove path (e.g. “jdbc/myDatabase” if the
Variable Name javax.servlet.jsp.jstl.fmt.locale
java.uti.TimeZone absolute JNDI name is
“java:comp/env/jdbc/myDatabase”), or a JDBC
Set by <fmt:setTimeZone>, Config API, web.xml parameters string (“url, driver, user, password”) (e.g.
Java Constant Config.FMT_LOCALE
“jdbc:mysql://localhost/,com.mysql.Driver”).
Type String (e.g. en_US) or java.util.Locale Variable Name javax.servlet.jsp.jstl.sql.dataSource

Set by <fmt:setLocale>, Config API, web.xml Java Constant Config.SQL_DATA_SOURCE

Type String (JNDI relative path or JDBC


Fallback Locale parameters string) or
Specifies the default locale to be used for finding javax.sql.DataSource
resource bundle messages. This locale will be used
if a message cannot be found using any of the Set by <fmt:setDataSource>, Config API,
web.xml
preferred locales.
Variable Name javax.servlet.jsp.jstl.fmt.fallbackLocale
Max Rows
Java Constant Config.FMT_FALLBACK_LOCALE Sets the maximum number of rows that can be
returned by any <sql:query> tag. A value of -1
Type String (e.g. en_US) or java.util.Locale indicates no limit.
Set by Config API, web.xml Variable Name javax.servlet.jsp.jstl.sql.maxRows

Java Constant Config.SQL_MAX_ROWS


I18n Localization Context
Type Integer
Specifies the default resource bundle to use for
localized messages. If a String is used (e.g. via the Config API, web.xml
Set by
<fmt:setBundle> tag or a context-initialization
parameter), the value refers to the name of the
resource bundle (including any package name but
excluding .properties or .class).
Variable Name javax.servlet.jsp.jstl.fmt.localizationConte
xt

Java Constant Config.FMT_LOCALIZATION_CONTEXT

Type String (e.g.


resources.ApplicationResources) or
javax.servlet.jsp.jstl.fmt.LocalizationConte
xt

Set by <fmt:setBundle>, Config API, web.xml

Time Zone
Specifies the default time zone to be used by the
formatting tags.
Variable Name javax.servlet.jsp.jstl.fmt.timeZone

You might also like