1.1 JSTL Overview

   

In late 1997, Sun Microsystems introduced the Servlet API. Servlets were a godsend to CGI developers because servlets are much more elegant, efficient, powerful, and portable than CGI. [2] But it soon became apparent that the Servlet API had a serious shortcoming: developers created user interfaces by emitting HTML with servlet print statements, which is a terrible way to implement maintainable and extensible code. That servlet shortcoming was addressed with the introduction of JavaServer Pages (JSP), which lets you embed Java code in HTML.

[2] CGI stands for Common Gateway Interface.

But, as is often the case, the solution to the problem turned out to have a serious shortcoming of its own: embedding Java code in HTML can quickly lead to complicated JSP pages that mix presentation and business logic and are, therefore, difficult to understand and maintain. Also, with only a limited set of standard tags, such as <jsp:useBean> and <jsp:include>, JSP was great for Java developers who could write scriptlets, but difficult for page authors with no Java experience. In reaction to that shortcoming, Java developers quickly took advantage of JSP's mechanism for implementing custom tags, and a profusion of JSP custom tags soon arose, including the Jakarta Taglibs hosted by the Apache Software Foundation. [3]

[3] See http://jakarta.apache.org/taglibs/index.html for more information about Jakarta Taglibs.

From the crucible of Jakarta Taglibs and developer discontent with the JSP status quo, the JavaServer Pages Standard Tag Library (JSTL) was born. With an expression language and a comprehensive standard tag library, JSTL nearly eradicates the need for JSP scriptlets and expressions.

In late 2000, the Java Community Process (JCP) selected an expert group for JSTL. Since that time, the expert group has defined the JSTL specification and produced a reference implementation. JSTL is designed to work with servlet containers that support Servlet 2.3 and JSP 1.2 or higher. See "Getting Started" on page 23 for more information about JSTL prerequisites.

Core Warning

graphics/openglobe.gif

JSTL works only with servlet containers that support the Servlet 2.3 and JSP 1.2 APIs.

What Is JSTL?

JSTL is composed of:

  • An expression language

  • Standard Action Libraries (42 actions in four libraries)

  • Tag Library Validators (2 validators)

The expression language is arguably JSTL's single most important feature. The expression language makes it easy to access implicit objects such as the servlet request and response and scoped variables , meaning objects stored in a JSP scope (page, request, session, or application). The expression language drastically reduces the need for JSP expressions and scriptlets, which in turn increases maintainability and extensibility of JSP-based Web applications. Starting with JSP 2.0, the expression language will be defined in the JSP specification. See Chapter 2, "The JSTL Expression Language," for more details.

The standard action libraries provide a solid base of functionality for building Web applications, from general actions that iterate over collections or import URLs to more specialized actions that you can use to internationalize your website, access databases and manipulate XML.

JSTL also provides two tag library validators that let you restrict the use of scriptlets and tag libraries used in JSP pages. Those validators are provided as a proof of concept and are not part of JSTL's core functionality.

Core Definition

graphics/openglobe.gif

Scoped variable: An object stored in one of the four JSP scopes.

The JSTL Expression Language

The JSTL expression language is a simple language based on ECMAScript and XPath. It provides expressions and identifiers; arithmetic, logical, and relational operators; and automatic type conversion.

One of the most significant features of the expression language is the implicit objects it defines. Those implicit objects let you access request parameters and headers, context initialization parameters, scoped variables, and cookies. The pageContext implicit object lets you access the page context, which has references to the request, response, session, servlet context, servlet config, etc. For example, the following code fragment displays the value of a request parameter named name :

 <c:out value='  ${param.name}  '/> 

In the preceding code fragment, the param identifier is an implicit object that's a map of request parameters. You can also use the expression language to access context initialization parameters; for example, the following code fragment iterates over the application's context initialization parameters and displays their values:

 <%-- Loop over the JSTL initParam implicit object,       which is a map --%> <c:forEach items='  ${initParam}  ' var='parameter'>    <ul>       <%-- Display the key of the current item, which            corresponds to the name of the init param --%>       <li>Name: <c:out value='  ${parameter.key}  '/></li>       <%-- Display the value of the current item, which            corresponds to the value of the init param --%>       <li>Value: <c:out value='  ${parameter.value}  '/></li>    </ul> </c:forEach> 

The preceding code fragment uses the <c:forEach> action to iterate over context initialization parameters. The initParam identifier is an implicit object that's a map of context initialization parameters. Each item in that map is a map entry, so the body of the <c:forEach> action accesses the keys and values of each map entry.

