Introduction To JSTL
(Java Server Pages Tag
Library)
Author: Yuval Zilberstein,
yuvalzi@gmail.com
Advantages
• Avoid conflicts between jar versions (XML, JDBC
etc’)
• Eases page development for page authors
• Easy to rea...
Disadvantages
• Not as flexible as scriptlets
• May seem burdensome for experienced
programmers
• Not a general purpose pr...
Installing
• The following must be available in your project
– standard.jar
– jstl.jar
– web.xml
– DOCTYPE – Some containe...
Installing
• web.xml example
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, In...
EL Expression Language
• A data access language, that eases access to
application data.
• Allows page authors to access an...
Accessing Application Data
• EL expressions must be enclosed between ${ and }.
• ${data} – scoped variable data.
• The dot...
Operators
• The second version (in parenthesis) is to avoid the
use of entity references in XML syntax
Operator Descriptio...
Implicit Objects
Implicit Object Content
pageScope access to the scoped variables
requestScope access to the scoped variab...
Tag libraries
• There are two groups of twin tag libraries
– one that supports the expression language (EL)
– one that sup...
Tag libraries
• To use a JSTL library, you declare it:
– E.g.: <@ taglib prefix="c" uri="http://java.sun.com/jstl/core">
•...
The Core Tag Library
http://java.sun.com/jstl/core
The Core Tag Library
• Supports the following abilities
– Output
– Manipulation of scoped variables
– Conditional logic
– ...
General Purpose Tags
• <c:out> - writing data
• <c:set> - set the value of a scoped attribute
• <c:remove> - remove a scop...
General Purpose Tags
• Print with a default value:
– <c:out value="${customer.city}" default="unknown"/>
• Setting a varia...
Conditional Actions
• <c:if>
• If / then / else – Consists of the following
three tags:
– <c:choose>
– <c:when>
– <c:other...
Conditional Actions – E.g.
• <c:if> example:
– <c:if test="${customer.country == 'Canada'}">
This customer is based in Can...
Conditional Actions – E.g.
• <c:choose>
<c:when test="${customer.country == 'UK'}">
UK has mild winters.
</c:when>
<c:othe...
Iteration Actions - forEach
• <c:forEach> iteration over collection of
items.
• <c:forEach var="customer" items="${custome...
Iteration Actions - forEach
• E.g.: Print the headers
• <c:forEach var="head" items="${headerValues}">
param: <c:out value...
URL Actions
• <c:import> - import local and remote resources.
• As opposed to the standard jsp include action and
directiv...
URL Actions
• <c:url> - URL rewriting tasks.
• It can be combined with <c:param>, which encodes
query-string parameters.
•...
URL Actions
• <c:redirect> (to support HTTP redirect)
• <c:redirect url="https://www.somewhere.com/register">
The XML Tag Library
http://java.sun.com/jstl/xml
The XML Tag Library
• XML actions to address basic needs of page
authors.
• Support XPath expressions - Path
expressions t...
XML Core actions
• <x:out> - writing XML data
• <x:set> - set the value of an XML attribute
• <x:parse> - parse the docume...
XML Control Flow
• <x:if>
• If .. Then .. else
– <x:choose>
– <x:when>
– <x:otherwise>
• <x:forEach>
• Xml control flow ta...
XML control flow
• <x:parse xml="${xmldoc}" var="output"/>
----------------------------------------------------
• <x:if se...
XML control flow
<x:choose>
<x:when select="$output/portfolio/stock[price > '70']">
You still have stocks worth over $70.
...
Code Sample 1
<c:set var="xmltext">
<books>
<book>
<title>Book Title A</title>
<author>A. B. C.</author>
<price>17.95</pri...
Code Sample 2
http://www.javacourses.com/stocks
.xml<?xml version="1.0" encoding="UTF-8"?>
<portfolio>
<stock>
<symbol>SUN...
Code Sample 2
• Import the document from remote web
server :
– <c:import url="http://www.javacourses.com/stocks.xml" var="...
Code Sample 3: xml-ex2.jsp
<c:import url="http://www.javacourses.com/stocks.xml"
var="xmldoc"/>
<x:parse xml="${xmldoc}" v...
Transforming XML
• Supports XSLT to transform XML within
JSP pages
• The result of the transformation is written
to the pa...
Code Sample 5: xml-ex3.jsp
<h3>Transforming stocks.xml into HTML using stocks.xsl</h3>
<c:import url="http://www.javacours...
The SQL Tag Library
http://java.sun.com/jstl/sql
The SQL Tag Library
• For special and unique situations
• E.g.:
– prototyping/testing
– small scale/simple applications
– ...
The SQL Tag Library
• Perform database queries (select)
• Easily access query results
• Perform database updates (insert, ...
Data Source
• SQL actions operate on a data source
• Is specified by:
– dataSource attribute in SQL actions
– configuratio...
Querying a Database
• <sql:query>
Querying a Database
<sql:query var="customers" dataSource="${dataSource}">
SELECT * FROM customers
WHERE country = ’China’...
Querying a Database
<!-- column headers -->
<c:forEach var=”columnName” items=”${result.columnNames}”>
<c:out value="${col...
Updating a Database
• <sql:update>
Updating a Database
<sql:transaction dataSource="${dataSource}">
<sql:update>
UPDATE account
SET Balance = Balance - ?
WHE...
SQL Statement Parameters
• Implemented by
– <sql:query>
– <sql:update>
SQL Statement Parameters
<sql:update>
UPDATE PersonalInfo
SET BirthDate = ?
WHERE clientId = ?
<acme:dateParam year="${yea...
Database Access
• Implemented actions:
– <sql:query>
– <sql:update>
– <sql:transaction>
• DataSource attribute of the SQL ...
Database Access
• <sql:query>
• <sql:update>
• <sql:transaction>
• <sql:setDataSource>
• <sql:param>
• <sql:dateParam>
Configuration Settings
Developing and Using
Functions
Developing and Using Functions
• Define expression functions.
• Must be programmed as
– public static method
– public clas...
Developing and Using Functions
package jsp2.examples.el;
import java.util.*;
public class Compute {
public static int add(...
Developing and Using Functions
<function>
<description>add x and y</description>
<name>add</name>
<function-class>jsp2.exa...
Developing and Using Functions
<%@ taglib prefix="my" uri="http://jakarta.apache.org/tomcat/jsp2-example-
taglib %>
<BODY>...
Tag Handlers
Tag Handlers
• Simple Tag Extension
(JSP2.0/JSTL1.2)
– Java developers: implement
javax.servlet.jsp.tagext.SimpleTag
inter...
Implementing SimpleTag
• Implement
javax.servlet.jsp.tagext.Simpl
eTag interface.
• Define a tag descriptor in a TLD
• JSP...
Implementing SimpleTag
package jsp2.examples.simpletag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.ta...
Implementing SimpleTag
<tag>
<description>Prints this is my first tag</description>
<name>hello</name>
<tag-class>jsp2.exa...
Implementing SimpleTag
<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>
<HTML>
<HEAD>
<TITLE>Simpl...
Tag File
Tag File
• Make JSP code reusable
• Allow to create reusable tag libraries
• .tag extesion
Tag File
Hello there. How are you doing?
Tag File
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<HTML>
<HEAD>
<TITLE>JSP 2.0 Examples - Hello World Using a Ta...
Tag File Templates
• Can be used as a template.
Tag File Templates
• E.g. display.tag:
<%@ attribute name="color" %>
<%@ attribute name="bgcolor" %>
<%@ attribute name="t...
Tag File Templates
• E.g. newsportal.jsp
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<TABLE border="0">
<TR><TD>
<t...
I18N capable formatting tag
library
http://java.sun.com/jstl/fmt
Internationalization (i18n) Actions
I18N Key Concepts
• Three internationalization key concepts:
– Locale
• Language code (e.g. “ca” for Catalan, “zh” for Chi...
I18N Key Concepts
• E.g. basename Registration
• two resource bundles:
– Registration_fr (French language)
– Registration_...
<fmt:message>
• <fmt:message> - I18N a message
– <fmt:param> - Supports message variables.
<fmt:message>
<fmt:message key="greeting"/>
------------------------------------------------
---
<fmt:message key="athlete...
I18n Localization Context
• Localization context contains two pieces of information
– Resource bundle
– Locale for which t...
I18n Localization Context
<%-- Use configuration setting --%>
------------------------------------------------------------...
Preferred Locales
• Setting prefered locale by
– Application-based (priority)
•javax.servlet.jsp.jstl.fmt.locale
configura...
Preferred Locales
• <fmt:setLocale> - set
javax.servlet.jsp.jstl.fmt.loca
le configuration variable
– E.g.
•<fmt:setLocale...
Resource Bundle Lookup
• Searched in the following order:
– basename + "_" + language + "_" + country +
"_" + variant
– ba...
Resource Bundle Determination
Algorithm
• Step 1: Find a match within the ordered
set of preferred locales
• Step 2: Find ...
Response Encoding
• Set the locale
– <fmt:setLocale>
– <fmt:bundle>
– <fmt:message>
– formatting actions
• Set the encodin...
Commands Summary
• <fmt:setLocale> - stores the locale.
Disables Browser-based locale setting
capabilities.
• <fmt:bundle>...
Commands Summary
• <fmt:message>
• <fmt:param> - param to containing
<fmt:message>
• <fmt:requestEncoding> - character
enc...
Configuration Settings
Configuration Settings
Formatting Actions
Formatting Actions
• Format and parse elements in a locale-
sensitive or customized manner
Formatting Numbers, Currencies,
and Percentages
• <fmt:formatNumber> - format numbers,
currencies, and percentages accordi...
Formatting Dates and Times
• <jsp:useBean id="now"
class="java.util.Date" />
• <fmt:formatDate value=”${now}”
timeStyle="l...
Formatting Locale
• <jsp:useBean id="now" class="java.util.Date" />
• <%-- Formatting locale lookup --%>
• <fmt:formatDate...
Actions
• <fmt:timeZone>
• <fmt:timeZone value=”timeZone”>
• body content
• </fmt:timeZone>
• <fmt:setTimeZone>
• <fmt:set...
Configuration Settings
Functions
function tag library
Functions
• fn:contains
• fn:containsIgnoreCase
• fn:endsWith
• fn:escapeXml
• fn:indexOf
• fn:join
• fn:length
• fn:repla...
JSTL 1.2
• <c:forTokens>
• <x:param> - Set transformation
parameters.
Conclusion
• Simpler consistent programming
environment.
• Advanced programmers may prefer
scriptlets.
• JavaBeans are use...
For More Information
• Fast Track JSP 1.2
• JavaServer Pages Technology
• JavaServer Pages Specification (JSR 152)
• The T...
Upcoming SlideShare
Loading in...5
×

Jstl Guide

4,528

Published on

JSTL Tutorial

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,528
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
242
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • Avoid conflicts between jar versions (XML, JDBC etc’)
    Eases Web page Development
    Open Source Extensions
    Easy to read and maintain
    Reuse Valuable Components and Reusable standard tags
    Eases packaging of the application - Searches for the tld’s in several places (tld, META-INF)
    Eases Database Access
    As a matter of practice, a JSP page should be a view page, it should not have Java code embedded in scriptlets. This aids in separation of concerns. A JSP page can use JSTL elements for common tasks like conditional processing, database access, internationalization and more.
    Database access can be controlled using an data-sources.xml file
    The idea is that once the libraries are installed correctly, the page is dead-simple to put together.
  • It is important to have a DOCTYPE element to a
  • JSTL is not a general purpose programming language.
    Is simply a data access language, which makes it possible to easily access application data.
    JSTL allows page authors to access an object using a simplified syntax.
    &amp;lt;someTags:aTag attribute=&amp;quot;${aName}&amp;quot;&amp;gt;
    &amp;lt;someTags.aTag attribute=&amp;quot;${aCustomer.address.country}&amp;quot;&amp;gt;
  • As a property of an object, using the dot (.) operator
    As named array element using the bracket [&amp;apos;name&amp;apos;] operator.
    E.g. ${data} – scoped variable data.
    The dot (.) operator is used to retrieve a named property.
    ${customer.name}
    The bracket operator ([]) can be used to retrieve a named property.
    ${customer[&amp;quot;name&amp;quot;]}.
    ${customers[0]}
    ${customer.name} is equivalent to ${customer[&amp;quot;name&amp;quot;]}.
    All EL expressions must be enclosed between ${ and }.
    EL evaluates an identifier by using PageContext.findAttribute(String).
  • Supports output, manipulation of scoped variables, conditional logic, loops, URL manipulation, and error handling.
  • &amp;lt;c:out&amp;gt; - writing data
    &amp;lt;c:set&amp;gt; - set the value of a scoped attribute
    &amp;lt;c:remove&amp;gt; - remove a scoped variable.
    &amp;lt;c:catch&amp;gt; - handling errors. See the next setion for an example
  • jsp include action and directive does not allow include of remote resources
  • XML is becoming increasingly important to page authors, and the JSTL provides XML actions that address the basic needs of those developers. The XML actions can be divided into core, control flow, and transformation actions. The XML core actions are similar to those provided in the core actions discussed above, and include &amp;lt;x:out&amp;gt;, &amp;lt;x:set&amp;gt;, and &amp;lt;x:parse&amp;gt;. The main difference between the core actions discussed above and the XML core actions is that XML actions support XPath expressions, while the core actions do not. As a matter of fact, the XML actions are based on XPath expressions. If you&amp;apos;re unfamiliar with XPath, it&amp;apos;s a language for defining parts of an XML document; XPath uses path expressions to identify nodes in an XML document.
  • XML Core - similar to the basic core actions
    &amp;lt;x:out&amp;gt;
    &amp;lt;x:set&amp;gt;
    and &amp;lt;x:parse&amp;gt;
    XML Control Flow
  • You can implement an if/then/else clause using the &amp;lt;x:choose&amp;gt; action, which selects one among a number of possible alternatives. It consists of a sequence of &amp;lt;x:when&amp;gt; elements, followed by an optional &amp;lt;x:otherwise&amp;gt;. Each &amp;lt;x:when&amp;gt; element has a single attribute, select, that specifies an XPath expression. When a &amp;lt;x:choose&amp;gt; element is processed, each of the &amp;lt;x:when&amp;gt; elements has its expressions evaluated in turn. Only the body of the first &amp;lt;x:when&amp;gt; element (whose result is true) is rendered. If none of the test conditions of nested tags evaluates to true, the body of the &amp;lt;x:otherwise&amp;gt; tag is evaluated, if present.
    Here is an example:
    &amp;lt;x:parse xml=&amp;quot;${xmldoc}&amp;quot; var=&amp;quot;output&amp;quot;/&amp;gt;
    &amp;lt;x:choose&amp;gt;
    &amp;lt;x:when select=&amp;quot;$output/portfolio/stock[price &amp;gt; &amp;apos;70&amp;apos;]&amp;quot;&amp;gt;
    You still have stocks worth over $70.
    &amp;lt;/x:when&amp;gt;
    &amp;lt;x:otherwise&amp;gt;
    You have no stocks worth over $70.
    &amp;lt;/x:otherwise&amp;gt;
    &amp;lt;/x:choose&amp;gt;
    -----------------------------------------------------------
    The &amp;lt;x:forEach&amp;gt; action evaluates the given XPath expression, and iterates over the result.
    E.g. Print stock information from an XML document.
    &amp;lt;x:parse xml=&amp;quot;${xmldoc}&amp;quot; var=&amp;quot;output&amp;quot;/&amp;gt;
    &amp;lt;x:forEach select=&amp;quot;$output/portfolio/stock&amp;quot; var=&amp;quot;item&amp;quot;&amp;gt;
    &amp;lt;x:out select=&amp;quot;symbol&amp;quot;/&amp;gt;
    &amp;lt;x:out select=&amp;quot;name&amp;quot;/&amp;gt;
    &amp;lt;x:out select=&amp;quot;price&amp;quot;/&amp;gt;
    &amp;lt;/x:forEach&amp;gt;
  • parses an XML document, then selects (using an XPath expression) the stock with the symbol SUNW &amp;lt;x:parse xml=&amp;quot;${xmldoc}&amp;quot; var=&amp;quot;output&amp;quot;/&amp;gt;
    &amp;lt;x:if select=&amp;quot;$output/portfolio/stock[symbol = &amp;apos;SUNW&amp;apos;]&amp;quot;&amp;gt;
    You still have Microsystems Stocks!
    &amp;lt;/x:if&amp;gt;
    --------------------------------------------------------------------
    &amp;lt;x:forEach select=&amp;quot;$output/portfolio/stock&amp;quot;&amp;gt;
    &amp;lt;x:out select=&amp;quot;price&amp;quot;/&amp;gt;
    &amp;lt;/x:forEach&amp;gt;
    --------------------------------------------------------------------
  • Many web applications use XSLT stylesheets to transform XML within JSP pages, and the JSTL supports this. The XML document to be transformed, as well as the XSLT stylesheet to be used, can be retrieved from a relative, absolute, or remote URL. The result of the transformation is written to the page. As an example, the stocks.xml document shown in Code Sample 2 (which is located at a remote web server) is transformed using the XSLT stylesheet (stocks.xsl) shown in Code Sample 4 but fetched from a local web server:
    Code Sample 4: stocks.xsl
    &amp;lt;?xml version=&amp;quot;1.0&amp;quot;?&amp;gt; &amp;lt;xsl:stylesheet xmlns:xsl= &amp;quot;http://www.w3.org/1999/XSL/Transform&amp;quot; version=&amp;quot;1.0&amp;quot;&amp;gt; &amp;lt;xsl:output method=&amp;quot;html&amp;quot; indent=&amp;quot;yes&amp;quot;/&amp;gt; &amp;lt;xsl:template match=&amp;quot;/&amp;quot;&amp;gt; &amp;lt;html&amp;gt; &amp;lt;body&amp;gt; &amp;lt;xsl:apply-templates/&amp;gt; &amp;lt;/body&amp;gt; &amp;lt;/html&amp;gt; &amp;lt;/xsl:template&amp;gt; &amp;lt;xsl:template match=&amp;quot;portfolio&amp;quot;&amp;gt; &amp;lt;table border=&amp;quot;2&amp;quot; width=&amp;quot;50%&amp;quot;&amp;gt; &amp;lt;xsl:for-each select=&amp;quot;stock&amp;quot;&amp;gt; &amp;lt;tr&amp;gt; &amp;lt;td&amp;gt; &amp;lt;i&amp;gt;&amp;lt;xsl:value-of select=&amp;quot;symbol&amp;quot;/&amp;gt;&amp;lt;/i&amp;gt; &amp;lt;/td&amp;gt; &amp;lt;td&amp;gt; &amp;lt;xsl:value-of select=&amp;quot;name&amp;quot;/&amp;gt; &amp;lt;/td&amp;gt; &amp;lt;td&amp;gt; &amp;lt;xsl:value-of select=&amp;quot;price&amp;quot;/&amp;gt; &amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt; &amp;lt;/xsl:for-each&amp;gt; &amp;lt;/table&amp;gt; &amp;lt;/xsl:template&amp;gt; &amp;lt;/xsl:stylesheet&amp;gt; The following example, xml-ex3.jsp (shown in Code Sample 5) demonstrates how to transform an XML document located on a remote web server using the stocks.xsl stylesheet shown in Code Sample 4.
    Code Sample 5: xml-ex3.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;c&amp;quot; uri=&amp;quot;http://java.sun.com/jstl/core&amp;quot; %&amp;gt; &amp;lt;%@ taglib prefix=&amp;quot;x&amp;quot; uri=&amp;quot;http://java.sun.com/jstl/xml&amp;quot; %&amp;gt; &amp;lt;html&amp;gt; &amp;lt;head&amp;gt; &amp;lt;title&amp;gt;JSTL: Importing XML Document&amp;lt;/title&amp;gt; &amp;lt;/head&amp;gt; &amp;lt;body bgcolor=&amp;quot;#FFFFCC&amp;quot;&amp;gt; &amp;lt;h3&amp;gt;Transforming stocks.xml into HTML using stocks.xsl&amp;lt;/h3&amp;gt; &amp;lt;c:import url=&amp;quot;http://www.javacourses.com/stocks.xml&amp;quot; var=&amp;quot;xmldocument&amp;quot;/&amp;gt; &amp;lt;c:import url=&amp;quot;./stocks.xsl&amp;quot; var=&amp;quot;xslt&amp;quot;/&amp;gt; &amp;lt;x:transform xml=&amp;quot;${xmldocument}&amp;quot; xslt=&amp;quot;${xslt}&amp;quot;/&amp;gt; &amp;lt;/body&amp;gt; &amp;lt;/html&amp;gt; When you load xml-ex3.jsp, you should see something in the browser similar to Figure 3.
    Figure 3: Transforming an XML document using an XSLT stylesheet
  • Many web applications need to access relational databases as the source of dynamic
    data for their presentation layer. While it is generally preferred to have database
    operations handled within the business logic of a web application designed with an
    MVC architecture, there are situations where page authors require this capability
    within their JSP pages (e.g. prototyping/testing, small scale/simple applications,
    lack of developer resources).
    The JSTL SQL actions provide the basic capabilities to easily interact with relational
    databases.
  • The JSTL SQL actions allow page authors to:
    ■ Perform database queries (select)
    ■ Easily access query results
    ■ Perform database updates (insert, update, delete)
    ■ Group several database operations into a transaction
  • SQL actions operate on a data source, as defined by the Java class
    javax.sql.DataSource. A DataSource object provides connections to the
    physical data source it represents. Within the context of a Connection retrieved
    from the DataSource, SQL statements are executed and results are returned.
    A data source can be specified explicitly via the dataSource attribute in SQL
    actions, or it can be totally transparent to a page author by taking advantage of the
    data source configuration setting (javax.servlet.jsp.jstl.sql.dataSource).
    There are two ways a data source can be specified as a string.
    The first way is through a JNDI relative path, assuming a container supporting
    JNDI. For example, with the absolute JNDI resource path java:comp/env/jdbc/
    myDatabase, the JNDI relative path to the data source resource would simply be
    jdbc/myDatabase, given that java:comp/env is the standard JNDI root for a
    J2EE application.
    The second way is by specifying the parameters needed by the JDBC
    DriverManager class, using the following syntax (see Section 10.6 for details on the
    JDBC parameters)
    url[,[driver][,[user][,password]]]
    For example,
    jdbc:mysql://localhost/,org.gjt.mm.mysql.Driver
    where the database has been setup for access without any username or password. If
    the ‘,’ character occurs in any of the JDBC parameters, it can be escaped by ‘’. The
    character ‘’ itself can be escaped in the same way.
    While the JDBC DriverManager class provides a low cost way to use SQL actions,
    it is not recommended to use it other than for prototyping purposes because it does
    not provide connection management features one can expect from a properly
    designed DataSource object.
  • The most common use of the database actions is to query a database and display the
    results of the query.
    The following sample code selects all customers from China from the customers
    table in the database, orders them by last name, and finally displays their last name,
    first name, and address in an HTML table.
    &amp;lt;sql:query var=&amp;quot;customers&amp;quot; dataSource=&amp;quot;${dataSource}&amp;quot;&amp;gt;
    SELECT * FROM customers
    WHERE country = ’China’
    ORDER BY lastname
    &amp;lt;/sql:query&amp;gt;
    &amp;lt;table&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;row&amp;quot; items=&amp;quot;${customers.rows}&amp;quot;&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.lastName}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.firstName}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.address}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/table&amp;gt;
    This next example shows a generic way to display the results of a query with
    column names as headers:
    &amp;lt;table&amp;gt;
    &amp;lt;!-- column headers --&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;c:forEach var=”columnName” items=”${result.columnNames}”&amp;gt;
    &amp;lt;th&amp;gt;&amp;lt;c:out value=&amp;quot;${columnName}&amp;quot;/&amp;gt;&amp;lt;/th&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;!-- column data --&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;row&amp;quot; items=&amp;quot;${result.rowsByIndex}&amp;quot;&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;column&amp;quot; items=&amp;quot;${row}&amp;quot;&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${column}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/table&amp;gt;
  • The most common use of the database actions is to query a database and display the
    results of the query.
    The following sample code selects all customers from China from the customers
    table in the database, orders them by last name, and finally displays their last name,
    first name, and address in an HTML table.
    &amp;lt;sql:query var=&amp;quot;customers&amp;quot; dataSource=&amp;quot;${dataSource}&amp;quot;&amp;gt;
    SELECT * FROM customers
    WHERE country = ’China’
    ORDER BY lastname
    &amp;lt;/sql:query&amp;gt;
    &amp;lt;table&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;row&amp;quot; items=&amp;quot;${customers.rows}&amp;quot;&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.lastName}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.firstName}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.address}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/table&amp;gt;
    This next example shows a generic way to display the results of a query with
    column names as headers:
    &amp;lt;table&amp;gt;
    &amp;lt;!-- column headers --&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;c:forEach var=”columnName” items=”${result.columnNames}”&amp;gt;
    &amp;lt;th&amp;gt;&amp;lt;c:out value=&amp;quot;${columnName}&amp;quot;/&amp;gt;&amp;lt;/th&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;!-- column data --&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;row&amp;quot; items=&amp;quot;${result.rowsByIndex}&amp;quot;&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;column&amp;quot; items=&amp;quot;${row}&amp;quot;&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${column}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/table&amp;gt;
  • The most common use of the database actions is to query a database and display the
    results of the query.
    The following sample code selects all customers from China from the customers
    table in the database, orders them by last name, and finally displays their last name,
    first name, and address in an HTML table.
    &amp;lt;sql:query var=&amp;quot;customers&amp;quot; dataSource=&amp;quot;${dataSource}&amp;quot;&amp;gt;
    SELECT * FROM customers
    WHERE country = ’China’
    ORDER BY lastname
    &amp;lt;/sql:query&amp;gt;
    &amp;lt;table&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;row&amp;quot; items=&amp;quot;${customers.rows}&amp;quot;&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.lastName}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.firstName}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${row.address}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/table&amp;gt;
    This next example shows a generic way to display the results of a query with
    column names as headers:
    &amp;lt;table&amp;gt;
    &amp;lt;!-- column headers --&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;c:forEach var=”columnName” items=”${result.columnNames}”&amp;gt;
    &amp;lt;th&amp;gt;&amp;lt;c:out value=&amp;quot;${columnName}&amp;quot;/&amp;gt;&amp;lt;/th&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;!-- column data --&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;row&amp;quot; items=&amp;quot;${result.rowsByIndex}&amp;quot;&amp;gt;
    &amp;lt;tr&amp;gt;
    &amp;lt;c:forEach var=&amp;quot;column&amp;quot; items=&amp;quot;${row}&amp;quot;&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;c:out value=&amp;quot;${column}&amp;quot;/&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/tr&amp;gt;
    &amp;lt;/c:forEach&amp;gt;
    &amp;lt;/table&amp;gt;
  • Updating a Database
    The &amp;lt;sql:update&amp;gt; action updates a database. To ensure database integrity, several
    updates to a database may be grouped into a transaction by nesting the
    &amp;lt;sql:update&amp;gt; actions inside a &amp;lt;sql:transaction&amp;gt; action.
    For example, the following code transfers money between two accounts in one
    transaction:
    &amp;lt;sql:transaction dataSource=&amp;quot;${dataSource}&amp;quot;&amp;gt;
    &amp;lt;sql:update&amp;gt;
    UPDATE account
    SET Balance = Balance - ?
    WHERE accountNo = ?
    &amp;lt;sql:param value=&amp;quot;${transferAmount}&amp;quot;/&amp;gt;
    &amp;lt;sql:param value=&amp;quot;${accountFrom}&amp;quot;/&amp;gt;
    &amp;lt;/sql:update&amp;gt;
    &amp;lt;sql:update&amp;gt;
    UPDATE account
    SET Balance = Balance + ?
    WHERE accountNo = ?
    &amp;lt;sql:param value=&amp;quot;${transferAmount}&amp;quot;/&amp;gt;
    &amp;lt;sql:param value=&amp;quot;${accountTo}&amp;quot;/&amp;gt;
    &amp;lt;/sql:update&amp;gt;
    &amp;lt;/sql:transaction&amp;gt;
  • Updating a Database
    The &amp;lt;sql:update&amp;gt; action updates a database. To ensure database integrity, several
    updates to a database may be grouped into a transaction by nesting the
    &amp;lt;sql:update&amp;gt; actions inside a &amp;lt;sql:transaction&amp;gt; action.
    For example, the following code transfers money between two accounts in one
    transaction:
    &amp;lt;sql:transaction dataSource=&amp;quot;${dataSource}&amp;quot;&amp;gt;
    &amp;lt;sql:update&amp;gt;
    UPDATE account
    SET Balance = Balance - ?
    WHERE accountNo = ?
    &amp;lt;sql:param value=&amp;quot;${transferAmount}&amp;quot;/&amp;gt;
    &amp;lt;sql:param value=&amp;quot;${accountFrom}&amp;quot;/&amp;gt;
    &amp;lt;/sql:update&amp;gt;
    &amp;lt;sql:update&amp;gt;
    UPDATE account
    SET Balance = Balance + ?
    WHERE accountNo = ?
    &amp;lt;sql:param value=&amp;quot;${transferAmount}&amp;quot;/&amp;gt;
    &amp;lt;sql:param value=&amp;quot;${accountTo}&amp;quot;/&amp;gt;
    &amp;lt;/sql:update&amp;gt;
    &amp;lt;/sql:transaction&amp;gt;
  • SQL Statement Parameters
    The JSTL database actions support substituting parameter values for parameter
    markers (“?”) in SQL statements (as shown in the previous example). This form of
    parametric replacement is exposed by the SQLExecutionTag interface (see
    Section 10.10).
    The SQLExecutionTag interface is implemented by the tag handlers for
    &amp;lt;sql:query&amp;gt; and &amp;lt;sql:update&amp;gt;. It is exposed in order to support custom parameter
    actions. These custom actions may retrieve their parameters from any source and
    process them before substituting them for a parameter marker in the SQL statement
    of the enclosing SQLExecutionTag action.
    For example, a GUI front end may have a user enter a date as three separate fields
    (year, month, and day), and use this information in a database query. If the database
    table being accessed provides only a single column for the complete date, action
    &amp;lt;acme:dateParam&amp;gt; could assemble the three separate input parameters into one and
    pass it to the addSQLParameter() method of its enclosing SQLExecutionTag
    action:
    &amp;lt;sql:update&amp;gt;
    UPDATE PersonalInfo
    SET BirthDate = ?
    WHERE clientId = ?
    &amp;lt;acme:dateParam year=&amp;quot;${year}&amp;quot; month=&amp;quot;${month}&amp;quot; day=&amp;quot;${day}&amp;quot;/&amp;gt;
    &amp;lt;sql:param value=”${clientId}”/&amp;gt;
    &amp;lt;/sql:update&amp;gt;
    The JSTL formatting tags may be used to parse the string representation of dates and
    numbers into instances of java.util.Date and java.lang.Number, respectively,
    before supplying them to an enclosing SQLExecutionTag for parametric
    replacement:
    &amp;lt;sql:update sql=&amp;quot;${sqlUpdateStmt}” dataSource=&amp;quot;${dataSource}&amp;quot;&amp;gt;
    &amp;lt;fmt:parseDate var=&amp;quot;myDate&amp;quot; value=&amp;quot;${someDate}”/&amp;gt;
    &amp;lt;sql:param value=&amp;quot;${myDate}&amp;quot;/&amp;gt;
    &amp;lt;/sql:update&amp;gt;
  • SQL Statement Parameters
    The JSTL database actions support substituting parameter values for parameter
    markers (“?”) in SQL statements (as shown in the previous example). This form of
    parametric replacement is exposed by the SQLExecutionTag interface (see
    Section 10.10).
    The SQLExecutionTag interface is implemented by the tag handlers for
    &amp;lt;sql:query&amp;gt; and &amp;lt;sql:update&amp;gt;. It is exposed in order to support custom parameter
    actions. These custom actions may retrieve their parameters from any source and
    process them before substituting them for a parameter marker in the SQL statement
    of the enclosing SQLExecutionTag action.
    For example, a GUI front end may have a user enter a date as three separate fields
    (year, month, and day), and use this information in a database query. If the database
    table being accessed provides only a single column for the complete date, action
    &amp;lt;acme:dateParam&amp;gt; could assemble the three separate input parameters into one and
    pass it to the addSQLParameter() method of its enclosing SQLExecutionTag
    action:
    &amp;lt;sql:update&amp;gt;
    UPDATE PersonalInfo
    SET BirthDate = ?
    WHERE clientId = ?
    &amp;lt;acme:dateParam year=&amp;quot;${year}&amp;quot; month=&amp;quot;${month}&amp;quot; day=&amp;quot;${day}&amp;quot;/&amp;gt;
    &amp;lt;sql:param value=”${clientId}”/&amp;gt;
    &amp;lt;/sql:update&amp;gt;
    The JSTL formatting tags may be used to parse the string representation of dates and
    numbers into instances of java.util.Date and java.lang.Number, respectively,
    before supplying them to an enclosing SQLExecutionTag for parametric
    replacement:
    &amp;lt;sql:update sql=&amp;quot;${sqlUpdateStmt}” dataSource=&amp;quot;${dataSource}&amp;quot;&amp;gt;
    &amp;lt;fmt:parseDate var=&amp;quot;myDate&amp;quot; value=&amp;quot;${someDate}”/&amp;gt;
    &amp;lt;sql:param value=&amp;quot;${myDate}&amp;quot;/&amp;gt;
    &amp;lt;/sql:update&amp;gt;
  • Database Access
    This section describes the algorithm used by the SQL actions (&amp;lt;sql:query&amp;gt;,
    &amp;lt;sql:update&amp;gt;, &amp;lt;sql:transaction&amp;gt;) to access a database.
    Try to get a reference to a data source as follows:
    If the attribute dataSource is specified, use the value specified for that
    attribute as the data source.
    Otherwise, get the configuration setting associated with
    javax.servlet.jsp.jstl.sql.dataSource using Config.find() (see
    Section 2.8). Use the value found as the data source if it is not null.
    If a data source is obtained from the previous step:
    If it is a DataSource object, this is the data source used by the action to access
    the database.
    Otherwise, if it is a String:
    Assume this is a JNDI relative path and retrieve the data source from the
    container’s JNDI naming context by concatenating the specified relative path
    to the J2EE defined root (java:comp/env/).
    If the previous step fails (data source not found), assume the string specifies
    JDBC parameters using the syntax described in Section 10.1.1 and do as
    follows:
    If driver is specified, ensure it is loaded
    Access the named URL through the DriverManager class, using an
    empty string for user or password if they are not specified.
    If the previous step fails, throw an exception.
    Otherwise, throw an exception.
    An implementation need not create new objects each time a SQL action is called and
    the algorithm above does not yield a DataSource object directly; i.e when a JNDI
    path or parameters for the JDBC DriverManager class are used. It may reuse
    objects that it previously created for identical arguments.
  • Developing and Using Functions
    The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD).
    To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns their sum.
    Code Sample 3: Compute.java
    package jsp2.examples.el;
    import java.util.*;
    public class Compute {
    public static int add(String x, String y) {
    int a = 0;
    int b = 0;
    try {
    a = Integer.parseInt(x);
    b = Integer.parseInt(y);
    }
    catch(Exception e) {
    }
    return a + b;
    }
    }
    Once this is successfully compiled using javac, the next step is to map the function&amp;apos;s signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will tell you where to add this later.
    Code Sample 4: Function Descriptor
    &amp;lt;function&amp;gt;
    &amp;lt;description&amp;gt;add x and y&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;add&amp;lt;/name&amp;gt;
    &amp;lt;function-class&amp;gt;jsp2.examples.el.Compute &amp;lt;/function-class&amp;gt;
    &amp;lt;function-signature&amp;gt;int add(java.lang.String,java.lang.String) &amp;lt;/function-signature&amp;gt;
    &amp;lt;/function&amp;gt;
    Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the &amp;quot;Add Numbers&amp;quot; button is clicked, the function is called to add the numbers. The result is displayed on the same page.
    Code Sample 5: math.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;my&amp;quot; uri=&amp;quot;http://jakarta.apache.org/tomcat/jsp2-example-taglib %&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Functions&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H3&amp;gt;Add Numbers&amp;lt;/H3&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;FORM action=&amp;quot;/developer/technicalArticles/javaserverpages/JSP20/math.jsp&amp;quot; method=&amp;quot;GET&amp;quot;&amp;gt;
    X = &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;x&amp;quot; value=&amp;quot;${param[&amp;quot;x&amp;quot;]}&amp;quot;&amp;gt;
    &amp;lt;BR&amp;gt;
    Y = &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;y&amp;quot; value=&amp;quot;${param[&amp;quot;y&amp;quot;]}&amp;quot;&amp;gt;
    &amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Add Numbers&amp;quot;&amp;gt;
    &amp;lt;/FORM&amp;gt;
    &amp;lt;P&amp;gt;
    The sum is: ${my:add(param[&amp;quot;x&amp;quot;],param[&amp;quot;y&amp;quot;])}
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy Compute.java and save it at: C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplesel
    Compile Compute.java using javac
    Edit the file C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld and append the snippet of code in Code Sample 4 after the last &amp;lt;/function&amp;gt; in the file and before &amp;lt;/taglib&amp;gt;
    Copy math.jsp to c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the jsp file math.jsp from a web browser
    If all goes well, you should see something similar to Figure 3.
    Figure 3: Using Functions
  • Developing and Using Functions
    The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD).
    To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns their sum.
    Code Sample 3: Compute.java
    package jsp2.examples.el;
    import java.util.*;
    public class Compute {
    public static int add(String x, String y) {
    int a = 0;
    int b = 0;
    try {
    a = Integer.parseInt(x);
    b = Integer.parseInt(y);
    }
    catch(Exception e) {
    }
    return a + b;
    }
    }
    Once this is successfully compiled using javac, the next step is to map the function&amp;apos;s signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will tell you where to add this later.
    Code Sample 4: Function Descriptor
    &amp;lt;function&amp;gt;
    &amp;lt;description&amp;gt;add x and y&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;add&amp;lt;/name&amp;gt;
    &amp;lt;function-class&amp;gt;jsp2.examples.el.Compute &amp;lt;/function-class&amp;gt;
    &amp;lt;function-signature&amp;gt;int add(java.lang.String,java.lang.String) &amp;lt;/function-signature&amp;gt;
    &amp;lt;/function&amp;gt;
    Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the &amp;quot;Add Numbers&amp;quot; button is clicked, the function is called to add the numbers. The result is displayed on the same page.
    Code Sample 5: math.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;my&amp;quot; uri=&amp;quot;http://jakarta.apache.org/tomcat/jsp2-example-taglib %&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Functions&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H3&amp;gt;Add Numbers&amp;lt;/H3&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;FORM action=&amp;quot;/developer/technicalArticles/javaserverpages/JSP20/math.jsp&amp;quot; method=&amp;quot;GET&amp;quot;&amp;gt;
    X = &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;x&amp;quot; value=&amp;quot;${param[&amp;quot;x&amp;quot;]}&amp;quot;&amp;gt;
    &amp;lt;BR&amp;gt;
    Y = &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;y&amp;quot; value=&amp;quot;${param[&amp;quot;y&amp;quot;]}&amp;quot;&amp;gt;
    &amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Add Numbers&amp;quot;&amp;gt;
    &amp;lt;/FORM&amp;gt;
    &amp;lt;P&amp;gt;
    The sum is: ${my:add(param[&amp;quot;x&amp;quot;],param[&amp;quot;y&amp;quot;])}
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy Compute.java and save it at: C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplesel
    Compile Compute.java using javac
    Edit the file C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld and append the snippet of code in Code Sample 4 after the last &amp;lt;/function&amp;gt; in the file and before &amp;lt;/taglib&amp;gt;
    Copy math.jsp to c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the jsp file math.jsp from a web browser
    If all goes well, you should see something similar to Figure 3.
    Figure 3: Using Functions
  • Developing and Using Functions
    The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD).
    To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns their sum.
    Code Sample 3: Compute.java
    package jsp2.examples.el;
    import java.util.*;
    public class Compute {
    public static int add(String x, String y) {
    int a = 0;
    int b = 0;
    try {
    a = Integer.parseInt(x);
    b = Integer.parseInt(y);
    }
    catch(Exception e) {
    }
    return a + b;
    }
    }
    Once this is successfully compiled using javac, the next step is to map the function&amp;apos;s signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will tell you where to add this later.
    Code Sample 4: Function Descriptor
    &amp;lt;function&amp;gt;
    &amp;lt;description&amp;gt;add x and y&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;add&amp;lt;/name&amp;gt;
    &amp;lt;function-class&amp;gt;jsp2.examples.el.Compute &amp;lt;/function-class&amp;gt;
    &amp;lt;function-signature&amp;gt;int add(java.lang.String,java.lang.String) &amp;lt;/function-signature&amp;gt;
    &amp;lt;/function&amp;gt;
    Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the &amp;quot;Add Numbers&amp;quot; button is clicked, the function is called to add the numbers. The result is displayed on the same page.
    Code Sample 5: math.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;my&amp;quot; uri=&amp;quot;http://jakarta.apache.org/tomcat/jsp2-example-taglib %&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Functions&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H3&amp;gt;Add Numbers&amp;lt;/H3&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;FORM action=&amp;quot;/developer/technicalArticles/javaserverpages/JSP20/math.jsp&amp;quot; method=&amp;quot;GET&amp;quot;&amp;gt;
    X = &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;x&amp;quot; value=&amp;quot;${param[&amp;quot;x&amp;quot;]}&amp;quot;&amp;gt;
    &amp;lt;BR&amp;gt;
    Y = &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;y&amp;quot; value=&amp;quot;${param[&amp;quot;y&amp;quot;]}&amp;quot;&amp;gt;
    &amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Add Numbers&amp;quot;&amp;gt;
    &amp;lt;/FORM&amp;gt;
    &amp;lt;P&amp;gt;
    The sum is: ${my:add(param[&amp;quot;x&amp;quot;],param[&amp;quot;y&amp;quot;])}
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy Compute.java and save it at: C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplesel
    Compile Compute.java using javac
    Edit the file C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld and append the snippet of code in Code Sample 4 after the last &amp;lt;/function&amp;gt; in the file and before &amp;lt;/taglib&amp;gt;
    Copy math.jsp to c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the jsp file math.jsp from a web browser
    If all goes well, you should see something similar to Figure 3.
    Figure 3: Using Functions
  • Developing and Using Functions
    The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD).
    To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns their sum.
    Code Sample 3: Compute.java
    package jsp2.examples.el;
    import java.util.*;
    public class Compute {
    public static int add(String x, String y) {
    int a = 0;
    int b = 0;
    try {
    a = Integer.parseInt(x);
    b = Integer.parseInt(y);
    }
    catch(Exception e) {
    }
    return a + b;
    }
    }
    Once this is successfully compiled using javac, the next step is to map the function&amp;apos;s signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will tell you where to add this later.
    Code Sample 4: Function Descriptor
    &amp;lt;function&amp;gt;
    &amp;lt;description&amp;gt;add x and y&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;add&amp;lt;/name&amp;gt;
    &amp;lt;function-class&amp;gt;jsp2.examples.el.Compute &amp;lt;/function-class&amp;gt;
    &amp;lt;function-signature&amp;gt;int add(java.lang.String,java.lang.String) &amp;lt;/function-signature&amp;gt;
    &amp;lt;/function&amp;gt;
    Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the &amp;quot;Add Numbers&amp;quot; button is clicked, the function is called to add the numbers. The result is displayed on the same page.
    Code Sample 5: math.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;my&amp;quot; uri=&amp;quot;http://jakarta.apache.org/tomcat/jsp2-example-taglib %&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Functions&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H3&amp;gt;Add Numbers&amp;lt;/H3&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;FORM action=&amp;quot;/developer/technicalArticles/javaserverpages/JSP20/math.jsp&amp;quot; method=&amp;quot;GET&amp;quot;&amp;gt;
    X = &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;x&amp;quot; value=&amp;quot;${param[&amp;quot;x&amp;quot;]}&amp;quot;&amp;gt;
    &amp;lt;BR&amp;gt;
    Y = &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;y&amp;quot; value=&amp;quot;${param[&amp;quot;y&amp;quot;]}&amp;quot;&amp;gt;
    &amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Add Numbers&amp;quot;&amp;gt;
    &amp;lt;/FORM&amp;gt;
    &amp;lt;P&amp;gt;
    The sum is: ${my:add(param[&amp;quot;x&amp;quot;],param[&amp;quot;y&amp;quot;])}
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy Compute.java and save it at: C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplesel
    Compile Compute.java using javac
    Edit the file C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld and append the snippet of code in Code Sample 4 after the last &amp;lt;/function&amp;gt; in the file and before &amp;lt;/taglib&amp;gt;
    Copy math.jsp to c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the jsp file math.jsp from a web browser
    If all goes well, you should see something similar to Figure 3.
    Figure 3: Using Functions
  • Tag Handlers
    The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways:
    Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface.
    Page authors who do not know Java: by using tag files.
    Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!.
    Code Sample 6: HelloTag.java
    package jsp2.examples.simpletag;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.tagext.SimpleTagSupport;
    import java.io.IOException;
    /**
    * SimpleTag handler that prints &amp;quot;This is my first tag!“
    */
    public class HelloTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
    getJspContext().getOut().write(&amp;quot;This is my first tag!&amp;quot;);
    }
    }
    Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor:
    Code Sample 7: Tag Descriptor
    &amp;lt;tag&amp;gt;
    &amp;lt;description&amp;gt;Prints this is my first tag&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;hello&amp;lt;/name&amp;gt;
    &amp;lt;tag-class&amp;gt;jsp2.examples.simpletag.HelloTag&amp;lt;/tag-class&amp;gt;
    &amp;lt;body-content&amp;gt;empty&amp;lt;/body-content&amp;gt;
    &amp;lt;/tag&amp;gt;
    And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed.
    &amp;lt;%@ taglib prefix=&amp;quot;mytag&amp;quot; uri=&amp;quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Simple Tag Handler&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;Simple Tag Handler&amp;lt;/H2&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;B&amp;gt;My first tag prints&amp;lt;/B&amp;gt;: &amp;lt;mytag:hello/&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag
    Compile the HelloTag.java using javac
    Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &amp;lt;/taglib&amp;gt;
    Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request helloworld.jsp from a web browser
    If all goes well you should see something similar to Figure 4.
    Figure 4: Simple Tag Handler Example
  • Tag Handlers
    The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways:
    Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface.
    Page authors who do not know Java: by using tag files.
    Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!.
    Code Sample 6: HelloTag.java
    package jsp2.examples.simpletag;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.tagext.SimpleTagSupport;
    import java.io.IOException;
    /**
    * SimpleTag handler that prints &amp;quot;This is my first tag!“
    */
    public class HelloTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
    getJspContext().getOut().write(&amp;quot;This is my first tag!&amp;quot;);
    }
    }
    Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor:
    Code Sample 7: Tag Descriptor
    &amp;lt;tag&amp;gt;
    &amp;lt;description&amp;gt;Prints this is my first tag&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;hello&amp;lt;/name&amp;gt;
    &amp;lt;tag-class&amp;gt;jsp2.examples.simpletag.HelloTag&amp;lt;/tag-class&amp;gt;
    &amp;lt;body-content&amp;gt;empty&amp;lt;/body-content&amp;gt;
    &amp;lt;/tag&amp;gt;
    And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed.
    &amp;lt;%@ taglib prefix=&amp;quot;mytag&amp;quot; uri=&amp;quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Simple Tag Handler&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;Simple Tag Handler&amp;lt;/H2&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;B&amp;gt;My first tag prints&amp;lt;/B&amp;gt;: &amp;lt;mytag:hello/&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag
    Compile the HelloTag.java using javac
    Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &amp;lt;/taglib&amp;gt;
    Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request helloworld.jsp from a web browser
    If all goes well you should see something similar to Figure 4.
    Figure 4: Simple Tag Handler Example
  • Tag Handlers
    The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways:
    Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface.
    Page authors who do not know Java: by using tag files.
    Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!.
    Code Sample 6: HelloTag.java
    package jsp2.examples.simpletag;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.tagext.SimpleTagSupport;
    import java.io.IOException;
    /**
    * SimpleTag handler that prints &amp;quot;This is my first tag!“
    */
    public class HelloTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
    getJspContext().getOut().write(&amp;quot;This is my first tag!&amp;quot;);
    }
    }
    Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor:
    Code Sample 7: Tag Descriptor
    &amp;lt;tag&amp;gt;
    &amp;lt;description&amp;gt;Prints this is my first tag&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;hello&amp;lt;/name&amp;gt;
    &amp;lt;tag-class&amp;gt;jsp2.examples.simpletag.HelloTag&amp;lt;/tag-class&amp;gt;
    &amp;lt;body-content&amp;gt;empty&amp;lt;/body-content&amp;gt;
    &amp;lt;/tag&amp;gt;
    And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed.
    &amp;lt;%@ taglib prefix=&amp;quot;mytag&amp;quot; uri=&amp;quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Simple Tag Handler&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;Simple Tag Handler&amp;lt;/H2&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;B&amp;gt;My first tag prints&amp;lt;/B&amp;gt;: &amp;lt;mytag:hello/&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag
    Compile the HelloTag.java using javac
    Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &amp;lt;/taglib&amp;gt;
    Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request helloworld.jsp from a web browser
    If all goes well you should see something similar to Figure 4.
    Figure 4: Simple Tag Handler Example
  • Tag Handlers
    The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways:
    Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface.
    Page authors who do not know Java: by using tag files.
    Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!.
    Code Sample 6: HelloTag.java
    package jsp2.examples.simpletag;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.tagext.SimpleTagSupport;
    import java.io.IOException;
    /**
    * SimpleTag handler that prints &amp;quot;This is my first tag!“
    */
    public class HelloTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
    getJspContext().getOut().write(&amp;quot;This is my first tag!&amp;quot;);
    }
    }
    Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor:
    Code Sample 7: Tag Descriptor
    &amp;lt;tag&amp;gt;
    &amp;lt;description&amp;gt;Prints this is my first tag&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;hello&amp;lt;/name&amp;gt;
    &amp;lt;tag-class&amp;gt;jsp2.examples.simpletag.HelloTag&amp;lt;/tag-class&amp;gt;
    &amp;lt;body-content&amp;gt;empty&amp;lt;/body-content&amp;gt;
    &amp;lt;/tag&amp;gt;
    And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed.
    &amp;lt;%@ taglib prefix=&amp;quot;mytag&amp;quot; uri=&amp;quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Simple Tag Handler&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;Simple Tag Handler&amp;lt;/H2&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;B&amp;gt;My first tag prints&amp;lt;/B&amp;gt;: &amp;lt;mytag:hello/&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag
    Compile the HelloTag.java using javac
    Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &amp;lt;/taglib&amp;gt;
    Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request helloworld.jsp from a web browser
    If all goes well you should see something similar to Figure 4.
    Figure 4: Simple Tag Handler Example
  • Tag Handlers
    The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways:
    Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface.
    Page authors who do not know Java: by using tag files.
    Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my first tag!.
    Code Sample 6: HelloTag.java
    package jsp2.examples.simpletag;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.tagext.SimpleTagSupport;
    import java.io.IOException;
    /**
    * SimpleTag handler that prints &amp;quot;This is my first tag!“
    */
    public class HelloTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
    getJspContext().getOut().write(&amp;quot;This is my first tag!&amp;quot;);
    }
    }
    Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a sample tag descriptor:
    Code Sample 7: Tag Descriptor
    &amp;lt;tag&amp;gt;
    &amp;lt;description&amp;gt;Prints this is my first tag&amp;lt;/description&amp;gt;
    &amp;lt;name&amp;gt;hello&amp;lt;/name&amp;gt;
    &amp;lt;tag-class&amp;gt;jsp2.examples.simpletag.HelloTag&amp;lt;/tag-class&amp;gt;
    &amp;lt;body-content&amp;gt;empty&amp;lt;/body-content&amp;gt;
    &amp;lt;/tag&amp;gt;
    And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed.
    &amp;lt;%@ taglib prefix=&amp;quot;mytag&amp;quot; uri=&amp;quot;/WEB-INF/jsp2/jsp2-example-taglib.tld&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Simple Tag Handler&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;Simple Tag Handler&amp;lt;/H2&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;B&amp;gt;My first tag prints&amp;lt;/B&amp;gt;: &amp;lt;mytag:hello/&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy HelloTag.java and save it under C:Tomcat5.0webappsjsp-examplesWEB-INFclassesjsp2examplessimpletag
    Compile the HelloTag.java using javac
    Append the tag description shown in Code Sample 7 to the end of the file: C:Tomcat5.0webappsjsp-examplesWEB-INFjsp2jsp2-example-taglib.tld, before &amp;lt;/taglib&amp;gt;
    Copy helloworld.jsp and save it at: c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request helloworld.jsp from a web browser
    If all goes well you should see something similar to Figure 4.
    Figure 4: Simple Tag Handler Example
  • Tag File
    The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action. In other words, tag files allow JSP page authors to create reusable tag libraries using JSP syntax. The required file extension for a tag file is .tag.
    To demonstrate how easy this is, consider the tag file in Code Sample 9. That is right, this is a tag file!
    Code Sample 9: greetings.tag
    Hello there. How are you doing?
    Once a tag file has been defined, you can write a JSP page that uses this custom action. As an example, consider the JSP page in Code Sample 10.
    Code Sample 10: chat.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;JSP 2.0 Examples - Hello World Using a Tag File&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;Tag File Example&amp;lt;/H2&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;B&amp;gt;The output of my first tag file is&amp;lt;/B&amp;gt;: &amp;lt;tags:greetings/&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the tag file, greetings.tag, and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ags
    Copy the JSP page, chat.jsp, and save it at c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the chat.jsp file from a Web browser
    If all goes well, you should see something similar to Figure 5.
    Figure 5: Simple Tag File Example
    Note: What is important to notice here is that I did not need to write a TLD for the greetings tag. I just created the tag file in a special directory, and imported it using the taglib directive, and used it!
    Another Tag File Example
    Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &amp;lt;attribute&amp;gt; element in the TLD; it allows for the declaration of custom action attributes.
    Code Sample 11: display.tag
    &amp;lt;%@ attribute name=&amp;quot;color&amp;quot; %&amp;gt; &amp;lt;%@ attribute name=&amp;quot;bgcolor&amp;quot; %&amp;gt; &amp;lt;%@ attribute name=&amp;quot;title&amp;quot; %&amp;gt; &amp;lt;TABLE border=&amp;quot;0&amp;quot; bgcolor=&amp;quot;${color}&amp;quot;&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;B&amp;gt;${title}&amp;lt;/B&amp;gt;&amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD bgcolor=&amp;quot;${bgcolor}&amp;quot;&amp;gt; &amp;lt;jsp:doBody/&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/TABLE&amp;gt;
    Code Sample 12 shows a simple JSP page that uses the display tag.
    Code Sample 12: newsportal.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt; &amp;lt;HTML&amp;gt; &amp;lt;HEAD&amp;gt; &amp;lt;TITLE&amp;gt;Another Tag File Example&amp;lt;/TITLE&amp;gt; &amp;lt;/HEAD&amp;gt; &amp;lt;BODY&amp;gt; &amp;lt;H2&amp;gt;News Portal: Another Tag File Example&amp;lt;/H2&amp;gt; &amp;lt;TABLE border=&amp;quot;0&amp;quot;&amp;gt; &amp;lt;TR valign=&amp;quot;top&amp;quot;&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#ff0000&amp;quot; bgcolor=&amp;quot;#ffc0c0&amp;quot; title=&amp;quot;Travel&amp;quot;&amp;gt; Last French Concorde Arrives in NY&amp;lt;br/&amp;gt; Another Travel Headline&amp;lt;br/&amp;gt; Yet Another Travel Headline&amp;lt;br/&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#00fc00&amp;quot; bgcolor=&amp;quot;#c0ffc0&amp;quot; title=&amp;quot;Technology&amp;quot;&amp;gt; Java for in-flight entertainment&amp;lt;BR&amp;gt; Another Technology Headline&amp;lt;BR&amp;gt; Another Technology Headline&amp;lt;BR&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#ffcc11&amp;quot; bgcolor=&amp;quot;#ffffcc&amp;quot; title=&amp;quot;Sports&amp;quot;&amp;gt; American Football&amp;lt;BR/&amp;gt; NBA&amp;lt;BR/&amp;gt; Soccer&amp;lt;BR/&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/TABLE&amp;gt; &amp;lt;/BODY&amp;gt; &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag
    Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the newsportal.jsp from a Web browser
    Now, you should see something similar to Figure 6.
    Figure 6: Using Tag File as a Template
  • Tag File
    The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action. In other words, tag files allow JSP page authors to create reusable tag libraries using JSP syntax. The required file extension for a tag file is .tag.
    To demonstrate how easy this is, consider the tag file in Code Sample 9. That is right, this is a tag file!
    Code Sample 9: greetings.tag
    Hello there. How are you doing?
    Once a tag file has been defined, you can write a JSP page that uses this custom action. As an example, consider the JSP page in Code Sample 10.
    Code Sample 10: chat.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;JSP 2.0 Examples - Hello World Using a Tag File&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;Tag File Example&amp;lt;/H2&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;B&amp;gt;The output of my first tag file is&amp;lt;/B&amp;gt;: &amp;lt;tags:greetings/&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the tag file, greetings.tag, and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ags
    Copy the JSP page, chat.jsp, and save it at c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the chat.jsp file from a Web browser
    If all goes well, you should see something similar to Figure 5.
    Figure 5: Simple Tag File Example
    Note: What is important to notice here is that I did not need to write a TLD for the greetings tag. I just created the tag file in a special directory, and imported it using the taglib directive, and used it!
    Another Tag File Example
    Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &amp;lt;attribute&amp;gt; element in the TLD; it allows for the declaration of custom action attributes.
    Code Sample 11: display.tag
    &amp;lt;%@ attribute name=&amp;quot;color&amp;quot; %&amp;gt; &amp;lt;%@ attribute name=&amp;quot;bgcolor&amp;quot; %&amp;gt; &amp;lt;%@ attribute name=&amp;quot;title&amp;quot; %&amp;gt; &amp;lt;TABLE border=&amp;quot;0&amp;quot; bgcolor=&amp;quot;${color}&amp;quot;&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;B&amp;gt;${title}&amp;lt;/B&amp;gt;&amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD bgcolor=&amp;quot;${bgcolor}&amp;quot;&amp;gt; &amp;lt;jsp:doBody/&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/TABLE&amp;gt;
    Code Sample 12 shows a simple JSP page that uses the display tag.
    Code Sample 12: newsportal.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt; &amp;lt;HTML&amp;gt; &amp;lt;HEAD&amp;gt; &amp;lt;TITLE&amp;gt;Another Tag File Example&amp;lt;/TITLE&amp;gt; &amp;lt;/HEAD&amp;gt; &amp;lt;BODY&amp;gt; &amp;lt;H2&amp;gt;News Portal: Another Tag File Example&amp;lt;/H2&amp;gt; &amp;lt;TABLE border=&amp;quot;0&amp;quot;&amp;gt; &amp;lt;TR valign=&amp;quot;top&amp;quot;&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#ff0000&amp;quot; bgcolor=&amp;quot;#ffc0c0&amp;quot; title=&amp;quot;Travel&amp;quot;&amp;gt; Last French Concorde Arrives in NY&amp;lt;br/&amp;gt; Another Travel Headline&amp;lt;br/&amp;gt; Yet Another Travel Headline&amp;lt;br/&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#00fc00&amp;quot; bgcolor=&amp;quot;#c0ffc0&amp;quot; title=&amp;quot;Technology&amp;quot;&amp;gt; Java for in-flight entertainment&amp;lt;BR&amp;gt; Another Technology Headline&amp;lt;BR&amp;gt; Another Technology Headline&amp;lt;BR&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#ffcc11&amp;quot; bgcolor=&amp;quot;#ffffcc&amp;quot; title=&amp;quot;Sports&amp;quot;&amp;gt; American Football&amp;lt;BR/&amp;gt; NBA&amp;lt;BR/&amp;gt; Soccer&amp;lt;BR/&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/TABLE&amp;gt; &amp;lt;/BODY&amp;gt; &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag
    Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the newsportal.jsp from a Web browser
    Now, you should see something similar to Figure 6.
    Figure 6: Using Tag File as a Template
  • Tag File
    The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action. In other words, tag files allow JSP page authors to create reusable tag libraries using JSP syntax. The required file extension for a tag file is .tag.
    To demonstrate how easy this is, consider the tag file in Code Sample 9. That is right, this is a tag file!
    Code Sample 9: greetings.tag
    Hello there. How are you doing?
    Once a tag file has been defined, you can write a JSP page that uses this custom action. As an example, consider the JSP page in Code Sample 10.
    Code Sample 10: chat.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;JSP 2.0 Examples - Hello World Using a Tag File&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;Tag File Example&amp;lt;/H2&amp;gt;
    &amp;lt;P&amp;gt;
    &amp;lt;B&amp;gt;The output of my first tag file is&amp;lt;/B&amp;gt;: &amp;lt;tags:greetings/&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the tag file, greetings.tag, and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ags
    Copy the JSP page, chat.jsp, and save it at c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the chat.jsp file from a Web browser
    If all goes well, you should see something similar to Figure 5.
    Figure 5: Simple Tag File Example
    Note: What is important to notice here is that I did not need to write a TLD for the greetings tag. I just created the tag file in a special directory, and imported it using the taglib directive, and used it!
    Another Tag File Example
    Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &amp;lt;attribute&amp;gt; element in the TLD; it allows for the declaration of custom action attributes.
    Code Sample 11: display.tag
    &amp;lt;%@ attribute name=&amp;quot;color&amp;quot; %&amp;gt; &amp;lt;%@ attribute name=&amp;quot;bgcolor&amp;quot; %&amp;gt; &amp;lt;%@ attribute name=&amp;quot;title&amp;quot; %&amp;gt; &amp;lt;TABLE border=&amp;quot;0&amp;quot; bgcolor=&amp;quot;${color}&amp;quot;&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;B&amp;gt;${title}&amp;lt;/B&amp;gt;&amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD bgcolor=&amp;quot;${bgcolor}&amp;quot;&amp;gt; &amp;lt;jsp:doBody/&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/TABLE&amp;gt;
    Code Sample 12 shows a simple JSP page that uses the display tag.
    Code Sample 12: newsportal.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt; &amp;lt;HTML&amp;gt; &amp;lt;HEAD&amp;gt; &amp;lt;TITLE&amp;gt;Another Tag File Example&amp;lt;/TITLE&amp;gt; &amp;lt;/HEAD&amp;gt; &amp;lt;BODY&amp;gt; &amp;lt;H2&amp;gt;News Portal: Another Tag File Example&amp;lt;/H2&amp;gt; &amp;lt;TABLE border=&amp;quot;0&amp;quot;&amp;gt; &amp;lt;TR valign=&amp;quot;top&amp;quot;&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#ff0000&amp;quot; bgcolor=&amp;quot;#ffc0c0&amp;quot; title=&amp;quot;Travel&amp;quot;&amp;gt; Last French Concorde Arrives in NY&amp;lt;br/&amp;gt; Another Travel Headline&amp;lt;br/&amp;gt; Yet Another Travel Headline&amp;lt;br/&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#00fc00&amp;quot; bgcolor=&amp;quot;#c0ffc0&amp;quot; title=&amp;quot;Technology&amp;quot;&amp;gt; Java for in-flight entertainment&amp;lt;BR&amp;gt; Another Technology Headline&amp;lt;BR&amp;gt; Another Technology Headline&amp;lt;BR&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#ffcc11&amp;quot; bgcolor=&amp;quot;#ffffcc&amp;quot; title=&amp;quot;Sports&amp;quot;&amp;gt; American Football&amp;lt;BR/&amp;gt; NBA&amp;lt;BR/&amp;gt; Soccer&amp;lt;BR/&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/TABLE&amp;gt; &amp;lt;/BODY&amp;gt; &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag
    Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the newsportal.jsp from a Web browser
    Now, you should see something similar to Figure 6.
    Figure 6: Using Tag File as a Template
  • Another Tag File Example
    Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &amp;lt;attribute&amp;gt; element in the TLD; it allows for the declaration of custom action attributes.
    Code Sample 11: display.tag
    &amp;lt;%@ attribute name=&amp;quot;color&amp;quot; %&amp;gt; &amp;lt;%@ attribute name=&amp;quot;bgcolor&amp;quot; %&amp;gt; &amp;lt;%@ attribute name=&amp;quot;title&amp;quot; %&amp;gt; &amp;lt;TABLE border=&amp;quot;0&amp;quot; bgcolor=&amp;quot;${color}&amp;quot;&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;B&amp;gt;${title}&amp;lt;/B&amp;gt;&amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD bgcolor=&amp;quot;${bgcolor}&amp;quot;&amp;gt; &amp;lt;jsp:doBody/&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/TABLE&amp;gt;
    Code Sample 12 shows a simple JSP page that uses the display tag.
    Code Sample 12: newsportal.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt; &amp;lt;HTML&amp;gt; &amp;lt;HEAD&amp;gt; &amp;lt;TITLE&amp;gt;Another Tag File Example&amp;lt;/TITLE&amp;gt; &amp;lt;/HEAD&amp;gt; &amp;lt;BODY&amp;gt; &amp;lt;H2&amp;gt;News Portal: Another Tag File Example&amp;lt;/H2&amp;gt; &amp;lt;TABLE border=&amp;quot;0&amp;quot;&amp;gt; &amp;lt;TR valign=&amp;quot;top&amp;quot;&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#ff0000&amp;quot; bgcolor=&amp;quot;#ffc0c0&amp;quot; title=&amp;quot;Travel&amp;quot;&amp;gt; Last French Concorde Arrives in NY&amp;lt;br/&amp;gt; Another Travel Headline&amp;lt;br/&amp;gt; Yet Another Travel Headline&amp;lt;br/&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#00fc00&amp;quot; bgcolor=&amp;quot;#c0ffc0&amp;quot; title=&amp;quot;Technology&amp;quot;&amp;gt; Java for in-flight entertainment&amp;lt;BR&amp;gt; Another Technology Headline&amp;lt;BR&amp;gt; Another Technology Headline&amp;lt;BR&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt; &amp;lt;tags:display color=&amp;quot;#ffcc11&amp;quot; bgcolor=&amp;quot;#ffffcc&amp;quot; title=&amp;quot;Sports&amp;quot;&amp;gt; American Football&amp;lt;BR/&amp;gt; NBA&amp;lt;BR/&amp;gt; Soccer&amp;lt;BR/&amp;gt; &amp;lt;/tags:display&amp;gt; &amp;lt;/TD&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/TABLE&amp;gt; &amp;lt;/BODY&amp;gt; &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag
    Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the newsportal.jsp from a Web browser
    Now, you should see something similar to Figure 6.
    Figure 6: Using Tag File as a Template
  • Another Tag File Example
    Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &amp;lt;attribute&amp;gt; element in the TLD; it allows for the declaration of custom action attributes.
    Code Sample 11: display.tag
    &amp;lt;%@ attribute name=&amp;quot;color&amp;quot; %&amp;gt;
    &amp;lt;%@ attribute name=&amp;quot;bgcolor&amp;quot; %&amp;gt;
    &amp;lt;%@ attribute name=&amp;quot;title&amp;quot; %&amp;gt;
    &amp;lt;TABLE border=&amp;quot;0&amp;quot; bgcolor=&amp;quot;${color}&amp;quot;&amp;gt;
    &amp;lt;TR&amp;gt;
    &amp;lt;TD&amp;gt;
    &amp;lt;B&amp;gt;${title}&amp;lt;/B&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;/TR&amp;gt;
    &amp;lt;TR&amp;gt;
    &amp;lt;TD bgcolor=&amp;quot;${bgcolor}&amp;quot;&amp;gt;
    &amp;lt;jsp:doBody/&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;/TR&amp;gt;
    &amp;lt;/TABLE&amp;gt;
    Code Sample 12 shows a simple JSP page that uses the display tag.
    Code Sample 12: newsportal.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Another Tag File Example&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;News Portal: Another Tag File Example&amp;lt;/H2&amp;gt;
    &amp;lt;TABLE border=&amp;quot;0&amp;quot;&amp;gt;
    &amp;lt;TR valign=&amp;quot;top&amp;quot;&amp;gt;
    &amp;lt;TD&amp;gt;
    &amp;lt;tags:display color=&amp;quot;#ff0000&amp;quot; bgcolor=&amp;quot;#ffc0c0&amp;quot; title=&amp;quot;Travel&amp;quot;&amp;gt;
    Last French Concorde Arrives in NY&amp;lt;br/&amp;gt;
    Another Travel Headline&amp;lt;br/&amp;gt;
    Yet Another Travel Headline&amp;lt;br/&amp;gt;
    &amp;lt;/tags:display&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;TD&amp;gt;
    &amp;lt;tags:display color=&amp;quot;#00fc00&amp;quot; bgcolor=&amp;quot;#c0ffc0&amp;quot; title=&amp;quot;Technology&amp;quot;&amp;gt;
    Java for in-flight entertainment&amp;lt;BR&amp;gt;
    Another Technology Headline&amp;lt;BR&amp;gt;
    Another Technology Headline&amp;lt;BR&amp;gt;
    &amp;lt;/tags:display&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;TD&amp;gt;
    &amp;lt;tags:display color=&amp;quot;#ffcc11&amp;quot; bgcolor=&amp;quot;#ffffcc&amp;quot; title=&amp;quot;Sports&amp;quot;&amp;gt;
    American Football&amp;lt;BR/&amp;gt;
    NBA&amp;lt;BR/&amp;gt;
    Soccer&amp;lt;BR/&amp;gt;
    &amp;lt;/tags:display&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;/TR&amp;gt;
    &amp;lt;/TABLE&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag
    Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the newsportal.jsp from a Web browser
    Now, you should see something similar to Figure 6.
    Figure 6: Using Tag File as a Template
  • Another Tag File Example
    Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the &amp;lt;attribute&amp;gt; element in the TLD; it allows for the declaration of custom action attributes.
    Code Sample 11: display.tag
    &amp;lt;%@ attribute name=&amp;quot;color&amp;quot; %&amp;gt;
    &amp;lt;%@ attribute name=&amp;quot;bgcolor&amp;quot; %&amp;gt;
    &amp;lt;%@ attribute name=&amp;quot;title&amp;quot; %&amp;gt;
    &amp;lt;TABLE border=&amp;quot;0&amp;quot; bgcolor=&amp;quot;${color}&amp;quot;&amp;gt;
    &amp;lt;TR&amp;gt;
    &amp;lt;TD&amp;gt;
    &amp;lt;B&amp;gt;${title}&amp;lt;/B&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;/TR&amp;gt;
    &amp;lt;TR&amp;gt;
    &amp;lt;TD bgcolor=&amp;quot;${bgcolor}&amp;quot;&amp;gt;
    &amp;lt;jsp:doBody/&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;/TR&amp;gt;
    &amp;lt;/TABLE&amp;gt;
    Code Sample 12 shows a simple JSP page that uses the display tag.
    Code Sample 12: newsportal.jsp
    &amp;lt;%@ taglib prefix=&amp;quot;tags&amp;quot; tagdir=&amp;quot;/WEB-INF/tags&amp;quot; %&amp;gt;
    &amp;lt;HTML&amp;gt;
    &amp;lt;HEAD&amp;gt;
    &amp;lt;TITLE&amp;gt;Another Tag File Example&amp;lt;/TITLE&amp;gt;
    &amp;lt;/HEAD&amp;gt;
    &amp;lt;BODY&amp;gt;
    &amp;lt;H2&amp;gt;News Portal: Another Tag File Example&amp;lt;/H2&amp;gt;
    &amp;lt;TABLE border=&amp;quot;0&amp;quot;&amp;gt;
    &amp;lt;TR valign=&amp;quot;top&amp;quot;&amp;gt;
    &amp;lt;TD&amp;gt;
    &amp;lt;tags:display color=&amp;quot;#ff0000&amp;quot; bgcolor=&amp;quot;#ffc0c0&amp;quot; title=&amp;quot;Travel&amp;quot;&amp;gt;
    Last French Concorde Arrives in NY&amp;lt;br/&amp;gt;
    Another Travel Headline&amp;lt;br/&amp;gt;
    Yet Another Travel Headline&amp;lt;br/&amp;gt;
    &amp;lt;/tags:display&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;TD&amp;gt;
    &amp;lt;tags:display color=&amp;quot;#00fc00&amp;quot; bgcolor=&amp;quot;#c0ffc0&amp;quot; title=&amp;quot;Technology&amp;quot;&amp;gt;
    Java for in-flight entertainment&amp;lt;BR&amp;gt;
    Another Technology Headline&amp;lt;BR&amp;gt;
    Another Technology Headline&amp;lt;BR&amp;gt;
    &amp;lt;/tags:display&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;TD&amp;gt;
    &amp;lt;tags:display color=&amp;quot;#ffcc11&amp;quot; bgcolor=&amp;quot;#ffffcc&amp;quot; title=&amp;quot;Sports&amp;quot;&amp;gt;
    American Football&amp;lt;BR/&amp;gt;
    NBA&amp;lt;BR/&amp;gt;
    Soccer&amp;lt;BR/&amp;gt;
    &amp;lt;/tags:display&amp;gt;
    &amp;lt;/TD&amp;gt;
    &amp;lt;/TR&amp;gt;
    &amp;lt;/TABLE&amp;gt;
    &amp;lt;/BODY&amp;gt;
    &amp;lt;/HTML&amp;gt;
    To run this example:
    Copy the file display.tag and save it under c:Tomcat5.0webappsjsp-examplesWEB-INF ag
    Copy the file newsportal.jsp and save it under c:Tomcat5.0webappsjsp-examplesjsp2-tutorial
    Request the newsportal.jsp from a Web browser
    Now, you should see something similar to Figure 6.
    Figure 6: Using Tag File as a Template
  • 8.1 Overview
    There are three key concepts associated with internationalization: locale, resource
    bundle, and basename.
    A locale represents a specific geographical, political, or cultural region. A locale is
    identified by a language code, along with an optional country code1.
    1. Language code
    The language code is the lower-case two-letter code as defined by ISO-639 (e.g.
    “ca” for Catalan, “zh” for Chinese). The full list of these codes can be found at a
    number of sites, such as:
    http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
    2. Country code
    The country code is the upper-case two-letter code as defined by ISO-3166 (e.g.
    “IT” for Italy, “CR” for Costa Rica). The full list of these codes can be found at a
    number of sites, such as:
    http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html.
    A resource bundle contains locale-specific objects. Each message in a resource bundle
    is associated with a key. Since the set of messages contained in a resource bundle can
    be localized for many locales, the resource bundles that translate the same set of
    messages are identified by the same basename. A specific resource bundle is therefore
    uniquely identified by combining its basename with a locale.
    For instance, a web application could define the registration resource bundles with
    basename Registration to contain the messages associated with the registration
    portion of the application. Assuming that French and English are the only languages
    supported by the application, there will be two resource bundles:
    Registration_fr (French language) and Registration_en (English language).
    Depending on the locale associated with the client request, the key “greeting” could
    be mapped to the message “Bonjour” (French) or “Hello” (English).
  • 8.1 Overview
    There are three key concepts associated with internationalization: locale, resource
    bundle, and basename.
    A locale represents a specific geographical, political, or cultural region. A locale is
    identified by a language code, along with an optional country code1.
    1. Language code
    The language code is the lower-case two-letter code as defined by ISO-639 (e.g.
    “ca” for Catalan, “zh” for Chinese). The full list of these codes can be found at a
    number of sites, such as:
    http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
    2. Country code
    The country code is the upper-case two-letter code as defined by ISO-3166 (e.g.
    “IT” for Italy, “CR” for Costa Rica). The full list of these codes can be found at a
    number of sites, such as:
    http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html.
    A resource bundle contains locale-specific objects. Each message in a resource bundle
    is associated with a key. Since the set of messages contained in a resource bundle can
    be localized for many locales, the resource bundles that translate the same set of
    messages are identified by the same basename. A specific resource bundle is therefore
    uniquely identified by combining its basename with a locale.
    For instance, a web application could define the registration resource bundles with
    basename Registration to contain the messages associated with the registration
    portion of the application. Assuming that French and English are the only languages
    supported by the application, there will be two resource bundles:
    Registration_fr (French language) and Registration_en (English language).
    Depending on the locale associated with the client request, the key “greeting” could
    be mapped to the message “Bonjour” (French) or “Hello” (English).
  • 8.1.1 &amp;lt;fmt:message&amp;gt;
    It is possible to internationalize the JSP pages of a web application simply by using
    the &amp;lt;fmt:message&amp;gt; action as shown below:
    &amp;lt;fmt:message key=&amp;quot;greeting&amp;quot;/&amp;gt;
    In this case, &amp;lt;fmt:message&amp;gt; leverages the default i18n localization context, making it
    extremely simple for a page author to internationalize JSP pages.
    &amp;lt;fmt:message&amp;gt; also supports compound messages, i.e. messages that contain one or
    more variables. Parameter values for these variables may be supplied via one or
    more &amp;lt;fmt:param&amp;gt; subtags (one for each parameter value). This procedure is
    referred to as parametric replacement.
    &amp;lt;fmt:message key=&amp;quot;athletesRegistered&amp;quot;&amp;gt;
    &amp;lt;fmt:param&amp;gt;
    &amp;lt;fmt:formatNumber value=”${athletesCount}”/&amp;gt;
    &amp;lt;/fmt:param&amp;gt;
    &amp;lt;/fmt:message&amp;gt;
    Depending on the locale, this example could print the following messages:
    french: Il y a 10 582 athletes enregistres.
    english: There are 10,582 athletes registered.
  • 8.1.1 &amp;lt;fmt:message&amp;gt;
    It is possible to internationalize the JSP pages of a web application simply by using
    the &amp;lt;fmt:message&amp;gt; action as shown below:
    &amp;lt;fmt:message key=&amp;quot;greeting&amp;quot;/&amp;gt;
    In this case, &amp;lt;fmt:message&amp;gt; leverages the default i18n localization context, making it
    extremely simple for a page author to internationalize JSP pages.
    &amp;lt;fmt:message&amp;gt; also supports compound messages, i.e. messages that contain one or
    more variables. Parameter values for these variables may be supplied via one or
    more &amp;lt;fmt:param&amp;gt; subtags (one for each parameter value). This procedure is
    referred to as parametric replacement.
    &amp;lt;fmt:message key=&amp;quot;athletesRegistered&amp;quot;&amp;gt;
    &amp;lt;fmt:param&amp;gt;
    &amp;lt;fmt:formatNumber value=”${athletesCount}”/&amp;gt;
    &amp;lt;/fmt:param&amp;gt;
    &amp;lt;/fmt:message&amp;gt;
    Depending on the locale, this example could print the following messages:
    french: Il y a 10 582 athletes enregistres.
    english: There are 10,582 athletes registered.
  • 8.2I18n Localization Context
    I18n actions use an i18n localization context to localize their data. An i18n
    localization context contains two pieces of information: a resource bundle and the
    locale for which the resource bundle was found.
    An i18n action determine its i18n localization context in one of several ways, which
    are described in order of precedence:
    &amp;lt;fmt:message&amp;gt; bundle attribute
    If attribute bundle is specified in &amp;lt;fmt:message&amp;gt;, the i18n localization context associated with it is used for localization.
    &amp;lt;fmt:bundle&amp;gt; action
    If &amp;lt;fmt:message&amp;gt; actions are nested inside a &amp;lt;fmt:bundle&amp;gt; action, the i18n localization context of the enclosing &amp;lt;fmt:bundle&amp;gt; action is used for localization. The &amp;lt;fmt:bundle&amp;gt; action determines the resource bundle of its i18n localization context according to the resource bundle determination algorithm in Section 8.3, using the basename attribute as the resource bundle basename.
    I18n default localization context
    The i18n localization context whose resource bundle is to be used for localization is specified via the javax.servlet.jsp.jstl.fmt.localizationContext configuration setting (see Section 8.11.3). If the configuration setting is of type LocalizationContext, its resource bundle component is used for localization. Otherwise, the configuration setting is of type String, and the action establishes its own i18n localization context whose resource bundle component is determined according to the resource bundle determination algorithm in Section 8.3, using the configuration setting as the resource bundle basename.
    The example below shows how the various localization contexts can be established
    to define the resource bundle used for localization.
    &amp;lt;%-- Use configuration setting --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;Welcome&amp;quot; /&amp;gt;
    &amp;lt;fmt:setBundle basename=&amp;quot;Errors&amp;quot; var=&amp;quot;errorBundle&amp;quot; /&amp;gt;
    &amp;lt;fmt:bundle basename=&amp;quot;Greetings&amp;quot;&amp;gt;
    &amp;lt;%-- Localization context established by
    parent &amp;lt;fmt:bundle&amp;gt; tag --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;Welcome&amp;quot; /&amp;gt;
    &amp;lt;%-- Localization context established by attribute bundle --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;WrongPassword&amp;quot; bundle=&amp;quot;${errorBundle}&amp;quot; /&amp;gt;
    &amp;lt;/fmt:bundle&amp;gt;
    I18n actions use an i18n localization context to localize their data. An i18n
    localization context contains two pieces of information: a resource bundle and the
    locale for which the resource bundle was found.
    An i18n action determine its i18n localization context in one of several ways, which
    are described in order of precedence:
    &amp;lt;fmt:message&amp;gt; bundle attribute
    If attribute bundle is specified in &amp;lt;fmt:message&amp;gt;, the i18n localization context associated with it is used for localization.
    &amp;lt;fmt:bundle&amp;gt; action
    If &amp;lt;fmt:message&amp;gt; actions are nested inside a &amp;lt;fmt:bundle&amp;gt; action, the i18n localization context of the enclosing &amp;lt;fmt:bundle&amp;gt; action is used for localization. The &amp;lt;fmt:bundle&amp;gt; action determines the resource bundle of its i18n localization context according to the resource bundle determination algorithm in Section 8.3, using the basename attribute as the resource bundle basename.
    I18n default localization context
    The i18n localization context whose resource bundle is to be used for localization is specified via the javax.servlet.jsp.jstl.fmt.localizationContext configuration setting (see Section 8.11.3). If the configuration setting is of type LocalizationContext, its resource bundle component is used for localization. Otherwise, the configuration setting is of type String, and the action establishes its own i18n localization context whose resource bundle component is determined according to the resource bundle determination algorithm in Section 8.3, using the configuration setting as the resource bundle basename.
    The example below shows how the various localization contexts can be established
    to define the resource bundle used for localization.
    &amp;lt;%-- Use configuration setting --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;Welcome&amp;quot; /&amp;gt;
    &amp;lt;fmt:setBundle basename=&amp;quot;Errors&amp;quot; var=&amp;quot;errorBundle&amp;quot; /&amp;gt;
    &amp;lt;fmt:bundle basename=&amp;quot;Greetings&amp;quot;&amp;gt;
    &amp;lt;%-- Localization context established by
    parent &amp;lt;fmt:bundle&amp;gt; tag --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;Welcome&amp;quot; /&amp;gt;
    &amp;lt;%-- Localization context established by attribute bundle --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;WrongPassword&amp;quot; bundle=&amp;quot;${errorBundle}&amp;quot; /&amp;gt;
    &amp;lt;/fmt:bundle&amp;gt;
  • 8.2I18n Localization Context
    I18n actions use an i18n localization context to localize their data. An i18n
    localization context contains two pieces of information: a resource bundle and the
    locale for which the resource bundle was found.
    An i18n action determine its i18n localization context in one of several ways, which
    are described in order of precedence:
    &amp;lt;fmt:message&amp;gt; bundle attribute
    If attribute bundle is specified in &amp;lt;fmt:message&amp;gt;, the i18n localization context associated with it is used for localization.
    &amp;lt;fmt:bundle&amp;gt; action
    If &amp;lt;fmt:message&amp;gt; actions are nested inside a &amp;lt;fmt:bundle&amp;gt; action, the i18n localization context of the enclosing &amp;lt;fmt:bundle&amp;gt; action is used for localization. The &amp;lt;fmt:bundle&amp;gt; action determines the resource bundle of its i18n localization context according to the resource bundle determination algorithm in Section 8.3, using the basename attribute as the resource bundle basename.
    I18n default localization context
    The i18n localization context whose resource bundle is to be used for localization is specified via the javax.servlet.jsp.jstl.fmt.localizationContext configuration setting (see Section 8.11.3). If the configuration setting is of type LocalizationContext, its resource bundle component is used for localization. Otherwise, the configuration setting is of type String, and the action establishes its own i18n localization context whose resource bundle component is determined according to the resource bundle determination algorithm in Section 8.3, using the configuration setting as the resource bundle basename.
    The example below shows how the various localization contexts can be established
    to define the resource bundle used for localization.
    &amp;lt;%-- Use configuration setting --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;Welcome&amp;quot; /&amp;gt;
    &amp;lt;fmt:setBundle basename=&amp;quot;Errors&amp;quot; var=&amp;quot;errorBundle&amp;quot; /&amp;gt;
    &amp;lt;fmt:bundle basename=&amp;quot;Greetings&amp;quot;&amp;gt;
    &amp;lt;%-- Localization context established by parent &amp;lt;fmt:bundle&amp;gt; tag --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;Welcome&amp;quot; /&amp;gt;
    &amp;lt;%-- Localization context established by attribute bundle --%&amp;gt;
    &amp;lt;fmt:message key=&amp;quot;WrongPassword&amp;quot; bundle=&amp;quot;${errorBundle}&amp;quot; /&amp;gt;
    &amp;lt;/fmt:bundle&amp;gt;
  • Preferred Locales
    If the resource bundle of an i18n localization context needs to be determined, it is
    retrieved from the web application’s resources according to the algorithm described
    in section Section 8.3. This algorithm requires two pieces of information: the
    basename of the resource bundle (as described in the previous section) and the
    preferred locales.
    The method for setting the preferred locales is characterized as either applicationbased
    or browser-based.
    Application-based locale setting has priority over browser-based locale setting. In this
    mode, the locale is set via the javax.servlet.jsp.jstl.fmt.locale
    configuration setting (see Section 8.11.1). Setting the locale this way is useful in
    situations where an application lets its users pick their preferred locale and then sets
    the scoped variable accordingly. This may also be useful in the case where a client’s
    preferred locale is retrieved from a database and installed for the page using the
    &amp;lt;fmt:setLocale&amp;gt; action.
  • Offers simpler consistent programming environment.
    Advanced programmers may prefer scriptlets over JSTL.
    JSTL allows HTML programmers to program in one consistent environment.
    Back-end programmers still create JavaBeans, which are used in conjunction with JSTL.
    Conclusion
    JSP 2.0 makes is easier than ever to rapidly develop and easily maintain dynamic Web pages. Despite the fact the word &amp;quot;Java&amp;quot; appears in JavaServer Pages, with JSP 2.0 page authors can develop innovative dynamic Web pages without having to learn the Java programming language. The examples shown throughout the article demonstrate how easy it is to get started using the new features in JSP 2.0 to develop dynamic Web pages.
  • Jstl Guide

    1. 1. Introduction To JSTL (Java Server Pages Tag Library) Author: Yuval Zilberstein, yuvalzi@gmail.com
    2. 2. Advantages • Avoid conflicts between jar versions (XML, JDBC etc’) • Eases page development for page authors • Easy to read and maintain • Reuse of valuable components • As a matter of principle – A JSP page should be a view page without scriptlets.
    3. 3. Disadvantages • Not as flexible as scriptlets • May seem burdensome for experienced programmers • Not a general purpose programming language. • Hard to debug
    4. 4. Installing • The following must be available in your project – standard.jar – jstl.jar – web.xml – DOCTYPE – Some containers must have a DOCTYPE element in web.xml
    5. 5. Installing • web.xml example <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <description>Learning JSTL (or whatever you like</description> </web-app>
    6. 6. EL Expression Language • A data access language, that eases access to application data. • Allows page authors to access an object using a simplified syntax: – <someTags:aTag attribute="${aName}"> – <someTags.aTag attribute="${aCustomer.address.country}">
    7. 7. Accessing Application Data • EL expressions must be enclosed between ${ and }. • ${data} – scoped variable data. • The dot (.) operator. • The bracket ['name'] operator. • E.g. – ${customer.name} – ${customer["name"]} – ${customers[0]} • ${customer.name} is equivalent to $ {customer["name"]}.
    8. 8. Operators • The second version (in parenthesis) is to avoid the use of entity references in XML syntax Operator Description + Addition - Subtraction * Multiplication / ( or div) Division % ( or mod ) Modulus (Reminder) == ( or eq ) Equality != ( or ne ) Inequity < ( or lt ) Less than > ( or gt ) Greater than <= ( or le ) Less than or equal >= ( or ge ) Greater than or equal && ( or and ) Logical AND || ( or or ) Logical OR ! ( or not ) Boolean complement empty Check for empty value
    9. 9. Implicit Objects Implicit Object Content pageScope access to the scoped variables requestScope access to the scoped variables sessionScope access to the scoped variables applicationScope access to the scoped variables param a Map object. param["foo"] returns the first string value associated with request parameter foo. paramValues a Map object. paramValues["foo"] returns an array of strings associated with request parameter foo. header a Map object. header["foo"] returns the first string value associated with header foo. headerValues a Map object. headerValues["foo"] returns an array of strings associated with header foo. initParam access to context initialization parameters cookie exposes cookies received in the request pageContext PageContext properties (e.g. HttpServletRequest, ServletContext, HttpSession)
    10. 10. Tag libraries • There are two groups of twin tag libraries – one that supports the expression language (EL) – one that supports request time expression values (RT) (using scriptlets) EL-based Tag Libraries Functional Area URI Prefix core http://java.sun.com/jstl/core c XML processing http://java.sun.com/jstl/xml x I18N capable formatting http://java.sun.com/jstl/fmt fmt relational db access (SQL) http://java.sun.com/jstl/sql sql RT-based Tag Libraries Functional Area URI Prefix core http://java.sun.com/jstl/core_rt c_rt XML processing http://java.sun.com/jstl/xml_rt x_rt I18N capable formatting http://java.sun.com/jstl/fmt_rt fmt_rt relational db access (SQL) http://java.sun.com/jstl/sql_rt sql_rt
    11. 11. Tag libraries • To use a JSTL library, you declare it: – E.g.: <@ taglib prefix="c" uri="http://java.sun.com/jstl/core"> • prefix attribute – Namespace reference
    12. 12. The Core Tag Library http://java.sun.com/jstl/core
    13. 13. The Core Tag Library • Supports the following abilities – Output – Manipulation of scoped variables – Conditional logic – Loops – URL manipulation – Error handling.
    14. 14. General Purpose Tags • <c:out> - writing data • <c:set> - set the value of a scoped attribute • <c:remove> - remove a scoped variable. • <c:catch> - handling errors
    15. 15. General Purpose Tags • Print with a default value: – <c:out value="${customer.city}" default="unknown"/> • Setting a variable – <c:set var="name" value="expression"/> • Setting with an inline body – <c:set var="xmltext"> <books> <book> <title>Book Title A</title> <author>A. B. C.</author> <price>17.95</price> </book> </books> </c:set> • Setting with an inline body – <c:remove var="cache" scope="application/>
    16. 16. Conditional Actions • <c:if> • If / then / else – Consists of the following three tags: – <c:choose> – <c:when> – <c:otherwise> • Conditional actions use the attribute test to check weather the condition has a true or false value
    17. 17. Conditional Actions – E.g. • <c:if> example: – <c:if test="${customer.country == 'Canada'}"> This customer is based in Canada. </c:if> • <c:if> and <c:catch> • <c:catch var="exception"> <!-- execution we can recover from. --> ... </c:catch> <c:if test="${exception != null}"> Processing could not be performed. Here is why.... </c:if>
    18. 18. Conditional Actions – E.g. • <c:choose> <c:when test="${customer.country == 'UK'}"> UK has mild winters. </c:when> <c:otherwise> Country is unknown. </c:otherwise> </c:choose>
    19. 19. Iteration Actions - forEach • <c:forEach> iteration over collection of items. • <c:forEach var="customer" items="${customers}"> Customer: <c:out value="${customer}"/> </c:forEach> • <c:forEach var=“i" begin="1" end="100"> <c:out value="${i % 2 == 0}"/> </c:forEach>
    20. 20. Iteration Actions - forEach • E.g.: Print the headers • <c:forEach var="head" items="${headerValues}"> param: <c:out value="${head.key}"/><br> values: <c:forEach var="val" items="${head.value}"> <c:out value="${val}"/> </c:forEach> <p> </c:forEach> </body> </html>
    21. 21. URL Actions • <c:import> - import local and remote resources. • As opposed to the standard jsp include action and directive, the jstl import allows importing of remote resources. – <c:import url="./copyright.html"/> – <c:import url="http://www.somewhere.com/hello.xml"/>
    22. 22. URL Actions • <c:url> - URL rewriting tasks. • It can be combined with <c:param>, which encodes query-string parameters. • <c:url value="http://www.somewhere.com/customers/register" var="registrationURL"> <c:param name="name" value="${param.name}"/> <c:param name="country" value="${param.country}"/> </c:url> <a href='<c:out value="${registrationURL}"/>'>Customer Registration>/a>
    23. 23. URL Actions • <c:redirect> (to support HTTP redirect) • <c:redirect url="https://www.somewhere.com/register">
    24. 24. The XML Tag Library http://java.sun.com/jstl/xml
    25. 25. The XML Tag Library • XML actions to address basic needs of page authors. • Support XPath expressions - Path expressions to identify nodes in XML.
    26. 26. XML Core actions • <x:out> - writing XML data • <x:set> - set the value of an XML attribute • <x:parse> - parse the document
    27. 27. XML Control Flow • <x:if> • If .. Then .. else – <x:choose> – <x:when> – <x:otherwise> • <x:forEach> • Xml control flow tags use the select attribute to match to an XPath expressions.
    28. 28. XML control flow • <x:parse xml="${xmldoc}" var="output"/> ---------------------------------------------------- • <x:if select="$output/portfolio/stock[symbol = 'SUNW']"> You still have Microsystems Stocks! </x:if> ---------------------------------------------------- • <x:forEach select="$output/portfolio/stock"> <x:out select="price"/> </x:forEach>
    29. 29. XML control flow <x:choose> <x:when select="$output/portfolio/stock[price > '70']"> You still have stocks worth over $70. </x:when> <x:otherwise> You have no stocks worth over $70. </x:otherwise> </x:choose>
    30. 30. Code Sample 1 <c:set var="xmltext"> <books> <book> <title>Book Title A</title> <author>A. B. C.</author> <price>17.95</price> </book> <book> <title>Book Title B</title> <author>X. Y. Z.</author> <price>24.99</price> </book> </books> </c:set> <x:parse xml="${xmltext}" var="output"/> The title of the first book is: <x:out select="$output/books/book[1]/title"/> The price of the second book: <x:out select="$output/books/book[2]/price"/>
    31. 31. Code Sample 2 http://www.javacourses.com/stocks .xml<?xml version="1.0" encoding="UTF-8"?> <portfolio> <stock> <symbol>SUNW</symbol> <name>Sun Microsystems</name> <price>17.1</price> </stock> <stock> <symbol>AOL</symbol> <name>America Online</name> <price>51.05</price> </stock> <stock> <symbol>IBM</symbol> <name>International Business Machines</name> <price>116.10</price> </stock> <stock> <symbol>MOT</symbol> <name>Motorola</name> <price>15.20</price> </stock> </portfolio>
    32. 32. Code Sample 2 • Import the document from remote web server : – <c:import url="http://www.javacourses.com/stocks.xml" var="xmldoc"/>
    33. 33. Code Sample 3: xml-ex2.jsp <c:import url="http://www.javacourses.com/stocks.xml" var="xmldoc"/> <x:parse xml="${xmldoc}" var="output"/> <x:forEach select="$output/portfolio/stock" var="item"> <x:out select="symbol"/> <x:out select="name"/> <x:out select="price"/> </x:forEach>
    34. 34. Transforming XML • Supports XSLT to transform XML within JSP pages • The result of the transformation is written to the page.
    35. 35. Code Sample 5: xml-ex3.jsp <h3>Transforming stocks.xml into HTML using stocks.xsl</h3> <c:import url="http://www.javacourses.com/stocks.xml" var="xmldocument"/> <c:import url="./stocks.xsl" var="xslt"/> <x:transform xml="${xmldocument}" xslt="${xslt}"/>
    36. 36. The SQL Tag Library http://java.sun.com/jstl/sql
    37. 37. The SQL Tag Library • For special and unique situations • E.g.: – prototyping/testing – small scale/simple applications – lack of developer resources • Provide basic capabilities to interact with databases.
    38. 38. The SQL Tag Library • Perform database queries (select) • Easily access query results • Perform database updates (insert, update, delete) • Run transactions
    39. 39. Data Source • SQL actions operate on a data source • Is specified by: – dataSource attribute in SQL actions – configuration setting: javax.servlet.jsp.jstl.sql.dataSou rce. – data source action: • JNDI relative path. • JDBC Parameters
    40. 40. Querying a Database • <sql:query>
    41. 41. Querying a Database <sql:query var="customers" dataSource="${dataSource}"> SELECT * FROM customers WHERE country = ’China’ ORDER BY lastname </sql:query> ---------------------------------------------------------- <c:forEach var="row" items="${customers.rows}"> <c:out value="${row.lastName}"/> <c:out value="${row.firstName}"/> <c:out value="${row.address}"/> </c:forEach>
    42. 42. Querying a Database <!-- column headers --> <c:forEach var=”columnName” items=”${result.columnNames}”> <c:out value="${columnName}"/> </c:forEach> ---------------------------------------------------------- <!-- column data --> <c:forEach var="row" items="${result.rowsByIndex}"> <c:forEach var="column" items="${row}"> <td><c:out value="${column}"/></td> </c:forEach> </c:forEach>
    43. 43. Updating a Database • <sql:update>
    44. 44. Updating a Database <sql:transaction dataSource="${dataSource}"> <sql:update> UPDATE account SET Balance = Balance - ? WHERE accountNo = ? <sql:param value="${transferAmount}"/> <sql:param value="${accountFrom}"/> </sql:update> <sql:update> UPDATE account SET Balance = Balance + ? WHERE accountNo = ? <sql:param value="${transferAmount}"/> <sql:param value="${accountTo}"/> </sql:update> </sql:transaction>
    45. 45. SQL Statement Parameters • Implemented by – <sql:query> – <sql:update>
    46. 46. SQL Statement Parameters <sql:update> UPDATE PersonalInfo SET BirthDate = ? WHERE clientId = ? <acme:dateParam year="${year}" month="${month}" day="${day}"/> <sql:param value=”${clientId}”/> </sql:update> ----------------------------------------------------------------- <sql:update sql="${sqlUpdateStmt}” dataSource="${dataSource}"> <fmt:parseDate var="myDate" value="${someDate}”/> <sql:param value="${myDate}"/> </sql:update>
    47. 47. Database Access • Implemented actions: – <sql:query> – <sql:update> – <sql:transaction> • DataSource attribute of the SQL action. • DataSource name at the “javax.servlet.jsp.jstl.sql.dataSource” configuration setting: – DataSource object – String • Retrieve the data source from the JNDI relative path • JDBC parameters
    48. 48. Database Access • <sql:query> • <sql:update> • <sql:transaction> • <sql:setDataSource> • <sql:param> • <sql:dateParam>
    49. 49. Configuration Settings
    50. 50. Developing and Using Functions
    51. 51. Developing and Using Functions • Define expression functions. • Must be programmed as – public static method – public class. • Map signature in a (TLD). – Write the Java code – Map function's signature in the tag library – Write the JSP page that uses the function
    52. 52. Developing and Using Functions package jsp2.examples.el; import java.util.*; public class Compute { public static int add(String x, String y) { int a = 0; int b = 0; try { a = Integer.parseInt(x); b = Integer.parseInt(y); } catch(Exception e) { } return a + b; } }
    53. 53. Developing and Using Functions <function> <description>add x and y</description> <name>add</name> <function-class>jsp2.examples.el.Compute </function-class> <function-signature> int add(java.lang.String,java.lang.String) </function-signature> </function>
    54. 54. Developing and Using Functions <%@ taglib prefix="my" uri="http://jakarta.apache.org/tomcat/jsp2-example- taglib %> <BODY> <H3>Add Numbers</H3> <P> <FORM action="/developer/technicalArticles/javaserverpages/JSP20/math.jsp" method="GET"> X = <input type="text" name="x" value="${param["x"]}"> <BR> Y = <input type="text" name="y" value="${param["y"]}"> <input type="submit" value="Add Numbers"> </FORM> <P> The sum is: ${my:add(param["x"],param["y"])} </BODY> </HTML>
    55. 55. Tag Handlers
    56. 56. Tag Handlers • Simple Tag Extension (JSP2.0/JSTL1.2) – Java developers: implement javax.servlet.jsp.tagext.SimpleTag interface. – Page authors: tag files.
    57. 57. Implementing SimpleTag • Implement javax.servlet.jsp.tagext.Simpl eTag interface. • Define a tag descriptor in a TLD • JSP page that uses the tag
    58. 58. Implementing SimpleTag package jsp2.examples.simpletag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; /** * SimpleTag handler that prints "This is my first tag!“ */ public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().write("This is my first tag!"); } }
    59. 59. Implementing SimpleTag <tag> <description>Prints this is my first tag</description> <name>hello</name> <tag-class>jsp2.examples.simpletag.HelloTag</tag-class> <body-content>empty</body-content> </tag>
    60. 60. Implementing SimpleTag <%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %> <HTML> <HEAD> <TITLE>Simple Tag Handler</TITLE> </HEAD> <BODY> <H2>Simple Tag Handler</H2> <P> <B>My first tag prints</B>: <mytag:hello/> </BODY> </HTML>
    61. 61. Tag File
    62. 62. Tag File • Make JSP code reusable • Allow to create reusable tag libraries • .tag extesion
    63. 63. Tag File Hello there. How are you doing?
    64. 64. Tag File <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> <HTML> <HEAD> <TITLE>JSP 2.0 Examples - Hello World Using a Tag File</TITLE> </HEAD> <BODY> <H2>Tag File Example</H2> <P> <B>The output of my first tag file is</B>: <tags:greetings/> </BODY> </HTML>
    65. 65. Tag File Templates • Can be used as a template.
    66. 66. Tag File Templates • E.g. display.tag: <%@ attribute name="color" %> <%@ attribute name="bgcolor" %> <%@ attribute name="title" %> <TABLE border="0" bgcolor="${color}"> <TR> <TD> <B>${title}</B> </TD> </TR> <TR> <TD bgcolor="${bgcolor}"> <jsp:doBody/> </TD> </TR> </TABLE>
    67. 67. Tag File Templates • E.g. newsportal.jsp <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> <TABLE border="0"> <TR><TD> <tags:display color="#ff0000" bgcolor="#ffc0c0" title="Travel"> Last French Concorde Arrives in NY<br/> </tags:display> </TD><TD> <tags:display color="#00fc00" bgcolor="#c0ffc0" title="Technology"> Java for in-flight entertainment<BR> </tags:display> </TD><TD> <tags:display color="#ffcc11" bgcolor="#ffffcc" title="Sports"> American Football<BR/> </tags:display> </TD></TR> </TABLE>
    68. 68. I18N capable formatting tag library http://java.sun.com/jstl/fmt
    69. 69. Internationalization (i18n) Actions
    70. 70. I18N Key Concepts • Three internationalization key concepts: – Locale • Language code (e.g. “ca” for Catalan, “zh” for Chinese) • Optional country code (e.g.“IT” for Italy, “CR” for Costa Rica). – Resource bundle - contains locale-specific objects. A specific resource bundle is uniquely identified by combining its basename with a locale. – Basename – Identifies resource bundle group
    71. 71. I18N Key Concepts • E.g. basename Registration • two resource bundles: – Registration_fr (French language) – Registration_en (English language).
    72. 72. <fmt:message> • <fmt:message> - I18N a message – <fmt:param> - Supports message variables.
    73. 73. <fmt:message> <fmt:message key="greeting"/> ------------------------------------------------ --- <fmt:message key="athletesRegistered"> <fmt:param> <fmt:formatNumber value=”${athletesCount}”/> </fmt:param> </fmt:message>
    74. 74. I18n Localization Context • Localization context contains two pieces of information – Resource bundle – Locale for which the resource bundle was found. • i18n localization is determined in one of several ways: – <fmt:message> bundle attribute – Enclosing <fmt:bundle> action and basename attribute – I18n default localization context • javax.servlet.jsp.jstl.fmt.localizationContext configuration setting. – type LocalizationContext – type String.
    75. 75. I18n Localization Context <%-- Use configuration setting --%> ---------------------------------------------------------------------- --- <fmt:message key="Welcome" /> ---------------------------------------------------------------------- --- <fmt:setBundle basename="Errors" var="errorBundle" /> ---------------------------------------------------------------------- --- <fmt:bundle basename="Greetings"> <%-- Localization context established by parent <fmt:bundle> tag --%> <fmt:message key="Welcome" /> <%-- Localization context established by attribute bundle --%> <fmt:message key="WrongPassword" bundle="${errorBundle}" /> </fmt:bundle>
    76. 76. Preferred Locales • Setting prefered locale by – Application-based (priority) •javax.servlet.jsp.jstl.fmt.locale configuration setting – Browser-based • browser settings – ServletRequest.getLocales()
    77. 77. Preferred Locales • <fmt:setLocale> - set javax.servlet.jsp.jstl.fmt.loca le configuration variable – E.g. •<fmt:setLocale value=”en_US” />
    78. 78. Resource Bundle Lookup • Searched in the following order: – basename + "_" + language + "_" + country + "_" + variant – basename + "_" + language + "_" + country – basename + "_" + language
    79. 79. Resource Bundle Determination Algorithm • Step 1: Find a match within the ordered set of preferred locales • Step 2: Find a match with the fallback locale: javax.servlet.jsp.jstl.fmt.fall backLocale • load the root resource bundle with the given basename
    80. 80. Response Encoding • Set the locale – <fmt:setLocale> – <fmt:bundle> – <fmt:message> – formatting actions • Set the encoding – <fmt:requestEncoding>
    81. 81. Commands Summary • <fmt:setLocale> - stores the locale. Disables Browser-based locale setting capabilities. • <fmt:bundle> - Creates i18n context to be used by its body content • <fmt:setBundle> - creates an i18n context
    82. 82. Commands Summary • <fmt:message> • <fmt:param> - param to containing <fmt:message> • <fmt:requestEncoding> - character encoding
    83. 83. Configuration Settings
    84. 84. Configuration Settings
    85. 85. Formatting Actions
    86. 86. Formatting Actions • Format and parse elements in a locale- sensitive or customized manner
    87. 87. Formatting Numbers, Currencies, and Percentages • <fmt:formatNumber> - format numbers, currencies, and percentages according to the client’s cultural formatting conventions. • <fmt:formatNumber value="9876543.21" type="currency"/> • <fmt:formatNumber value="12.3" pattern=".000"/> • <fmt:formatNumber value="123456.7891" pattern="#,#00.0#"/> • <fmt:formatNumber value="123456789" type="currency" var="cur"/> • <fmt:parseNumber value="${cur}" type="currency"/>
    88. 88. Formatting Dates and Times • <jsp:useBean id="now" class="java.util.Date" /> • <fmt:formatDate value=”${now}” timeStyle="long" • dateStyle="long"/> • <fmt:formatDate value=”${now}” pattern="dd.MM.yy"/> • <fmt:timeZone value="GMT+1:00"> • <fmt:formatDate value=”${now}” type="both" dateStyle="full" • timeStyle="full"/> • </fmt:timeZone>
    89. 89. Formatting Locale • <jsp:useBean id="now" class="java.util.Date" /> • <%-- Formatting locale lookup --%> • <fmt:formatDate value=”${now}” /> • <fmt:bundle basename="Greetings"> • <%-- I18n localization context from parent <fmt:bundle> tag --%> • <fmt:message key="Welcome" /> • <fmt:formatDate value=”${now}” /> • </fmt:bundle>
    90. 90. Actions • <fmt:timeZone> • <fmt:timeZone value=”timeZone”> • body content • </fmt:timeZone> • <fmt:setTimeZone> • <fmt:setTimeZone value=”timeZone” • [var=”varName”] • [scope=”{page|request|session|application}”]/> • <fmt:formatDate> • <fmt:parseDate>
    91. 91. Configuration Settings
    92. 92. Functions function tag library
    93. 93. Functions • fn:contains • fn:containsIgnoreCase • fn:endsWith • fn:escapeXml • fn:indexOf • fn:join • fn:length • fn:replace • fn:split • fn:startsWith • fn:substring • fn:substringAfter • fn:substringBefore • fn:toLowerCase • fn:toUpperCase • fn:trim
    94. 94. JSTL 1.2 • <c:forTokens> • <x:param> - Set transformation parameters.
    95. 95. Conclusion • Simpler consistent programming environment. • Advanced programmers may prefer scriptlets. • JavaBeans are used in conjunction with JSTL. • Easier to develop and maintain.
    96. 96. For More Information • Fast Track JSP 1.2 • JavaServer Pages Technology • JavaServer Pages Specification (JSR 152) • The Tomcat 5 Servlet/JSP Container • JSP Developers Forum • JavaServer Pages Standard Tag Library (JSTL) • Faster Development with JavaServer Pages Standard Tag Library (JSTL 1.0)
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×