heavyz > homepage
 

JSTL :: Core Taglib

Overview

Released in June 2002, JSTL 1.0 consists of 4 custom tag libraries (core, format, xml, and sql) and 2 general-purpose tag library validators (ScriptFreeTLV and PermittedTaglibsTLV).

Explanations for the 4 custom tag libraries:

  • core: provides custom actions to manage data through scoped variables, as well as to perform iteration and conditionalization of page content. It also provides tags to generate and operate on URLs.
  • format: defines actions to format data, specifically numbers and dates. It also provides support for internationalizing JSP pages using localized resource bundles.
  • xml: includes tags to manipulate data represented through XML.
  • sql: defines actions to query relational databases.

The 2 JSTL tag library validators allow developers to enforce coding standards within their JSP applications:

  • The ScriptFreeTLV validator can be used to prohibit the use of the various types of JSP scripting elements -- scriptlets, expressions, and declarations -- within a JSP page.
  • The PermittedTaglibsTLV validator can be used to restrict the set of custom tag libraries (including the JSTL tag libraries) that may be accessed by an application's JSP pages.

Installing JSTL

The Apache Taglibs project contains a reference implementation of JSTL. Visite http://jakarta.apache.org/taglibs to know more.

Apache Standard taglib may be installed on Apache Tomcat (version 5.0.28) by the following steps:

  • Download JSP Standard Tag Library 1.1 implementation (binary release) from Apache Taglibs project.
  • Unzip the release in a directory (referred as [TAGLIBS_STANDARD_HOME]).
  • To install Standard taglib for all web applications, copy [TAGLIBS_STANDARD_HOME]/lib/*.jar into [TOMCAT_HOME]/shared/lib/ directory. To install Standard taglib for a certain web application, copy [TAGLIBS_STANDARD_HOME]/lib/*.jar into [WEBAPP_BASEDIR]/WEB-INF/lib/ directory. The Standard taglib release contains two JAR files: jstl.jar and standard.jar.
  • Copy [TAGLIBS_STANDARD_HOME]/standard-examples/ directory into [TOMCAT_HOME]/webapps/ directory.
  • start Tomcat.
  • Verify whether the standard-examples web application can run properly.

Note: In order to use JSTL EL, web application's web.xml file must follow the format below:

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"
         version="2.4">
  ... ... ... ...
</web-app>
        

If the following URIs are used, declaring taglibs in web.xml is not necessary:

  • http://java.sun.com/jsp/jstl/core for core taglib.
  • http://java.sun.com/jsp/jstl/fmt for format taglib.
  • http://java.sun.com/jsp/jstl/functions for functions taglib.
  • http://java.sun.com/jsp/jstl/sql for SQL taglib.
  • http://java.sun.com/jsp/jstl/xml for XML taglib.

Expression Language (EL)

Expression Language (EL) provides identifiers, accessors, and operators for retrieving and manipulating data resident in the JSP container. The EL is geared toward looking up objects and their properties, and performing simple operations on them. Its format is like: ${user.firstName}, where user is the identifier, dot (.) is the accessor, and firstName is the name of property.

Scoped Variables

The JSP API, through the <jsp:useBean> action, allows data to be stored and retrieved from 4 different scopes within the JSP container:

  • Page Scope: Objects stored in page scope can only be retrieved during the processing of that page for a specific request.
  • Request Scope: Objects stored in request scope can be retrieved during the processing of all pages taking part in the processing of a request (such as if the processing of a request encounters one or more <jsp:include> or <jsp:forward> actions).
  • Session Scope: Object stored in session scope can be retrieved by any pages accessed by a user during a single interactive session with the Web application (that is, until the HttpSession object associated with that user's interaction is invalidated).
  • Application Scope: Object stored in application scope is accessible from all pages and for all users, until the Web application itself is unloaded (typically as a result of the JSP container being shut down).

In the EL, identifiers not associated with implicit objects are assumed to name objects stored in the 4 JSP scopes. Checking order is: page scope, request scope, session scope, and finally application scope. If not found, null is returned.

11 identifiers are defined as implicit objects for EL:

Category Identifier Description
JSP pageContext This identifier corresponds to the processing of the current page
Scopes pageScope A Map associating the names and values of page-scoped attributes
requestScope A Map associating the names and values of request-scoped attributes
sessionScope A Map associating the names and values of session-scoped attributes
applicationScope A Map associating the names and values of application-scoped attributes
RequestParams param A Map storing the primary values of the request parameters by name
paramValues A Map storing all values of the request parameters as String arrays
RequestHeaders header A Map storing the primary values of the request headers by name
headerValues A Map storing all values of the request headers as String arrays
Cookies cookie A Map storing the cookies accompanying the request by name
InitParams initParam A Map storing the context initialization parameters of the Web application by name

While JSP and EL implicit objects have only one object in common (pageContext), other JSP implicit objects are still accessible from the EL.

EL Accessors

EL can automatically wrap and unwrap primitives in their corresponding Java classes. For pointers to full-blown Java objects, EL provides 2 accessors -- the dot operator (.) and the bracket operator ([]):

  • Dot operator is used for accessing the properties of an object. When the property being accessed is itself an object, the dot operator can be applied recursively.
  • Bracket operator is used to retrieve elements of arrays and collections:
    • for collections implementing the java.util.List interface), the index of the element to be retrieved is specified inside the brackets.
    • for collections implementing the java.util.Map interface, the key is specified inside the brackets.
  • The dot operator and the bracket operator are somewhat interchangeable. For example, ${user["firstName"]} is the same as ${user.firstName}, just as ${commands.dir} is the same as ${commands["dir"]}.

EL Operators

EL includes several operators to manipulate and compare data accessed by EL expressions:

Category Operators
Arithmetic +, -, *, / (div), % (mod)
Relational == (eq), != (ne), < (lt), > (gt); <= (le), >= (ge)
Logical && (and), || (or), ! (not)
Validation empty (this operator takes a single expression as its argument (${empty input}), and returns a boolean value indicating whether or not the expression evaluates to an "empty" value. Expressions that evaluate to null are considered empty, as are collections or arrays with no elements. The empty operator will also return true if its argument evaluates to a String of zero length.

Here are 2 examples:

  • ${item.price * (1 + taxRate[user.address.zipcode])}
  • ${(x >= min) && (x <= max)}

Literals

Numbers, character strings, booleans, and nulls can all be specified as literal values in EL expressions. Character strings are delimited by either single or double quotes. Boolean values are designated by true and false.

Variable Tags and Output

Firstly, include a taglib directive in the JSP pages that will use JSTL core tag library:

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

Variable Tags

The <c:set> action provides a tag-based mechanism for creating and setting scoped variables. The <c:remove> action is used to delete a scoped variable:

<c:set var="variable_name" scope="page | request | session | application" value="expression"/>
<c:set var="variable_name" scope="page | request | session | application">expression</c:set>
<c:remove var="variable_name" scope="page | request | session | application" />
          

Notes:

  • The scope attribute is optional and defaults to page.
  • It's acceptable for the body content of the <c:set> tag to employ custom tags itself.
  • All content generated within the body of <c:set> will be assigned to the specified variable as a String value.

Output

The <c:out> tag evaluates the expression specified by its value attribute, then prints the result. If the optional default attribute is specified, this action will instead print its value if the value attribute's expression evaluates either to null or an empty String. The escapeXml attribute is also optional. It controls whether or not characters such as "<", ">", and "&", which have special meanings in both HTML and XML, should be escaped when output:

<c:out value="expression" default="expression" escapeXml="boolean" />
          

Setting Variables with Default Values

<c:set var="timezone" scope="session">
   <c:out value="${cookie['tzPref'].value}" default="CST"/>
</c:set>
          

Flow Control

The JSTL core library provides several custom actions to manage flow control in the form of iteration, conditionalization, and exception handling.

Iteration

The <c:forEach> custom tag is used to fetch and display collections of data, typically in the form of a list or sequence of rows in a table. This tag supports two different styles of iteration:

  • iteration over an integer range (like the Java language's for statement)
  • iteration over a collection (like the Java language's Iterator and Enumeration classes)

Syntax for numerical iteration through the <c:forEach> action:

<c:forEach var="variable_name" varStatus="name"
    begin="expression" end="expression" step="expression">
  body content
</c:forEach>
          

The index of the iteration starts at the value of the begin attribute, is incremented by the value of the step attribute, and halts iteration when it exceeds the value of the end attribute. If the step attribute is omitted, the step size defaults to 1.

If the var attribute is specified, then a scoped variable with the indicated name will be created and assigned the current value of the index for each pass through the iteration. This scoped variable has nested visibility -- it can only be accessed within the body of the <c:forEach> tag.

Syntax for iterating through a collection through the <c:forEach> action:

<c:forEach var="name" items="expression" varStatus="name"
    begin="expression" end="expression" step="expression">
  body content
</c:forEach>
          

The items attribute is the only required attribute. The value of the items attribute should be the collection over whose members the iteration is to occur, and is typically specified using an EL expression. Here is a complete list of the values supported by the items attribute:

Value Type for items Resulting item value
java.util.Collection Elements from call to iterator()
java.util.Map Instances of java.util.Map.Entry
java.util.Iterator Iterator elements
java.util.Enumeration Enumeration elements
Array of Object instances Array elements
Array of primitive values Wrapped array elements
Comma-delimited String Substrings
javax.servlet.jsp.jstl.sql.Result Rows from an SQL query

varStatus attribute:

The varStatus plays the same role whether iterating over integers or collections. When present, it is used to create a scoped variable and is assigned an instance of the javax.servlet.jsp.jstl.core.LoopTagStatus class. This class defines a set of properties that describe the current state of an iteration:

Property Getter Method Description
current getCurrent() The item (from the collection) for the current round of iteration
index getIndex() The 0-based index for the current round of iteration
count getCount() The 1-based count for the current round of iteration
first isFirst() Flag indicating whether the current round is the first pass through the iteration
last isLast() Flag indicating whether the current round is the last pass through the iteration
begin getBegin() The value of the begin attribute
end getEnd() The value of the end attribute
step getStep() The value of the step attribute

<c:forTokens> iteration tag:

<c:forTokens var="name" items="expression"
    delims="expression" varStatus="name"
    begin="expression" end="expression" step="expression">
  body content
</c:forTokens>
          

The <c:forTokens> action is the JSTL analog of the Java language's StringTokenizer class. For this iteration tag, the string to be tokenized is specified through the items attribute, while the set of delimiters used to generate the tokens is provided through the delims attribute.

Conditionalization

  • <c:if>: evaluates a single test expression and then processes its body content only if that expression evaluates to true. If not, the tag's body content is ignored.
  • <c:choose>: is provided for cases in which mutually exclusive tests are required to determine what content should be displayed.

Syntax for the <c:if> conditional action:

<c:if test="expression" var="name" scope="scope">
  body content
</c:if>
          

Syntax for the <c:choose> action:

<c:choose>
  <c:when test="expression">
    body content
  </c:when>
  ...
  <c:otherwise>
    body content
  </c:otherwise>
</c:choose>
          

Exception Handling

The <c:catch> action allows for rudimentary exception handling within a JSP page. Any exceptions raised within the body content of this tag will be caught and ignored (that is, the standard JSP error-handling mechanism will not be invoked). However, if an exception is raised and the <c:catch> tag's optional var attribute has been specified, the exception will be assigned to the specified variable (with page scope), enabling custom error handling within the page itself.

Syntax for the <c:catch> action:

<c:catch var="name">
  body content
</c:catch>
          

The following code implements a try-catch block in JSTL:

<c:catch var="ex">
  body content
</c:catch>
<c:if test="${not empty ex}">
  handle the exception caught
</c:if>
          

URL Actions

The <c:url> tag is used to generate URLs. In particular, this tag provides three elements of functionality that are particularly important when constructing URLs for J2EE Web applications:

  • Prepending the name of the current servlet context
  • URL re-writing for session management
  • URL encoding of request-parameter names and values

Syntax for the <c:url> action:

<c:url value="expression" context="expression"
    var="name" scope="scope">
  <c:param name="expression" value="expression"/>
  ...
</c:url>
        

The value attribute is used to specify a base URL, which the tag then transforms as necessary. If this base URL starts with a forward slash, then a servlet context name will be prepended. An explicit context name can be provided using the context attribute. If this attribute is omitted, then the name of the current servlet context will be used.

URL rewriting is automatically performed by the <c:url> action. If the JSP container detects a cookie storing the user's current session ID, no rewriting is necessary. If no such cookie is present, however, all URLs generated by <c:url> will be rewritten to encode the session ID. Note that if an appropriate cookie is present in subsequent requests, <c:url> will stop rewriting URLs to include this ID.

If a value is supplied for the var attribute (optionally accompanied by a corresponding value for the scope attribute), the generated URL will be assigned as the value of the specified scoped variable. Otherwise, the resulting URL will be output using the current JspWriter.

If any request parameters are specified through nested <c:param> tags, then their names and values will be appended to the generated URL using the standard notation for HTTP GET requests. In addition, URL encoding is performed.

Importing Content

The <c:import> tag is a request-time (NOT compilation-time) action, and its basic task is to insert the content of some other web resource into a JSP page.

Syntax for the <c:import> action:

<c:import url="expression" context="expression"
    charEncoding="expression" var="name" scope="scope">
  <c:param name="expression" value="expression"/>
  ...
</c:import>
        

The URL for the content to be imported is specified through the url attribute, which is the tag's only required attribute. It accepts three kinds of URLs:

  • Relative URLs are resolved against the URL of the current page.
  • If the value of the url attribute starts with a forward slash, it is interpreted as an absolute URL within the local JSP container. Without a value for the context attribute, such an absolute URL is assumed to reference a resource in the current servlet context. If an explicit context is specified through the context attribute, then the absolute (local) URL is resolved against the named servlet context.
  • Complete URIs, including protocol and host names, is also supported. Any protocol supported by the java.net.URL class may be used in the value for the url.

The var attribute causes the content fetched from the specified URL to be stored (as a String value) in a scoped variable, rather than included in the current JSP page. The scope attribute controls the scoping of this variable, and defaults to page scope.

Optional nested <c:param> tags may be used to specify request parameters for the URL being imported.

Request Redirection

The <c:redirect> action is used to send an HTTP redirect response to a user's browser, and is the JSTL equivalent of the sendRedirect() method of javax.servlet.http.HttpServletResponse. The behavior of this tag's attributes and nested tags is identical to the behavior of <c:import>'s attributes and nested tags.

Syntax for the <c:redirect> action:

<c:redirect url="expression" context="expression">
  <c:param name="expression" value="expression"/>
  ...
</c:redirect>
        

References and Resources