The JSTL expression language is discussed in detail in Chapter 2, "The JSTL Expression Language," and JSTL implicit objects are discussed in "Implicit Objects" on page 64.

The JSTL Tag Libraries

Although its name suggests that JSTL is a single tag library, it's actually composed of four libraries that contain a total of 42 actions. Those libraries are listed in Table 1.1.

Table 1.1. JSTL Libraries

Library

Actions

Description

Core

14

Fundamentals: if / then statements and switch constructs; creating output; creating and destroying scoped variables; manipulating properties of JavaBeans components ; handling exceptions; iterating over collections; constructing URLs and importing their content.

Formatting

12

Internationalization and Formatting: Setting locales and resource bundles; localizing text and compound messages; formatting and parsing numbers , percents, currencies, and dates.

SQL

6

Database Access: Specifying a data source; executing queries, updates, and transactions; iterating over query results.

XML

10

XML Parsing and Transforming: Parsing XML; accessing and transforming XML with XPath and XSLT, respectively.

As you can see from Table 1.1, JSTL actions are pretty well distributed among the four libraries listed above. Each of those libraries is discussed, in the order listed in Table 1.1, starting at "Core Actions" on page 11.

Twin Libraries

Most JSTL actions have dynamic attributes ”attributes that can have runtime values; for example, you can specify a runtime expression for the <c:out> action, which evaluates an expression and sends the result to the current JspWriter , like this:

 <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %>  <c:out value='${user.preferences.backgroundColor}'/> 

The preceding code fragment uses the <c:out> action and the JSTL expression language to display the background color stored in a user's preferences.

The JSTL expression language is not nearly as powerful as the Java programming language, so sometimes you might need to specify a JSTL action attribute with a Java expression. Because of that need, JSTL provides two versions of each of its libraries, one that supports the JSTL expression language ”known as the EL library ”and another that supports JSP expressions ”known as the RT library. The RT library knows nothing about the JSTL expression language; instead, you specify dynamic attributes for the actions in that library with JSP expressions; for example, the following code fragment uses the <c_rt:forEach> action to iterate over the locales available for formatting dates: [4]

[4] The following code fragment is discussed in "Formatting and Parsing Dates and Times" on page 333.

  <%@ taglib uri='http://java.sun.com/jstl/core_rt' prefix='c_rt' %>  <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %> ... <form>    <table>       ...       <%-- Create an HTML select element whose name is locale --%>       <select name='locale'>          <%-- For each of the available locales for date               formatting, create an HTML option element --%>  <c_rt:forEach var='thisLocale'   items='<%= java.text.DateFormat.   getAvailableLocales()%>'>  <%-- Begin the <option> start tag --%>             <option             <%-- See if the locale request parameter is the same                  as the locale that we're creating an option for             --%>             <c:if test='${param.locale == thisLocale}'>                <%-- Now we've generated: <option selected --%>                selected             </c:if>             <%-- Generate the ending bracket for the <option> start                  tag and specify the value of the current locale                  as the value for the option element --%>             ><c:out value='${thisLocale}'/>             <%-- Generate the <option> end tag --%>             </option>  </c_rt:forEach>  </select>    </table> </form> 

The preceding code fragment creates an HTML select element whose option elements represent the locales available for formatting dates. For access to those locales, it's necessary to write a scriptlet or use the <c_rt:forEach> action, which accepts a JSP expression for its items attribute.

Notice the taglib declarations in the preceding code fragments . The RT version of the Core library is specified with a URI of http://java.sun.com/jstl/core_rt and a prefix of c_rt , whereas the EL library is specified with a URI of http://java.sun.com/jstl/core and a prefix of c . Those URIs are the standard URIs that you use to access the core actions for JSP expressions and EL expressions, respectively.

The prefixes used in the preceding code fragment are recommended by the JSTL specification. Table 1.2 and Table 1.3 list the URIs and prefixes for all of the JSTL libraries.

Table 1.2. JSTL Taglib URIs for the EL Libraries

Library

URI

Prefix [a]

Core

http://java.sun.com/jstl/core

C

Formatting

http://java.sun.com/jstl/fmt

fmt

SQL

http://java.sun.com/jstl/sql

sql

XML

http://java.sun.com/jstl/xml

x

[a] The prefix is merely a recommendation; you can use any prefix you choose.

Table 1.3. JSTL Taglib URIs for the RT Libraries

Library

