Java Standard Template Language
CONTENTS
Using JSTL tags
Philosophy
Core tags
c:out
c:set
c:remove
c:catch
c:if
c:choose
c:forEach
c:forTokens
c:url
c:import
c:redirect

Using JSTL tags

There are four JSTL taglibs: core, xml, internationalization and sql. In order to be used in a JSP page, they need to be declared in the page, and possibly in web.xml.
If the absolute URI's are used, you can just reference them in the JSP page. Here are the relevant declarations to place in the JSP page:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="xml" uri="http://java.sun.com/jsp/jstl/xml" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
Alternatively, you can define logical names for the taglibs in web.xml, and reference the logical names in the JSP page. Here's the page:
<%@ taglib prefix="c" uri="/jstl-core" %> <%@ taglib prefix="xml" uri="/jstl-xml" %> <%@ taglib prefix="fmt" uri="/jstl-fmt" %> <%@ taglib prefix="sql" uri="/jstl-sql" %>
and the relevant section of web.xml:
<taglib> <taglib-uri>/jstl-core</taglib-uri> <taglib-location>/WEB-INF/c.tld</taglib-location> </taglib> <taglib> <taglib-uri>/jstl-xml</taglib-uri> <taglib-location>/WEB-INF/xml.tld</taglib-location> </taglib> <taglib> <taglib-uri>/jstl-fmt</taglib-uri> <taglib-location>/WEB-INF/fmt.tld</taglib-location> </taglib> <taglib> <taglib-uri>/jstl-sql</taglib-uri> <taglib-location>/WEB-INF/sql.tld</taglib-location> </taglib>
The jar files containing the tag implementations must also be made available. The JSTL tags are implemented in two jar files: standard.jar and jstl.jar, and these should be placed in the WEB-INF/lib directory.
In addition, there are the JSTL functions, which are declared in the JSP page thusly:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
to top

Philosophy

The JSTL eschews the use of scripting variables. Instead, it deals mainly with attributes on one of the various scoped objects. These are known as 'scoped' variables. In this way, the JSTL tags work well with EL expressions, which implicitly have access to these scoped variables.
The JSTL convention is to use the attribute name "var" to name variables which are exported into the the JSP environment as scoped variables.
Nearly all of the attributes of the JSTL tags accept run-time expressions. The exceptions are those attributes which define the name and scope of exported variables, and the select attribute of certain XML tags, which represents an XPath expression.
to top

Core tags

c:out

Writes a value to the current JspWriter. The standard usage is to provide a 'value' attribute, which is evaluated and written. The value can be a scripting variable or an EL expression. Example:
<c:out value="${firstname}"/>
In fact, the following would appear to all be equivalent, supposing that an object of class DataForm, with a method getInfo() had been stored on the request object using the name 'data':
<!-- the direct method --> <%= ((DataForm) request.getAttribute("info")).getUser() %> <!-- via a scripting variable and a JSP expression --> <jsp:useBean id="data" class="net.alethis.web.form.DataForm" scope="request"/> <%= data.getInfo() %> <!-- via a scripting variable and an EL expression --> <jsp:useBean id="data" class="net.alethis.web.form.DataForm" scope="request"/> ${data.info} <!-- using JSTL and an EL expression --> <c:out value="${data.info}"/> <!-- using JSTL --> <!-- using JSTL and a JSP expression --> <c:out value="<%= data.getInfo() %>"/> <!-- using JSTL --> <!-- using Struts --> <bean:write name="info" property="user"/>
The value to write can include template text:
<c:out value="The id of product ${product} is ${productId}"/>
Formal definition:
<c:out value="value" [default="default value"] [escapeXml="true|false"]/> <c:out value="value" [escapeXml="true|false"]>default value</c:out>
Name Description Notes
value The value to write; can include static text, EL expressions and JSP expressions Required
default The default value to write, in case the value evaluates to null. The default value can also be specified via the tag body. Optional
escapeXml A boolean ('true'/'false') which controls whether XML special characters are escaped (e.g. > becomes &gt; on output). Optional; default is 'true'.
BODY CONTENT Alternative mechanism for supplying a default value. Optional; only one of the 'default' attribute and tag body may be supplied.
If the value is null, and no default is supplied, the empty string is written.

c:set

