JSTL Overview

 < Day Day Up > 



JSTL can be broken into two functional areas: a set of tag libraries and an expression language. The tag libraries provide a set of tags that implement general-purpose functionality for iteration and conditional processing, data formatting and localization, XML manipulation, and database access. The expression language simplifies access to Java language constructs within JSPs. Together, the two make up a powerful set of functionality for developing applications with JSPs.

JSTL arose out of the Java Community Process (JCP) and thus had the input and forethought of many high-profile organizations and influential individuals in the industry. In June of 2000, the first JSTL specification was finalized and targeted to work with the JSP 1.2 and Servlet 2.3 specifications. Since then, a maintenance release (1.1) became available in January of 2004. Currently, JSTL expressions can only be used as an attribute value with Tag Library tags that support them. However, when JSP 2.0 is finalized, expressions will be supported throughout JSPs. This means that the expressions will be usable anywhere inside the JSP and will not be limited to just JSTL-enabled tags as they are now.

You can download JSTL from Sun's Web site at http://java.sun.com/products/jsp/jstl/ .

The JSTL Expression Language

JSTL's greatest strength lies in its expression language. The expression language simplifies access to Java language constructs from within JSPs and provides the foundation for the JSTL tag libraries' usefulness. With the expression language, you create simple expressions that return a value. For example, one expression might retrieve the value of a request parameter. Another might evaluate a conditional expression that returns a boolean result. This latter use is extremely helpful when conditionally processing portions of a JSP.

JSTL expressions are surrounded by an opening ${ and a closing }, as shown in the following snippet:

<c:out value="${userObj}"/>

Everything between the opening ${ and closing } constitutes the expression. Expressions can contain references to JSP page-scoped objects and implicit objects and can use operators to traverse the objects and manipulate them. The following sections describe the details of the expression language.

Accessing Objects

The JSTL expression language provides a simple mechanism for accessing objects and their properties. The dot (.) operator is used to traverse object hierarchies and access properties. The following snippet illustrates a basic example of the dot operator's usage:

<c:out value="${customer.address.city}"/> 

In this example, the dot operator is used to access the customer object's address property and then the address object's city property. Each instance of the dot operator in the expression evaluates to a getter method call for the property on the left of the operator. Thus, the first dot will call a getAddress( ) method on the customer object. The second dot will then call a getCity( ) method on the object returned from the getAddress( ) call. In order for the dot operator to work, the object on the right of the operator must have a getter method for the property on the left of the operator. Otherwise, the operator will fail.

As you can see, this method of traversing object hierarchies is quick and simple. Without JSTL, you'd have to use a JSP expression similar to the following to access properties down a hierarchy:

<%= customer.getAddress().getCity() %>

The dot operator is great for accessing simple properties; however, it doesn't allow you to access elements of arrays or collections. For that, JSTL has the brackets ([ ]) operator. The brackets operator allows you to specify the index of an element you want to access, as shown next:

<c:set var="highBid" value="${bids[0]}"/>

This approach works for arrays and list-based collections. For map-based collections, you specify the key for the element you want to access, as shown next:

<c:set var="color" value="${param['color']}"/>

Implicit Objects

JSTL makes several objects available to the expression language as implicit objects. The implicit objects are built in and can be used by any expression without having to be initialized or otherwise set up. They are available by default. Utilizing an implicit object is as simple as referencing its name in an expression, as shown here:

<c:out value="${header['User-Agent']}"/>

In this example, the Core Tag Library's out tag is used to output the value of the 'User-Agent' HTTP header. The header implicit object is a java.util.Map instance containing the incoming request's HTTP headers.

The following table lists and describes each of the JSTL implicit objects.

Category

Implicit Object

Description

Cookies

cookie

A java.util.Map instance containing the current request's cookies

Initialization parameters

initParam

A java.util.Map instance containing the Web application's context initialization parameters specified in web.xml

JSP

pageContext

A javax.servlet.jsp.PageContext instance for the current page

Request headers

header

A java.util.Map instance containing the primary values for the current request's HTTP headers

 

headerValues

A java.util.Map instance containing all the values for the current request's HTTP headers

Request parameters

param

A java.util.Map instance containing the primary values for the current request's parameters

 

paramValues

A java.util.Map instance containing all the values for the current request's parameters

Scopes

applicationScope

A java.util.Map instance containing application-scoped attributes

 

pageScope

A java.util.Map instance containing page-scoped attributes

 

requestScope

A java.util.Map instance containing request-scoped attributes

 

sessionScope

A java.util.Map instance containing session-scoped attributes

Using Operators

The JSTL expression language supports several operators for comparing and manipulating data in expressions. When expressions contain operators, the operators are applied to the operands and the resulting value is used as the expression's value. Take for example the following snippet:

<c:set var="sqrFt" value="${width * length}"/>

This example uses the asterisk (*) multiplication operator to multiply a width variable times a length variable and stores the result in a JSP scripting variable.

Operators can also be combined to create complex expressions, as shown next:

<c:set var="halfSqrFt" value="${(width * length) / 2}"/>

Here, width and length are multiplied and then divided and the resulting value is stored.

Logical and relational operators work the same; however, their results are often used with conditional tags, as shown here:

<c:if test="${count == 5}"> Count equals 5. </c:if>