URI

Prefix [a]

Core

http://java.sun.com/jstl/core_rt

c_rt

Formatting

http://java.sun.com/jstl/fmt_rt

fmt_rt

SQL

http://java.sun.com/jstl/sql_rt

sql_rt

XML

http://java.sun.com/jstl/xml_rt

x_rt

[a] The prefix is merely a recommendation; you can use any prefix you choose.

Although it's not strictly necessary, adhering to the prefixes listed in the two preceding tables is a good idea, if for no other reason than doing so will make your code easier for other JSP developers to understand.

The _rt suffixes added to the URIs and prefixes stand for runtime expression values, which is the name for values assigned to dynamic action attributes. [5]

[5] That's what <rtexprvalue> ”used to specify that an attribute can be set to a runtime expression value in a tag library descriptor ”stands for ( runtime expression value ).

The rest of this section briefly introduces each of the libraries listed in Table 1.2, in the order in which they are listed. "Getting Started" on page 23 shows you how to download and install the software that you need to get started with JSTL and "A Simple JSTL Web Application" on page 30 shows you how to implement a simple JSTL-based application. Finally, this chapter concludes with "JSTL Design Principles" on page 34, which discusses some of the JSTL design principles that affect your everyday use of JSTL actions.

Core Approach

graphics/openglobe.gif

The JSTL expression language is rich enough that you will rarely need to use the RT ( runtime) libraries. Because the RT and EL (expression language) libraries are identical except for the language used to specify dynamic attributes, this book covers the EL libraries almost exclusively.

Core Actions

The JSTL core actions embody fundamental functionality that is implemented by many JSP pages. That functionality includes:

  • Send output to the current JspWriter

  • Create and destroy scoped variables

  • Manipulate JavaBeans component (bean) properties and collections

  • Manipulate entries in a map

  • Implement if/then constructs and switch statements

  • Handle exceptions

  • Iterate over data structures, integer values, or strings

  • Create URLs and import resources

  • Redirect servlet responses

The core JSTL actions are listed in Table 1.4.

Table 1.4. Core Actions

Action

Description

<c:catch>

Catches exceptions thrown in the action's body

<c:choose>

Chooses one of potentially many code fragments

<c:forEach>

Iterates over a collection of objects, or iterates a fixed number of times

<c:forTokens>

Iterates over tokens in a string

<c:if>

Conditionally performs some functionality

<c:import>

Imports a URL

<c: otherwise >

Specifies default functionality in a <c:choose> action

<c:out>

Sends output to the current JspWriter

<c:param>

Specifies a URL parameter for <c:import> or <c:url>

<c:redirect>

Redirects a response to a specified URL

<c:remove>

Removes a scoped variable

<c:set>

Creates a scoped variable

<c:url>

Creates a URL, with URL rewriting as appropriate

<c:when>

Specifies one of several conditions in a <c:choose> action

Until JSP 2.0 is finalized, the <c:out> action will probably be the most heavily used JSTL action. The <c:out> action evaluates an EL expression and sends the result to the current JspWriter ; for example, the following code fragment uses the <c:out> action to display the value of a request parameter named amount .

 <c:if test='${not empty param.amount}'>     <c:out value='${param.amount}'/> </c:if> 

In the preceding example, the <c:if> action evaluates an EL expression that tests to see whether a request parameter named amount exists and has a non- null value; [6] if it does, the <c:if> action evaluates its body content.

[6] See "The empty Operator" on page 60 for more information about the empty operator.

The JSP 2.0 specification incorporates the JSTL expression language, which means that JSP template text will accommodate EL expressions; so, for example, with JSP 2.0, you could rewrite the preceding code fragment like this:

 <%-- This code fragment will only work with JSP 2.0 --%>  <c:if test='${not empty param.amount}'>    ${param.amount} </c:if> 

In the preceding example, the <c:out> action is not needed because JSP 2.0 template text is JSTL-expression-aware.

There's a lot more to the Core library than evaluating expressions and displaying the result; for example, you can implement if/then statements and switch constructs. The following code fragment implements the former: if a request parameter named name exists and has a non- null value, the code prints a greeting; otherwise, it asks users to enter their name and includes a JSP page that contains a registration form.

 <html>     ...    <body>       <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %>  <c:choose>  <  c:when  test='${not empty param.name}'>             Hello <c:out value='${param.name}'/>.  </c:when>   <c:otherwise>  <font color='red'>                Please enter your name:<p>             </font>             <jsp:include page='index.jsp'/>  </c:otherwise>   </c:choose>  </body> </html> 

