Java / JSP / JSTL

Index

JSTL Introduction & Core Libary

The JavaServer Pages Standard Tag Library (JSTL) encapsulates as simple tags the core functionality common to many Web applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags.

JSP Syntax

With a HTML document that is served in a JSP container (e.g. Tomcat), all JSP syntax, know as scriplets is include with specific tags.

  <% %>
  

For Example

  <% out.println("Hello World"); %>
  
JSTL Syntax

The JSTL provides separate tag libraries, each containing custom actions that target a specific functional area:

  • (1) core actions
  • (2) XML processing
  • (3) I18N capable formatting
  • (4) Database access
  • (5) Functions (new in 1.1)

In addition, the JSTL introduces the concept of an expression language (EL) to simplify page development.

The syntax for all JSTL tags is similar to HTML tags, following strict XHTML requirements for closed tags. The syntax of tags is of the form:

  <taglib:function  attribute="value" />
  
JSTL Core Library

The core tag library supports actions, including: output, manipulation of scoped variables, conditional logic, loops, URL manipulation, and error handling.
The following is the list of tags within the core libary.
c:catch ,c:choose c:if ,c:import c:forEach,c:forTokens c:out ,c:otherwise c:param ,c:redirect c:remove ,c:set c:url ,c:when

The following is an example miniminal program using the core action output syntax.

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

  <c:out value="Hello World"/>

  

The first line of JSP code that defines the taglib is always required in each file. In JSTL 1.1, the jsp/ addition was added to the uri

The <c:output> syntax as shown has a mandatory attribute of value.
In addition an optional escapeXML attribute is used for reserved XML characters. This attribute determines whether characters <,>,&,'," in the resulting string should be converted to their corresponding character entity codes. The Default value for escapeXML is true.
For example, look at the following example.

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

  <c:out value="<b>Hello World</b>"/><br />
  <c:out value="<b>Hello World</b>" escapeXml="false" />
  

The second category within the core libary is variable management.

File 5.3 - file5.3.jsp
  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <c:set var="hello" value="Hello World from a variable"/>
  <c:out value="${hello}"/>
  

For <c:set> both var and value are mandatory. An additional optional attribute scope allows you to set the scope of a variable, the default is page, but options include session and application.

The ${} is the first example of the Expression Language (EL) that is used within the JSTL.
As of the JSP 2.0 specification (i.e. Tomcat 5), the EL is now incoporated directly within the JSP. The above example, could now be rewritten.

File 5.4 - file5.4.jsp
  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <c:set var="hello" value="Hello World from a variable"/>
  ${hello}
  

A number of Implicit Objects existing within the JSTL expression language. For Example:

  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <c:set var="browser" value="${header['User-Agent']}"/>
  <c:out value="${browser}"/>
  
This can also be written as:
  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <c:out value="${header['User-Agent']}"/>
  
JSTL Implicit Objects
Variable Description
param A collection of all request parameters as a single string value for each parameter.
paramValues A collection of all request parameters as a string array value for each parameter.
header A collection of all request headers as a single string value for each header.
headerValues A collection of all request headers as a string array value for each header.
cookie A collection of all request cookies as a single javax.servlet.http.Cookie instance value for each cookie.
initParams A collection of all application init parameters as a single string value for each parameter.
pageContext An instance of the javax.servlet.jspPageContext class.
pageScope A collection of all page scope objects.
requestScope A collection of all request scope objects.
sessionScope A collection of all session scope objects.
applicationScope A collection of all application scope objects.

EL Operators

The EL evaluates an identifier by looking up its value as an attribute using PageContext.findAttribute(String). If the attribute is not found, null is returned.

In addition to the property and array element operators and the arithmetic, relational, and logical operators, a special operator for testing if an object is "empty" or not can be used in an EL expression. The following table lists all operators:

Operator Description
. Access a property
[] Access an array/list element
() Group a subexpression
+ Addition
- Subtraction or negation of a number
/ or div Division
% or mod Modulo (remainder)
== or eq Test for equality
!= or ne Test for inequality
< or lt Test for less than
> or gt Test for greater than
<= or le Test for less than or equal
>= or gt Test for greater than or equal
&& or and Test for logical AND
|| or or Test for logical OR
! or not Unary Boolean complement
empty Test for empty value (null, empty string, or an empty collection)