Assigns a value to an attribute, creating it if it didn't exist previously. The value can be specified via the 'value' attribute, or in the body of the tag. Note that this does not create a scripting variable, but that once the attribute has been created, <jsp:useBean> can be used to create a scripting variable. For example, this creates an attribute from a parameter:
<c:set var="productId" value="${param.product}"/>
The possible attributes are:
Formal definition:
<c:set var="varname" value="value" [scope="page|request|session|application"]/> <c:set var="varname" [scope="page|request|session|application"]>value</c:set> <c:set target="target" value="value" property="propertyName"/> <c:set target="target" property="propertyName">value</c:set>
Name Description Notes
var The name of the attribute to set or create. Either the var or the target attribute must be supplied.
scope The scope in which to find for or create the variable. Optional; the default is 'page'.
target The name of a scripting variable; must be a JavaBean or a java.util.Map. Either the var or the target attribute must be supplied.
property The name of the JavaBean property, or the key into the Map. Required if target is specified.
value The value to assign. If not specified, then the value is taken from the tag's body.
BODY CONTENT Alternative mechanism for supplying a value. Only one of the 'value' attribute and tag body may be supplied.

c:remove

This tag removes a scripting variable:
<c:remove var="productId"/>
Formal definition:
<c:remove var="varName" [scope="page|request|session|application"]/>
Name Description Notes
var The name of the attribute to remove. Required.
scope The scope from which to remove the variable. Optional; if not supplied, it will be removed from all scopes.

c:catch

This tag catches a Throwable thrown by a nested tag:
<c:catch var="exception"/> ... nested stuff ... </c:catch> <c:if test="${exception != null}"> do something about that damn exception </c:if>
Formal definition:
<c:catch [var="varName"]> ... </c:catch>
Name Description Notes
var The name of the scoped variable which will store the Throwable. Optional; if not specified, the exception is not saved.
BODY JSP code which may throw a Throwable.

c:if

This tag includes or does not include its body based on the result of a test, or else creates a scoped variable which contains the result of a test.
<c:if test="product.price > 100.00"/> ... conditionally included stuff ... </c:if> <c:if test="product.price > 100.00" var="expensiveProduct" scope="request"/>
Formal definition:
<c:if test="expression" [var="varName"] [scope="page|request|session|application"]> ... </c:catch>
Name Description Notes
test The expression to evaluate. It must be boolean. Required.
var The name of the scoped variable which will be assigned the result of the test. Optional. If supplied, there should be no body, and vice versa.
scope The scope of the scoped variable which will be assigned the result of the test. Optional. If not supplied, the default is 'page'.
BODY JSP code which is included if the result of evaluating the test expression is true. No body is supplied if the var attribute is.

c:choose