Besides handling exceptions with JSP's error page mechanism, you can use the <c:catch> action to catch an exception and deal with it in the same JSP page; for example, the following code fragment uses <c:catch> to catch an exception:

 <  c:catch  var='exception'>     <%-- Actions that could possibly throw exceptions... --%> </  c:catch  > <%-- If the exception scoped variable is not      empty, handle the exception here --%> <c:if test='  ${not empty exception}  '>    <%-- Display an error message --%> </c:if> 

If an exception is thrown within the <c:catch> body, the <c:catch> action stores that exception in a scoped variable. In the preceding code fragment, that exception, named exception , is accessed in the body of the <c:if> action.

JSTL also provides URL actions that simplify importing resources and creating URLs. For example, the <jsp:include> action can import resources, but only from the same Web application. The <c:import> action can do that too, but it can also import resources from absolute URLs and foreign contexts. [7] For example, the following code fragment imports content from an absolute URL:

[7] A foreign context is another Web application in a website.

 <c:import url='http://www.mysite.com/mydoc.txt'/> 

The following code fragment imports content from a resource in a foreign context (another Web application) on the same server.

 <c:import url='/jsp/test_2.jsp' context='/core-jstl'/> 

The preceding examples are just some of the things that the Core library actions can do. Chapters 3 “5 in this book discuss all of the Core library actions in detail.

Formatting Actions

The JSTL formatting actions let you internationalize your Web applications so you can easily localize them for different locales. You can:

  • Specify a resource bundle used to localize messages

  • Specify a locale used for formatting and parsing

  • Localize messages

  • Format and parse numbers, currencies, and percents

  • Format and parse dates

  • Set a request encoding

The formatting JSTL actions are listed in Table 1.5.

Table 1.5. Formatting Actions

Action

Description

<fmt:bundle>

Sets a localization context for enclosed <fmt:message> and formatting actions

<fmt:setBundle>

Sets a localization context for <fmt:message> and formatting actions

<fmt:setLocale>

Sets the locale used by <fmt:message> and formatting actions

<fmt:formatDate>

Formats a date in a locale-sensitive manner

<fmt:formatNumber>

Formats a number, currency, or percent in a locale-sensitive manner

<fmt:message>

Retrieves a message from a resource bundle

<fmt:param>

Supplies a parameter for an enclosing <fmt:message> action

<fmt:parseDate>

Parses a date in a locale-sensitive manner

<fmt:parseNumber>

Parses a number, currency, or percent in a locale-sensitive manner

<fmt:requestEncoding>

Sets the request encoding for a JSP page

<fmt:setTimeZone>

Sets the time zone used by date and time formatting actions

<fmt:timeZone>

Sets the time zone used by enclosed date and time formatting actions

The most heavily used action listed in Table 1.5 is undoubtedly <fmt:message>, which retrieves localized messages from a resource bundle; for example, the following code fragment uses <fmt:message> to display a company name and slogan :

 <html>  ...    <body>       <%-- Use <fmt:message> to display localized messages            from a resource bundle --%>       <font size='5'>  <fmt:message key='company.name'/>  </font>       <p>  <fmt:message key='company.slogan'/>  <hr>    </body> </html> 

The <fmt:message> action's mandatory key attribute specifies a key in a resource bundle; the <fmt:message> action retrieves the corresponding object ”typically a string ”associated with that key, coerces that object to a string, and sends it to the current JspWriter .

Besides localizing messages, the formatting actions also let you format and parse numbers, currencies, percents, dates, and times; for example, the following code fragment formats the current date and time for the U.S. English locale:

 <fmt:setLocale value='en-US'/>  <jsp:useBean id='today' class='java.util.Date'/> <fmt:formatDate value='${today}' type='both'/> 

The preceding code fragment sets the locale for formatting actions with <fmt:setLocale> and creates an instance of java.util.Date with <jsp:useBean>. That date is subsequently passed to <fmt:formatDate>, which formats both the date and time according to the locale set by <fmt:setLocale>.

SQL Actions

The JSTL SQL actions let you:

  • Specify a data source

  • Execute database queries and access the query result

  • Execute database updates and transactions

  • Execute prepared statements

The SQL JSTL actions are listed in Table 1.6.

Table 1.6. SQL Actions

Action

Description

<sql:dateParam>

Specifies a date parameter for <sql:query> or <sql:update>

<sql:param>