This example compares the value of the count object to 5 to see if they match. If they do, the text enclosed between the opening and closing if tags is processed. Otherwise it is skipped.

The following table lists each of the JSTL expression language operators.

Category

Operators

Arithmetic

+, -, *, / (or div), % (or mod)

Logical

&& (or and), || (or or), ! (or not)

Relational

== (or eq), != (or ne), < (or lt), > (or gt), <= (or le), >= (or ge)

Validation

empty

As mentioned, multiple operators can be used together in a single expression. The following lists the order of precedence of operators:

  • [ ], .

  • ( )

  • unary -, not, !, empty

  • *, /, div, %, mod

  • +, binary -

  • <, >, <=, >=, lt, gt, le, ge

  • ==, !=, eq, ne

  • &&, and

  • ||, or

The JSTL Tag Libraries

JSTL's tag libraries provide a common thread for JSP applications to be sewn from, offering the base functionality needed by most applications. The JSTL tag libraries work like any other JSP tag libraries with the added functionality of supporting JSTL expressions for tag attribute values. The following table lists each of the JSTL tag libraries. The following sections describe the tags in each library.

Library

Taglib Prefix

Description

Core

c

Provides tags for conditional logic, loops, output, variable creation, text imports, and URL manipulation

Format

fmt

Provides tags for formatting dates and numbers and for localizing text messages

SQL

sql

Provides tags for making SQL queries to databases

XML

x

Provides tags for parsing of XML documents, selection of XML fragments, flow control based on XML, and XSLT transformations

The Core Tag Library Tags

The following table lists each of the tags in the Core Tag Library and provides a short description of each tag's purpose.

Tag

Description

catch

Catches and optionally exposes any exception (i.e. anything derived from java.lang.Throwable) that may be thrown from nested instances of other tags in this library.

choose

Establishes a context for mutually exclusive conditional operations, marked by nested when and otherwise tags.

forEach

Iterates over each element in a collection.

forTokens

Iterates over tokens, separated by the supplied delimiters.

if

Evaluates its body if the supplied condition is true and optionally exposes a java.lang.Boolean scripting variable representing the evaluation of this condition.

import

Retrieves an absolute or relative URL and exposes its contents to the page, a String specified by its var attribute, or a Reader specified by its varReader attribute.

out

Outputs JSTL expressions. Equivalent to JSP's <%= … > for JSTL expressions.

otherwise

Subtag of choose that follows when tags and runs only if all of the prior conditions evaluate to false.

param

Adds a parameter to a containing import tag's URL.

redirect

Redirects to a new URL.

remove

Removes a scoped variable (from a particular scope, if specified).

set

Sets the result of an expression evaluation in a scope.

url

Creates a URL with optional query parameters.

when

Subtag of choose that includes its body if its condition evaluates to true.

The Format Tag Library Tags

The following table lists each of the tags in the Format Tag Library and provides a short description of each tag's purpose.

Tag

Description

bundle

Loads a resource bundle to be used by nested instances of other tags in this library.

formatDate

Formats a date and/or time using the supplied styles and pattern.

formatNumber

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

message

Specifies a localized message from the current bundle and performs parametric replacement on it and then outputs it.

param

Supplies an argument for parametric replacement to a containing message tag.

parseDate

Parses the string representation of a date and/or time.

parseNumber

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

requestEncoding

Sets the request character encoding.

setBundle

Loads a resource bundle and stores it in the named scoped variable or the bundle configuration variable.

setLocale

Stores the given locale in the locale configuration variable.

setTimeZone

Stores the given time zone in the time zone configuration variable.

timeZone

Specifies the time zone for any time formatting or parsing tags nested in its body.

The SQL Tag Library Tags

The following table lists each of the tags in the SQL Tag Library and provides a short description of each tag's purpose.

Tag

Description

dateParam

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

param

Sets a parameter in an SQL statement to the specified value.

query

Executes the SQL query defined in its body or through its sql attribute.

setDataSource

Specifies a JDBC data source for which nested instances of other tags in this library will use when to execute SQL statements.

transaction

Provides nested instances of other tags in this library with a shared connection, set up to execute all statements as one transaction.

update

Executes the SQL update defined in its body or through its sql attribute.

The XML Tag Library Tags

The following table lists each of the tags in the XML Tag Library and provides a short description of each tag's purpose.

Tag

Description

choose

Establishes a context for mutually exclusive conditional operations, marked by when and otherwise.

forEach

Iterates over a collection of XML tags.

if

Evaluates its body if the supplied XPath expression evaluates to true.

otherwise

Subtag of choose that follows when tags and runs only if all of the prior conditions evaluated to false.

out

Outputs XPath (XML Path) expressions. Equivalent to JSP's <%= … > for XPath expressions. XPath is a set of syntax rules for defining parts of an XML document.

param

Adds a parameter to a containing transform tag.

parse

Parses XML content from a specified source attribute or from body content.

set

Saves the result of an XPath expression evaluation in a scope.

transform

Conducts a transformation given a source XML document and an XSLT stylesheet.

when

Subtag of choose that includes its body if its expression evaluates to true.



 < Day Day Up > 



Struts. The Complete Reference
Struts: The Complete Reference, 2nd Edition
ISBN: 0072263865
EAN: 2147483647
Year: 2003
Pages: 134
Authors: James Holmes

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net