Accessing Application Data

You can access application data either as a property of an object, using the dot (.) operator, or a named array element using the bracket ['name'] operator.

The JSTL expression ${data} represents the scoped variable named data. You can retrieve properties from collections using either the dot (.) or bracket ([]) operator:

  • The dot (.) operator is used to retrieve a named property. For example, the expression ${customer.name} indicates the name property of the customer scoped variable.
  • The bracket operator ([]) can be used to retrieve a named property, as in ${customer["name"]}. The bracket operator can also be used as ${customers[0]} to refer to the first item in the customers collection.

The expression language unifies the treatment of dot (.) and bracket ([]) operators. Therefore, ${customer.name} is equivalent to ${customer["name"]}. As you can see, all EL expressions must be enclosed between ${ and }.

Conditional Actions

The JSTL conditional actions support simple conditional execution (using <c:if>) and mutually exclusive conditional execution (using <c:choose>, <c:when>, and <c:otherwise>).

The <c:if> tag allows you to conditionally include a piece of the page, depending on runtime information. For example, the following snippet of code checks if a customer is based in Canada:

<c:if test="${customer.country == 'Canada'}">
   This customer is based in Canada.
</c:if>s

Here is another example that demonstrates the use of <c:if> with <c:catch>:

<c:catch var="exception">
  <!-- execution we can recover from. -->
  ...
</c:catch>
<c:if test="${exception != null}">
  Processing could not be performed. Here is why....
</c:if>

You can achieve the equivalent of an if/then/else statement with <c:choose>, <c:when>, and <c:otherwise>, as follows:

<c:choose>
  <c:when test="${customer.country == 'UK'}">
     UK has mild winters.
  </c:when>
  <c:when test="${customer.country == 'Canada'}">
     Canada has wild winters.
  </c:when>
  <c:when test="$customer.country == 'UAE'}">
     UAE has hot winters and good gold.
  </c:when>
  <c:otherwise>
     Country is unknown.
  </c:otherwise>
</c:choose>

Iteration Actions

Iterating over a collection of objects is a common task in JSP pages. The following snippet of code uses <c:forEach> to iterate over a list of customers:

<c:forEach var="customer" items="${customers}">
  Customer: <c:out value="${customer}"/>
</c:forEach>

The <c:forEach> tag allows iteration over a subset of the collection items. The begin and end indices can be specified for this, along with steps. Here is a simple example:

<c:forEach var="k" begin="1" end"100">
  <c:out value="${i % 2 == 0}"/>
</c:forEach>

As a more complete example, consider the following snippet of code, which prints all header parameters:

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

<html>
<head>
  <title>JSTL Implicit Objects</title>
</head>
<body bgcolor="#FFFFCC">
<h3>Header info:</h3>

<c:forEach var="head" items="${headerValues}">
  param: <c:out value="${head.key}"/><br>
  values:
   <c:forEach var="val" items="${head.value}">
     <c:out value="${val}"/>
   </c:forEach>
   <p>
</c:forEach>

</body>
</html>

If you are, however, interested in a specific header (the User-Agent for example), you can retrieve that information using the following syntax: ${header['User-Agent']}.

URL Actions

The <jsp:include> action, in the JSP specification, provides for the inclusion of static and dynamic resources located in the same context as the current page. This action is widely used, but it doesn't allow page authors to include resources that are available remotely.

The JSTL provides a comprehensive set of actions for URL-related tasks. For example, you can use the <c:import> action to import local and remote resources. Here are some examples:

<c:import url="./copyright.html"/>
<c:import url="http://www.somewhere.com/hello.xml"/>

You can use the <c:url> action to take care of all URL rewriting tasks. It can be combined with the <c:param> action, which transparently encodes query-string parameters. Consider the following example, which rewrites and encodes a URL for user registration:

<c:url value="http://www.somewhere.com/customers/register" var="registrationURL">
  <c:param name="name" value="${param.name}"/>
  <c:param name="country" value="${param.country}"/>
</c:url>
<a href='<c:out value="${registrationURL}"/>'>Customer Registration>/a>

Finally, <c:redirect> (to support HTTP redirect) completes the list of URL-related actions. Here is an example:

<c:redirect url="https://www.somewhere.com/register">



JSTL Formatting Library




© Copyright 2004 - ARABX Pty Ltd. All Rights Reserved