Specifies a parameter for <sql:query> or <sql:update>

<sql:query>

Executes a database query

<sql:setDataSource>

Sets a data source for <sql:query>, <sql:update>, and <sql:transaction> actions

<sql:transaction>

Wraps a transaction around enclosed <sql:query> and <sql:update> actions

<sql:update>

Executes a database update

On page 4, we saw how to execute database queries and iterate over the result. You can also use the SQL actions to perform database updates and execute transactions; for example: [8]

[8] See "Executing Database Transactions" on page 411 for a discussion of that code.

  <sql:transaction>  <%-- Withdraw money from the "from" customer's account --%>    <sql:update>       UPDATE ACCOUNTS SET BALANCE = BALANCE - ?  WHERE CUST_ID = ?       <sql:param value='${param.amount}'/>       <sql:param value='${param.fromCustomer}'/>  </sql:update>  <%-- Deposit the money withdrawn from the "from"         customer's account in the "to" customer's account --%>  <sql:update>  UPDATE ACCOUNTS SET BALANCE = BALANCE + ?  WHERE CUST_ID = ?       <sql:param value='${param.amount}'/>       <sql:param value='${param.toCustomer}'/>  </sql:update>   </sql:transaction>  

The preceding JSP page uses the <sql:transaction> action to perform a database transaction that consists of two database updates that transfer funds from one account to another.

XML Actions

The JSTL XML actions let you manipulate XML documents. Those actions offer the following functionality:

  • Parse an XML document

  • Transform an XML document with XSLT

  • Set a system ID for resolving external entities

  • Apply a SAX filter to an XML document

The XML actions are listed in Table 1.7.

Table 1.7. XML Actions

Action

Description

<x:choose>

XML version of <c:choose>

<x:forEach>

XML version of <c:forEach>

<x:if>

XML version of <c:if>

<x:otherwise>

XML version of <c:otherwise>

<x:out>

XML version of <c:out>

<x:param>

XML version of <c:param>; specifies a transformation parameter for an <x:transform> action

<x:parse>

Parses an XML document

<x:set>

XML version of <c:set>

<x:transform>

Transforms an XML document

<x:when>

XML version of <c:when>

Although there are many XML actions, all but two of those actions are XML versions of JSTL core actions. The core actions, such as <c:out>, <c:set> and <c:if>, accept EL expressions, whereas the corresponding XML actions, such as <x:out>, <x:set>, and <x:if>, accept XPath expressions. [9] The only two XML actions that are not XML versions of core actions ”<x:parse> and <x:transform> ”let you parse and transform XML documents.

[9] You can also use JSP expressions with the RT libraries; see "Twin Libraries" on page 9 for more information.

To get an idea of how to use the XML actions, let's parse a simple XML document and display the result. A partial listing of that XML document is listed below.

 <rolodex>     <contact>       <firstName>Anna</firstName>       <lastName>Keeney</lastName>       <email>anna.keeney@worldlink.net</email>       <phone type="work">716-873-9644</phone>       <phone type="home">716-834-8772</phone>    </contact>    ... </rolodex> 

The preceding XML document is a Rolodex that keeps track of a collection of contacts. For brevity, only the first entry in the Rolodex is listed above. The code fragment listed below parses that document and creates an HTML table that shows the data associated with each entry in the address book: [10]

[10] See " Parsing XML " on page 432 for more information about that code.

 <c:import var='rolodex_xml' url='rolodex.xml'/>  <  x:parse  var='document' xml='${rolodex_xml}'/> <table>    <  x:forEach  select='$document//contact'>       <table>          <tr><td>First Name:</td>              <td><  x:out  select='firstName'/></td></tr>          <tr><td>Last Name:</td>              <td><  x:out  select='lastName'/></td></tr>          <tr><td>Email:</td>              <td><  x:out  select='email'/></td></tr>          <tr><td>Work Phone:</td>              <td><x  :out  select='phone[@type="work"]'/></td></tr>          <  x:if  select='phone[@type="home"]'>             <tr><td>Home Phone:</td>                 <td><  x:out  select='phone[@type="home"]'/></td>          </x:if>       </table><br>    </x:forEach> </table> 

The preceding code fragment uses the <x:parse> action to parse the Rolodex XML document. Subsequently, it uses the <x:forEach>, <x:out>, and <x:if> actions to show the contacts in an HTML table; that output looks like this:

First Name:

Anna

Last Name:

Keeney

Email:

anna.keeney@worldlink.net

Work Phone:

