Appendix C. JSTL Reference

The Java Standard Tag Library (JSTL) is a standardized collection of custom tags. It has a number of tags for common tasks such as iterating through lists, interacting with databases, handling XML data, formatting data, and much more.

The latest version of JSTL (at the time of writing) is 1.1. An implementation of JSTL can be downloaded from the Apache Jakarta Web site (http://jakarta.apache.org/).

JSTL consist of four sets of tags and a library of functions, grouped according to their functionality:

  • JSTL core tags

  • JSTL XML tags

  • JSTL formatting tags

  • JSTL SQL tags

  • JSTL functions

JSTL Core Tags

The JSTL core tag library contains tags that deal with flow control in JSP pages, iterating over collections, evaluating expressions, and importing resources.

Before using the core tag library, the following directive needs to be added to the JSP page:

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

The equivalent XML syntax for this directive is as follows:

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

The following table summarizes the JSTL core tags.

Tag Name

Description

catch

Catches any Throwable exception that occurs in the body of the tag

choose

Provides conditional operation and allows for choosing between mutually exclusive options

if

Provides conditional operation

import

Imports a resource specified by a URL and exposes it to the page, variable, or reader

forEach

Iterates over collections

forTokens

Iterates over tokens

out

Outputs expressions to the Web page

otherwise

A conditional operation tag for choosing between mutually exclusive options. This tag is a subtag of the choose tag.

param

Used along with the import, redirect, or url tags to add a parameter to a URL

redirect

Redirects to a new URL

remove

Removes a variable from a scope

set

Sets the value of an attribute

url

Creates a URL

when

A conditional operation tag that includes its body when an expression evaluates to true. This tag is a subtag of the choose tag.

catch

The catch tag is used to catch any java.lang.Throwable exception in the body of the tag. The syntax of the catch tag is as follows:

<c:catch [var="variable_name"]>
    JSP body content
</c:catch>

The catch tag has one attribute:

  • var: Name of the variable that is set to the thrown exception. This is an optional attribute.

An example of the catch tag is listed here:

<c:catch var="exp">
  <c:import url="http://www.foobar.com/stuff.html"/>
</c:catch>
<c:if test="${not empty exp}">
  Sorry, unable to import from URL, got exception <c:out value="${exp}" />
</c:if>

choose

The choose tag is used to provide conditional operation, and allows for choosing between mutually exclusive options. The actual selection is done using its subtags: when and otherwise. The syntax of the choose tag is shown here:

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

An example of the choose tag is as follows:

<c:choose>
  <c:when test="${userrole} == 'admin'}">
    Welcome admin. Proceed to your admin page <a href="/admin">here</a>
  </c:when>
  <c:when test="${userrole} == 'member'}">
    Welcome member. Proceed to your home page <a href="/memberhome">here</a>
  </c:when>
  <c:otherwise>
    Welcome guest. Log in <a href="/login">here</a>.
  </c:otherwise>
</c:choose>

if

The if tag evaluates a test condition. If it is true, it processes its body. If the test condition is false, the body is ignored. The syntax of the if tag is shown here:

<c:if test="test condition>
      [var="variable name"]
      [scope="page|request|session|application"]>
    JSP body content
</c:if>

The if tag has three attributes:

  • test: The test condition that determines whether the body of the tag is to be processed. This is a mandatory attribute.

  • var: Variable that holds the result (true or false) of the test condition evaluation. This variable can be used for future test conditions (depending on the scope of the variable), thus avoiding reevaluation of the test condition. This is an optional attribute.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

An example of the if tag is listed here:

<c:if test="${not empty exp}">
  Sorry, unable to import from URL, got exception <c:out value="${exp}" />
</c:if>

import

The import tag imports a resource specified by a URL and exposes it to the page, variable, or reader. It is similar to the <jsp:include> directive, but with more features. The body of the import tag can have param tags for adding parameters to the URL. The syntax for the tag is shown here:

<c:import url="resource URL"
          [var="variable name"]
          [scope="page|request|session|application"]
          [varReader="variable name"]
          [context="context name"]
          [charEncoding="character encoding"]>
     JSP body content
</c:import>

The import tag has six attributes:

  • url: The relative or absolute URL of the resource being imported. This is a mandatory attribute.

  • var: The variable in which the content retrieved from the specified URL should be stored. This is an optional attribute.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

  • varReader: Name of the Reader for the URL resource. This is an optional attribute.

  • context: When the URL being imported is a relative URL in another context, the context name is specified in this attribute. This is an optional attribute.

  • charEncoding: The character encoding of the content at the specified URL. This is an optional attribute.

An example of the import tag is listed here:

<c:import url="http://www.foobar.com/stuff.html"/>

forEach

The forEach tag is used for iteration over collections. The syntax of the forEach tag is shown here:

<c:forEach [items="collection of items"]
           [begin="begin index"]
           [end="end index"]
           [step="step size"]
           [var="variable name"]
[varStatus="status variable name"]>
     JSP body content
</c:forEach>

The forEach tag has six attributes:

  • items: The collection of items to iterate over. The collection can be any Java object of type java.util.Collection or java.util.Map. This is an optional attribute.

  • begin: The start index for the iteration. This is an optional attribute.

  • end: The end index for the iteration. This is an optional attribute.

  • step: The size of the index increment while iterating over the collection. The iteration will process every step item of the collection, starting from the begin index (or first item, if begin is not specified). For example, if step is 5, the index is incremented by 5 every iteration. This is an optional attribute.

  • var: The name of the variable in which the current item in the iteration is stored. This is an optional attribute.

  • varStatus: The name of the variable in which the status of the iteration is stored.

An example of the forEach tag is listed here:

<ul>
      <c:forEach items="${list}" var="listItem" varStatus="status">
          <li><c:out value="${listItem}"/></li>
      </c:forEach>
  </ul>

forTokens

The forTokens tag is used for iterating over tokens separated by a delimiter. The syntax of the forTokens tag is shown here:

<c:forTokens items="string of tokens"
             delims="delimiter characters"
            [begin="begin index"]
            [end="end index"]
            [step="step size"]
            [var="variable name"]
            [varStatus="status variable name"]>
     JSP body content
</c:forTokens>

The forTokens tag has seven attributes:

  • items: The string of tokens to iterate over. This is a mandatory attribute.

  • delims: The set of characters that separate the tokens in the string (i.e., delimiters). This is a mandatory attribute.

  • begin: The start index for the iteration, which defaults to 0. This is an optional attribute.

  • end: The end index for the iteration. This is an optional attribute.

  • step: The size of the index increment while iterating over the tokens. The iteration will process every step token, starting from the begin index (or first item, if begin is not specified). This is an optional attribute.

  • var: The name of the variable in which the current item in the iteration is stored. This is an optional attribute.

  • varStatus: The name of the variable in which the status of the iteration is stored.

An example of the forTokens tag is listed here:

<ul>
      <c:forTokens items="${list}" delims =":" var="listItem" varStatus="status">
          <li><c:out value="${listItem}"/></li>
      </c:forTokens>
  </ul>

out

The out tag is used to output the result of an expression. It functions similarly to the <%= ... => JSP syntax. The syntax of the out tag is shown here:

<c:out value="expression"
       [default="default expression value"]
       [escapeXml="true|false"]>
   JSP body content
</c:out>

The out tag has three attributes:

  • value: The expression to be evaluated. The result of the expression is output to the page. This is a mandatory attribute.

  • default: The default value of the expression in case it results in a null. This is an optional attribute.

  • escapeXml: Determines whether the <, >, " and ' characters in the resultant string should be converted to their corresponding character entity codes. This is an optional attribute and defaults to true.

An example of the out tag is listed here:

<ul>
      <c:forTokens items="${list}" delims =":" var="listItem" varStatus="status">
          <li><c:out value="${listItem}"/></li>
      </c:forTokens>
  </ul>

otherwise

The otherwise tag is used for conditional evaluation of its body. It is a subtag of the choose tag and executes only if none of the when tags evaluate to true. The syntax of the otherwise tag is shown here:

<c:otherwise>
    JSP body content
</c:otherwise>

An example for the otherwise tag is listed here:

<c:choose>
  <c:when test="${userrole} == 'admin'}">
    Welcome admin. Proceed to your admin page <a href="/admin">here</a>
  </c:when>
  <c:when test="${userrole} == 'member'}">
    Welcome member. Proceed to your home page <a href="/memberhome">here</a>
  </c:when>
  <c:otherwise>
    Welcome guest. Log in <a href="/login">here</a>.
  </c:otherwise>
</c:choose>

param

The param tag is used along with the import, redirect, or url tags to add a parameter to a URL. The syntax of the param tag is shown here:

<c:param name="parameter name" [value="parameter value"]>
    JSP body content
</c:param>

The param tag has two attributes:

  • name: The name of the parameter. This is a mandatory attribute.

  • value: The value for the parameter. This is an optional attribute.

An example for the param tag is listed here. This generates a URL of the form http://www.google.com/search?q=<search term>.

<c:url value="http://www.google.com/search">
  <c:param name="q" value="${searchTerm}"/>
</c:url>

redirect

The redirect tag redirects the user to a new URL. The body of the redirect tag can have param tags for adding parameters to the URL. The syntax for the tag is shown here:

<c:redirect url="resource URL>
            [context="context name"]>
    JSP body content
</c:redirect>

The redirect tag has two attributes:

  • url: The relative or absolute URL of the resource being imported. This is an optional attribute.

  • context: When the URL to which one is being redirected is a relative URL in another context, the context name is specified in this attribute. This is an optional attribute.

An example of the redirect tag is listed here:

<c:catch var="exp">
  <c:import url="http://www.foobar.com/stuff.html"/>
</c:catch>
<c:if test="${not empty exp}">
  <c:redirect url="/error.jsp"/>
</c:if>

remove

The remove tag removes a variable from a scope. The syntax of the remove tag is shown here:

<c:remove var="variable name"
          [scope="page|request|session|application"] />

The remove tag has two attributes:

  • var: The variable to be removed. This is a mandatory attribute.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

An example of the remove tag is listed here:

<c:remove var="foobar"/>

set

The set tag sets a variable or a property to the value of an expression. The syntax of the set tag is shown here:

<c:set   [var="variable name"]
         [value="expression"]
         [target="JavaBean or Map object name"]
         [property="target property name"]
[scope="page|request|session|application"] >
    JSP body content
</c:set>

The set tag has five attributes:

  • var: The variable that is set to the value of the expression. This is an optional attribute.

  • value: The expression to be evaluated. This is an optional attribute.

  • target: The target object (JavaBean or Map object) whose property will be set.

  • property: Name of the property to be set in the target attribute.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

An example of the set tag is listed here:

<c:set var="index" value="1" scope="page" />

url

The url tag creates a URL. The body of the url tag can have param tags for adding parameters to the URL. The syntax for the tag is shown here:

<c:url   [var="variable name"]
         [scope="page|request|session|application"]
         [value="url"]
         [context="context name"]>
    JSP body content
</c:url>

The url tag has four attributes:

  • var: The variable that contains the processed URL.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

  • value: The URL to be processed. This is an optional attribute.

  • context: When the URL is a relative URL in another context, the context name is specified in this attribute. This is an optional attribute.

An example of the url tag is listed here:

<c:url value="http://www.google.com/search">
  <c:param name="q" value="${searchTerm}"/>
</c:url>

when

The when tag is used for conditional evaluation of its body. It is a subtag of the choose tag, and its body is included only if the test condition is true. The syntax of the otherwise tag is shown here:

<c:when test="test condition" >
    JSP body content
</c:when>

The when tag has one attribute:

  • test: The test condition that determines whether the body of the tag is to be processed. This is a mandatory attribute.

An example of the when tag is listed here:

<c:choose>
  <c:when test="${userrole} == 'admin'}">
    Welcome admin. Proceed to your admin page <a href="/admin">here</a>
  </c:when>
  <c:when test="${userrole} == 'member'}">
    Welcome member. Proceed to your home page <a href="/memberhome">here</a>
  </c:when>
  <c:otherwise>
    Welcome guest. Log in <a href="/login">here</a>.
  </c:otherwise>
</c:choose>

JSTL XML Tags

The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing XML, transforming XML data, and flow control based on XPath expressions.

XPath is a syntax for addressing parts of an XML document. It allows for both relative and absolute paths to a XML element or attribute. For example, child::foo refers to an XML element called foo that is a child of the current XML node, and /employee/dependent refers to all XML elements called dependent that are children of the root element employee.

For more information on XPath, XSL, and other XML technologies, refer to Beginning XML, 2nd Edition (ISBN 0-7645-4394-6).

Before using the XML tag library, the following directive needs to be added to the JSP page:

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

The equivalent XML syntax for this directive is as follows:

<jsp:directive.taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" />

The following table summarizes the JSTL XML tags.

Tag Name

Description

choose

Provides conditional operation and allows for choosing between mutually exclusive options.

forEach

Iterates over collections based on XPath expressions.

if

Provides conditional operation based on XPath expressions.

otherwise

A conditional operation tag for choosing between mutually exclusive options. Subtag of the choose tag.

out

Outputs expressions to the Web page.

param

Used along with the transform tag to add a parameter to the XML transformer.

parse

Parses XML content.

set

Evaluates an XPath expression and sets the value of an attribute to it.

transform

Applies an XSLT stylesheet to XML data.

when

A conditional operation tag that includes its body when an expression evaluates to true. Subtag of the choose tag.

choose

The choose tag is used to provide conditional operation and allows for choosing between mutually exclusive options. The actual selection is made using its subtags: when and otherwise. The syntax of the choose tag is shown here:

<x:choose>
  <x:when test="XPath expression">
    JSP body content
  </x:when>
  ...
  <x:otherwise>
    JSP body content
  </x:otherwise>
</x:choose>

An example of the choose tag is listed here:

<x:choose>
  <x:when select="message[.= 'warning']">
    An error occurred.
  </x:when>
  <x:when select="message[.= 'fatal']">
    A fatal error occurred.
  </x:when>
  <x:otherwise>
    Welcome guest. Log in <a href="/login">here</a>.
  </x:otherwise>
</x:choose>

forEach

The forEach tag is used for iterating over collections. The syntax of the forEach tag is shown here:

<x:forEach select="XPath expression"
           [begin="begin index"]
           [end="end index"]
           [step="step size"]
           [var="variable name"]
           [varStatus="status variable name"]>
     JSP body content
</x:forEach>

The forEach tag has six attributes:

  • select: The XPath expression to be evaluated. This is a mandatory attribute.

  • begin: The start index for the iteration. This is an optional attribute.

  • end: The end index for the iteration. This is an optional attribute.

  • step: The size of the index increment while iterating over the collection. The iteration will process every step item of the collection, starting from the begin index (or first item, if begin is not specified). This is an optional attribute.

  • var: The name of the variable in which the current item in the iteration is stored. This is an optional attribute.

  • varStatus: The name of the variable in which the status of the iteration is stored.

An example of the forEach tag is listed here:

<x:forEach select="$rssDocument//*[name()='item']">
  <li>
      <a href="<x:out select="./*[name()='link']"/>">
      <x:out select="./*[name()='title']" escapeXml="false"/>
      </a>
  </li>
</x:forEach>

if

The if tag evaluates a test XPath expression; if it is true, it processes its body. If the test condition is false, the body is ignored. The syntax of the if tag is shown here:

<x:if select="XPath expression"
      [var="variable name"]
      [scope="page|request|session|application"]>
    JSP body content
</x:if>

The if tag has three attributes:

  • select: The test XPath expression that determines whether the body of the tag is to be processed. This is a mandatory attribute.

  • var: Variable that holds the result (true or false) of the test condition evaluation. This variable can be used for future test conditions (depending on the scope of the variable), thus avoiding reevaluation of the test condition. This is an optional attribute.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

An example of the if tag is listed here:

<x:if select="message[.= 'warning']">
    An error occurred.
</x:if>

otherwise

The otherwise tag is used for conditional evaluation of its body. It is a subtag of the choose tag and executes only if none of the when tags evaluates to true. The syntax of the otherwise tag is as follows:

<x:otherwise>
    JSP body content
</x:otherwise>

An example of the otherwise tag is listed here:

<x:choose>
  <x:when select="message[.= 'warning']">
    An error occurred.
  </x:when>
  <x:when select="message[.= 'fatal']">
    An fatal error occurred.
  </x:when>
  <x:otherwise>
    Welcome guest. Log in <a href="/login">here</a>.
  </x:otherwise>
</x:choose>

out

The out tag is used to output the result of an XPath expression. It functions similarly to the <%= ... => JSP syntax. The syntax of the out tag is shown here:

<x:out select="XPath expression"
       [escapeXml="true|false"] />

The out tag has two attributes:

  • select: The XPath expression to be evaluated. The result of the expression is output to the page. This is a mandatory attribute.

  • escapeXml: Determines if the <, >, ", and ' characters in the resultant string should be converted to their corresponding character entity codes. This is an optional attribute and defaults to true.

An example of the out tag is listed here:

<x:out select="./*[name()='title']" escapeXml="false"/>

param

The param tag is used along with the transform tag to add a parameter to the transformer. The syntax of the param tag is shown here:

<x:param name="parameter name" [value="parameter value"]>
   JSP body content
</x:param>

The param tag has two attributes:

  • name: The name of the parameter. This is a mandatory attribute.

  • value: The value for the parameter. This is an optional attribute

An example of the param tag is listed here:

<x:transform xml="${xmlDoc}" xslt="${styleSheet}">
    <param name="id" value="${idvalue}" />
</x:transform>

parse

The parse tag is used to parse XML data specified either via an attribute or in the tag body. The syntax of the parse tag is shown here:

<x:parse [var="variable name"]
         [varDom="variable name"]
         [scope="page|request|session|application"]
         [scopeDom="page|request|session|application"]
         [doc="XML document"]
         [systemId="system identifier URI"]
         [filter="filter"]>
   JSP body content
</x:parse>

The parse tag has seven attributes:

  • var: A variable that contains the parsed XML data. The type of this data is implementation dependant.

  • varDom: A variable that contains the parsed XML data. The type of this data is org.w3c.dom.Document.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

  • scopeDom: Scope of the variable specified in the varDom attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

  • doc: XML document to be parsed

  • systemId: The system identifier URI for parsing the document

  • filter: The filter to be applied to the source document

The parse tag also has an attribute called xml, which has been deprecated; the doc attribute should be used instead.

An example of the parse tag is listed here:

<c:import var="rssFeed" url=" "http://www.theserverside.com/rss/theserverside-servletsjsp-rss2.xml"/>
<x:parse var="rssDocument" xml="${rssFeed}"/>

set

The set tag sets a variable to the value of an XPath expression. The syntax of the set tag is shown here:

<x:set   var="variable name"
         [select="XPath expression"]
         [scope="page|request|session|application"]/>

The set tag has three attributes:

  • var: A variable that is set to the value of the XPath expression. This is a mandatory attribute.

  • select: The XPath expression to be evaluated. This is an optional attribute.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

An example of the set tag is listed here:

<x:set var="firstTitle"
       select="$rssDocument//*[name()='channel']/*[name()='title'][1]}"/>

transform

The transform tag applies an XSL transformation on a XML document. The syntax for the tag is shown here:

<x:set   [var="variable name"]
         [scope="page|request|session|application"]
         [result=""]
         [doc=""]
         [docSystemId=""]
         [xslt=""]
         [xsltSystemId=""]>
JSP body content
</x:set>

XSL (Extensible Style Sheet) is a stylesheet language for XML. XSLT (XSL Transformation) is an XML language that describes the rules for transforming an XML document into another XML document.

The transform tag has seven attributes:

  • var: The org.w3c.dom.Document variable that is set to the transformed XML document. This is an optional attribute.

  • scope: Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified. This is an optional attribute.

  • result: The result object that captures or processes the transformation result. This is an optional attribute.

  • doc: The XML document to be transformed. This is an optional attribute.

  • docSystemId: The system identifier URI for parsing the XML document. This is an optional attribute.

  • xslt: The stylesheet, which is specified as a String, Reader, or Source object. This is an optional attribute.

  • xsltSystemId: The system identifier URI for parsing the XSLT stylesheet. This is an optional attribute.

The transform tag also has attributes called xml and xmlSystemId that have been deprecated; doc and docSystemId should be used instead.

An example of the transform tag is listed here:

<c:import var="rssFeed" url=" "http://www.theserverside.com/rss/theserverside-
servletsjsp-rss2.xml"/>
<c:import var="rssToHtml" url="/WEB-INF/xslt/rss2html.xsl"/>
<x:transform xml="${rssFeed}" xslt="${rssToHtml}"/>

when

The when tag is a subtag of choose, and it evaluates its body when the expression used in it is true. The syntax for the tag is shown here:

<x:when   select="XPath expression">
  JSP body content
</x:when>

The when tag has one attribute:

  • select: The XPath expression to be evaluated. This is a mandatory attribute.

An example of the when tag is listed here:

<x:when select="message[.= 'warning']">
    An error occurred.
  </x:when>

JSTL Formatting Tags

The JSTL formatting tag library provides support for internationalization (i18n); that is, it enables the formatting of data (dates, numbers, time) in different locales.

Before using the formatting tag library, the following directive needs to be added to the JSP page:

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

The equivalent XML syntax for this directive is as follows:

<jsp:directive.taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" />

The following table summarizes the JSTL formatting tags.

Tag Name

Description

bundle

Loads a resource bundle

formatDate

Formats date and time

formatNumber

Formats a numeric value as a number, currency, or a percentage

message

Outputs a localized string

param

Supplies an argument to a containing message tag

parseDate

Parses a string representation of date/time

parseNumber

Parses a string representation of a number, currency, or a percentage

requestEncoding

Sets the request character encoding

setBundle

Loads a resource bundle and stores it in a named variable

setLocale

Stores the locale in a named variable

setTimeZone

Stores the time zone in a named variable

timeZone

Specifies the time zone for formatting or parsing date/time data

bundle

The bundle tag loads a resource bundle for the body of the tag. The body usually contains a nested fmt:message tag to display a localized message. The syntax of the tag is shown here:

<fmt:bundle  basename="resource bundle basename"
             [prefix="message key prefix"]>
    JSP body content
</fmt:bundle>

The bundle tag has two attributes:

  • basename: The basename of the resource bundle. This is a mandatory attribute.

  • prefix: The prefix to be applied to the message key for any nested fmt:message tags. This is an optional attribute.

An example of the bundle tag is listed here:

<fmt:bundle basename="com.wrox.webapps.ErrorBundle">
    <fmt:message key="com.wrox.webapps.ErrorBundle.loginError"/>
</fmt:bundle>

formatDate

The formatDate tag formats date and time data according to a specified style and pattern. The syntax of the tag is shown here:

<fmt:formatDate  value="string representation"
                 [type="date|time|both"]
                 [dateStyle="formatting style"]
                 [timeStyle="formatting style"]
                 [pattern="formatting pattern"]
                 [timeZone="timezone"]
                 [var="variable name"]
                 [scope="page|request|session|application"] />

The formatDate tag has eight attributes:

  • value: The date/time to be formatted. This is a mandatory attribute.

  • type: Specifies if the data to be formatted contains a date, time, or both.

  • dateStyle: Formatting style used for dates. The valid style values are defined by the java.text.DateFormat class (i.e., default, short, medium, long, and full). Valid only if the type attribute is date or both.

  • timeStyle: Formatting style used for time values. The valid style values are defined by the java.text.DateFormat class (i.e., default, short, medium, long, and full). Valid only if the type attribute is time or both.

  • pattern: Custom formatting pattern for dates and times. The patterns are specified by the java.text.SimpleDateFormat class. Some examples include MM/dd/yyyy for dates and h:mm a for time.

  • timeZone: Time zone to be used for the time information.

  • var: Variable containing the parsed date/time value. This variable is of type java.util.Date.

  • scope: Scope of the var variable. This optional attribute can be page, request, session, or application.

An example of the formatDate tag is listed here:

The job posting time is <fmt:formatDate value="${timeValue}" pattern="h:mm a zz"/>.

formatNumber

The formatNumber tag formats a numeric value as a number, currency, or a percentage in a locale-specific manner. The syntax of the tag is shown here:

<fmt:formatNumber   [value="numeric value"]
                    [type="number|currency|percentage"]
                    [pattern="pattern"]
                    [currencyCode="currency code"]
                    [currencySymbol="currency symbol"]
                    [groupingUsed="true|false"]
                    [maxIntegerDigits="max integer digits"]
                    [minIntegerDigits="min integer digits"]
                    [maxFranctionDigits="max fractional digits"]
                    [minFractionDigits="min fractional digits"]
                    [var="variable name"]
                    [scope="page|request|session|application"]>
    JSP body content
</fmt:formatNumber>

The formatNumber tag has 12 attributes:

  • value: The numeric value to be formatted.

  • type: Specifies if the numeric value is to be formatted as a number, currency, or a percentage, and defaults to a number if not specified.

  • pattern: Custom formatting pattern. The patterns are as specified by the java.text.DecimalFormat class (for example, "#,###").

  • currencyCode: Currency codes as defined by the ISO 4217 standard (www.iso.ch/iso/en/prods-services/popstds/currencycodes.html). This is applicable only when the type attribute is currency.

  • currencySymbol: Symbol to use for currency. This is applicable only when the type attribute is currency. currencySymbol is not generally required and can be used to override the defaults.

  • groupingUsed: Specifies if the output format contains any grouping separators. These grouping are usually done using commas in English language locales (e.g., one thousand is 1,000.00) or using a period in some non-English locales (e.g., one thousand is 1.000,00). The groupingUsed attribute defaults to true.

  • maxIntegerDigits: Maximum number of digits in the integer portion of the formatted output.

  • minIntegerDigits: Minimum number of digits in the integer portion of the formatted output.

  • maxFractionDigits: Maximum number of digits in the fractional portion of the formatted output.

  • minFractionDigits: Minimum number of digits in the fractional portion of the formatted output.

  • var: Variable that contains the formatted numeric value as a string.

  • scope: Scope of the var variable. This is an optional attribute, and can be page, request, session, or application.

An example of the formatNumber tag is listed here:

This item costs <fmt:formatNumber value="1000" type="currency"/>.

message

The message tag displays a localized message. The body can contain a nested fmt:param tag to pass parameterized values to the message. The syntax of the tag is shown here:

<fmt:message [key="message key"]
             [bundle="localization bundle where key is looked up"]
             [var="variable that stores localized message"]
             [scope="page|request|session|application"]>
    JSP body content
</fmt:message>

The message tag has four attributes:

  • key: The message key corresponding to the message. This is an optional attribute.

  • bundle: The localization context in which the message key is looked up. This is an optional attribute.

  • var: The variable that stores the localized message. This is an optional attribute.

  • scope: Scope of the var variable. This is an optional attribute and can be page, request, session, or application.

An example of the message tag is listed here:

<fmt:bundle basename="com.wrox.webapps.ErrorBundle">
    <fmt:message key="com.wrox.webapps.ErrorBundle.loginError"/>
</fmt:bundle>

param

The param tag is nested within a fmt:message tag to pass parameterized values to the message. The syntax of the tag is shown here:

<fmt:param   [value="argument value"] >
    JSP body content
</fmt:param>

The param tag has one attribute:

  • value: Value used for parametric replacement in the fmt:message tag. This is an optional attribute.

An example of the param tag is listed here:

<fmt:message key="com.wrox.webapps.Messages.helloMessage">
    <fmt:param value="${user.Name}"/>
</fmt:message>

parseDate

The parseDate tag parses string representations of date and time specified either via an attribute or in its body content. The syntax of the tag is shown here:

<fmt:parseDate   [value="string representation"]
                 [type="date|time|both"]
                 [dateStyle="formatting style"]
                 [timeStyle="formatting style"]
                 [pattern="formatting pattern"]
                 [timeZone="timezone"]
                 [parseLocale="locale"]
                 [var="variable name"]
                 [scope="page|request|session|application"]>
    JSP body content
</fmt:parseDate>

The parseDate tag has nine attributes:

  • value: The string to be parsed.

  • type: Specifies if the value is to be parsed; contains a date, time, or both.

  • dateStyle: Formatting style used for the date. The valid style values are defined by the java.text.DateFormat class (i.e., default, short, medium, long, and full). Valid only if the type attribute is date or both.

  • timeStyle: Formatting style used for time values. The valid style values are defined by the java.text.DateFormat class (i.e., default, short, medium, long, and full). Valid only if the type attribute is time or both.

  • pattern: Custom formatting pattern for date and time strings. The patterns are specified by the java.text.SimpleDateFormat class. Some examples are MM/dd/yyyy for dates and h:mm a for time.

  • timeZone: Time zone to be used for the time information.

  • parseLocale: Locale to be used for formatting date and time values.

  • var: Variable that contains the parsed date/time value. This variable is of type java.util.Date.

  • scope: Scope of the var variable. This is an optional attribute and can be page, request, session, or application.

An example of the parseDate tag is listed here:

<c:set var="dateString">1/1/05 12:00 PM</c:set>
<fmt:parseDate value="${dateString}" parseLocale="en_US" type="both"
               dateStyle="short" timeStyle="short" var="usDate"/>

parseNumber

The parseNumber tag parses a string representation of a number, currency, or a percentage specified either via an attribute or in its body content. The syntax of the tag is shown here:

<fmt:parseNumber   [value="string representation"]
                   [type="number|currency|percentage"]
                   [pattern="pattern"]
                   [parseLocale="locale"]
                   [integerOnly="true|false"]
                   [var="variable name"]
                   [scope="page|request|session|application"]>
    JSP body content
</fmt:parseNumber>

The parseNumber tag has seven attributes:

  • value: The string to be parsed.

  • type: Specifies whether the value is to be parsed as a number, currency, or a percentage, and defaults to a number if not specified.

  • pattern: Custom formatting pattern for parsing the value attribute. The patterns are specified by the java.text.DecimalFormat class (for example, "#,###").

  • parseLocale: Locale to be used for parsing.

  • integerOnly: Specifies that only the integer part needs to be parsed.

  • var: Variable that contains the parsed numeric value.

  • scope: Scope of the var variable. This is an optional attribute and can be page, request, session, or application.

An example of the parseNumber tag is listed here:

<fmt:parseNumber value="${salePrice}" parseLocale="en_US" type="currency"/>

requestEncoding

The requestEncoding tag sets the character encoding for the request. The syntax of the tag is shown here:

<fmt:requestEncoding  [value="character encoding name"] />

The requestEncoding tag has one attribute:

  • value: The name of the character encoding for the request. Examples of request encodings include UTF-8, ISO-8859-1, JIS_C6220-1969-jp, and so on. A complete list of encodings can be found at www.iana.org/assignments/character-sets. This is an optional attribute.

An example of the requestEncoding tag is listed here:

<fmt:requestEncoding value="UTF-8"/>

setBundle

The setBundle tag loads a resource bundle for a specified scope (as compared to the bundle tag, which loads it only for its body). The syntax of the tag is shown here:

<fmt:setBundle  basename="resource bundle basename"
             [var="Localization context variable"]
             [scope="page|request|session|application"] />

The setBundle tag has three attributes:

  • basename: The basename of the resource bundle. This a mandatory attribute.

  • var: The name of the localization context variable (javax.servlet.jsp.jstl.fmt.LocalizationContext). This is an optional attribute.

  • scope: Scope of the localization context variable. This is an optional attribute, and can be page, request, session, or application.

An example of the setBundle tag is listed here:

<fmt:setBundle basename="com.wrox.webapps.ErrorBundle"/>

setLocale

The setLocale tag sets the locale value in the locale configuration variable. The syntax of the tag is shown here:

<fmt:setLocale  value="Locale string"
                    [variant="Vendor or browser specific variant"]
                    [scope="page|request|session|application"]
                    />

The setLocale tag has three attributes:

  • value: The name of the character encoding for the request. Examples of request encodings include UTF-8, ISO-8859-1, JIS_C6220-1969-jp, and so on. A complete list of encodings is at www.iana.org/assignments/character-sets. This is a mandatory attribute.

  • variant: This is a vendor/browser-specific value. Examples of the variants are WIN (for Windows), MAC (for Macintosh), and POSIX (for POSIX).

  • scope: Scope of the locale configuration. This is an optional attribute, and can be page, request, session, or application.

An example of the setLocale tag is listed here:

<fmt:setLocale value="en"/>

setTimeZone

The setTimeZone tag sets the time zone value in the time zone configuration variable for a specified scope (as compared to the timeZone tag, which sets it only for its body content). The syntax of the tag is shown here:

<fmt:setTimeZone  value="Time Zone string"
                      [var="time zone variable"]
                      [scope="page|request|session|application"]
                    />

The setTimeZone tag has three attributes:

  • value: The name of the time zone. This can be specified as a custom time zone ID ("GMT+8") or as a time zone supported by Java ("America/Los_Angeles"). This is a mandatory attribute.

  • var: Name of the time zone variable. This is an optional attribute.

  • scope: Scope of the time zone variable configuration. This is an optional attribute and can be page, request, session, or application.

An example of the setTimeZone tag is listed here:

<fmt:setTimeZone value="GMT-8"/>

timeZone

The timeZone tag specifies the time zone for any time formatting in its body content. The syntax of the tag is shown here:

<fmt:timeZone  value="time zone">
         JSP body content
    </fmt:timeZone>

The timeZone tag has one attribute:

  • value: The time zone value for the body content. This can be specified as a custom time zone ID ("GMT+8") or as a time zone supported by Java ("America/Los_Angeles"). This is a mandatory attribute.

An example of the timeZone tag is listed here:

<fmt:timeZone value="GMT-8">
         ...
    </fmt:timeZone>

JSTL SQL Tags

The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server. The tags are designed for rapid prototyping of applications or for developing simple Web applications; any serious database use in an enterprise application should be through a database tier, as described in Chapter 23, "Access to Databases," and demonstrated in Chapter 28, "JSP Project II: Shopping Cart Application."

Before using the SQL tag library, the following directive needs to be added to the JSP page:

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

The equivalent XML syntax for this directive is as follows:

<jsp:directive.taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" />

The following table summarizes JSTL SQL tags.

Tag Name

Description

dateParam

Sets a parameter in a SQL statement to a specified java.util.Date value

param

Sets a parameter in a SQL statement to a specified value

query

Executes a SQL query

setDataSource

Specifies a data source for the database connection

transaction

Provides one connection to all nested database actions so that they can be executed as a transaction

update

Executes a SQL update

dateParam

The dateParam tag is embedded in the body of a query or update tag. It is used to pass java.util.Date parameters to a SQL statement. The syntax of the tag is shown here:

<sql:dateParam  value="date parameter value"
                   [type="date|time|timestamp"] />

The dateparam tag has the following attributes:

  • value: The parameter value for the SQL statement. This can be a date, time, or timestamp. This is a mandatory attribute.

  • type: The type of parameter. This can be date, time, or timestamp. This is an optional attribute.

An example of the dateParam tag is listed here:

<sql:query sql="select * from employee where join_date > ?">
    <sql:dateParam value="${cutoff_date}" type="date"/>
  </sql:query>

param

The param tag is embedded in the body of a query or update tag. It is used to pass parameters to a SQL statement. The syntax of the tag is shown here:

<sql:param [value="parameter value"]>
         JSP body content
    </sql:param>

The param tag has one attribute:

  • value: The parameter value for the SQL statement

An example of the param tag is listed here:

<sql:query sql="select * from employee where salary > ?">
    <sql:param value="${min_salary}"/>
  </sql:query>

query

The query tag executes an SQL query statement specified either via an attribute or embedded in the body of the tag. A query tag can have nested param tags to pass parameters to the SQL statement. The syntax of the tag is shown here:

<sql:query  var="variable name"
            [scope="page|request|session|application"]
            [sql="SQL query statement"]
            [startRow="starting row"]
            [maxRows="maximum number of rows"]
            [dataSource="DataSource"]>
    JSP body content
</sql:query>

The query tag has six attributes:

  • var: This specifies the variable that contains the result of the SQL query statement. This is a mandatory attribute.

  • scope: Scope of the variable defined in the var attribute. This is an optional attribute, and can be page, request, session, or application.

  • sql: The SQL query statement to execute. This is an optional attribute.

  • startRow: The starting row for the returned results. This is an optional attribute and defaults to zero.

  • maxRows: The maximum number of rows to return. This is an optional attribute and defaults to −1 (i.e., no maximum limit) if not specified.

  • dataSource: The DataSource for the database to be accessed. This is an optional attribute; if not specified, the default JSTL DataSource is used.

An example of the query tag is listed here:

<sql:query sql="select * from employee where salary > ?">
    <sql:param value="${min_salary}"/>
  </sql:query>

Another example is as follows:

<sql:query var="roundlist"
  dataSource="jdbc:mysql://localhost/footydb,com.mysql.jdbc.Driver,footy,footy">
  SELECT * from round
</sql:query>

setDataSource

The setDataSource tag creates a DataSource for connecting to the database. The syntax for this tag is shown here:

<sql:setDataSource [var="variable name"]
                   [scope="page|request|session|application"]
                   [driver="JDBC driver"]
                   [url="JDBC URL for database"]
                   [user="Username to connect to the database"]
                   [password="Password to connect to the database"]
                   [dataSource="DataSource"]/>

The setDataSource tag has seven attributes:

  • var: This specifies the variable that contains the specified DataSource. This is an optional attribute.

  • scope: Scope of the variable defined in the var attribute. This is an optional attribute, and can be page, request, session, or application.

  • driver: JDBC driver class name.

  • url: JDBC URL for the database.

  • user: Username to connect to the JDBC database.

  • password: Password to connect to the JDBC database.

  • dataSource: The DataSource for the database to be accessed. This is an optional attribute, and if not specified, the default JSTL DataSource is used.

An example of the setDataSource tag is listed here:

<sql:setDataSource  url="jdbc:mysql:///taglib"
                    driver="org.gjt.mm.mysql.Driver"
                    user="admin"
                    password="secret"/>
<sql:query sql="select * from employee where salary > ?">
  <sql:param value="${min_salary}"/>
</sql:query>

transaction

Other SQL tags are nested within a transaction tag. The tag provides them with a shared connection object and allows all the nested tags to run as one transaction. The syntax of the transaction tag is shown here:

<sql:transaction [dataSource="DataSource"]
       [isolation="read_committed|read_uncommitted|repeatable_read|serializable"] >
    JSP body content
</sql:transaction>

The transaction tag has two attributes:

  • dataSource: The DataSource for the database to be accessed. This is an optional attribute, and if not specified, the default JSTL DataSource is used.

  • isolation: Isolation level for the transaction. This can be read_committed, read_uncommitted, repeatable_read, or serializable. This is an optional attribute and defaults to the DataSource isolation level.

An example of the transaction tag is listed here:

<sql:transaction>
  <sql:update sql="update employee set salary = ? where emp_id = ?">
    <sql:param value="${new_salary}"/>
    <sql:param value="${empId}"/>
  </sql:update>
  <sql:update sql="update employee set salary_deductions = ? where emp_id = ?">
    <sql:param value="${new_deductions}"/>
    <sql:param value="${empId}"/>
  </sql:update>
</sql:transaction>

update

The update tag executes an SQL update statement specified either via an attribute or embedded in the body of the tag. An update tag can have nested param tags to pass parameters to the SQL statement. The syntax of the tag is shown here:

<sql:update [var="variable name"]
            [scope="page|request|session|application"]
            [sql="SQL update statement"]
            [dataSource="DataSource"]>
    JSP body content
</sql:update>

The update tag has four attributes:

  • var: This specifies the variable that contains the result of the SQL update statement. This is an optional attribute.

  • scope: Scope of the variable defined in the var attribute. This is an optional attribute and can be page, request, session, or application.

  • sql: The SQL update statement to execute. This is an optional attribute.

  • dataSource: The DataSource for the database to be accessed. This is an optional attribute, and if not specified, the default JSTL DataSource is used.

An example of the update tag is listed here:

<sql:update>
      UPDATE round SET startdate = ?, enddate = ?
      WHERE number = ?
      <sql:param value="${param.round_startdate}" />
      <sql:param value="${param.round_enddate}" />
      <sql:param value="${param.round_number}" />
    </sql:update>

JSTL Functions

The JSTL function library contains a number of string manipulation functions. These include functions for splitting and concatenating strings, returning substrings, determining whether a string contains a specified substring, and many others.

Before using the function library, the following directive needs to be added to the JSP page:

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

The equivalent XML syntax for this directive is as follows:

<jsp:directive.taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" />

The following table summarizes the JSTL functions.

Tag Name

Description

contains

Tests whether an input string contains the specified substring. This is a case-sensitive search.

containsIgnoreCase

Tests whether an input string contains the specified substring in a case-insensitive way.

endsWith

Tests whether an input string ends with the specified suffix.

escapeXml

Escapes characters that could be interpreted as XML markup.

indexOf substring.

Returns the index within a string of the first occurrence of a specified

join

Concatenates all elements of an array into a string.

length

Returns the number of items in a collection or the number of characters in a string.

replace

Returns a string that results from replacing in an input string all occurrences of a "before" string into an "after" substring.

split

Splits a string into an array of substrings.

startsWith

Tests whether an input string starts with the specified prefix.

substring

Returns a subset of a string.

substringAfter

Returns a subset of a string following a specific substring.

substringBefore

Returns a subset of a string before a specific substring.

toLowerCase

Converts all of the characters of a string to lowercase.

toUpperCase

Converts all of the characters of a string to uppercase.

trim

Removes white spaces from both ends of a string.

contains

The contains function determines whether an input string contains a specified substring. The syntax of the function is shown here:

boolean contains(java.lang.String, java.lang.String)

An example of the contains function is listed here:

<c:if test="${fn:contains(theString, searchString)}">

containsIgnoreCase

The containsIgnoreCase function determines whether an input string contains a specified substring. The syntax of the function is shown here:

boolean containsIgnoreCase(java.lang.String, java.lang.String)

An example of the containsIgnoreCase function is listed here:

<c:if test="${fn:containsIgnoreCase(theString, searchString)}">

endsWith

The endsWith function determines whether an input string ends with a specified suffix. The syntax of the function is shown here:

boolean endsWith(java.lang.String, java.lang.String)

An example of the endsWith function is listed here:

<c:if test="${fn:endWith (theString, suffix)}">

escapeXml

The escapeXml function escapes characters that can be interpreted as XML markup. The syntax of the function is shown here:

java.lang.String escapeXml(java.lang.String)

An example of the escapeXml function is listed here:

${fn:escapeXml(xmlContainingText)}

indexOf

The indexOf function returns the index within a string of a specified substring. The syntax of the function is shown here:

int indexOf(java.lang.String, java.lang.String)

An example of the indexOf function is listed here:

${fn:indexOf(theString, searchString)}

join

The join function concatenates all the elements of an array into a string with a specified separator. The syntax of the function is shown here:

String join (java.lang.String[], java.lang.String)

An example of the join function is listed here:

Your Path settings should be ${fn:join(filenamesArray, ";")}.

length

The length function returns the string length or the number of items in a collection. The syntax of the function is shown here:

int length(java.lang.Object)

An example of the length function is listed here:

There are ${fn:length(shoppingCart.Items)} items in your shopping cart.

replace

The replace function replaces all occurrences of a string with another string. The syntax of the function is shown here:

boolean replace(java.lang.String, java.lang.String, java.lang.String)

An example of the replace function is listed here:

The CLASSPATH for Windows is ${fn:replace(classpathString, ":", ";")}.

split

The split function splits a string into an array of substrings based on a delimiter string. The syntax of the function is shown here:

java.lang.String[] split(java.lang.String, java.lang.String)

An example of the split function is listed here:

${fn:split(theString, delimiterString)}

startsWith

The startsWith function determines whether an input string starts with a specified substring. The syntax of the function is shown here:

boolean startsWith(java.lang.String, java.lang.String)

An example of the startsWith function is listed here:

<c:if test="${fn:startsWith(theString, prefixString)}">

substring

The substring function returns a subset of a string specified by start and end indices. The syntax of the function is shown here:

java.lang.String substring(java.lang.String, int, int)

An example of the substring function is listed here:

${fn:substring(theString, beginIndex, endIndex)}

substringAfter

The substringAfter function returns the part of a string after a specified substring. The syntax of the function is shown here:

java.lang.String substringAfter(java.lang.String, java.lang.String)

An example of the substringAfter function is listed here:

${fn:substringAfter(theString, substring)}

substringBefore

The substringBefore function returns the part of a string before a specified substring. The syntax of the function is shown here:

java.lang.String substringBefore(java.lang.String, java.lang.String)

An example of the substringBefore function is listed here:

${fn:substringBefore(theString, substring)}

toLowerCase

The toLowerCase function converts all the characters of a string to lowercase. The syntax of the function is shown here:

java.lang.String toLowerCase(java.lang.String)

An example of the toLowerCase function is listed here:

${fn:toLowerCase(theString)}

toUpperCase

The toUpperCase function converts all the characters of a string to uppercase. The syntax of the function is shown here:

java.lang.String toUpperCase(java.lang.String)

An example of the toUpperCase function is listed here:

${fn:toUpperCase(theString)}

trim

The trim function removes white space from both ends of a string. The syntax of the function is shown here:

java.lang.String trim(java.lang.String)

An example of the trim function is listed here:

${fn:trim(theString)}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.254.26