This tag selects among various alternative paths, based on the results of tests.
<c:choose> <c:when test="product.price > 100.00"> Ouch! </c:when> <c:when test="product.price > 10.00"> That's more like it! </c:when> <c:otherwise> Too cheap by half! </c:otherwise> </c:choose>
Formal definition:
<c:choose> <c:when test="expression"> ... </c:when> <c:when test="expression"> ... </c:when> <c:when test="expression"> ... </c:when> ... [<c:otherwise> ... </c:otherwise> </c:choose>
One or more <c:when> elements must be included. Zero or one <c:otherwise> element may be included. If a <c:otherwise> element is included, it must appear last.

c:forEach

This tag iterates over a collection or array of entries, including its body once for each entry, and initializing a scoped variable for the entry at each iteration.
<c:forEach var="product" items="productList"> <tr> <td><c:out value="${product.id}"/></td> <td><c:out value="${product.name}"/></td> </tr> </c:forEach>
The items attribute may refer to:
  • a Collection: List, Set, Vector, etc.
  • a Map
  • array of references
  • array of primitive (the scoped variable will be a standard wrapper, e.g. Integer)
  • some specialized classes for iterating over SQL result sets
When iterating over a Map, the scoped variable will be a Map.Entry object.
It is possible to iterate over a subset of the elements, using begin, end and step. For example, the following shows the 4th, 6th, 8th and 10th items:
<c:forEach var="product" items="productList" begin="4" end="10" step="2"> <tr> <td><c:out value="${product.id}"/></td> <td><c:out value="${product.name}"/></td> </tr> </c:forEach>
It is also possible to discover status information about the iteration. The status object implements LoopTagStatus:
interface LoopTagStatus { int getIndex(); // index of object in the collection int getCount(); // number of items that have been produced int getCurrent(); // gets the current object, without advancing the iteration int getBegin(); // gets the specified begin index int getEnd(); // gets the specified end index int getStep(); // gets the step increment boolean isFirst(); // is this the first object to be produced? boolean isLast(); // is this the last object to be produced? }
For example:
<c:forEach var="product" varStatus="status" items="productList"> <c:if test="${status.isFirst}"> <table> </c:if> <tr> <td><c:out value="${status.count}"/></td> <td><c:out value="${product.id}"/></td> <td><c:out value="${product.name}"/></td> </tr> <c:if test="${status.isLast}"> </table> </c:if> </c:forEach>
Formal definition:
<!-- iterates over elements of a collection --> <c:forEach items="items" [var="varName"] [varStatus="status"] [begin="begin"] [end="end"] [step="step"]> ... </c:forEach> <!-- iterates over a range of ints --> <c:forEach [var="varName"] [varStatus="status"] begin="begin" end="end" [step="step"]> ... </c:forEach>
items The collection or array to iterate over Optional. If not specified, then the iteration just produces ints from begin to end.
var The name of the scoped variable created to store the collection item for each iteration of the loop. Optional. But if var and varStatus are both not specified, then what's the point?
varStatus The name of the scoped variable created to store the status information for each iteration of the loop. Optional. But if var and varStatus are both not specified, then what's the point?
begin The starting index. Required if items is not specified, else optional. Value is 0 by default.
end The ending index. Required if items is not specified, else optional. Value is the size of the collection minus 1 by default
step The increment Optional. Value is 1 by default.

c:forTokens

This tag iterates over the tokens in a string. Very similar to c:forEach, except the items attribute should be a String, and there is a delims attribute to specify the delimiters.
<c:forTokens var="name" items="Albert,Betty,Carol,David,Edith" delims=","> <tr> <td><c:out value="${name}"/></td> </tr> </c:forEach>
Formal definition:
<!-- iterates over elements of a collection --> <c:forTokens items="items" delims="delims" [var="varName"] [varStatus="status"] [begin="begin"] [end="end"] [step="step"]> ... </c:forTokens>

c:url

Encodes a URL:
  • performs URL rewriting (if necessary)
  • encodes parameters
  • prepends the context to context relative paths
<c:url value="http://www.alethis.net/contest/freemoney" var="freeMoneyUrl"> <c:param name="guess" value="22784736 734343 8237456"/> </c:url> <a href='<c:out value="${freeMoneyUrl}"/>'>Get free money!</a>
Formal definition:
<c:url value="url" var="varName" [context="context"] [scope="page|request|session|application]"> <c:param name="name" value="value"/> <c:param name="name" value="value"/> ... </c:url>
Name Description Notes
url The url. Required.
var The scoped variable which will hold the encoded url. Required.
context Name of the context when specifying a context-relative url in a foreign context. Optional.
scope The scope in which the scoped variable will be created. Optional; default is 'page'.
BODY <c:param> elements with name and value attributes. Optional.

c:import

Imports a resource identified by a URL, and making it available either as a String or via a Reader.
<!-- absolute URL, imported as a string --> <c:url value="http://www.yahoo.com" var="yahooPage"/> <!-- relative URL, imported as a reader --> <c:url value="/data/products.txt" varReader="reader"/> <!-- relative URL in foreign context, imported directly into the page --> <c:url value="/templates/copyright.html" context="common"/> !</a>
This tag is more flexible than <jsp:import>, since it can access resources from a different context, and can present the data as a reader, which is more efficient for processing since it skips a save and a re-read.
The <c:import> tag can also have nested <c:param> tags.
Formal definition:
<!-- import directly --> <c:import value="url" [context="context"] [charEncoding="encoding"]> <c:param name="name" value="value"/> <c:param name="name" value="value"/> ... </c:import> <!-- import into a string --> <c:import value="url" [context="context"] [charEncoding="encoding"] var="varName" [scope="page|request|session|application]> <c:param name="name" value="value"/> <c:param name="name" value="value"/> ... </c:import> <!-- import via a reader --> <c:import value="url" [context="context"] [charEncoding="encoding"] varReader="reader" <c:param name="name" value="value"/> <c:param name="name" value="value"/> ... </c:import>
Name Description Notes
url The url. Required.
context Name of the context when specifying a context-relative url in a foreign context. Optional.
charEncoding The character encoding of the resource (normally this would not be needed when using the http protocol). Optional.
var The scoped string variable which will hold the imported data. Optional.
scope The scope in which the scoped variable will be created. Optional; default is 'page'.
varReader The scoped Reader variable which can be used to read the imported data. Optional.
BODY <c:param> elements with name and value attributes. Optional.

c:redirect

Sends a redirect to the client.
<c:redirect url="http://www.alethis.net/reference/jsptags.html"/>
Formal definition:
<c:redirect url="url" [context="context"]> <c:param name="name" value="value"/> <c:param name="name" value="value"/> </c:redirect> !</a>
Name Description Notes
url The url. Required.
context Name of the context when specifying a context-relative url in a foreign context. Optional.
BODY <c:param> elements with name and value attributes. Optional.
to top