716-873-9644

Home Phone:

716-834-8772

...

 
The JSTL Tag Library Validators

JSTL lets you eliminate almost all JSP scriptlets and expressions from your JSP code, which makes your code more maintainable and extensible. It will take some discipline on your part, however, to keep scriptlets and expressions out of your code; occasionally, you might have to implement a servlet or custom action to assist you in that endeavor.

Instead of relying on discipline to keep JSP scriptlets and expressions out of your code, you can use one of the JSTL tag library validators to enforce that restriction. That validator lets you allow or disallow the following:

  • JSP declarations

  • JSP expressions

  • JSP scriptlets

  • Runtime expression values

You don't have to write any code to use the JSTL validators, but you must create a tag library descriptor (TLD) because tag library validators are associated with a tag library; [11] for example, the following TLD specifies a validator element that disallows scriptlets:

[11] But validators have access to the entire JSP page, so they can perform general validation.

 <?xml version="1.0" encoding="ISO-8859-1"?>  <!DOCTYPE taglib PUBLIC   "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"   "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_2.dtd"> <taglib>    <tlib-version>1.0</tlib-version>    <jsp-version>1.2</jsp-version>    <short-name>Core JSTL Validation Example Tag</short-name>    <description>       This library has a validator that allows       JSP declarations, expressions, and       runtime expression values but disallows scriplets    </description>    <validator>       <validator-class>  javax.servlet.jsp.jstl.tlv.ScriptFreeTLV  </validator-class>       <init-param>          <param-name>  allowDeclarations  </param-name>          <param-value>  true  </param-value>       </init-param>       <init-param>          <param-name>  allowScriptlets  </param-name>          <param-value>  false  </param-value>       </init-param>       <init-param>          <param-name>  allowExpressions  </param-name>          <param-value>  true  </param-value>       </init-param>       <init-param>          <param-name>  allowRTExpressions  </param-name>          <param-value>  true  </param-value>       </init-param>    </validator>    <tag>       <name>DoNothingTag</name>       <tag-class>tags.DoNothingAction</tag-class>    </tag> </taglib> 

The other JSTL validator restricts the tag libraries that can be used in a JSP page; the following TLD lets you use only the JSTL core and formatting libraries:

 <?xml version="1.0" encoding="ISO-8859-1" ?>  <!DOCTYPE taglib PUBLIC   "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"   "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_2.dtd"> <taglib>    <tlib-version>1.0</tlib-version>    <jsp-version>1.2</jsp-version>    <short-name>Core JSTL Validation Example Tag</short-name>    <description>       This library has a validator that restricts the tag libraries       that a JSP developer can use    </description>    <validator>       <validator-class>  javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV  </validator-class>       <init-param>          <param-name>  permittedTaglibs  </param-name>          <param-value>             http://java.sun.com/jstl/core             http://java.sun.com/jstl/fmt          </param-value>       </init-param>    </validator>    <tag>       <name>DoNothingTag</name>       <tag-class>tags.DoNothingAction</tag-class>    </tag> </taglib> 

Notice that both of the preceding TLDs include a tag element because at least one tag element is required for each TLD. The name and tag-class elements are required for the tag element, so the preceding listing specifies those values. The tag class is a tag handler that, as its name suggests, does nothing; it looks like this:

 package tags;  import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class DoNothingAction extends TagSupport {    public int doStartTag() throws JspException {       return SKIP_BODY;    } } 

To use the validators, you simply add a taglib declaration at the top of your JSP pages, like this:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  <html>    <head>  <%@ taglib uri='WEB-INF/restrictJavaCode.tld' prefix='rjc' %>   <%@ taglib uri='WEB-INF/restrictTaglibs.tld'  prefix='rtl' %>  <%@ taglib uri='http://java.sun.com/jstl/fmt' prefix='fmt' %>       <title><fmt:message key='index.window-title'/></title>    </head>    <body>       <% new java.util.Date(); %>       <h2><fmt:message key='index.greeting'/></h2>    </body> </html> 

At translation time, the preceding JSP page will throw an exception because it has a scriptlet, which violates the first TLD declared in the page.

Now that you know what JSTL is and what it offers, let's get started by downloading and installing the necessary software and implementing a simple Web application that uses JSTL.

   


Core JSTL[c] Mastering the JSP Standard Tag Library
Core JSTL[c] Mastering the JSP Standard Tag Library
ISBN: 131001531
EAN: N/A
Year: 2005
Pages: 124

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