Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
JavaServer Pages™
Specification
Version2.0
(originally1.3)
f t
D ra
b l ic
P u
Tuesday, June 18, 2002
Mark Roth
Eduardo Pelegrí-Llopart
Version: 2.0
Status: Pre-FCS
Release: June 18, 2002
Copyright 2002 Sun Microsystems, Inc.
4150 Network Circle, Santa Clara, California 95054, U.S.A
All rights reserved.
NOTICE
The Specification is protected by copyright and the information described
therein may be protected by one or more U.S. patents, foreign patents, or pending
applications. Except as provided under the following license, no part of the
Specification may be reproduced in any form by any means without the prior
written authorization of Sun Microsystems, Inc. (“Sun”) and its licensors, if any.
Any use of the Specification and the information described therein will be
governed by the terms and conditions of this license and the Export Control and
General Terms as set forth in Sun’s website Legal Terms. By viewing,
downloading or otherwise copying the Specification, you agree that you have
read, understood, and will comply with all of the terms and conditions set forth
herein.
Subject to the terms and conditions of this license, Sun hereby grants you a
fully-paid, non-exclusive, non-transferable, worldwide, limited license (without
the right to sublicense) under Sun’s intellectual property rights to review the
Specification internally for the purposes of evaluation only. Other than this limited
license, you acquire no right, title or interest in or to the Specification or any other
Sun intellectual property. The Specification contains the proprietary and
confidential information of Sun and may only be used in accordance with the
license terms set forth herein. This license will expire ninety (90) days from the
date of Release listed above and will terminate immediately without notice from
Sun if you fail to comply with any provision of this license. Upon termination,
you must cease use of or destroy the Specification.
TRADEMARKS
No right, title, or interest in or to any trademarks, service marks, or trade
names of Sun or Sun’s licensors is granted hereunder. Sun, Sun Microsystems, the
Sun logo, Java, the Java Coffee Cup logo, JSP, and JavaServer Pages are
PUBLIC DRAFT
iv
DISCLAIMER OF WARRANTIES
THE SPECIFICATION IS PROVIDED “AS IS” AND IS EXPERIMENTAL
AND MAY CONTAIN DEFECTS OR DEFICIENCIES WHICH CANNOT OR
WILL NOT BE CORRECTED BY SUN. SUN MAKES NO
REPRESENTATIONS OR WARRANTIES, EITHER EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO, WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-
INFRINGEMENT THAT THE CONTENTS OF THE SPECIFICATION ARE
SUITABLE FOR ANY PURPOSE OR THAT ANY PRACTICE OR
IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY
THIRD PARTY PATENTS, COPYRIGHTS, TRADE SECRETS OR OTHER
RIGHTS. This document does not represent any commitment to release or
implement any portion of the Specification in any product.
THE SPECIFICATION COULD INCLUDE TECHNICAL
INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE
PERIODICALLY ADDED TO THE INFORMATION THEREIN; THESE
CHANGES WILL BE INCORPORATED INTO NEW VERSIONS OF THE
SPECIFICATION, IF ANY. SUN MAY MAKE IMPROVEMENTS AND/OR
CHANGES TO THE PRODUCT(S) AND/OR THE PROGRAM(S)
DESCRIBED IN THE SPECIFICATION AT ANY TIME. Any use of such
changes in the Specification will be governed by the then-current license for the
applicable version of the Specification.
LIMITATION OF LIABILITY
TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL
SUN OR ITS LICENSORS BE LIABLE FOR ANY DAMAGES, INCLUDING
WITHOUT LIMITATION, LOST REVENUE, PROFITS OR DATA, OR FOR
SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
OF LIABILITY, ARISING OUT OF OR RELATED TO ANY FURNISHING,
PRACTICING, MODIFYING OR ANY USE OF THE SPECIFICATION, EVEN
IF SUN AND/OR ITS LICENSORS HAVE BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
You will indemnify, hold harmless, and defend Sun and its licensors from any
claims based on your use of the Specification for any purposes other than those of
PUBLIC DRAFT
v
internal evaluation, and from any claims that later versions or releases of any
Specification furnished to you are incompatible with the Specification provided to
you under this license.
REPORT
You may wish to report any ambiguities, inconsistencies or inaccuracies you
may find in connection with your evaluation of the Specification (“Feedback”). To
the extent that you provide Sun with any Feedback, you hereby: (i) agree that such
Feedback is provided on a non-proprietary and non-confidential basis, and (ii)
grant Sun a perpetual, non-exclusive, worldwide, fully paid-up, irrevocable
license, with the right to sublicense through multiple levels of sublicensees, to
incorporate, disclose, and use without limitation the Feedback for any purpose
related to the Specification and future versions, implementations, and test suites
thereof.
LFI#113874/Form ID#01180
PUBLIC DRAFT
vi
PUBLIC DRAFT
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
The JavaServer Pages™ Technology . . . . . . . . . . . . . . . . . . . . . . xxv
Basic Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxviii
Users of JavaServer Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxx
PART I. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1
JSP.1 Core Syntax and Semantics . . . . . . . . . . . . . . . . . . . . . . . 1-2
JSP.1.1 What is a JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
JSP.1.1.1 Web Containers and Web Components . . . . . . 1-2
JSP.1.1.2 XML Document for a JSP Page . . . . . . . . . . . . 1-3
JSP.1.1.3 Translation and Execution Phases . . . . . . . . . . 1-3
JSP.1.1.4 Events in JSP Pages . . . . . . . . . . . . . . . . . . . . . 1-4
JSP.1.1.5 JSP Configuration Information . . . . . . . . . . . . 1-4
JSP.1.1.6 Naming Conventions for JSP Files . . . . . . . . . 1-4
JSP.1.1.7 Compiling JSP Pages . . . . . . . . . . . . . . . . . . . . 1-5
JSP.1.1.8 Debugging JSP Pages . . . . . . . . . . . . . . . . . . . 1-6
JSP.1.2 Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
JSP.1.2.1 Relative URL Specifications . . . . . . . . . . . . . . 1-7
JSP.1.3 Syntactic Elements of a JSP Page . . . . . . . . . . . . . . . . . 1-8
JSP.1.3.1 Elements and Template Data . . . . . . . . . . . . . . 1-8
JSP.1.3.2 Element Syntax . . . . . . . . . . . . . . . . . . . . . . . . 1-8
JSP.1.3.3 Start and End Tags . . . . . . . . . . . . . . . . . . . . . . 1-9
JSP.1.3.4 Empty Elements . . . . . . . . . . . . . . . . . . . . . . . . 1-9
JSP.1.3.5 Attribute Values Using XML Attributes . . . . 1-10
JSP.1.3.6 Attribute Values Using XML Elements . . . . . 1-10
JSP.1.3.7 Valid Names for Actions and Attributes . . . . 1-11
JSP.1.3.8 White Space . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
JSP.1.3.9 Standard JSP Syntax Grammar . . . . . . . . . . . 1-13
JSP.1.4 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-25
JSP.1.4.1 Translation Time Processing Errors . . . . . . . . 1-25
JSP.1.4.2 Request Time Processing Errors . . . . . . . . . . 1-25
PUBLIC DRAFT
ix
PUBLIC DRAFT
x
PUBLIC DRAFT
xii
PUBLIC DRAFT
xiii
PART II . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1
JSP.10 JSP Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
JSP.10.1 JSP Page Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
JSP.10.1.1 Protocol Seen by the Web Server . . . . . . . . . . 2-2
JSP.10.2 JSP Page Implementation Class . . . . . . . . . . . . . . . . . . 2-4
JSP.10.2.1 API Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
JSP.10.2.2 Request and Response Parameters . . . . . . . . . . 2-6
JSP.10.2.3 Omitting the extends Attribute . . . . . . . . . . . . . 2-6
JSP.10.2.4 Using the extends Attribute . . . . . . . . . . . . . . 2-10
JSP.10.3 Buffering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
JSP.10.4 Precompilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
JSP.10.4.1 Request Parameter Names . . . . . . . . . . . . . . . 2-11
JSP.10.4.2 Precompilation Protocol . . . . . . . . . . . . . . . . . 2-12
JSP.10.5 Debugging Requirements . . . . . . . . . . . . . . . . . . . . . . 2-12
JSP.11 Core API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
JSP.11.1 JSP Page Implementation Object Contract . . . . . . . . . 2-14
JSP.11.1.1 JspPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
JSP.11.1.2 HttpJspPage . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
JSP.11.1.3 JspFactory . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
JSP.11.1.4 JspEngineInfo . . . . . . . . . . . . . . . . . . . . . . . . 2-18
JSP.11.2 Implicit Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
JSP.11.2.1 JspContext . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
JSP.11.2.2 PageContext . . . . . . . . . . . . . . . . . . . . . . . . . . 2-23
JSP.11.2.3 JspWriter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-29
JSP.11.3 An Implementation Example . . . . . . . . . . . . . . . . . . . 2-37
JSP.11.4 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-37
JSP.11.4.1 JspException . . . . . . . . . . . . . . . . . . . . . . . . . 2-37
JSP.11.4.2 JspTagException . . . . . . . . . . . . . . . . . . . . . . 2-39
PUBLIC DRAFT
xiv
PUBLIC DRAFT
xv
PUBLIC DRAFT
Preface
JSP 2.0 extends JavaServer Pages™ 1.2 Specification (JSP 1.2) in the following
ways:
• Adding new syntax elements for defining custom actions using the JSP tech-
nology directly. These elements are delivered into .tag files which can be au-
thored by developers and page authors alike to provide encapsulation and
reusability of common actions.
• Adding a new Simple Invocation Protocol that exploits what we expect to be
the prevalent use of script-less pages. The simple invocation protocol avoids
the complex “inverted closure” mechanism of the classic invocation protocol
introducted in JSP 1.1 and is used for implementing the tag files.
We expect to add a number of other features before the Proposed Final Draft.
The Expert Group has already discussed most of them but some of them are better
understood than others; among the former are:
• Improve the XML syntax of JSP using namespaces rather than requiring all
documents to use jsp:root.
• Conversion of the TLD to XML schema.
• Making the JSP technology usable as a general templating mechanism sepa-
rate from Servlets.
• Adding additional information to the TLD so page authoring tools can pro-
vide a better user experience.
In combination with the JSP Standard Tag Library, the new features introduced
in this specification (such as a built-in expression language, a new invocation proto-
col and JSP fragments) will have a substantial impact on the methodology page
authors will use to write JSPs. The impact is strong enough that the expert group felt
it was appropriate the upgrade the major version number of the JSP specification to
JSP 2.0.
Among other benefits, we believe this version number upgrade will help draw
developer’s attention to these new features. It will also allow one to more easily
differentiate between the two different programming models (JSP 1.x style vs.
JSP 2.x style).
PUBLIC DRAFT
xix
Licensing of Specification
Details on the conditions under which this document is distributed are described
in the license on page 2.
Related Documents
Implementors of JSP containers and authors of JSP pages may find the follow-
ing documents worth consulting for additional information:
PUBLIC DRAFT
xx
Historical Note
The following individuals were pioneers who did ground-breaking work in the
Java platform areas related to this specification: James Gosling’s work on a Web
Server in Java in 1994/1995, became the foundation for servlets. A larger project
emerged in 1996 with Pavani Diwanji as lead engineer and with many other key
members listed below. From this project came Sun’s Java Web Server product.
Things started to move quickly in 1999. The servlet expert group, with James
Davidson as lead, delivered the Servlet 2.1 specification in January and the Servlet
2.2 specification in December, while the JSP group, with Larry Cable and
Eduardo Pelegri-Llopart as leads, delivered JSP 1.0 in June and JSP 1.1 in
December.
The year 2000 saw a lot of activity, with many implementations of containers,
tools, books, and training that target JSP 1.1, Servlet 2.2, and the Java 2 Enterprise
Edition platform. Tag libraries were an area of intense development, as were
varying approaches to organizing all these features together. The adoption of JSP
technology has continued in the year 2001, with many talks at the “Web, Services
and beyond” track at JavaOne being dedicated to the technology.
Tracking the industry in a printed document is at best difficult; the industry
pages at the web site at http://java.sun.com/products/jsp do a better job.
PUBLIC DRAFT
xxi
Note – More history will go here.. - Including some on JSP 1.2, and JSP 2.0
Acknowledgments
Note – In progress...
PUBLIC DRAFT
xxii
PUBLIC DRAFT
Status
This is the Public Draft for the JSP 2.0 specification, developed by the expert
group JSR-152 under the Java Community Process (more details at http://jcp.org/
jsr/detail/152.jsp).
The original Java Specification Request (JSR-152) listed the version number
of the specification as 1.3. The scope and content of the specification effort has
not changed, but the Expert Group realized that the new features would have a
deep impact in the development model of JSP applications and decided that 2.0
would more appropriatedly reflect that impact.
In the tradition of previous JSP specifications, we plan an early access
implementation of this draft to get practical experience that we can incorporate
into later Public Drafts. This approach has been very succesful in delivering
usable features.
The JCP is designed to be a very flexible process so each expert group can
address the requirements of the specific communities it serves. The reference imple-
mentation for JSP 2.0 and Servlet 2.4 uses code that is being developed as an open
source project under an agreement with the Apache Software Foundation.
This specification includes chapters that are derived directly from the javadoc
comments in the API classes, but, were there to be any discrepancies, this
specification has precedence over the javadoc comments.
The JCP process provides a mechanism for updating the specification through
a maintenance process using Erratas. If they are available, the erratas will have
precedence over this specification.
Appendices C and D are normative; the other appendices are non-normative.
PUBLIC DRAFT
Overview
General Concepts
The JavaServer Pages technology provides the means for textual specification of
the creation of a dynamic response to a request. The technology builds on the fol-
lowing concepts:
• Template Data
A substantial portion of most dynamic content is fixed or template content.
Text or XML fragments are typical template data. JSP technology supports
natural manipulation of template data.
• Encapsulation of Functionality
JSP technology provides two related mechanisms for the encapsulation of
functionality: JavaBeans component architecture, and tag libraries delivering
custom actions, functions, listener classes and validation.
• Separation of Roles
JSP supports the separation of developer and author roles: Developers write
components that interact with server-side objects. Authors put static data and
dynamic content together to create presentations suited for their intended
audiences.
Each group may do their job without knowing the job of the other. Each role
emphasizes different abilities and, although these abilities may be present in
the same individual, they most commonly will not be. Separation allows a nat-
ural division of labor.
A subset of the developer community may be engaged in developing reusable
components intended to be used by authors.
PUBLIC DRAFT
xxvii
PUBLIC DRAFT
xxviii
Basic Concepts
This section introduces basic concepts that will be defined formally later in the
specification.
• Standard directives
• Standard actions
• Scripting elements
• Tag Extension mechanism
• Template content
Web Applications
The concept of a web application is inherited from the Servlet specification. A
web application can be composed from:
PUBLIC DRAFT
xxix
The JavaServer Pages specification inherits from the Servlet specification the
concepts of web applications, ServletContexts, sessions, requests and responses.
See the Java Servlet 2.4 specification for more details.
JSP pages may be translated prior to their use, providing the web application,
with a servlet class that can serve as the textual representation of the JSP page.
The translation may also be done by the JSP container at deployment time, or
on-demand as the requests reach an untranslated JSP page.
PUBLIC DRAFT
xxx
There are six classes of users that interact with JavaServer Pages technology.
This section describes each class of user, enumerates the technologies each must be
familiar with, and identifies which sections of this specification are most relevant to
each user class. The intent is to ensure that JavaServer Pages remains a practical and
easy-to-use technology for each class of user, even as the language continues to
grow.
Page Authors
Page Authors are application component providers that use JavaServer Pages to
develop the presentation component of a web application. It is expected that they
will not make use of the scripting capabilities of JavaServer Pages, but rather limit
their use to standard and custom actions. Therefore, it is assumed that they know the
target language (e.g. HTML or XML), and basic XML concepts, but they need not
know Java at all.
The following sections are most relevant to this class of user:
• Chapter JSP.1, “Core Syntax and Semantics”, except for Section JSP.1.12,
“Scripting Elements” and Section JSP.1.14, “Tag Attribute Interpretation Se-
mantics” which both talk about scripting.
• Chapter JSP.2, “Expression Language”
• Chapter JSP.3, “JSP Configuration”
• Chapter JSP.4, “Localization Issues”
• Chapter JSP.5, “Standard Actions”
• Chapter JSP.6, “JSP Documents”, except for sections that discuss declara-
tions, scriplets, expressions, and request-time attributes, and except for
Section JSP.6.4, “Validating an XML View of a JSP page”.
PUBLIC DRAFT
xxxi
PUBLIC DRAFT
xxxii
Deployers
A deployer is an expert in a specific operational environment who is responsible
for configuring a web application for, and deploying the web application to, that
environment. The deployer does not need to understand the target language or Java,
but must have an understanding of XML or use tools that provide the ability to read
deployment descriptors.
The following sections are most relevant to this class of user:
• Section JSP.1.1, “What is a JSP Page” and Section JSP.1.2, “Web Applica-
tions” of Chapter JSP.1, “Core Syntax and Semantics”
• Chapter JSP.3, “JSP Configuration”
• Chapter JSP.4, “Localization Issues”
• Chapter JSP.10, “JSP Container”
• All Appendices.
PUBLIC DRAFT
xxxiii
Note –
PUBLIC DRAFT
PART I
T he next chapters form the core of the JSP specification. These chapters pro-
vide information for Page authors, Tag Library developers, deployers and Container
and Tool vendors.
The chapter of this part are
Note – The XML syntax part of the JSP Documents should be integrated with
the Core Syntax Chapter. The XML view part should probably go to Part II.
Note – Most of the JSP fragments chapter moves elsewhere; the rest becomes
a chapter focused on Tag files which probably moves ahead.
This chapter describes the core syntax and semantics for the JavaServer Pages
2.0 specification (JSP 2.0).
A JSP page is a textual document that describes how to create a response object
from a request object for a given protocol. The processing of the JSP page may
involve creating and/or using other objects.
A JSP page defines a JSP page implementation class that implements the
semantics of the JSP page. This class is a subclass of Servlet (see Chapter JSP.10
for details). At request time a request intended for the JSP page is delivered to the
JSP page implementation object for processing.
HTTP is the default protocol for requests and responses. Additional request/
response protocols may be supported by JSP containers (See below). The default
request and response objects are of type HttpServletRequest and HttpServletRe-
sponse respectively.
Note – This will be revisited after incorporating the XML syntax changes.
PUBLIC DRAFT
What is a JSP Page 1-4
PUBLIC DRAFT
1-5 CORE SYNTAX AND SEMANTICS
By default the extension “.jsp” means a JSP page, but we recommend, but do
not mandate, to differentiate between top-level JSP pages and included pages so
that:
• “.jsp” files correspond to top level JSP files containing a JSP page.
• Included fragments not use the “.jsp” extension. Any other extension will do,
although “.jspf” and “.jsf” seem reasonable extensions and are offered as sug-
gestions.
• Removal of the start-up lag that occurs when a container must translate a JSP
page upon receipt of the first request.
• Reduction of the footprint needed to run a JSP container, as the java compiler
is not needed.
PUBLIC DRAFT
Web Applications 1-6
1. A JSP page delivered in source form (probably the most common case).
2. A JSP page translated into an implementation class plus deployment informa-
tion. The deployment information indicates support classes needed and the
mapping between the original URL path to the JSP page and the URL for the
JSP page implementation class for that page.
Web applications are described in more detail in the Servlet 2.4 specification.
A web application contains a deployment descriptor web.xml that contains
information about the JSP pages, servlets, and other resources used in the web
PUBLIC DRAFT
1-7 CORE SYNTAX AND SEMANTICS
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-8
translation. The semantics outlined here apply to the translation-time phase, and
to the request-time phase.
Directives
Directives provide global information that is conceptually valid independent
of any specific request received by the JSP page. They provide information for
the translation phase.
Directive elements have a syntax of the form <%@ directive...%>
Actions
Actions provide information for the request processing phase. The interpreta-
tion of an action may, and often will, depend on the details of the specific
request received by the JSP page. An Actions can either be standard, that is.
defined in this specification, or custom, that is provided via the portable tag
extension mechanism.
PUBLIC DRAFT
1-9 CORE SYNTAX AND SEMANTICS
Action elements follow the syntax of an XML element.: They have a start tag
including the element name, and may have attributes, an optional body, and a
matching end tag, or they be an empty tag possibly with attributes:
and
An element has an element type describing its tag name, its valid attributes
and its semantics. We refer to the type by its tag name.
JSP tags are case-sensitive, as in XML and XHTML.
An action may create objects and may make them available to the scripting
elements through scripting-specific variables.
Scripting Elements
Scripting elements provide glue around template text and actions. There are
three types of scripting elements: declarations, scriptlets and expressions.
Declarations follow the syntax <%! ... %>; scriptlets follow the syntax
<% ... %>; expressions follow the syntax <%= ... %>.
<x:foo></x:foo>
<x:foo />
<x:foo/>
<x:foo><%-- any comment --%></x:foo>
<foo> </foo>
<foo><%= expression %></foo>
<foo><% scriptlet %></foo>
<foo><bar/></foo>
<foo><!-- a comment --></foo>
PUBLIC DRAFT
1-11 CORE SYNTAX AND SEMANTICS
The following example uses an XML element attribute to define the value of
the param1 attribute, and uses an attribute standard action to define the value of
the param2 attribute. In this example, the value of param2 comes from the result
of a custom action invocation.
<mytag:paramTag param1=”value1”>
<jsp:attribute name=”param2”>
<mymath:add x=”2” y=”2”/>
</jsp:attribute>
</mytag:paramTag>
If a page author wishes to pass both an attribute standard action and a tag
body, the <jsp:body> standard action must be used to specify the body. A
translation error will result if the custom action invocation has <jsp:attribute>
elements but does not define the body using a <jsp:body> element. See
Section JSP.5.11 for more details on the <jsp:body> standard action.
The following example shows two equivalent tag invocations to the
hypothetical <mytag:formatBody> custom action. The first invocation uses an
XML element attribute to pass the values of the color and size attributes. The
second example uses an attribute standard action to pass the value of the color
attribute. Both examples have tag body containing simply the words “Template
Text”.
<mytag:tagWithBody size=”12”>
<jsp:attribute name=”color”>blue</jsp:attribute>
<jsp:body>
Template Text
</jsp:body>
</mytag:tagWithBody>
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-12
The result is
The next two tables show another example, with input and output.,
The result is
PUBLIC DRAFT
1-13 CORE SYNTAX AND SEMANTICS
http://www.w3c.org/TR/2000/REC-xml-20001006#sec-notation
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-14
the attribute is required and must appear in order for this production to be
matched. If an attribute that matches the “Attribute” production with a name
not listed appears adjacent to any of the other attributes, the production is not
matched.
For example, consider the production ATTR[ !name, =value, =!repeat ]. This
production is matched if and only if all of the following hold true:
• The name attribute appears extactly once and matches the NonRTAttribute
production.
• The value attribute appears at most once. If it appears, the Attribute pro-
duction must be matched.
• The repeat attribute appears exactly once and matches the Attribute pro-
duction.
• There must be no other attributes aside from name, value, or repeat.
PUBLIC DRAFT
1-15 CORE SYNTAX AND SEMANTICS
JSPDirectiveBody ::= S?
( ( ‘page’ S PageDirectiveAttrList )
| ( ‘taglib’ S TagLibDirectiveAttrList )
| ( ‘include’ S IncludeDirectiveAttrList )
)
S? ‘%>’
| <TRANSLATION_ERROR>
TagDefDirectiveBody::= S?
( ( ‘tag’ S TagDirectiveAttrList )
| ( ‘taglib’ S TagLibDirectiveAttrList )
| ( ‘include’ S IncludeDirectiveAttrList )
| ( ‘attribute’ S AttributeDirectiveAttrList )
| ( ‘variable’ S VariableDirectiveAttrList )
| ( ‘fragment-input’ S
FragmentInputDirectiveAttrList
)
)
S? ‘%>’
| <TRANSLATION_ERROR>
IncludeDirectiveAttrList::=ATTR[ !file ]
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-16
PUBLIC DRAFT
1-17 CORE SYNTAX AND SEMANTICS
ScriptlessOptionalBody::=EmptyBody | ScriptlessActionBody
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-18
AttributeBodyRequired::=‘>’(ScriptlessBody - ‘’)‘</jsp:attribute>’
PUBLIC DRAFT
1-19 CORE SYNTAX AND SEMANTICS
CustomActionJSPContent::= OptionalBody
[ vc: CustomActionJSPContentMatch ]
CustomActionScriptlessContent::= ScriptlessOptionalBody
[ vc: CustomActionScriptlessContentMatch ]
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-20
PUBLIC DRAFT
1-21 CORE SYNTAX AND SEMANTICS
S ::= XML::S
Eq ::= XML::Eq
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-22
PUBLIC DRAFT
1-23 CORE SYNTAX AND SEMANTICS
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-24
Table JSP.1-5 Valid body content and attributes for Standard Actions
Element Body Production Valid Attribute Combinations
PUBLIC DRAFT
1-25 CORE SYNTAX AND SEMANTICS
Table JSP.1-5 Valid body content and attributes for Standard Actions
jsp:invoke EmptyBody ( !fragment, !varReader, scope)
ParamBody ( !fragment )
Errors may occur at translation time or at request time. This section describes
how errors are treated by a compliant implementation.
1.
Note that this is independent of scripting language. This specification re-
quires that unhandled errors occurring in a scripting language environ-
ment used in a JSP container implementation to be signalled to the JSP
page implementation class via the Java programming language exception
mechanism.
PUBLIC DRAFT
Comments 1-26
These exceptions may be caught and handled (as appropriate) in the body of
the JSP page implementation class.
Any uncaught exceptions thrown in the body of the JSP page implementation
class result in the forwarding of the client request and uncaught exception to the
errorPage URL specified by the JSP page (or the implementation default behavior,
if none is specified).
The offending java.lang.Throwable describing the error that occurred is stored
in the javax.ServletRequest instance for the client request using the setAttribute()
method, using the name “javax.servlet.jsp.jspException”. Names starting with the
prefixes “java” and “javax” are reserved by the different specifications of the Java
platform. The “javax.servlet” prefix is reserved and used by the Servlet and JSP
specifications.
If the errorPage attribute of a page directive names a URL that refers to
another JSP, and that JSP indicates that it is an error page (by setting the page
directive’s isErrorPage attribute to true) then the “exception” implicit scripting
language variable of that page is initialized to the offending Throwable reference
JSP.1.5 Comments
There are two types of comments in a JSP page: comments to the JSP page
itself, documenting what the page is doing; and comments that are intended to
appear in the generated document sent to the client.
PUBLIC DRAFT
1-27 CORE SYNTAX AND SEMANTICS
The body of the content is ignored completely. Comments are useful for
documentation but also are used to “comment out” some portions of a JSP page.
Note that JSP comments do not nest.
An alternative way to place a “comment” in JSP is to use the comment
mechanism of the scripting language. For example:
Quoting in Attributes
Quotation is done consistently regardless of whether the attribute value is a
literal or a request-time attribute expression. Quoting can be used in attribute
values regardless of whether they are delimited using single or double quotes. It is
only required as described below.
■
A ‘ is quoted as \’. This is required within a single quote-delimited attribute
value.
■
A “ is quoted as \”. This is required within a double quote-delimited attribute
value.
■
A \ is quoted as \\
■
A %> is quoted as %\>
■
A <% is quoted as <\%
PUBLIC DRAFT
Quoting and Escape Conventions 1-28
■
The entities ' and " are available to describe single and double
quotes.
Examples
The following line shows an illegal attribute values.
XML Representation
The quoting conventions are different from those of XML. See Chapter JSP.6.
PUBLIC DRAFT
1-29 CORE SYNTAX AND SEMANTICS
• Initially, out is a new JspWriter object. This object may be different from the
stream object returned from response.getWriter(), and may be considered to be
interposed on the latter in order to implement buffering (see
Section JSP.1.10.1, “The page Directive””). This is the initial out object. JSP
page authors are prohibited from writing directly to either the PrintWriter or
OutputStream associated with the ServletResponse.
• The JSP container should not invoke response.getWriter() until the time when
the first portion of the content is to be sent to the client. This enables a number
of uses of JSP, including using JSP as a language to ‘glue’ actions that deliver
binary content, or reliably forwarding to a servlet, or change dynamically the
content type of the respose before generating content. See Chapter JSP.4.
• Within the body of some actions, out may be temporarily re-assigned to a dif-
ferent (nested) instance of JspWriter object. Whether this is the case depends
on the details of the action’s semantics. Typically the content of these tempo-
rary streams is appended to the stream previously referred to by out, and out is
subsequently re-assigned to refer to the previous (nesting) stream. Such nest-
ed streams are always buffered, and require explicit flushing to a nesting
stream or their contents will be discarded.
• If the initial out JspWriter object is buffered, then depending upon the value of
the autoFlush attribute of the page directive, the content of that buffer will ei-
ther be automatically flushed out to the ServletResponse output stream to ob-
viate overflow, or an exception shall be thrown to signal buffer overflow. If the
initial out JspWriter is unbuffered, then content written to it will be passed di-
rectly through to the ServletResponse output stream.
PUBLIC DRAFT
Objects 1-30
A JSP page can also describe what should happen when some specific events
occur. In JSP 2.0, the only events that can be described are the initialization and
the destruction of the page. These events are described using “well-known method
names” in declaration elements. (See Section JSP.10.1.1.1).
JSP.1.8 Objects
A JSP page can access, create, and modify server-side objects. Objects can be
made visible to actions and to scripting elements. An object has a scope describing
what entities can access the object.
Actions can access objects using a name in the PageContext object.
An object exposed through a scripting variable has a scope within the page.
Scripting elements can access some objects directly via a scripting variable.
Some implicit objects are visible via scripting variables in any JSP page.
PUBLIC DRAFT
1-31 CORE SYNTAX AND SEMANTICS
objects are created explicitly through actions, or created directly using scripting
code. Created objects have a scope attribute defining where there is a reference to
the object and when that reference is removed.
The created objects may also be visible directly to scripting elements through
scripting-level variables (see Section JSP.1.8.3, “Implicit Objects”).
Each action and declaration defines, as part of its semantics, what objects it
creates, with what scope attribute, and whether they are available to the scripting
elements.
Objects are created within a JSP page instance that is responding to a request
object. There are several scopes:
• page - Objects with page scope are accessible only within the page where they
are created. All references to such an object shall be released after the response
is sent back to the client from the JSP page or the request is forwarded some-
where else. References to objects with page scope are stored in the pageCon-
text object.
• request - Objects with request scope are accessible from pages processing the
same request where they were created. References to the object shall be re-
leased after the request is processed. In particular, if the request is forwarded
to a resource in the same runtime, the object is still reachable. References to
objects with request scope are stored in the request object.
• session - Objects with session scope are accessible from pages processing re-
quests that are in the same session as the one in which they were created. It is
not legal to define an object with session scope from within a page that is not
session-aware (see Section JSP.1.10.1, “The page Directive”). All references
to the object shall be released after the associated session ends. References to
objects with session scope are stored in the session object associated with the
page activation.
• application - Objects with application scope are accessible from pages pro-
cessing requests that are in the same application as they one in which they were
created. Objects with application scope can be defined (and reached) from pag-
es that are not session-aware. References to objects with application scope are
stored in the application object associated with a page activation. The
application object is the servlet context obtained from the servlet configuration
object. All references to the object shall be released when the runtime environ-
ment reclaims the ServletContext.
PUBLIC DRAFT
Objects 1-32
A name should refer to a unique object at all points in the execution, that is all
the different scopes really should behave as a single name space. A JSP container
implementation may or may not enforce this rule explicitly due to performance
reasons.
Each implicit object has a class or interface type defined in a core Java
technology or Java Servlet API package, as shown in Table JSP.1-6.
Variable
Name Type Semantics & Scope
PUBLIC DRAFT
1-33 CORE SYNTAX AND SEMANTICS
Variable
Name Type Semantics & Scope
Variable
Name Type Semantics & Scope
Object names with prefixes jsp, _jsp, jspx and _jspx, in any combination of
upper and lower case, are reserved by the JSP specification.
PUBLIC DRAFT
Template Text Semantics 1-34
Note – If we make JSP files not depend on Servlets, we may want to expose
the JspContext object, not the PageContext object.
The semantics of template (or uninterpreted) Text is very simple: the template
text is passed through to the current out JspWriter implicit object, after applying the
substitutions of Section JSP.1.6, “Quoting and Escape Conventions”.
JSP.1.10 Directives
Directives are messages to the JSP container. Directives have this syntax:
There may be optional white space after the “<%@” and before “%>”.
This syntax is easy to type and concise but it is not XML-compatible.
Chapter JSP.6 describes the mapping of directives into XML elements.
Directives do not produce any output into the current out stream.
There are three directives: the page and the taglib directives are described
next, while the include directive is described in the next chapter.
PUBLIC DRAFT
1-35 CORE SYNTAX AND SEMANTICS
A translation unit (JSP source file and any files included via the include
directive) can contain more than one instance of the page directive, all the
attributes will apply to the complete translation unit (i.e. page directives are
position independent). However, there shall be only one occurrence of any
attribute/value defined by this directive in a given translation unit with the
exception of the “import” attribute; multiple uses of this attribute are cumulative
(with ordered set union semantics). Other such multiple attribute/value
(re)definitions result in a fatal translation error.
The attribute/value namespace is reserved for use by this, and subsequent, JSP
specification(s).
Unrecognized attributes or values result in fatal translation errors.
Examples
The following directive provides some user-visible information on this JSP
page:
The following directive requests no buffering, indicates that the page is thread
safe, and provides an error page.
The following directive indicates that the scripting language is based on Java,
that the types declared in the package com.myco are directly available to the
scripting code, and that a buffering of 16KB should be used.
Syntax
<%@ page page_directive_attr_list %>
PUBLIC DRAFT
Directives 1-36
PUBLIC DRAFT
1-37 CORE SYNTAX AND SEMANTICS
Table JSP.1-8
PUBLIC DRAFT
Directives 1-38
Table JSP.1-8
PUBLIC DRAFT
1-39 CORE SYNTAX AND SEMANTICS
Table JSP.1-8
PUBLIC DRAFT
Directives 1-40
Table JSP.1-8
PUBLIC DRAFT
1-41 CORE SYNTAX AND SEMANTICS
Table JSP.1-8
Examples
In the following example, a tag library is introduced and made available to
this page using the super prefix; no other tag libraries should be introduced
in this page using this prefix. In this particular case, we assume the tag library
includes a doMagic element type, which is used within the page.
Syntax
<%@ taglib ( uri=”tagLibraryURI” | tagdir=”tagDir” ) prefix=”tagPrefix” %>
PUBLIC DRAFT
Directives 1-42
Table JSP.1-9
A fatal translation-time error will result if the JSP page translator encounters a
tag with name prefix: Name using a prefix is introduced using the taglib directive,
and Name is not recognized by the corresponding tag library.
PUBLIC DRAFT
1-43 CORE SYNTAX AND SEMANTICS
Examples
The following example requests the inclusion, at translation time, of a copy-
right file. The file may have elements which will be processed too.
Syntax
<%@ include file="relativeURLspec" %>
The Spec column describes what type of specification is valid to appear in the
given element. The JSP specification requires a relative URL spec. The reference
is resolved by the web/application server and its URL map is involved. Include
PUBLIC DRAFT
EL Elements 1-44
directives are interpreted relative to the current JSP file; jsp:include actions are
interpreted relative to the current JSP page.
An include directive regards a resource like a JSP page as a static object; i.e.
the bytes in the JSP page are included. An include action regards a resource like a
JSP page as a dynamic object; i.e. the request is sent to that object and the result of
processing it is included.
Implicit include directives can also be requested for a collection of pages
through the use of the <include-prelude> and <include-coda> elements of the JSP
configuration section of web.xml.
JSP.1.11 EL Elements
Note – A section talking about the use of EL at the top level of a page, in the
body of tags, and in attribute values.
Note – Describe how to disable them using page directives and JSP configura-
tion information.
PUBLIC DRAFT
1-45 CORE SYNTAX AND SEMANTICS
elements in the JSP page. Expressions are complete expressions in the scripting
language that get evaluated at response time; commonly, the result is converted
into a string and inserted into the output stream.
All JSP containers must support scripting elements based on the Java
programming language. Additionally, JSP containers may also support other
scripting languages. All such scripting languages must support:
The precise definition of the semantics for scripting done using elements
based on the Java programming language is given in Chapter JSP.9.
The semantics for other scripting languages are not precisely defined in this
version of the specification, which means that portability across implementations
cannot be guaranteed. Precise definitions may be given for other languages in the
future.
Each scripting element has a “<%”-based syntax as follows:
White space is optional after “<%!”, “<%”, and “<%=”, and before “%>”.
The equivalent XML elements for these scripting elements are described in
Section JSP.6.2.
JSP.1.12.1 Declarations
Declarations are used to declare variables and methods in the scripting language
used in a JSP page. A declaration should be a complete declarative statement, or
sequence thereof, according to the syntax of the scripting language specified.
Declarations do not produce any output into the current out stream.
Declarations are initialized when the JSP page is initialized and are made
available to other declarations, scriptlets, and expressions.
Examples
For example, the first declaration below declares an integer, global to the
page. The second declaration does the same and initializes it to zero. This type
PUBLIC DRAFT
Scripting Elements 1-46
Syntax
<%! declaration(s) %>
JSP.1.12.2 Scriptlets
Scriptlets can contain any code fragments that are valid for the scripting lan-
guage specified in the language directive. Whether the code fragment is legal
depends on the details of the scripting language (see Chapter JSP.9).
Scriptlets are executed at request-processing time. Whether or not they
produce any output into the out stream depends on the code in the scriptlet.
Scriptlets can have side-effects, modifying the objects visible to them.
When all scriptlet fragments in a given translation unit are combined in the
order they appear in the JSP page, they must yield a valid statement, or sequence
of statements, in the specified scripting language.
To use the %> character sequence as literal characters in a scriptlet, rather
than to end the scriptlet, escape them by typing %\>.
Examples
Here is a simple example where the page changed dynamically depending on
the time of day.
A scriptlet can also have a local variable declaration, for example the following
scriptlet just declares and initializes an integer, and later displays its value and incre-
ments it.
PUBLIC DRAFT
1-47 CORE SYNTAX AND SEMANTICS
Syntax
<% scriptlet %>
JSP.1.12.3 Expressions
An expression element in a JSP page is a scripting language expression that is
evaluated and the result is coerced to a String. The result is subsequently emitted
into the current out JspWriter object.
If the result of the expression cannot be coerced to a String the following
must happen: If the problem is detected at translation time, a translation time error
shall occur. If the coercion cannot be detected during translation, a ClassCastEx-
ception shall be raised at request time.
A scripting language may support side-effects in expressions when the
expression is evaluated. Expressions are evaluated left-to-right in the JSP page. If
an expression appears in more than one run-time attribute, they are evaluated left-
to-right in the tag. An expression might change the value of the out object,
although this is not something to be done lightly.
The expression must be a complete expression in the scripting language in
which it is written.
Expressions are evaluated at HTTP processing time. The value of an
expression is converted to a String and inserted at the proper position in the .jsp
file.
Examples
This example inserts the current date.
Syntax
<%= expression %>
PUBLIC DRAFT
Actions 1-48
JSP.1.13 Actions
Actions may affect the current out stream and use, modify and/or create objects.
Actions may depend on the details of the specific request object received by the JSP
page.
The JSP specification includes some actions that are standard and must be
implemented by all conforming JSP containers; these actions are described in
Chapter 5.
New actions are defined according to the mechanisms described in Chapters 7
and 12 and are introduced using the taglib directive.
The syntax for action elements is based on XML. Actions can be empty or
non-empty.
The interpretation of all actions start by evaluating the values given to its
attributes left to right, and assigning the values to the attributes. In the process some
conversions may be applicable; the rules for them are described in
Section JSP.1.14.2.
Many values are fixed ‘translation-time values’, but JSP 2.0 also provides a
mechanism for describing values that are computed at request time, the rules are
described in Section JSP.1.14.1.
PUBLIC DRAFT
1-49 CORE SYNTAX AND SEMANTICS
translation error. The type of an action element indicates whether a given attribute
will accept request-time attribute values.
Most attributes in the standard actions from Chapter 5 have page translation-
time semantics, but the following attributes accept request-time attribute
expressions:
PUBLIC DRAFT
Tag Attribute Interpretation Semantics 1-50
These conversions are part of the generic mechanism used to assign values
to attributes of actions: when an attribute value that is not a request-time
attribute is assigned to a given attribute, the conversion described here is used,
using the type of the attribute as the target type. The type of each attribute of the
standard actions is described in this specification, while the types of the
attributes of a custom action are described in its associated Tag Library Descrip-
tor.
A given action may also define additional ways where type/value conver-
sions are used. In particular, Section JSP.5.2 describes the mechanism used for
the setProperty standard action.
PUBLIC DRAFT
C H A P T E R JSP.2
Expression Language
The JSP expression language (EL) has been developed in collaboration with
the JSP Standard Tag Library (JSTL) Expert Group (JSR-052) and it is used in both
specifications.
This chapter describes the expression language for JSP 2.0. Ideally, this
version of the expression language will be compatible with that used in JSTL 1.0,
but the JSR-052 EG has agreed to incorporate any changes the JSR-152 decides
there are required into a maintenance release of JSTL 1.0.
JSP.2.1 Overview
different areas. The feedback received from users of JSTL 1.0 has been very
positive.
The only intrinsic dependencies on JSP or Servlet concepts are in the set of
implicit objects; the EL concept and machinery can be reused in other contexts
and this is made more feasible through the EL evaluation API that is described
later in this chapter.
The EL is available in attribute values for standard and custom actions and
within template text; in both cases the EL is invoked consistently via the construct
${expr}.
The addition of the EL to the JSP technology facilitates much the writing of
script-less JSP pages. These pages can use EL expressions but can’t use Java
scriptlets, Java expressions, or Java declaration elements. This usage pattern can
be enforced through the isScriptingEnabled page directive and also through the
scripting-enabled JSP configuration element.
EL expressions can be used in any attribute that can accept a run-time expres-
sion, be it a standard action or a custom action (see the section below on backward
compatibility issues).
There are three use cases for expressions in attribute values:
PUBLIC DRAFT
1-53 EXPRESSION LANGUAGE
In this case, the attribute's String value is coerced to the attribute's expected
type according to the type conversion rules described later. These rules are
equivalent to the JSP 1.2 conversions, except that empty strings are treated
differently.
JSP.2.2.1 Examples
The following shows a conditional action that uses the EL to test whether a
property of a bean is less than 3.
Note that the normal JSP coercion mechanism already allows for:
There may be literal values that include the character sequence "${". If that is
the case, a literal with that value can be used as shown here:
The resulting attribute value would then be the string “an expression is
${expr}”.
The EL can be used directly in template text, be it inside the body of a custom or
standard actions or in template text outside of any action. Exceptions are if the body
of the tag is tagdependent, or if EL is turned off (usually for compatibility issues)
explicitly through a directive or implicitly; see the next section.
The semantics of an EL is the same as with Java expressions: the value is
computed and inserted into the current output.
JSP.2.3.1 Examples
The following shows a custom action where two EL expressions are used to
access bean properties:
PUBLIC DRAFT
Deactivating EL Evaluation 1-54
<c:wombat>
One value is ${bean1.a} and another is ${bean2.a.c}
</c:if>
Since the syntactic pattern ${expr} was not reserved in the JSP specifications
before JSP 1.2, there may be situations where such a pattern appears but the inten-
tion is not to activate EL expression evaluation but rather to pass through the pattern
verbatim. To address this, the EL evaluation machinery can be deactivated as indi-
cated in this section.
Each JSP page has a default EL evaluation mode that may be true or false.
The default mode for JSP pages in a Web Application delivered using a
web.xml using the Servlet 2.3 format is false; this provides for backward
compatibility.
The default mode for JSP pages in a Web Application delivered using a
web.xml using the Servlet 2.4 format is true; this provides automatically the
default that most applications want.
The default can be changed by setting the value of the elEvaluation property of
the page, either through a page directive, or through the JSP configuration
information for the web application using the el-evaluation element.
With the addition of the EL some JSP page authors, or page authoring groups,
may want to follow a methodology where scripting elements are not allowed. Previ-
ous versions of JSP enabled this through the notion of a TagLibraryValidator that
would verify that the elements are not present. JSP 2.0 makes this slightly easier
through a page directive to disable scripting elements and a corresponding JSP con-
figuration element.
Disabling scripting elements can be done through using the isScriptingEnabled
page directive and through the isScriptingEnabled element of the JSP
configuration.
PUBLIC DRAFT
1-55 EXPRESSION LANGUAGE
JSP.2.6.1 Overview
The syntax is quite simple. Variables are accessed by name. A generalized []
operator can be used to access maps, lists, arrays of objects and properties of a Java-
Beans object; the operator can be nested arbitrarily. The "." operator can be used as
a convenient shorthand for property access when the property name follows the con-
ventions of java identifiers, but the [] operator allows for more generalized access.
Relational comparisons are allowed using the standard Java relational
operators. Comparisons may be made against other values, or against boolean (for
equality comparisons only), String, integer, or floating point literals.
Arithmetic operators can be used to compute integer and floating point vlaues.
Logical operators are available.
JSP.2.6.2 Literals
There are literals for boolean, integer, floating point, string, null.
PUBLIC DRAFT
General Syntax 1-56
Note – The details of error handling, which are tightly coupled with default-
ing and with the API to the EL evaluation, are still being investigated in the expert
group.
Note – The EG has received some requests for customizing - through the API
- the interpretation of “.” for non-JSP uses of the EL. We still have not discussed
this.
The EL follows ECMAScript in unifying the treatment of the "." and "[]" opera-
tors.
expr-a.identifier-b is equivalent to a["identifier-b"]; that
is, the identifier identifier-b is used to construct a literal whose value is the
identifier, and then the "[]" operator is used with that value.
To evaluate expr-a[expr-b]:
PUBLIC DRAFT
1-57 EXPRESSION LANGUAGE
• Addition: "+"
• Substraction: "-"
• Multiplication: "*"
• Division: "/" and "div"
• Remainder (modulo): "%" and "mod"
The last two operators are available in both syntaxes to be consistent with
XPath and ECMAScript.
The evaluation of arithmetic operators is described in the following sections.
A and B are the evaluation of subexpressions
PUBLIC DRAFT
General Syntax 1-58
• If A is null, return 0
• If A is a String
■
If A contains ".", "e", or "E", coerce to a Double and apply operator
■
Otherwise, coerce to a Long and apply operator
■
If operator results in exception, error
• If A is Byte, Short, Integer, Long, Float, Double
■
Retain type, apply operator
■
If operator results in exception, error
• Otherwise, error
PUBLIC DRAFT
1-59 EXPRESSION LANGUAGE
The second versions of the last 4 operators are made available to avoid having
to use entity references in XML syntax and have the exact same behavior, i.e. "<"
behaves the same as "lt" and so on.
The evaluation of relational operators is described in the following sections.
JSP.2.6.5.6 A {<,>,<=,>=,lt,gt,le,ge} B
• If A==B, if operator is <=, le, >= or ge return true otherwise return false
• If A is null or B is null, return false
• If A or B is Float or Double coerce both A and B to Double apply oper-
ator
• If A or B is Byte, Short, Character, Integer, Long coerce both A
and B to Long and apply operator
• If A or B is String coerce both A and B to String, compare lexically
• If A is Comparable if A.compareTo (B) throws exception error otherwise use
result of A.compareTo(B)
• If B is Comparable if B.compareTo (A) throws exception error otherwise use
result of B.compareTo(A)
• Otherwise, error
JSP.2.6.5.7 A {==,!=,eq,ne} B
PUBLIC DRAFT
General Syntax 1-60
PUBLIC DRAFT
1-61 EXPRESSION LANGUAGE
JSP.2.6.8 Parentheses
Parentheses can be used to change precedence, as in: "${ ( a * (b + c)
) }"
• [] .
• ()
• - (unary) not ! empty
• * / div % mod
• + - (binary)
• < > <= >= lt gt le ge
• == != eq ne
• && and
• || or
The following words are reserved for the language and should not be used as
identifiers without being quoted.
and eq gt true instanceof
or ne le false empty
not lt ge null div mod
Note that many of these words are not in the language now, but they may be in
the future, so developers should avoid using these words now.
PUBLIC DRAFT
Functions 1-62
${product}
This expression will look for the attribute named "product", searching the
page, request, session, and application scopes, and will return its value. If the
attribute is not found, null is returned.
Note that an identifier that matches one of the implicit objects described in the
next section will return that implicit object instead of an attribute value.
JSP.2.9 Functions
Note – The EG is exploring this functionality and would like to get feedback
on its usefulness; if the feedback is not conclusive we will drop this functionality
from JSP 2.0.
The EL has qualified functions, reusing the notion of qualification from XML
namespaces (& attributes), XSL functions, and JSP custom actions. Functions are
mapped into public static methods in Java classes. In JSP 2.0 the map is specified
in the TLD.
Note – The TLD description has not yet been updated with the new elements
described here.
ns:f(a1,a2... an)
As with the rest of EL, this element can appear in attributes and directly in
template text.
An alternate syntax:
f(a1,a2... an)
PUBLIC DRAFT
1-63 EXPRESSION LANGUAGE
PUBLIC DRAFT
Functions 1-64
JSP.2.9.3 Example
The following TLD fragment describes a function with name nickname that is
intended to fetch the nickname of the user:
<taglib>
...
<function>
<name>nickname</name>
<function-class>mypkg.MyFunctions</function-class>
<function-signature>String nickName(String)</function-signature>
</function>
</taglib>
<h2>Dear ${nickname(user)}</h2>
JSP.2.9.4 Semantics
PUBLIC DRAFT
1-65 EXPRESSION LANGUAGE
• Locate the function element with a name subelement with value “f" in that
TLD. If none can be found, this shall be a translation-time error.
• Locate the public class with name equal to the value of the function-class ele-
ment. Locate the public static method with name and signature equal to the
value of the function-signature element. If any of these don’t exist, a transla-
tion-time error shall occur..
• Evaluate each argument to the corresponding type indicated in the signature
• Evaluate the public static Java method. The resulting type is that of the return
value in the function-signature element.
The EL defines a set of implicit objects which depends on the context in which
the EL is being used. When an expression references one of these objects by name,
the appropriate object is returned instead of the corresponding attribute. For exam-
ple in the context of JSP pages, ${pageContext} returns the PageContext object,
even if there is an existing pageContext attribute containing some other value.
The following implicit objects are available to EL expressions used in JSP
pages:
PUBLIC DRAFT
Type Conversion 1-66
• header - a Map that maps header names to a single String header value (ob-
tained by calling ServletRequest.getHeader(String name))
• headerValues - a Map that maps header names to a String[] of all values for
that header (obtained by calling ServletRequest.getHeaders(String))
• cookie - a Map that maps cookie names to a single Cookie object. Cookies
are retrieved according to the semantics of HttpServletRequest.getCookies(). If
the same name is shared by multiple cookies, an implementation must use the
first one encountered in the array of Cookie objects returned by the getCook-
ies() method. However, users of the cookie implicit object must be aware that
the ordering of cookies is currently unspecified in the Servlet specification.
• initParam - a Map that maps context initialization parameter names to their
String parameter value (obtained by calling ServletContext.getInitParame-
ter(String name))
The following table shows some examples of using these implicit objects:
Expression Result
The request's URI (obtained from
${pageContext.request.requestURI}
HttpServletRequest)
The session-scoped attribute named profile
${sessionScope.profile}
(null if not found)
The String value of the productId
${param.productId}
parameter, or null if not found
The String[] containing all values of the
${paramValues.productId}
productId parameter, or null if not found
• If A is String: return A
• Otherwise, if A is null: return "".
PUBLIC DRAFT
1-67 EXPRESSION LANGUAGE
PUBLIC DRAFT
API to Expression Evaluator 1-68
PUBLIC DRAFT
1-69 EXPRESSION LANGUAGE
PUBLIC DRAFT
Collected Syntax 1-70
PUBLIC DRAFT
1-71 EXPRESSION LANGUAGE
| ‘eq’
| '‘!=’
| ‘ne’
PUBLIC DRAFT
Collected Syntax 1-72
Notes:
PUBLIC DRAFT
1-73 EXPRESSION LANGUAGE
PUBLIC DRAFT
C H A P T E R JSP.3
JSP Configuration
JSP.3.1.1 <jsp-config>
A jsp-config is a subelement of web-app that is used to provide global
configuration information for the JSP files in a Web Application.
The web.xml file can include an explicit taglib map between URIs and TLD
resource paths described using the taglib elements of the Web Application Deploy-
ment descriptor in WEB-INF/web.xml, as described in the Servlet 2.3 spec and in
“http://java.sun.com/j2ee/dtds/web-app_2_3.dtd”.
Note – The above needs updating to reflect the new separation between the
two specifications.
JSP.3.2.1 <taglib>
A taglib is a subelement of jsp-config that can be used to provide information
on a tag library that is used by a JSP page within the Web Application.
A taglib element has two subelements and one attribute:
JSP.3.2.2 <taglib-uri>
A taglib-uri element describes a URI identifying a tag library used in the web
application.
The body of the taglib-uri element may be either an absolute URI specifica-
tion, or a relative URI as in Section JSP.1.2.1. There should be no entries in
web.xml with the same taglib-uri value.
JSP.3.2.3 <taglib-location>
A taglib-location contains the location (as a resource) of the Tag Library
Description File for the tag library.
PUBLIC DRAFT
JSP Property Groups 1-76
A JSP property group is a collection of properties that apply to a set of JSP files.
Currently all the properties correspond to page directives.
The applicability of a JSP property group is defined through one or more URL
patterns; all the properties in the group apply to the resources in the Web
Application that match any of the URL patterns. There is an implicit property: that
of being a JSP file.
Note – There is no mechanism to indicate that a resource is not a JSP file; that
means that all .jsp resources are JSP files, unless overridden by the servlet map-
pings. Please provide feedback if you feel an explicit property is needed.
Note – Need to clarify how to resolve overlaps on being a JSP file between
servlet mappings and JSP configuration info.
If a resource matches URL patterns in more than one group, the pattern that is
most specific (following the same rules as in the Servlet specification) applies.
JSP.3.3.1 <jsp-property-group>
A jsp-property-group is a subelement of jsp-config:
PUBLIC DRAFT
1-77 JSP CONFIGURATION
For example, the following web.xml fragment defines a group that activates
EL evaluation for all JSP pages delivered using the “.jsp” extension:
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-evaluation>true</el-evaluation>
</jsp-property-group>
For example, the following web.xml fragment defines a group that disables
scripting elements for all JSP pages delivered using the “.jsp” extension:
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-enabled>false</scripting-enabled>
</jsp-property-group>
PUBLIC DRAFT
JSP Property Groups 1-78
For example, the following web.xml fragment defines a group that explicitly
assigns ISO-8859-1 to all JSP pages delivered using the “.jsp” extension:
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>ISO-8859-1</page-encoding>
</jsp-property-group>
PUBLIC DRAFT
1-79 JSP CONFIGURATION
will be processed in the same order as they appear in the JSP configuration section
of web.xml.
For example, the following web.xml fragment defines two groups. Together
they indicate that JSP pages in directory foo/ have /preludes/p1.jsp and /preludes/
p2.jsp at the beginning and /codas/c1.jsp and /codas/c2.jsp at the end, in that order,
while other .jsp files only have /preludes/p1.jsp at the beginning and /codas/c1.jsp
at the end .
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<include-prelude>/preludes/p1.jsp</include-prelude>
<include-coda>/codas/c1.jsp</include-coda>
</jsp-property-group>
<jsp-property-group>
<url-pattern>two/*.jsp</url-pattern>
<include-prelude>/preludes/p2.jsp</include-prelude>
<include-coda>/codas/c2.jsp</include-coda>
</jsp-property-group>
PUBLIC DRAFT
C H A P T E R JSP.4
Localization Issues
The Java Platform support for localized content is based on a uniform represen-
tation of text internally as Unicode 2.0 (ISO010646) characters and the support for a
number of character encodings to and from Unicode.
A Java Virtual Machine (JVM) must support Unicode and Latin-1 encodings
but most support many more. The character encodings supported by the JVM
from Sun are described at:
http://java.sun.com/products/jdk/1.1/docs/guide/intl/encoding.doc.html
http://www.iana.org/assignments/character-sets
The pageEncoding attribute should be used only when the character encoding
of a JSP page is organized so that ASCII characters stand for themselves. The
Table JSP.4-1 Effects of declared page encoding and content type on JSP
source encoding and output content type.
pageEncoding contentType
Page Directive Page Directive Input JSP
Attribute Attribute Source
(<encoding>) (<contentType>) Encoding Output Content Type
Where:
PUBLIC DRAFT
Static Content Type 1-82
Also see Chapter 3 for information on using the page-encoding element in the
JSP configuration to indicate the encoding of a JSP page.
Most JSP pages are written to deliver a response using a specific content type
and character encoding. A JSP page can use the contentType attribute of the page
directive to indicate the content type of the response it provides to requests.
When used this way, a given page will always provide the same content type.
If a page determines that the response should be of a different content type, it
should do so “early”, determine what other JSP page or servlet will handle this
request, and forward the request to the other JSP page or servlet.
For JSP Pages in standard syntax, the default value for TYPE is "text/html"
and the default value for the character encoding is ISO-8859-1. For JSP
Documents in XML syntax, the default value for TYPE is "text/xml" and the
default value for the character encoding is UTF-8. Table JSP.4-1 clarifies the
relationship between the declared page encoding and content type and the output
content type used.
A registry of content type names is kept by IANA. See:
http://www.iana.org/assignments/media-types/index.html
The contentType attribute must only be used when the character encoding is
organized such that ASCII characters stand for themselves, at least until the con-
tentType attribute is found. The directive containing the contentType attribute
should appear as early as possible in the JSP page.
Some JSP pages are designed so they can deliver content using different
content types (and character sets) depending on request time input. These pages
may be organized as custom actions or scriptlets that determine the response
content type and provide glue into other code actually generating the content of
the response.
The initial content type for the response (including the character set) is
determined as shown in the "Output Content Type" column in Table JSP.4-1. In all
cases, the container must call response.setContentType() with the initial content
type before processing the page.
PUBLIC DRAFT
1-83 LOCALIZATION ISSUES
The content type (and character set) can then be changed dynamically by
calling setContentType() or setLocale() on the response object. The most recent
call takes precedence. Changing the content type can be done up until the point
where the response is committed. Data is sent to the response stream on buffer
flushes for buffered pages, or on encountering the first content (beware of
whitespace) on unbuffered pages. Whitespace is notoriously tricky for JSP Pages
in JSP syntax, but much more manageable for JSP Documents in XML syntax.
The JSP specification does not mandate any specific approach for structuring
localized content, and different approaches are possible. Two common approaches
are to use a template taglib and pull localized strings from a resource repository, or
to use-per-locale JSP pages. Each approach has benefits and drawbacks. Some users
have been using transformations on JSP documents to do simple replacement of ele-
ments by localized strings, thus maintaining JSP syntax with no performance cost at
run-time. Combinations of these approaches also make sense.
There are a number of different efforts that are exploring how to best do
localization. We expect JSR-052, the standard JSP tag library, to address some of
these issues.
PUBLIC DRAFT
C H A P T E R JSP.5
Standard Actions
This chapter describes the standard actions of JavaServer Pages 2.0 (JSP 2.0).
Note – In principle, we intend to allow EL expressions whenever a Java
expression is allowed in a standard action. We will be adding this in more detail as
part of a later draft.
JSP.5.1 <jsp:useBean>
Note – The details of how useBean interacts with a script-less page will be
added in a later draft. Essentially, it will only make the object available through
the EL, but we need to check the details.
The jsp:useBean action is quite flexible; its exact semantics depends on the
attributes given. The basic semantic tries to find an existing object using id and
scope. If the object is not found it will attempt to create the object using the other
attributes.
It is also possible to use this action to give a local name to an object defined
elsewhere, as in another JSP page or in a Servlet. This can be done by using the
type attribute and not providing class or beanName attributes.
At least one of type and class must be present, and it is not valid to provide
both class and beanName. If type and class are present, class must be assignable
to type (in the Java platform sense). For it not to be assignable is a translation-
time error.
The attribute beanName specifies the name of a Bean, as specified in the
JavaBeans specification. It is used as an argument to the instantiate() method in
the java.beans.Beans class. It must be of the form “a.b.c”, which may be either a
class, or the name of a resource of the form “a/b/c.ser” that will be resolved in the
current ClassLoader. If this is not true, a request-time exception, as indicated in
the semantics of instantiate() will be raised. The value of this attribute can be a
request-time attribute expression.
More detail on the role of id and scope is given next.
The id Attribute
The id=”name” attribute/value tuple in a jsp:useBean element has special mean-
ing to a JSP container, at page translation time and at client request processing time.
In particular:
•the name must be unique within the translation unit, and identifies the particular
element in which it appears to the JSP container and page.
Duplicate id’s found in the same translation unit shall result in a fatal transla-
tion error.
•The JSP container will associate an object (a JavaBean component) with the
named value and accessed via that name in various contexts through the page-
context object described later in this specification.
The name is also used to expose a variable (name) in the page’s scripting lan-
guage environment. The scope of the scripting language variable is dependent
upon the scoping rules and capabilities of the scripting language used in the
page.
Note that this implies the name value syntax must comply with the variable
naming syntax rules of the scripting language used in the page. Chapter JSP.9
provides details for the case where the language attribute is ”java”.
PUBLIC DRAFT
<jsp:useBean> 1-86
<%
/*
* the tag above creates or obtains the Customer Bean
* reference, associates it with the name “customer” in the
* PageContext, and declares a Java programming language
* variable of the same name initialized to the object reference
* in this block’s scope.
*/
%>
...
<%= customer.getName(); %>
...
<% } // close the block %>
<%
// the variable customer is out of scope now but
// the object is still valid (and accessible via pageContext)
%>
Table JSP.5-1
PUBLIC DRAFT
1-87 STANDARD ACTIONS
Table JSP.5-1
request The named object is available from the current page’s Serv-
letRequest object using the getAttribute(name) method.
This reference must be discarded upon completion of the
current client request.
It is illegal to change the value of an instance object so asso-
ciated so that its runtime type is a subset of the type(s) of
the object previously so associated.
session The named object is available from the current page’s
HttpSession object (which can in turn be obtained from the
ServletRequest object) using the getAttribute(name) method.
This reference must be discarded upon invalidation of the
current session.
It is Illegal to change the value of an instance object so
associated so that its new runtime type is a subset of the
type(s) of the object previously so associated.
Note it is a fatal translation error to attempt to use session
scope when the JSP page so attempting has declared, via the
<%@ page ... %> directive (see later) that it does not partic-
ipate in a session.
application The named object is available from the current page’s Serv-
letContext object using the getAttribute(name) method.
This reference shall be discarded upon reclamation of the
ServletContext.
It is Illegal to change the value of an instance object so
associated, such that its new runtime type is a subset of the
type(s) of the object previously so associated.
Semantics
The actions performed in a jsp:useBean action are:
1. An attempt to locate an object based on the attribute values id and scope. The
inspection is done synchronized per scope namespace to avoid non-determin-
istic behavior.
2. A scripting language variable of the specified type (if given) or class (if type
is not given) is defined with the given id in the current lexical scope of the
scripting language.
3. If the object is found, the variable’s value is initialized with a reference to the
PUBLIC DRAFT
<jsp:useBean> 1-88
located object, cast to the specified type. If the cast fails, a java.lang.ClassCas-
tException shall occur. This completes the processing of this jsp:useBean ac-
tion.
4. If the jsp:useBean element had a non-empty body it is ignored. This completes
the processing of this jsp:useBean action.
5. If the object is not found in the specified scope and neither class nor beanName
are given, a java.lang.InstantiationException shall occur. This completes the
processing of this jsp:useBean action.
6. If the object is not found in the specified scope, and the class specified names
a non-abstract class that defines a public no-args constructor, then the class is
instantiated. The new object reference is associated with the scripting variable
and with the specified name in the specified scope using the appropriate scope
dependent association mechanism (see PageContext). After this, step 7 is per-
formed.
If the object is not found, and the class is either abstract, an interface, or no
public no-args constructor is defined therein, then a java.lang.InstantiationEx-
ception shall occur. This completes the processing of this jsp:useBean action.
7. If the object is not found in the specified scope; and beanName is given, then
the method instantiate() of java.beans.Beans will be invoked with the Class-
Loader of the Servlet object and the beanName as arguments. If the method
succeeds, the new object reference is associated the with the scripting variable
and with the specified name in the specified scope using the appropriate scope
dependent association mechanism (see PageContext). After this, step 7 is per-
formed.
8. If the jsp:useBean element has a non-empty body, the body is processed. The
variable is initialized and available within the scope of the body. The text of
the body is treated as elsewhere. Any template text will be passed through to
the out stream. Scriptlets and action tags will be evaluated.
A common use of a non-empty body is to complete initializing the created in-
stance. In that case the body will likely contain jsp:setProperty actions and
scriptlets that are evaluated. This completes the processing of this useBean ac-
tion.
Examples
In the following example, a Bean with name “connection” of type
“com.myco.myapp.Connection” is available after actions on this element,
either because it was already created and found, or because it is newly cre-
ated.
PUBLIC DRAFT
1-89 STANDARD ACTIONS
In the next example, the timeout property is set to 33 if the Bean was instanti-
ated.
In the final example, the object should have been present in the session. If so,
it is given the local name wombat with WombatType. A ClassCastException
may be raised if the object is of the wrong class, and an InstantiationException
may be raised if the object is not defined.
Syntax
This action may or not have a body. If the action has no body, it is of the form:
In this case, the body will be invoked if the Bean denoted by the action is
created. Typically, the body will contain either scriptlets or jsp:setProperty tags
that will be used to modify the newly created object, but the contents of the body
are not restricted.
PUBLIC DRAFT
<jsp:useBean> 1-90
Table JSP.5-2
PUBLIC DRAFT
1-91 STANDARD ACTIONS
JSP.5.2 <jsp:setProperty>
The jsp:setProperty action sets the values of properties in a Bean. The name
attribute that denotes the Bean must be defined before this action appears.
There are two variants of the jsp:setProperty action. Both variants set the
values of one or more properties in the Bean based on the type of the properties.
The usual Bean introspection is done to discover what properties are present, and,
for each, its name, whether it is simple or indexed, its type, and the setter and
getter methods. Introspection also indicates if a given property type has a Proper-
tyEditor class.
Properties in a Bean can be set from one or more parameters in the request
object, from a String constant, or from a computed request-time expression.
Simple and indexed properties can be set using jsp:setProperty.
When assigning from a parameter in the request object, the conversions
described in Section JSP.1.14.2.1 are applied, using the target property to
determine the target type.
When assigning from a value given as a String constant, the conversions
described in Section JSP.1.14.2.1 are applied, using the target property to
determine the target type.
When assigning from a value given as a request-time attribute, no type
conversions are applied, as indicated in Section JSP.1.14.2.2.
When assigning values to indexed properties the value must be an array; the
rules described in the previous paragraph apply to the elements.
A conversion failure leads to an error, whether at translation time or request-
time.
Examples
The following two elements set a value from the request parameter values.
Syntax
<jsp:setProperty name="beanName" prop_expr />
PUBLIC DRAFT
<jsp:setProperty> 1-92
prop_expr ::=
property="*" |
property=”propertyName”|
property=”propertyName” param="parameterName"|
property=”propertyName” value=”propertyValue”
Table JSP.5-3
1.
See syntax for expression scriptlet “<%= ... %>”
PUBLIC DRAFT
1-93 STANDARD ACTIONS
Table JSP.5-3
JSP.5.3 <jsp:getProperty>
Examples
<jsp:getProperty name=”user” property=”name” />
Syntax
<jsp:getProperty name=”name” property=”propertyName” />
PUBLIC DRAFT
<jsp:include> 1-94
Table JSP.5-4
name The name of the object instance from which the property is
obtained.
property Names the property to get.
JSP.5.4 <jsp:include>
A <jsp:include .../> element provides for the inclusion of static and dynamic
resources in the same context as the current page. See Table JSP.1-10 for a sum-
mary of include facilities.
Inclusion is into the current value of out. The resource is specified using a
relativeURLspec that is interpreted in the context of the web server (i.e. it is
mapped).
The page attribute of both the jsp:include and the jsp:forward actions are
interpreted relative to the current JSP page, while the file attribute in an include
directive is interpreted relative to the current JSP file. See below for some
examples of combinations of this.
An included page only has access to the JspWriter object and it cannot set
headers. This precludes invoking methods like setCookie(). Attempts to invoke
these methods will be ignored. The constraint is equivalent to the one imposed on
the include() method of the RequestDispatcher class.
A jsp:include action may have jsp:param subelements that can provide values
for some parameters in the request to be used for the inclusion.
Request processing resumes in the calling JSP page, once the inclusion is
completed.
The flush attribute controls flushing. If true, then, if the page output is
buffered and the flush attribute is given a 'true' value, then the buffer is flushed
prior to the inclusion, otherwise the buffer is not flushed. The default value for the
flush attribute is 'false'
Examples
<jsp:include page=”/templates/copyright.html”/>
PUBLIC DRAFT
1-95 STANDARD ACTIONS
• A.jsp says <%@ include file=”dir/B.jsp”%> and dir/B.jsp says <%@ include
file=”C.jsp”%>. In this case the relative specification “C.jsp” resolves to “dir/
C.jsp”
• A.jsp says <jsp:include page=”dir/B.jsp”/> and dir/B.jsp says <jsp:include
page=”C.jsp” />. In this case the relative specification “C.jsp” resolves to “dir/
C.jsp”.
• A.jsp says <jsp:include page=”dir/B.jsp”/> and dir/B.jsp says <%@ include
file=”C.jsp” %>. In this case the relative specification “C.jsp” resolves to “dir/
C.jsp”.
• A.jsp says <%@ include file=”dir/B.jsp”%> and dir/B.jsp says <jsp:include
page=”C.jsp”/>. In this case the relative specification “C.jsp” resolves to
“C.jsp”.
Syntax
<jsp:include page=”urlSpec” flush="true|false"/>
and
The first syntax just does a request-time inclusion. In the second case, the
values in the param subelements are used to augment the request for the purposes
of the inclusion.
PUBLIC DRAFT
<jsp:forward> 1-96
Table JSP.5-5
JSP.5.5 <jsp:forward>
Examples
The following element might be used to forward to a static page based on
some dynamic condition.
Syntax
<jsp:forward page=”relativeURLspec” />
PUBLIC DRAFT
1-97 STANDARD ACTIONS
and
<jsp:forward page=”urlSpec”>
{ <jsp:param .... /> }*
</jsp:forward>
This tag allows the page author to cause the current request processing to be
effected by the specified attributes as follows:
Table JSP.5-6
JSP.5.6 <jsp:param>
JSP.5.6.1 Syntax
This action has two mandatory attributes: name and value. Name indicates
the name of the parameter, and value, which may be a request-time expression,
indicates its value.
PUBLIC DRAFT
<jsp:plugin> 1-98
JSP.5.7 <jsp:plugin>
The plugin action enables a JSP page author to generate HTML that contains
the appropriate client browser dependent constructs (OBJECT or EMBED) that will
result in the download of the Java Plugin software (if required) and subsequent exe-
cution of the Applet or JavaBeans component specified therein.
The <jsp:plugin> tag is replaced by either an <object> or <embed> tag, as
appropriate for the requesting user agent, and emitted into the output stream of the
response. The attributes of the <jsp:plugin> tag provide configuration data for the
presentation of the element, as indicated in the table below.
The <jsp:param> elements indicate the parameters to the Applet or JavaBeans
component.
The <jsp:fallback> element indicates the content to be used by the client
browser if the plugin cannot be started (either because OBJECT or EMBED is not
supported by the client browser or due to some other problem). If the plugin can
start but the Applet or JavaBeans component cannot be found or started, a plugin
specific message will be presented to the user, most likely a popup window
reporting a ClassNotFoundException.
The actual plugin code need not be bundled with the JSP container and a
reference to Sun’s plugin location can be used instead, although some vendors
will choose to include the plugin for the benefit of their customers.
Examples
<jsp:plugin type=”applet” code=”Molecule.class” codebase=”/html” >
<jsp:params>
<jsp:param
name=”molecule”
value=”molecules/benzene.mol”/>
</jsp:params>
<jsp:fallback>
<p> unable to start plugin </p>
</jsp:fallback>
</jsp:plugin>
PUBLIC DRAFT
1-99 STANDARD ACTIONS
Syntax
<jsp:plugintype="bean|applet"
code="objectCode"
codebase="objectCodebase"
{ align="alignment" }
{ archive="archiveList" }
{ height="height" }
{ hspace="hspace" }
{ jreversion="jreversion" }
{ name="componentName" }
{ vspace="vspace" }
{ width="width" }
{ nspluginurl="url" }
{ iepluginurl="url" }>
{ <jsp:params>
{ <jsp:param name="paramName" value=”paramValue" /> }+
</jsp:params> }
Table JSP.5-7
PUBLIC DRAFT
<jsp:params> 1-100
Table JSP.5-7
JSP.5.8 <jsp:params>
The jsp:params action is part of the jsp:plugin action and can only occur as a
direct child of a <jsp:plugin> element. Using the jsp:params element in any other
context shall result in a translation-time error.
The semantics and syntax of jsp:params are described in Section JSP.5.7.
JSP.5.9 <jsp:fallback>
The jsp:fallback action is part of the jsp:plugin action and can only occur as a
direct child of a <jsp:plugin> element. Using the jsp:fallback element in any other
context shall result in a translation-time error.
The semantics and syntax of jsp:fallback are described in Section JSP.5.7.
JSP.5.10 <jsp:attribute>
The <jsp:attribute> standard action allows the page author to define the value
of a tag handler attribute in the body of an XML element instead of in the value of
an XML attribute. The action may only appear as a subelement of a standard or
custom action invocation.
The <jsp:attribute> action accepts a name attribute and a trim attribute. The
name attribute associates the action with one of the attributes the tag handler is
declared to accept. The optional trim attribute determines whether the whitespace
appearning at the beginning and at the end of the element body should be
discarded or not. By default, the leading and trailing whitespace is discarded.
PUBLIC DRAFT
1-101 STANDARD ACTIONS
<mytag:highlight>
<jsp:attribute name=”text”>
Inline definition.
</jsp:attribute>
</mytag:highlight>
JSP.5.11 <jsp:body>
PUBLIC DRAFT
Additional Standard Actions 1-102
The body standard action accepts one optional attribute. The value attribute
allows the page author to pass in an object of type
javax.servlet.jsp.tagext.JspFragment as the value of the body of this tag. If the
<jsp:body> action is present in the body of a custom action invocation, the page
author must either supply a body to the action, or supply a value attribute. A
translation error must result if both or neither are supplied.
If one or more <jsp:attribute> elements appear in the body of a tag invocation
but no <jsp:body> element appears, it is the equivalent of the tag having an empty
body.
It is also legal to use the <jsp:body> standard action to supply bodies to
standard actions, for any standard action that accepts a body.
The attribute is:
Additional Standard Actions are defined for tag files. See the following sections
for more details:
PUBLIC DRAFT
C H A P T E R JSP.6
JSP Documents
This chapter defines an XML syntax for JSP pages and the interpretation of
the pages written in this syntax. We use the term JSP document to refer to a JSP
page in XML syntax.
This chapter also defines a mapping between any JSP page and an XML
description of the page, its XML view. The XML view is defined for JSP pages
written in JSP and in XML syntax.
Note – We will drop the requirement that jsp:root is needed in a JSP docu-
ment, moving from "jsp as documents" to "jsp as namespace". That change will
make the XML syntax much easier to use.
The XML syntax for JSP pages can be used in a number of ways, including:
• JSP documents can be passed directly to the JSP container; this will become
more important as more and more content is authored as XML.
• The XML view of a JSP page can be used for validating the JSP page against
some description of the set of valid pages.
• JSP documents can be manipulated by XML-aware tools.
• A JSP document can be generated from a textual representation by applying
an XML transformation, like XSLT.
• A JSP document can be generated automatically, say by serializing some ob-
jects
Validation of the JSP page is supported in the JSP 2.0 specification through a
TagLibraryValidator class associated with a tag library. The validator class acts on
a PageData object that represents the XML view of the JSP page (see, for
example, Section JSP.7.5.1.2).
A JSP page in either syntax can include via a directive a JSP page in either
syntax. It is not valid, however, to intermix standard JSP syntax and XML syntax
inside the same source file.
• a jsp:root element that is used to introduce the namespace for custom tags in
the page.
• JSP directive elements
• JSP scripting elements
• JSP standard action elements
• JSP custom action elements
• jsp:text elements corresponding to template data.
• other XML fragments also corresponding to template data.
PUBLIC DRAFT
1-105 JSP DOCUMENTS
<jsp:root
xmlns:jsp=”http://java.sun.com/JSP/Page”
xmlns:prefix1=”URI-for-taglib1”
xmlns:prefix2=”URI-for-taglib2”... >
version="2.0">
JSP page
</jsp:root>
PUBLIC DRAFT
JSP Documents 1-106
If the uri value is of the form “urn:jsptld:path”, then the TLD is determined
following the mechanism described in Section JSP.7.3.2.
If the uri value is a plain “uri”, then a path is determined by consulting the
mapping indicated in web.xml extended using the implicit maps in the packaged
tag libraries (Sections JSP.7.3.3 and JSP.7.3.4), as indicated in Section JSP.7.3.6.
PUBLIC DRAFT
1-107 JSP DOCUMENTS
• jsp:useBean
• jsp:setProperty
• jsp:getProperty
• jsp:include
• jsp:forward
• jsp:param
• jsp:params
• jsp:plugin
• jsp:text
PUBLIC DRAFT
JSP Documents 1-108
The semantics and constraints are as in Chapter JSP.5, and the interpretation
of the scripting elements is as in Chapter JSP.9. Tag libraries introduce new
elements through an xmlns attribute on a jsp:root element and their syntax and
semantics are as in Chapter JSP.7.
PUBLIC DRAFT
1-109 JSP DOCUMENTS
The result is
This section describes the XML view of a JSP page: the mapping between a JSP
page, written in either XML syntax or in JSP syntax, and an XML document
describing it.
• Expand all include directives into the JSP fragments they include.
• If the JSP container supports the jsp:id attribute, add the attribute. See
Section JSP.6.3.13.
• Expand all include directives into the JSP fragments they include.
• Add a jsp:root element as the root, with appropriate xmlns:jsp attribute, and
convert the taglib directive into xmlns: attributes of the jsp:root element.
PUBLIC DRAFT
XML View of a JSP Page 1-110
<%@ page ... %> <jsp:directive.page ... />. Optionally add jsp:id
In more detail:
PUBLIC DRAFT
1-111 JSP DOCUMENTS
is translated into an xmlns:prefix attribute on the root of the JSP document, with
a value that depends on uriValue. If uriValue is a relative path, then the value used is
“urn:jsptld:uriValue”; otherwise, the uriValue is used directly.
is expanded into the JSP fragment indicated by value. This is done to allow for
validation of the page.
JSP.6.3.7 Declarations
Declarations are translated into a jsp:declaration element. For example, the sec-
ond example from Section JSP.1.12.1:
PUBLIC DRAFT
XML View of a JSP Page 1-112
JSP.6.3.8 Scriptlets
Scriptlets are translated into a jsp:scriptlet element. In the XML document cor-
responding to JSP pages, directives are represented using the syntax:
JSP.6.3.9 Expressions
In the XML document corresponding to JSP pages, directives are represented
using the jsp:expression element:
PUBLIC DRAFT
1-113 JSP DOCUMENTS
Note – The details of jsp:id semantics still need to be discussed in the EG. A
specific proposal will be included in a later draft. Details include how ’unique’
will the id value be, and whether the value is available at run-time
A JSP container must support a jsp:id attribute. This attribute can only be
present in the XML view of a JSP page and can be used to improve the quality of
translation time error messages.
The XML view of any JSP page will have an additional jsp:id attribute added
to all XML elements. This attribute is given a value that is unique over all
elements in the XML view. See Chapter 12 for more details.
1.
Similarly, when applying an XSLT transformation to a JSP document,
XML fragments will be plainly visible, while the content of jsp:text
elements will not
PUBLIC DRAFT
Examples 1-114
JSP.6.5 Examples
This section presents two examples of JSP documents. The first shows a JSP
page in JSP syntax and its mapping to XML syntax. The second shows a JSP page
in XML syntax that includes XML fragments.
PUBLIC DRAFT
1-115 JSP DOCUMENTS
<jsp:text><![CDATA[<html>
<title>positiveTagLig</title>
<body>
]]></jsp:text>
<eg:test toBrowser="true" att1="Working>
<jsp:text>Positive test taglib directive</jsp:text>
</eg:test>
<jsp:text><![CDATA[
</body>
</html>
]]></jsp:text>
</jsp:root>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:mytags="prefix1-URL"
version="2.0">
<mytags:iterator count="4">
<foo> </foo>
</mytags:iterator>
</jsp:root>
PUBLIC DRAFT
C H A P T E R JSP.7
Tag Extensions
This chapter describes the tag library facility for introducing new actions into
a JSP page. The tag library facility includes portable run-time support, a validation
mechanism, and authoring tool support.
This chapter provides an overview of the tag library concept. It describes the
Tag Library Descriptor, and the taglib directive. A detailed description of the
APIs involved follows in Chapter JSP.12.
Note – This draft describes the new Simple Invocation Protocol in its own
chapter, but the descriptions will be integrated through the specification for a later
draft.
JSP.7.1 Introduction
Tag libraries are portable: they can be used in any legal JSP page regardless of
the scripting language used in that page.
The tag extension mechanism includes information to:
A Tag Library is described via the Tag Library Descriptor ( TLD), an XML
document that is described below.
JSP.7.1.1 Goals
The tag extension mechanism described in this chapter addresses the following
goals. It is designed to be:
Portable - An action described in a tag library must be usable in any JSP con-
tainer.
Simple - Unsophisticated users must be able to understand and use this mech-
anism. Vendors of JSP functionality must find it easy to make it available to
users as actions.
Expressive - The mechanism must support a wide range of actions, including
nested actions, scripting elements inside action bodies, and creation, use and
updating of scripting variables.
Usable from different scripting languages - Although the JSP specification
currently only defines the semantics for scripts in the Java programming lan-
guage, we want to leave open the possibility of other scripting languages.
Built upon existing concepts and machinery- We do not want to reinvent what
exists elsewhere. Also, we want to avoid future conflicts whenever we can
predict them.
JSP.7.1.2 Overview
The processing of a JSP page conceptually follows these steps:
Parsing
JSP pages can be authored using two different syntaxes: a JSP syntax and an
XML syntax. The semantics and validation of a JSP syntax page is described
with reference to the semantics and validation of an equivalent document in
PUBLIC DRAFT
Introduction 1-118
Validation
The tag libraries in the XML document are processed in the order in which
they appear in the page.
Each library is checked for a validator class. If one is present, the whole docu-
ment is made available to its validate() method as a PageData object. If the
JSP container supports jsp:id, then this information can be used to provide
location information on errors.
Each custom tag in the library is checked for a TagExtraInfo class. If one is
present, its isValid() method is invoked.
Translation
Finally, the XML document is processed to create a JSP page implementation
class. This process may involve creating scripting variables. Each custom
action will provide information about variables, either statically in the TLD,
or more flexibly by using the getVariableInfo method of a TagExtraInfo class.
Execution
Once a JSP page implementation class has been associated with a JSP page,
the class will be treated as any other Servlet class: Requests will be directed to
instances of the class. At run-time, tag handler instances will be created and
methods will be invoked in them.
PUBLIC DRAFT
1-119 TAG EXTENSIONS
• The Tag interface defines the basic methods needed in all tag handlers. These
methods include setter methods to initialize a tag handler with context data and
attribute values of the action, and the doStartTag() and doEndTag() methods.
• The IterationTag interface is an extension to Tag that provides the additional
method, doAfterBody(), invoked for the reevaluation of the body of the tag.
• The BodyTag interface is an extension of IterationTag with two new methods
for when the tag handler wants to manipulate the tag body: setBodyContent()
passes a buffer, the BodyContent object, and doInitBody() provides an oppor-
tunity to process the buffer before the first evaluation of the body into the buff-
er.
The use of interfaces simplifies making an existing Java object a tag handler.
There are also two support classes that can be used as base classes: TagSupport
and BodyTagSupport.
JSP 1.2 introduced a new interface designed to help maintain data integrity
and resource management in the presence of exceptions. The TryCatchFinally
interface is a “mix-in” interface that can be added to a class implementing any of
Tag, IterationTag or BodyTag.
PUBLIC DRAFT
Introduction 1-120
JSP.7.1.3.3 Conditionals
In some cases, a body needs to be invoked only when some (possibly complex)
condition happens. Again, this type of action is supported by the basic Tag interface
through the use of return values in the doStartTag() method.
JSP.7.1.3.4 Iterations
For iteration the IterationTag interface is needed. The doAfterBody() method is
invoked to determine whether to reevaluate the body or not.
PUBLIC DRAFT
1-121 TAG EXTENSIONS
and before the first body evaluation provides an opportunity to interact with the
body.
PUBLIC DRAFT
Tag Libraries 1-122
The URI identifying a tag library may be any valid URI as long as it can be
used to uniquely identify the semantics of the tag library.
The URI identifying the tag library is associated with a Tag Library
Description (TLD) file and with tag handler classes as indicated in
Section JSP.7.3 below.
PUBLIC DRAFT
1-123 TAG EXTENSIONS
If the JSP container cannot locate a TLD resource path for a given URI, a fatal
translation error shall result. Similarly, it is a fatal translation error for a uri
attribute value to resolve to two different TLD resource paths.
It is a fatal translation error for the taglib directive to appear after actions
using the prefix introduced by it.
Note – We expect an XML-Schema version of the TLD. This will allow for a
more extensible TLD that can be used as a true single-source document.
The Tag Library Descriptor (TLD) is an XML document that describes a tag
library. The TLD for a tag library is used by a JSP container to interpret pages that
include taglib directives referring to that tag library. The TLD is also used by JSP
page authoring tools that will generate JSP pages that use a library, and by authors
who do the same manually.
The TLD includes documentation on the library as a whole and on its
individual tags, version information on the JSP container and on the tag library,
and information on each of the actions defined in the tag library.
The TLD may name a TagLibraryValidator class that can validate that a JSP
page conforms to a set of constraints expected by the tag library.
Each action in the library is described by giving its name, the class of its tag
handler, information on any scripting variables created by the action, and
information on attributes of the action. Scripting variable information can be
given directly in the TLD or through a TagExtraInfo class. For each valid attribute
there is an indication about whether it is mandatory, whether it can accept request-
time expressions, and additional information.
A TLD file is useful for providing information on a tag library. It can be read
by tools without instantiating objects or loader classes. Our approach conforms to
the conventions used in other J2EE technologies.
The DTD for the tag library descriptor is organized so that interesting
elements have an optional ID attribute. This attribute can be used by other
documents, like vendor-specific documents, to provide annotations of the TLD
information.
PUBLIC DRAFT
The Tag Library Descriptor 1-124
PUBLIC DRAFT
1-125 TAG EXTENSIONS
• Each TLD file is examined. If it has a <uri> element, then a new <taglib> ele-
ment is created, with a <taglib-uri> subelement whose value is that of the <uri>
elemement, and with a <taglib-location> subelement that refers to the TLD file.
• If the created <taglib> element has a different <taglib-uri> to any in the taglib
map, it is added.
PUBLIC DRAFT
The Tag Library Descriptor 1-126
• If uri is NOROOT_REL_URI, a relative URI that does not start with “/”
Look in the taglib map for an entry whose TAGLIB_URI is NOROOT_REL_URI. If
found, the corresponding TAGLIB_LOCATION is the TLD resource path. If no such
entry is found, resolve NOROOT_REL_URI relative to the current JSP page where the
directive appears; that value (by definition, this is a relative URI specification that
starts with “/”) is the TLD resource path.
PUBLIC DRAFT
1-127 TAG EXTENSIONS
<taglib>
<taglib-uri>/myPRlibrary</taglib-uri>
<taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib-location>
</taglib>
Finally, the fallback rule allows a taglib directive to refer directly to the TLD.
This arrangement is very convenient for quick development at the expense of less
flexibility and accountability. For example, in the case above, it enables:
PUBLIC DRAFT
The Tag Library Descriptor Format 1-128
the behavior as that described by the required, portable tag library description
described by the URI.
A JSP container must always use the mapping specified for a URI in the
web.xml deployment descriptor if present. If the deployer wants to use the
platform-specific implementation of the well-known URI, the mapping for that
URI should be removed at deployment time.
This section describes the DTD for the JSP 1.2 version of the Tag Library
Descriptor. The JSP 1.2 version has information added from the JSP 1.1 version, as
well as a few changes to element names made to improve consistency with other
specifications.
TLDs in the 1.1 format must be accepted by JSP 1.2 containers.
Notation
<!NOTATION WEB-JSPTAGLIB.1_2 PUBLIC “-//Sun Microsystems, Inc.//DTD
JSP Tag Library 1.2//EN”>
<taglib>
The taglib element is the document root. A taglib has two attributes.
<!ATTLIST taglib
id
ID
#IMPLIED
xmlns
CDATA
#FIXED
"http://java.sun.com/JSP/TagLibraryDescriptor"
>
PUBLIC DRAFT
1-129 TAG EXTENSIONS
short-name a simple default short name that could be used by a JSP page
authoring tool to create names with a mnemonic value; for
example, the it may be used as the preferred prefix value in taglib
directives.
<!ELEMENT taglib
(tlib-version, jsp-version,
short-name, uri?, display-name?, small-icon?, large-icon?
description?, validator?, listener*, tag+) >
<tlib-version>
Describes the version (number) of the tag library.
The syntax is:
<jsp-version>
Describes the JSP specification version (number) this tag library requires in
order to function. This element is mandatory
The syntax is:
<short-name>
Defines a simple default short name that could be used by a JSP page author-
ing tool to create names with a mnemonic value; for example, the it may be
used as the preferred prefix value in taglib directives and/or to create prefixes
for IDs. Do not use white space, and do not start with digits or underscore.
The syntax is
PUBLIC DRAFT
The Tag Library Descriptor Format 1-130
<uri>
Defines a public URI that uniquely identifies this version of the tag library.
<description>
Defines an arbitrary text string describing the tag library, variable, attribute or
validator.
<validator>
Defines an optional TagLibraryValidator that can be used to validate the con-
formance of a JSP page to using this tag library. A validator may have some
optional initialization parameters.
The validator may have several subelements defining:
validator-class the class implementing
javax.servlet.jsp.tagext.TagLibraryValidator
init-param optional initialization parameters
<validator-class>
Defines the class of the optional TagLibraryValidator.
<init-param>
Defines an initialization parameter.
The init-param may have several subelements defining:
param-name the name of the parameter
PUBLIC DRAFT
1-131 TAG EXTENSIONS
<param-name>
The name of a parameter.
<param-value>
The value of a parameter.
<listener>
Defines an optional event listener object to be instantiated and registered auto-
matically.
<listener-class>
The listener-class element declares a class in the application that must be reg-
istered as a web application listener bean. See the Servlet 2.4 specification for
details.
<tag>
The tag defines an action in this tag library.
The common way to describe the semantics of a specific custom action that
are observable by other custom actions is the implementation class of the tag
handler in the tag-class element. But the description element can also be used
to indicate a type that further constraints those operations. The type can be
either void or a subtype of the tag handler implementation class. This infor-
mation can be used by a specialized container for a specific well known tag
libraries; see Section JSP.7.3.9.
The tag element has one attribute:
PUBLIC DRAFT
The Tag Library Descriptor Format 1-132
<!ELEMENT tag
(name, tag-class, tei-class?,
body-content?, display-name?, small-icon?, large-icon?,
description?, variable*, attribute*, example?) >
<tag-class>
Defines the tag handler implementation class for this custom action. The class
must implement the javax.serlvet.jsp.tagext.Tag interface. This element is
required.
The syntax is:
<tei-class>
Defines the subclass of javax.servlet.jsp.tagext.TagExtraInfo for this tag. This
element is optional.
The syntax is:
<body-content>
Provides a hint as to the content of the body of this action. Primarily intended
for use by page composition tools.
There are currently three values specified:
PUBLIC DRAFT
1-133 TAG EXTENSIONS
JSP The body of the action contains elements using the JSP syntax.
The body of the action may be empty.
<display-name>
The display-name elements contains a short name that is intended to be displayed by
tools.
The syntax is:
<large-icon>
The large-icon element contains the name of a file containing a large (32 x 32)
icon image. The file name is a path within the tag library relative to the loca-
tion of the TLD. The image must be either in the JPEG or GIF format, and the
file name must end with the suffix ".jpg" or ".gif" respectively. The icon can
be used by tools.
The syntax is:
<small-icon>
The small-icon element contains the name of a file containing a small (16 x
16) icon image. The file name is a path within the tag library relative to the
location of the TLD. The image must be either in the JPEG or GIF format,
and the file name must end with the suffix ".jpg" or ".gif" respectively. The
icon can be used by tools.
The syntax is:
PUBLIC DRAFT
The Tag Library Descriptor Format 1-134
<variable>
Provides information on the scripting variables defined by this tag. It is a
(translation-time) error for a tag that has one or more variable subelements to
have a TagExtraInfo class that returns a non-null object.
The subelements of variable are of the form:
name-given the variable name as a constant.
name-from-attribute
the name of an attribute whose (translation-time) value will give
the name of the variable. One of name-given or name-from-
attribute is required.
<!ELEMENT variable
((name-given | name-from-attribute), variable-class?,
declare?, scope?, description?) >
<name-given>
The name for the scripting variable. One of name-given or name-from-attribute is
required.
The syntax is:
<name-from-attribute>
The name of an attribute whose (translation-time) value will give the name of
the variable. One of name-given or name-from-attribute is required.
The syntax is:
<variable-class>
The optional name of the class for the scripting variable. The default is
java.lang.String.
The syntax is:
PUBLIC DRAFT
1-135 TAG EXTENSIONS
<declare>
Whether the scripting variable is to be defined or not. See TagExtraInfo for
details. This element is optional and “true” is the default.
The syntax is:
<scope>
The scope of the scripting variable. See TagExtraInfo for details. This ele-
ment is optional and “NESTED” is the default..
The syntax is:
<attribute>
Provides information on an attribute of this action. Attribute defines an id
attribute for external linkage.
<name>
Defines the canonical name of a tag or attribute being defined
The syntax is:
PUBLIC DRAFT
The Tag Library Descriptor Format 1-136
<required>
Defines if the nesting attribute is required or optional.
The syntax is:
If not present then the default is “false”, i.e the attribute is optional.
<rtexprvalue>
Defines if the nesting attribute can have scriptlet expressions as a value, i.e the
value of the attribute may be dynamically calculated at request time, as
opposed to a static value determined at translation time.
The syntax is:
If not present then the default is “false”, i.e the attribute has a static value
<type>
Defines the Java type of the attribute’s value. For literal values (rtexprvalue is
false) the type is always java.lang.String.
If the rtexprvalue element is true, then the type defines the return type
expected from any scriptlet expression specified as the value of this attribute.
The value of this attribute should match that of the underlying JavaBean com-
ponent property.
The syntax is:
An example is:
<example>
The content of this element is intended to be an example of how to use the tag.
This element is not intepreted by the JSP container and has no effect on the
semantics of the tag.
PUBLIC DRAFT
1-137 TAG EXTENSIONS
JSP.7.5 Validation
There are a number of reasons why the structure of a JSP page should conform
to some validation rules:
PUBLIC DRAFT
Conventions and Other Issues 1-138
The JSP container may optionally uniquely identify all XML elements in the
XML view of a JSP page through a jsp:id attribute. This attribute can be used to
provide better information on the location of an error.
The validator class mechanism is new as of the JSP 1.2 specification. A
TagLibraryValidator can be passed some initialization parameters in the TLD. This
eases the reuse of validator classes. We expect that validator classes will be
written based on different XML schema mechanisms (DTDs, XSchema, Relaxx,
others). Standard validator classes may be incorporated into a later version of the
JSP specification if a clear schema standard appears at some point.
PUBLIC DRAFT
1-139 TAG EXTENSIONS
PUBLIC DRAFT
Conventions and Other Issues 1-140
WEB-INF/ portion of the Web Application and access it via the getResource() call
on the ServletContext.
PUBLIC DRAFT
C H A P T E R JSP.8
JSP Fragments
This chapter describes the details of JSP fragments and supporting mecha-
nisms including Simple Tag Extensions and tag files. The mechanisms in this chap-
ter can be used only when the body of a tag invocation does not contain scripting
elements such as scriptlets or scriptlet expressions. The body of the invocation may
still contain template text, expressions written using the Expression Language, and
action elements.
Also presented is a facility that allows page authors to author tag extensions
using only JSP syntax. When used together, these concepts have the ability to
simplify JSP development substantially.
Note – This chapter will be split and merged with other chapters such as
Chapter JSP.7, “Tag Extensions”. For now it is in its own chapter for easier tracking
of changes. Eventually, we expect this chapter to only specify tag files. The rest will
be integrated elsewhere.
This section describes additional syntax and semantics for custom action invo-
cation. JSP 2.0 introduces a new mechanism for passing attributes when invoking
custom actions, using the <jsp:attribute> and <jsp:body> standard actions. This
new mechanism is useful for passing attribute values that are inconvenient or impos-
sible to express using the XML element attribute syntax. In addition, it facilitates the
passing of JSP fragments, which allow for dynamic re-evaluation of attributes, simi-
lar to the way tag bodies are currently handled.
JSP.8.1.2.1 javax.servlet.jsp.tagext.DynamicAttributes
To declare that it accepts attributes with dynamic names, a tag handler must
implement the javax.servlet.jsp.tagext.DynamicAttributes interface, defined as fol-
lows:
PUBLIC DRAFT
1-143 JSP FRAGMENTS
JSP.8.1.2.2 javax.servlet.jsp.tagext.AttributeNotSupportedException
This exception is thrown by a tag handler that wants to indicate that the pro-
vided dynamic attribute is not supported by this tag. The exception is defined as fol-
lows:
PUBLIC DRAFT
Simple Tag Extensions 1-144
• For each attribute specified in the tag invocation that does not have a corre-
sponding attribute or fragment-attribute element in the TLD for this tag, a call
must be made to setDynamicAttribute(), passing in the namespace of the at-
tribute (or null if in the default namespace), the name of the attribute, and the
final value of the attribute.
• Attributes must be set in the order in which they appear in the invocation.
• The JSP container must recognize dynamic attributes that are passed to the tag
handler using the <jsp:attribute> standard action.
In the following example, assume attributes a and b are declared using the
attribute element in the TLD, attributes d1 and d2 are not declared, and the
dynamic-attributes element is set to “true”. The attributes are set in the order a,
then d1, then b, then d2, using the calls setA( “1” ), setDynamicAttribute( null,
“d1”, “2” ), setB( “3” ), and setDynamicAttribute( null, “d2”, “4” ).
Version 1.1 of the JavaServer Pages specification introduced a tag library facil-
ity for defining custom actions that can be used in a JSP page. See Chapter JSP.7,
“Tag Extensions” for more details. The API and invocation protocol for this facility
is necessarily somewhat complex because scriptlets and scriptlet expressions in tag
bodies can rely on surrounding context defined using scriptlets in the enclosing
page.
With the advent of the Expression Language and JSP Standard Tag Library
(JSTL), it is now feasible to develop JSP pages that do not need scriptlets or
scriptlet expressions. This allows us to define a tag invocation protocol that is
easier to use for many use cases.
In that interest, JSP 2.0 introduces a new type of tag extension called a
“Simple Tag Extension.” Simple Tag Extensions can be written in one of two
ways:
PUBLIC DRAFT
1-145 JSP FRAGMENTS
tag library developers who need the flexibility of the Java language in order to
write their tag handlers.
• In JSP, using tag files. This method can be used by page authors who do not
know Java. It can also be used by advanced page authors or tag library devel-
opers who know Java but are producing tag libraries that are presentation-cen-
tric or can take advantage of existing tag libraries.
Note – The final TLD will be converted to XML Schema for JSP 2.0. Older
versions (JSP 1.2 and prior) will be supported for backwards compatibility.
1. Add “scriptless” to the possible values for the body-content element (only
comment is affected, but this may affect the XML Schema version). A body-
content of “scriptless” indicates the body only accepts template text and JSP
action elements.
2. Change tag-lib element to support tag-file (changes in bold):
PUBLIC DRAFT
Simple Tag Extensions 1-146
<!--
The tag element defines an action in this tag library. The tag element
has one attribute, id.
The tag element may have several subelements defining:
PUBLIC DRAFT
1-147 JSP FRAGMENTS
<!--
Defines the details of an attribute of type
javax.servlet.jsp.tagext.JspFragment.
<!--
Declares whether this tag handler supports dynamic attributes
or not. Valid values are “true” and “false”. Defaults to false.
-->
<!ELEMENT dynamic-attributes (#PCDATA)>
<!--
Describes the details of a single parameter that may be passed
from a tag handler to a fragment, when the fragment is invoked.
This allows the page author to know what variables to expect from
the tag when passing in a fragment.
PUBLIC DRAFT
Simple Tag Extensions 1-148
<!--
Defines an action in this tag library that is implemented
as a .tag file.
-->
<!ELEMENT tag-file ( name, path ) >
Because SimpleTag does not extend Tag, and because Tag.setParent() accepts
an object of type Tag, tag collaboration becomes complicated when classic
custom actions (i.e. those that implement the Tag interface) are nested inside Sim-
pleTag custom actions. The javax.servlet.jsp.tagext.TagAdapter class can wrap
any Object and expose it as a Tag instace. The original object can be retrieved
through its getAdaptee() method.
Whenever calling setParent() on a classic Tag in a case where the outer tag
does not implement Tag, the JSP Container must construct a new TagAdapter and
call setParent() on the classic Tag passing in the adapter. See the API for TagAda-
pter for more details.
1. Just as with classic tag handlers, simple tag handlers are created initially using
a zero argument constructor on the corresponding implementation class. Un-
like classic tag handlers, this instance must never be pooled by the container.
A new instance must be created for each tag invocation.
2. The setJspContext() and setParent() methods are invoked on the tag handler,
as with classic tag handlers.
3. The attributes specified as XML element attributes (if any) are evaluated next,
in the order in which they are declared, according to the following rules (re-
ferred to as “evaluating an XML element attribute” below):
■
If the attribute is a rtexprvalue (e.g. “<%= 1+1 %>” in JSP syntax, or “%=
PUBLIC DRAFT
Simple Tag Extensions 1-150
1+1 %” in XML syntax), the expression is evaluated, and the result is con-
verted as per the rules in Section JSP.1.14.2, “Type Conversions”, and passed
to the bean property setter.
■
Otherwise, if the attribute contains any Expression Language expressions
(e.g. “Hello ${name}”), the expression is evaluated, and the result is convert-
ed and passed to the setter.
■
Otherwise, the attribute value is taken verbatim, converted, and passed to the
setter.
4. The value for each <jsp:attribute> element is evaluated, and the corresponding
setter methods are invoked for each, in the order in which they appear in the
body of the tag. If the tag accepts dynamic attributes, the setDynamicAt-
tribute() method is invoked as the setter.
■
If the value attribute is specified, the XML element attribute is evaluated ac-
cording to the “evaluating an XML element attribute” procedure defined
above.
■
Otherwise, if the attribute is not of type javax.servlet.jsp.tagext.JspFrag-
ment, the container evaluates the body of the <jsp:attribute> element. This
evaluation can be done in a container-specific manner. Container implemen-
tors should note that in the process of evaluating this body, other custom ac-
tions may be invoked.
■
Otherwise, if the attribute is of type javax.servlet.jsp.tagext.JspFragment,
an instance of a JspFragment object is created as per the lifecycle described
in Section JSP.8.3.4.
5. The value for the body of the tag is determined, and the setJspBody() method
is called on the tag handler. If the tag is declared to have a body-content of
“empty” then null is passed to setJspBody(). Otherwise, the body of the tag is
either the body of the <jsp:body> element, or the body of the custom action in-
vocation if no <jsp:body> element is present.
■
If the value attribute is specified, the XML element attribute is evaluated ac-
cording to the “evaluating an XML element attribute” procedure above, and
the result of the evaluation is converted and passed to the setter.
■
Otherwise, an instance of a JspFragment object is created as per the lifecycle
described in Section JSP.8.3.4. and it is passed to the setter.
6. The doTag() method is invoked.
7. The implementation of doTag() performs its function, potentially calling other
tag handlers and invoking fragments.
8. The doTag() method returns, and the tag handler instance is discarded. The ap-
propriate action is taken, depending on the return value:
PUBLIC DRAFT
1-151 JSP FRAGMENTS
■
If EVAL_PAGE is returned, normal execution resumes at the next step and
the page continues to be evaluated.
■
If SKIP_PAGE is returned, the rest of the page is not evaluated and the re-
quest is completed. If this request was forwarded or included from another
page (or Servlet), only the current page evaluation stops.
9. For each tag scripting variable declared with scopes AT_BEGIN or AT_END,
the appropriate scripting variables and scoped attributes are declared, as with
classic tag handlers.
See Section JSP.8.3.4, “The <jsp:doBody> Standard Action” for the
lifecycle details of a JSP fragment. Check the TryCatchFinally interface for
additional details related to exception handling and resource management.
PUBLIC DRAFT
Defining and Invoking JSP Fragments 1-152
for future invocations, so tag handler implementations can rely on getting a unique
instance for each invocation.
The invoke() method executes the body and directs all output to the JspWriter
returned by the getOut() method of the JspContext associated with the fragment.
The method accepts a parameter map, containing the body-input parameters
passed to the body by its invoker (e.g. a tag handler). The keys in this map are
parameter names, and the values are parameter values. This allows the invoker to
parameterize a fragment invocation.
The implementation of each method can optionally throw a javax.jsp.serv-
let.JspException, which must be handled by the invoker. Note that tag library
developers and page authors should not generate JspFragment implementations
manually.
PUBLIC DRAFT
1-153 JSP FRAGMENTS
<jsp:invoke fragment=”frag1”/>
It is also possible to invoke the fragment and send the results to a scoped
attribute for further examination and manipulation. This can be accomplished by
specifying the varReader attribute in the action. In this usage, the fragment is be
invoked using the JspFragment.invoke() method, but a custom java.io.Writer is
passed in instead of null. The container must ensure that a java.io.Reader object is
constructed and is made available in a scoped attribute with the name specified by
varReader. The Reader object must produce the content sent by the fragment to
the provided Writer. The Reader must also be resettable. That is, if its reset()
method is called, the result of the invoked fragment must be able to be read again
without re-executing the fragment.
If xyz is a Reader exposed via varReader, then the evaluation of the EL
expression ‘${xyz}’ must produce the same output the fragment did when it was
invoked. Immediately following the evaluation, the Reader object must be reset
such that on the next evaluation of the expression the same value is produced.
<jsp:invoke fragment=”frag3”>
<jsp:param name=”param1” value=”value1”/>
<jsp:param name=”param2” value=”${val2}”/>
</jsp:invoke>
PUBLIC DRAFT
Defining and Invoking JSP Fragments 1-154
PUBLIC DRAFT
1-155 JSP FRAGMENTS
PUBLIC DRAFT
Defining and Invoking JSP Fragments 1-156
ing setJspContext().
3. The fragment calls JspContext.peekPageScope() and stores a reference to the
current page scope. This value is used during an invocation, to access the sur-
rounding context from the page in which the fragment was defined.
4. The JspFragment instance is associated with an instance of the tag handler of
the nearest enclosing tag invocation, or with null if there is no enclosing tag.
Whenever the fragment invokes a tag handler, the fragment must use this value
when calling setParent().
PUBLIC DRAFT
1-157 JSP FRAGMENTS
eters.
5. The fragment instance calls JspContext.pushPageScope(), passing in the
page scope stored during the creation of the fragment. This restores the page
scope of the page that defined this fragment.
6. For each key present in the Map, the fragment must make a page scope variable
available to the fragment body, so that the parameters can be accessed via the
Expression Language and via other mechanisms. Changes made to the value
of any page scope variable with the same name as a key in the Map must only
last for the duration of the fragment invocation, and must be scoped to this
fragment invocation only. That is, if the same fragment instance is invoked
more than once in the same thread of execution, changes to variables with the
same name as a key in the Map in one invocation must not affect the same vari-
ables in the other invocation.
7. The body of the fragment is evaluated by executing the generated code. The
body of the fragment may execute other standard or custom actions. The re-
sults of the body invocation must go to the JspWriter returned from the Jsp-
Context.getOut() method.
8. Once the body has completed its evaluation, even if an exception is thrown, the
page scope must be restored to its original state. The fragment instance calls
JspContext.popPageScope(), restoring the page scope of the caller of the
fragment.
9. The fragment returns from invoke()
10. If <jsp:invoke> or <jsp:doBody> is being used to invoke a fragment, if the
varReader attribute is specified, a variable with a name equal to the value of
the varReader attribute is created (or modified) in the page scope, and the val-
ue is set to a java.io.Reader that can produce the results of the fragment invo-
cation.
11. The fragment instance is not discarded until the tag invocation defining the
fragment is complete. The invoke() method can be called zero or more times
after this execution.
As of JSP version 2.0, the JSP Compiler is required to recognize tag files. A
tag file is a source file that provides a way for a page author to abstract a fragment
of JSP code and make it reusable via a custom action.
Tag files allow a JSP page author to create tag libraries using JSP syntax. This
means that page authors no longer need to know Java or ask someone who knows
PUBLIC DRAFT
Tag Files 1-158
Java to write a tag extension. Even for page authors or tag library developers who
know Java, writing tag files is more convenient when developing tags that
primarily output template text.
The recommended file extension for a tag file is .tag. As is the case with JSP
files, the actual tag may be composed of a top file that includes other files that
contain either a complete tag or a fragment of a tag file. Just as the recommended
extension for a fragment of a JSP file is .jspf, the recommended extension for a
fragment of a tag file is .tagf.
• Directives - Some directives are not available or have limited availability, and
some tag file specific directives are available. See Section JSP.8.4.4, “Tag File
Directives” for a discussion on tag file directives.
The EBNF grammar in Section JSP.1.3.9, “Standard JSP Syntax Grammar”
describes the syntax of tag files, building on top of the grammar defined in
Section JSP.1.3.9, “Standard JSP Syntax Grammar”. The root production for a tag
files is JSPTagDef.
• The tag file implementation must share a JspContext instance with the invok-
ing page, and push its own page scope by calling JspContext.pushPage-
Scope().
• The tag file implementation must restore the original page scope before re-
turning (even if an exception is thrown), by calling JspContext.popPage-
Scope().
PUBLIC DRAFT
1-159 JSP FRAGMENTS
PUBLIC DRAFT
Tag Files 1-160
installed in the “/WEB-INF/lib/” directory. Tags placed here are typically part of a
reusable library of tags that can be easily dropped into any web application. The
second possibility is in a subdirectory of, the “/WEB-INF/tags/” directory of the
web application. Tags placed here are within easy reach and require little
packaging. Tag files that appear in any other location are not considered tag
extensions and must be ignored by the JSP container. For example, a tag file that
appears in the root of a web application would be treated as content to be served.
To be accessible, tag files bundled in a JAR require a Tag Library Descriptor.
Tag files that are not defined in a TLD must be ignored by the JSP container. JSP
2.0 adds two additional TLD elements to describe tags within a tag library,
namely <tag-file> and <path>. The <tag-file> element can appear wherever the
<tag> element appears and describes the location of a tag file defining a tag in this
tag library. The <tag-file> element requires <name> and <path> subelements,
which define the tag name and the location of the tag file relative to the TLD
respectively. Note that it is possible to combine both classic tag handlers and tag
handlers implemented using tag files in the same tag library by combining the use
of <tag> and <tag-file> elements under the <taglib> element. This means that in
most instances the client is unaware of how the tag extension was implemented.
See Section for these and other new TLD elements introduced by JSP 2.0.
Tag files placed in the “/WEB-INF/tags/” directory, or a subdirectory, are
made easily accessible to JSPs without the need to explicitly write a Tag Library
Descriptor. This makes it convenient for page authors to quickly abstract reusable
JSP code by simply creating a new file and placing the code inside of it. See the
new tagdir attribute of the <%@ taglib %> directive in Section JSP.1.10.4 for
details on how JSP files access tags defined here.
The JSP container must interpret the “/WEB-INF/tags/” directory and each
subdirectory under it, as another implicitly defined tag library containing tag
handlers defined by the tag files that appear in that directory. There are no special
relationships between subdirectories - they are allowed simply for organizational
purposes. For example, the following web application contains three tag libraries:
/WEB-INF/tags/
/WEB-INF/tags/a.tag
/WEB-INF/tags/b.tag
/wEB-INF/tags/foo/
/WEB-INF/tags/foo/c.tag
/WEB-INF/tags/foo/footags.tld
/WEB-INF/tags/bar/baz/
/WEB-INF/tags/bar/baz/d.tag
PUBLIC DRAFT
1-161 JSP FRAGMENTS
A tld file may or may not exist in each directory. If more than one tld file
exists in a directory, the behavior is undefined. If a tld file exists, the file is parsed
and a tag library is created. If a tld file does not exist for a directory, the JSP
container generates an implicit tag library, and must act as though a tld file were
present in that directory with the following defaults:
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>bar-baz</short-name>
<tag-file>
<name>d</name>
<path>d.tag</path>
</tag-file>
</taglib>
Upon deployment, the JSP container must search for and process all tag files
appearing in these JAR files, directories, and subdirectories. In processing a tag
file, the container makes the custom actions defined in these tags available to JSP
files.
Alternatively, tag files can be compiled into Java classes and bundled as a tag
library as indicated in Section JSP.8.2.5. This is useful for the situation where a
tag library developer wishes to distribute a binary version of the tag library
without the original source. Tag library developers that choose this form of
packaging must use a tool that produces portable JSP code that uses only standard
APIs
PUBLIC DRAFT
Tag Files 1-162
PUBLIC DRAFT
1-163 JSP FRAGMENTS
The attribute/value namespace is reserved for use by this, and subsequent, JSP
specification(s).
Unrecognized attributes or values result in fatal translation errors.
Examples
<%@ tag name=”add”
display-name=”Addition”
body-content=”scriptless”
dynamic-attributes=”true”
small-icon=”/WEB-INF/sample-small.jpg”
large-icon=”/WEB-INF/sample-large.jpg”
description=”Sample usage of tag directive” %>
Syntax
<%@ tag tag_directive_attr_list %>
tag_directive_attr_list ::=
{ name=”tagname” }
{ display-name=”display-name” }
{ body-content=”scriptless|tagdependent|empty” }
{ dynamic-attributes=”true|false” }
{ small-icon=”small-icon” }
{ large-icon=”large-icon” }
{ description=”description” }
{ example=”example” }
{ pageEncoding=”peinfo” }
name (optional) The unique action name for this tag. Defaults to
the filename of the tag file, without the .tag extension.
display-name (optional) A short name that is intended to be displayed by
tools. Defaults to the value of name.
body-content (optional) Provides information on the content of the body of
this tag. Can be either “empty”, “tagdependent” or
“scriptless”. A translation error will result if “JSP” or any
other value is used. Defaults to “scriptless”.
PUBLIC DRAFT
Tag Files 1-164
Examples
<%@ attribute name=”x” required=”true” fragment=”false”
rtexprvalue=”false” type=”java.lang.Integer”
description=”The first operand” %>
PUBLIC DRAFT
1-165 JSP FRAGMENTS
Syntax
<%@ attribute attribute_directive_attr_list %>
attribute_directive_attr_list ::=
name=”attribute-name”
{ required=”true|false” }
{ fragment=”true|false” }
{ rtexprvalue=”true|false” }
{ type=”type” }
{ description=”description” }
PUBLIC DRAFT
Tag Files 1-166
Examples
<%@ variable name-given=”AT_BEGIN”
variable-class=”java.lang.Integer”
scope=”NESTED”
declare=”true”
description=”The sum of the two operands” %>
Syntax
<%@ variable variable_directive_attr_list %>
variable_directive_attr_list ::=
( name-given=”output-name”
| name-from-attribute=”attr-name”
)
{ variable-class=”output-type” }
{ scope=”AT_BEGIN|AT_END|NESTED” }
{ declare=”true|false” }
{ description=”description” }
PUBLIC DRAFT
1-167 JSP FRAGMENTS
PUBLIC DRAFT
Tag Files 1-168
Examples
<%@ fragment-input name=”op1” fragment=”prompt”
required=”true” type=”java.lang.Integer”
description=”The first operand” %>
Syntax
<%@ fragment-input fragmentinput_directive_attr_list %>
fragmentinput_directive_attr_list ::=
name=”inputname”
fragment=”attributename”
{ required=”true|false” }
{ type=”type” }
{ description=”description” }
PUBLIC DRAFT
1-169 JSP FRAGMENTS
<jsp:directive.tag tag_directive_attr_list/>
PUBLIC DRAFT
Example Scenario 1-170
<jsp:directive.attribute attribute_directive_attr_list/>
<jsp:directive.variable variable_directive_attr_list/>
<jsp:directive.fragment-input fragmentinput_directive_attr_list/>
PUBLIC DRAFT
1-171 JSP FRAGMENTS
<my:simpleTag x="10">
<jsp:attribute name="y" value="20"/>
<jsp:attribute name="nonfragment">
Nonfragment Template Text
</jsp:attribute>
<jsp:attribute name="frag">
Fragment Template Text ${param1}
</jsp:attribute>
<jsp:body>
Body of tag that defines an AT_BEGIN
scripting variable ${var1}.
</jsp:body>
</my:simpleTag>
PUBLIC DRAFT
Example Scenario 1-172
PUBLIC DRAFT
1-173 JSP FRAGMENTS
/**
* Takes a snapshot of the current JspContext and stores
* the results in a Map for later restoration. Also sets the
* new values in the page context, given the provided params.
*
* @param params The parameters to set in the page scope
* @return A map that contains a snapshot of the old page scope.
*/
protected java.util.Map preparePageScope( java.util.Map params ) {
java.util.Map originalValues = new java.util.HashMap();
return result;
}
PUBLIC DRAFT
Example Scenario 1-174
/**
* Restores the state of the page scope in the current page context,
* from the given map.
*
* @param originalValues The values to restore in the page
* context.
*/
protected void restorePageScope( java.util.Map originalValues ) {
keys = params.keySet().iterator();
while( keys.hasNext() ) {
String key = (String)keys.next();
// Value to be restored:
jspContext.setAttribute( key, originalValues.get( key ) );
originalValues.put( key, origPageScope.get( key ) );
}
}
}
// - parameter y
_jsp.mySimpleTag.setY( "20" );
// - parameter nonfragment
// (using PageContext.pushBody() is ons possible implementation -
// one limitation is that this code will only work for Servlet-based code).
out = ((PageContext)jspContext).pushBody();
out.write( "\n Nonfragment Template Text\n " );
_jsp_mySimpleTag.setNonfragment(
((javax.servlet.jsp.tagext.BodyContent)out).getString() );
out = jspContext.popBody();
PUBLIC DRAFT
1-175 JSP FRAGMENTS
// - parameter frag
_jsp_mySimpleTag.setFrag(
// Step C.1 - New instance of fragment created
// Step C.2 - Store jspContext
// Step C.4 - Association with nearest enclosing Tag instance
new JspFragmentBase( jspContext, null ) {
// Step C.3 done in constructor (see above)
public void invoke( Map params ) {
// Step F.1-F.4 done in tag file (see following example)
// Step F.5 - Restore page scope of defining page
this.jspContext.pushPageScope( this.origPageScope );
// Step F.6 - Expose parameters in page scope
java.util.Map originalValues = preparePageScope( params );
// Step F.7 - Evaluate body to JspContext.getOut()
try {
javax.servlet.jsp.JspWriter out = jspContext.getOut();
out.write( "\n Fragment Template Text " );
out.write( javax.servlet.jsp.el.
ExpressionEvaluatorManager.evaluate(
"template text",
"${param1}",
java.lang.String.class,
jspContext )
);
out.write( " \n " );
}
finally {
// Step F.8 - Restore page scope to invoker’s state
restorePageScope( originalValues );
jspContext.popPageScope();
}
PUBLIC DRAFT
Example Scenario 1-176
PUBLIC DRAFT
1-177 JSP FRAGMENTS
// Attributes:
private String x;
private String y;
private String nonfragment;
private javax.servlet.jsp.tagext.JspFragment frag;
PUBLIC DRAFT
Example Scenario 1-178
PUBLIC DRAFT
1-179 JSP FRAGMENTS
try {
// Tag template text:
out.write( "\n\n\n\n\n\n\nSome template text.\n" );
PUBLIC DRAFT
Example Scenario 1-180
return EVAL_PAGE;
}
}
PUBLIC DRAFT
C H A P T E R JSP.9
Scripting
This chapter describes the details of the Scripting Elements when the lan-
guage directive value is “java”.
The scripting language is based on the Java programming language (as
specified by “The Java Language Specification”), but note that there is no valid
JSP page, or a subset of a page, that is a valid Java program.
The following sections describe the details of the relationship between the
scripting declarations, scriptlets, and scripting expressions, and the Java
programming language. The description is in terms of the structure of the JSP
page implementation class. A JSP container need not generate the JSP page
implementation class, but it must behave as if one exists.
Some details of what makes a JSP page legal are very specific to the scripting
language used in the page. This is especially complex since scriptlets are language
fragments, not complete language statements.
Name of class
(_jspXXX) is
implementation
dependent.
Start of body of JSP {
page implementation
class
(1) Declaration // declarations...
Section
signature for public void _jspService(<ServletRequestSubtype>
generated method request,
<ServletResponseSubtype> response)
throws ServletException, IOException {
PUBLIC DRAFT
1-183 SCRIPTING
(2) Implicit Objects // code that defines and initializes request, response,
Section page, pageContext etc.
This section defines and initializes the implicit objects available to the JSP page.
See Section JSP.1.8.3, “Implicit Objects”.
This section provides the main mapping between a request and a response
object.
The content of code segment 2 is determined from scriptlets, expressions, and
the text body of the JSP page. The elements are processed sequentially in the
order in which they appear in the page. The translation for each one is determined
as indicated below, and its translation is inserted into this section. The translation
depends on the element type:
PUBLIC DRAFT
Main Section 1-184
JSP.9.4.2 Scriptlets
A scriptlet is transformed into its code fragment.:
JSP.9.4.3 Expressions
An expression is transformed into a Java statement to insert the value of the
expression, converted to java.lang.String if needed, into the stream curnamed by the
implicit variable out. No additional newlines or space is included.
Ignoring quotation and performance issues, this corresponds to a statement of
the form:
JSP.9.4.4 Actions
An action defining one or more objects is transformed into one or more variable
declarations for those objects, together with code that initializes the variables. Their
visibility is affected by other constructs, for example scriptlets.
The semantics of the action type determines the names of the variables
(usually the name of an id attribute, if present) and their type. The only standard
action in the JSP specification that defines objects is the jsp:usebean action. The
name of the variable introduced is the name of the id attribute and its type is the
type of the class attribute.
PUBLIC DRAFT
1-185 SCRIPTING
Note that the value of the scope attribute does not affect the visibility of the
variables within the generated program. It affects where and thus for how long
there will be additional references to the object denoted by the variable.
PUBLIC DRAFT
Main Section 1-186
PUBLIC DRAFT
PART II
T he next chapters provide detail specification information on some portions
of the JSP specification that are intended for JSP Container Vendors, .... etc..
The chapters are normative.
The chapters are
• JSP Container
• Core API
• Tag Extension API
This chapter describes the contracts between a JSP container and a JSP page,
including the precompilation protocol and debugging support requirements.
The information in this chapter is independent of the Scripting Language used
in the JSP page. Chapter JSP.9 describes information specific to when the lan-
guage attribute of the page directive has “java” as its value.).
JSP page implementation classes should use the JspFactory and PageContext
classes to take advantage of platform-specific implementations.
described by the HttpServlet class. Most JSP pages use the HTTP protocol, but
other protocols are allowed by this specification.
The JSP container automatically makes a number of server-side objects
available to the JSP page implementation object . See Section JSP.1.8.3.
PUBLIC DRAFT
JSP Page Implementation Class 2-4
The involved contracts are shown in Figure JSP.10-1. We now revisit this
whole process in more detail.
The JSP container creates a JSP page implementation class for each JSP page.
The name of the JSP page implementation class is implementation dependent.
The JSP Page implementation object belongs to an implementation-dependent
named package. The package used may vary between one JSP and another, so
minimal assumptions should be made. The unnamed package should not be used
without an explicit “import” of the class.
The JSP container may create the implementation class for a JSP page, or a
superclass may be provided by the JSP page author through the use of the extends
attribute in the page directive.
The extends mechanism is available for sophisticated users. It should be used
with extreme care as it restricts decisions that a JSP container can make. It may
restrict efforts to improve performance, for example.
The JSP page implementation class will implement Servlet and the Servlet
protocol will be used to deliver requests to the class.
PUBLIC DRAFT
2-5 JSP CONTAINER
A JSP page implementation class may depend on support classes. If the JSP
page implementation class is packaged into a WAR, any dependant classes will
have to be included so it will be portable across all JSP containers.
A JSP page author writes a JSP page expecting that the client and the server
will communicate using a certain protocol. The JSP container must guarantee that
requests from and responses to the page use that protocol. Most JSP pages use
HTTP, and their implementation classes must implement the HttpJspPage
interface, which extends JspPage. If the protocol is not HTTP, then the class will
implement an interface that extends JspPage.
PUBLIC DRAFT
JSP Page Implementation Class 2-6
PUBLIC DRAFT
2-7 JSP CONTAINER
imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;
/**
* An example of a superclass for an HTTP JSP class
*/
PUBLIC DRAFT
JSP Page Implementation Class 2-8
/**
* The entry point into service.
*/
_jspService(request, response);
}
/**
* abstract method to be provided by the JSP processor in the subclass
* Must be defined in subclass.
*/
PUBLIC DRAFT
2-9 JSP CONTAINER
imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;
/**
* An example of a class generated for a JSP.
*
* The name of the class is unpredictable.
* We are assuming that this is an HTTP JSP page (like almost all are)
*/
PUBLIC DRAFT
Buffering 2-10
Additionally, it is the responsibility of the JSP page author that the provided
superclass satisfies:
• The service() method of the Servlet API invokes the _jspService() method.
• The init(ServletConfig) method stores the configuration, makes it available as
getServletConfig, then invokes jspInit.
A JSP container may give a fatal translation error if it detects that the provided
superclass does not satisfy these requirements, but most JSP containers will not
check them.
JSP.10.3 Buffering
The JSP container buffers data (if the jsp directive specifies it using the buffer
attribute) as it is sent from the server to the client. Headers are not sent to the client
until the first flush method is invoked. Therefore, none of the operations that rely on
headers, such as the setContentType, redirect, or error methods are valid once the
flush method is executed and the headers are sent.
The javax.servlet.jsp.JspWriter class buffers and sends output. The JspWriter
class is used in the _jspService method as in the following example:
PUBLIC DRAFT
2-11 JSP CONTAINER
import javax.servlet.jsp.JspWriter;
JSP.10.4 Precompilation
A JSP page that is using the HTTP protocol will receive HTTP requests. JSP
2.0 compliant containers must support a simple precompilation protocol, as well as
some basic reserved parameter names. Note that the precompilation protocol is
related but not the same as the notion of compiling a JSP page into a Servlet class
(Appendix JSP.A).
PUBLIC DRAFT
Debugging Requirements 2-12
All JSPs pages should ignore (not depend on) any parameter that starts with
"jsp_"
1. ?jsp_precompile
2. ?jsp_precompile="true"
3. ?jsp_precompile="false"
4. ?foobar="foobaz"&jsp_precompile="true"
5. ?foobar="foobaz"&jsp_precompile="false"
1, 2, and 4 are legal; the request will not be delivered to the page. 3 and 5 are
legal; the request will not be delivered to the page.
6. ?jsp_precompile="foo"
This is illegal and will generate an HTTP error; 500 (Server error).
PUBLIC DRAFT
2-13 JSP CONTAINER
The exact mechanism for causing the JSP compiler to produce source map
debugging information is currently implementation-dependent.
PUBLIC DRAFT
C H A P T E R JSP.11
Core API
This section describes the basic contract between a JSP Page implementation
object and its container. The main contract is defined by the classes JspPage and
HttpJspPage. The JspFactory class describes the mechanism to portably instantiate
all needed runtime objects, and JspEngineInfo provides basic information on the cur-
rent JSP container.
None of the classes described here are intended to be used by JSP page
authors; an example of how these classes may be used is included elsewhere in
this chapter.
JSP.11.1.1 JspPage
Syntax
public interface JspPage extends javax.servlet.Servlet
2-14
2-15 CORE API
Description
The JspPage interface describes the generic interaction that a JSP Page Imple-
mentation class must satisfy; pages that use the HTTP protocol are described by
the HttpJspPage interface.
JSP.11.1.1.1 Methods
public void jspDestroy()
The jspDestroy() method is invoked when the JSP page is about to be
destroyed. A JSP page can override this method by including a definition for
it in a declaration element. A JSP page should redefine the destroy() method
from Servlet.
PUBLIC DRAFT
JSP Page Implementation Object Contract 2-16
JSP.11.1.2 HttpJspPage
Syntax
public interface HttpJspPage extends JspPage
Description
The HttpJspPage interface describes the interaction that a JSP Page Implementa-
tion Class must satisfy when using the HTTP protocol.
The behaviour is identical to that of the JspPage, except for the signature of the
_jspService method, which is now expressible in the Java type system and
included explicitly in the interface.
JSP.11.1.2.1 Methods
public void _jspService(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
The _jspService()method corresponds to the body of the JSP page. This
method is defined automatically by the JSP container and should never be
defined by the JSP page author.
If a superclass is specified using the extends attribute, that superclass may
choose to perform some actions in its service() method before or after calling
the _jspService() method. See using the extends attribute in the JSP_Engine
chapter of the JSP specification.
Throws:
IOException, ServletException
PUBLIC DRAFT
2-17 CORE API
JSP.11.1.3 JspFactory
Syntax
public abstract class JspFactory
Description
The JspFactory is an abstract class that defines a number of factory methods
available to a JSP page at runtime for the purposes of creating instances of vari-
ous interfaces and classes used to support the JSP implementation.
JSP.11.1.3.1 Constructors
public JspFactory()
JSP.11.1.3.2 Methods
public static synchronized JspFactory getDefaultFactory()
Returns: the default factory for this implementation
public abstract JspEngineInfo getEngineInfo()
called to get implementation-specific information on the current JSP engine
Returns: a JspEngineInfo object describing the current JSP engine
public abstract PageContext getPageContext(javax.servlet.Servlet servlet,
javax.servlet.ServletRequest request,
javax.servlet.ServletResponse response, java.lang.String errorPageURL,
boolean needsSession, int buffer, boolean autoflush)
obtains an instance of an implementation dependent javax.servlet.jsp.Page-
Context abstract class for the calling Servlet and currently pending request
and response.
This method is typically called early in the processing of the _jspService()
method of a JSP implementation class in order to obtain a PageContext object
for the request being processed.
PUBLIC DRAFT
JSP Page Implementation Object Contract 2-18
JSP.11.1.4 JspEngineInfo
Syntax
public abstract class JspEngineInfo
PUBLIC DRAFT
2-19 CORE API
Description
The JspEngineInfo is an abstract class that provides information on the current
JSP engine.
JSP.11.1.4.1 Constructors
public JspEngineInfo()
JSP.11.1.4.2 Methods
public abstract java.lang.String getSpecificationVersion()
Return the version number of the JSP specification that is supported by this
JSP engine.
Specification version numbers that consists of positive decimal integers sepa-
rated by periods “.”, for example, “2.0” or “1.2.3.4.5.6.7”. This allows an
extensible number to be used to represent major, minor, micro, etc versions.
The version number must begin with a number.
Returns: the specification version, null is returned if it is not known
The PageContext object and the JspWriter are available by default as implicit
objects.
JSP.11.2.1 JspContext
Syntax
public abstract class JspContext
Description
JspContext serves as the base class for the PageContext class and abstracts all
information that is not specific to servlets. This allows for Simple Tag Extensions
to be used outside of the context of a request/response Servlet.
PUBLIC DRAFT
Implicit Objects 2-20
JSP.11.2.1.1 Fields
public static final int APPLICATION_SCOPE
Application scope: named reference remains available in the ServletContext
until it is reclaimed.
public static final int PAGE_SCOPE
Page scope: (this is the default) the named reference remains available in this
JspContext until the return from the current Servlet.service() invocation.
public static final int REQUEST_SCOPE
Request scope: the named reference remains available from the Servlet-
Request associated with the Servlet until the current request is completed.
public static final int SESSION_SCOPE
Session scope (only valid if this page participates in a session): the named
reference remains available from the HttpSession (if any) associated with the
Servlet until the HttpSession is invalidated.
JSP.11.2.1.2 Constructors
public JspContext()
JSP.11.2.1.3 Methods
public abstract java.lang.Object findAttribute(java.lang.String name)
Searches for the named attribute in page, request, session (if valid), and appli-
cation scope(s) in order and returns the value associated or null.
Returns: the value associated or null
public abstract java.lang.Object getAttribute(java.lang.String name)
PUBLIC DRAFT
2-21 CORE API
Return the object associated with the name in the page scope or null if not
found.
Parameters:
name - the name of the attribute to get
Throws:
NullPointerException - if the name is null
IllegalArgumentException - if the scope is invalid
public abstract java.lang.Object getAttribute(java.lang.String name, int scope)
Return the object associated with the name in the specified scope or null if
not found.
Parameters:
name - the name of the attribute to set
scope - the scope with which to associate the name/object
Throws:
NullPointerException - if the name is null
IllegalArgumentException - if the scope is invalid
public abstract java.util.Enumeration getAttributeNamesInScope(int scope)
Enumerate all the attributes in a given scope
Returns: an enumeration of names (java.lang.String) of all the attributes the
specified scope
public abstract int getAttributesScope(java.lang.String name)
Get the scope where a given attribute is defined.
Returns: the scope of the object associated with the name specified or 0
public abstract ExpressionEvaluator getExpressionEvaluator()
Provides programmatic access to the ExpressionEvaluator. The JSP Con-
tainer must return a valid instance of an ExpressionEvaluator that can parse
EL expressions.
public abstract JspWriter getOut()
The current value of the out object (a JspWriter).
Returns: the current JspWriter stream being used for client response
public abstract java.util.Map peekPageScope()
Peeks at the top element of the page scope stack. This value is the current
state of the page scope. Does not modify the state of the stack or copy any
objects.
PUBLIC DRAFT
Implicit Objects 2-22
Returns: A Map representing the state of the page scope currently at the top
of the stack. This object can be passed to pushPageScope to restore this state.
The keys of the returned Map are Strings representing attribute names. The
values are the values of those attributes.
public abstract java.util.Map popPageScope()
Pops the page scope from the stack. After calling this method, the PageScope
will appear the same as it was before the last call to pushPageScope.
Returns: A Map representing the state of the page scope just before it was
popped. This object can be passed to pushPageScope to restore this state. The
keys of the returned Map are Strings representing attribute names. The values
are the values of those attributes.
Throws:
java.util.EmptyStackException - if this is the last page scope on the stack.
public abstract void pushPageScope(java.util.Map scopeState)
Pushes a page scope on the stack. The scopeState cannot be arbitrary. Only a
page scope returned from popPageScope() or peekPageScope() may be
passed in.
Parameters:
scopeState - If null, a new, empty, page scope is pushed. Otherwise, the state
of the page scope is restored to the contents of the provided Map.
public abstract void removeAttribute(java.lang.String name)
Remove the object reference associated with the given name, look in all
scopes in the scope order.
Parameters:
name - The name of the object to remove.
public abstract void removeAttribute(java.lang.String name, int scope)
Remove the object reference associated with the specified name in the given
scope.
Parameters:
name - The name of the object to remove.
scope - The scope where to look.
public abstract void setAttribute(java.lang.String name,
java.lang.Object attribute)
Register the name and object specified with page scope semantics.
Parameters:
name - the name of the attribute to set
PUBLIC DRAFT
2-23 CORE API
JSP.11.2.2 PageContext
Syntax
public abstract class PageContext extends JspContext
Description
PageContext extends JspContext to provide useful context information for when
JSP technology is used in a Servlet environment.
PUBLIC DRAFT
Implicit Objects 2-24
Some methods are intended to be used by the code generated by the container, not
by code written by JSP page authors, or JSP tag library authors.
The methods supporting lifecycle are initialize() and release()
The following methods enable the management of nested JspWriter streams to
implement Tag Extensions: pushBody() and popBody() To facilitate Simple Tag
Extensions, the pushPageScope(), popPageScope() and peekPageScope() meth-
ods are added.
Methods Intended for JSP authors
Some methods provide uniform access to the diverse objects representing
scopes. The implementation must use the underlying Servlet machinery corre-
sponding to that scope, so information can be passed back and forth between
Servlets and JSP pages. The methods are: setAttribute(), getAttribute(), find-
Attribute(), removeAttribute(), getAttributesScope() and getAttributeNamesIn-
Scope() .
The following methods provide support for forwarding, inclusion and error
handling: forward(), include(), and handlePageException().
JSP.11.2.2.1 Fields
public static final java.lang.String APPLICATION
Name used to store ServletContext in PageContext name table.
public static final int APPLICATION_SCOPE
Application scope: named reference remains available in the ServletContext
until it is reclaimed.
public static final java.lang.String CONFIG
Name used to store ServletConfig in PageContext name table.
public static final java.lang.String EXCEPTION
PUBLIC DRAFT
2-25 CORE API
JSP.11.2.2.2 Constructors
public PageContext()
JSP.11.2.2.3 Methods
public abstract void forward(java.lang.String relativeUrlPath)
This method is used to re-direct, or “forward” the current ServletRequest and
ServletResponse to another active component in the application.
If the relativeUrlPath begins with a “/” then the URL specified is calculated
relative to the DOCROOT of the ServletContext for this JSP. If the path does
PUBLIC DRAFT
Implicit Objects 2-26
not begin with a “/” then the URL specified is calculated relative to the URL
of the request that was mapped to the calling JSP.
It is only valid to call this method from a Thread executing within a _jsp-
Service(...) method of a JSP.
Once this method has been called successfully, it is illegal for the calling
Thread to attempt to modify the ServletResponse object. Any such attempt
to do so, shall result in undefined behavior. Typically, callers immediately
return from _jspService(...) after calling this method.
Parameters:
relativeUrlPath - specifies the relative URL path to the target resource as
described above
Throws:
ServletException, IOException
IllegalArgumentException - if target resource URL is unresolvable
IllegalStateException - if ServletResponse is not in a state where a forward
can be performed
SecurityException - if target resource cannot be accessed by caller
public abstract java.lang.Exception getException()
The current value of the exception object (an Exception).
Returns: any exception passed to this as an errorpage
public abstract java.lang.Object getPage()
The current value of the page object (a Servlet).
Returns: the Page implementation class instance (Servlet) associated with
this PageContext
public abstract javax.servlet.ServletRequest getRequest()
The current value of the request object (a ServletRequest).
Returns: The ServletRequest for this PageContext
public abstract javax.servlet.ServletResponse getResponse()
The current value of the response object (a ServletResponse).
Returns: the ServletResponse for this PageContext
public abstract javax.servlet.ServletConfig getServletConfig()
The ServletConfig instance.
Returns: the ServletConfig for this PageContext
public abstract javax.servlet.ServletContext getServletContext()
PUBLIC DRAFT
2-27 CORE API
PUBLIC DRAFT
Implicit Objects 2-28
Throws:
ServletException, IOException
NullPointerException - if the exception is null
SecurityException - if target resource cannot be accessed by caller
See Also: public abstract void handlePageException(java.lang.Exception
e)
public abstract void include(java.lang.String relativeUrlPath)
Causes the resource specified to be processed as part of the current Servlet-
Request and ServletResponse being processed by the calling Thread. The
output of the target resources processing of the request is written directly to
the ServletResponse output stream.
The current JspWriter “out” for this JSP is flushed as a side-effect of this call,
prior to processing the include.
If the relativeUrlPath begins with a “/” then the URL specified is calculated
relative to the DOCROOT of the ServletContext for this JSP. If the path does
not begin with a “/” then the URL specified is calculated relative to the URL
of the request that was mapped to the calling JSP.
It is only valid to call this method from a Thread executing within a _jsp-
Service(...) method of a JSP.
Parameters:
relativeUrlPath - specifies the relative URL path to the target resource to be
included
Throws:
ServletException, IOException
IllegalArgumentException - if the target resource URL is unresolvable
SecurityException - if target resource cannot be accessed by caller
public abstract void initialize(javax.servlet.Servlet servlet,
javax.servlet.ServletRequest request,
javax.servlet.ServletResponse response, java.lang.String errorPageURL,
boolean needsSession, int bufferSize, boolean autoFlush)
The initialize method is called to initialize an uninitialized PageContext so
that it may be used by a JSP Implementation class to service an incoming
request and response within it’s _jspService() method.
This method is typically called from JspFactory.getPageContext() in order to
initialize state.
This method is required to create an initial JspWriter, and associate the “out”
name in page scope with this newly created object.
PUBLIC DRAFT
2-29 CORE API
PUBLIC DRAFT
Implicit Objects 2-30
JSP.11.2.3 JspWriter
Syntax
public abstract class JspWriter extends java.io.Writer
Description
The actions and template data in a JSP page is written using the JspWriter object
that is referenced by the implicit variable out which is initialized automatically
using methods in the PageContext object.
Both approaches are valid, and thus both are supported in the JSP technology. The
behavior of a page is controlled by the autoFlush attribute, which defaults to true.
In general, JSP pages that need to be sure that correct and complete data has been
sent to their client may want to set autoFlush to false, with a typical case being
that where the client is an application itself. On the other hand, JSP pages that
send data that is meaningful even when partially constructed may want to set
autoFlush to true; such as when the data is sent for immediate display through a
browser. Each application will need to consider their specific needs.
PUBLIC DRAFT
2-31 CORE API
An alternative considered was to make the buffer size unbounded; but, this had
the disadvantage that runaway computations would consume an unbounded
amount of resources.
The “out” implicit variable of a JSP implementation class is of this type. If the
page directive selects autoflush=“true” then all the I/O operations on this class
shall automatically flush the contents of the buffer if an overflow condition would
result if the current operation were performed without a flush. If autof-
lush=“false” then all the I/O operations on this class shall throw an IOException
if performing the current operation would result in a buffer overflow condition.
JSP.11.2.3.1 Fields
protected boolean autoFlush
protected int bufferSize
public static final int DEFAULT_BUFFER
constant indicating that the Writer is buffered and is using the implementa-
tion default buffer size
public static final int NO_BUFFER
constant indicating that the Writer is not buffering output
public static final int UNBOUNDED_BUFFER
constant indicating that the Writer is buffered and is unbounded; this is used
in BodyContent
JSP.11.2.3.2 Constructors
protected JspWriter(int bufferSize, boolean autoFlush)
protected constructor.
JSP.11.2.3.3 Methods
public abstract void clear()
Clear the contents of the buffer. If the buffer has been already been flushed
then the clear operation shall throw an IOException to signal the fact that
some data has already been irrevocably written to the client response stream.
Throws:
IOException - If an I/O error occurs
public abstract void clearBuffer()
PUBLIC DRAFT
Implicit Objects 2-32
Clears the current contents of the buffer. Unlike clear(), this method will not
throw an IOException if the buffer has already been flushed. It merely clears
the current content of the buffer and returns.
Throws:
IOException - If an I/O error occurs
public abstract void close()
Close the stream, flushing it first
This method needs not be invoked explicitly for the initial JspWriter as the
code generated by the JSP container will automatically include a call to
close().
Closing a previously-closed stream, unlike flush(), has no effect.
Overrides: java.io.Writer.close() in class java.io.Writer
Throws:
IOException - If an I/O error occurs
public abstract void flush()
Flush the stream. If the stream has saved any characters from the various
write() methods in a buffer, write them immediately to their intended destina-
tion. Then, if that destination is another character or byte stream, flush it.
Thus one flush() invocation will flush all the buffers in a chain of Writers and
OutputStreams.
The method may be invoked indirectly if the buffer size is exceeded.
Once a stream has been closed, further write() or flush() invocations will
cause an IOException to be thrown.
Overrides: java.io.Writer.flush() in class java.io.Writer
Throws:
IOException - If an I/O error occurs
public int getBufferSize()
This method returns the size of the buffer used by the JspWriter.
Returns: the size of the buffer in bytes, or 0 is unbuffered.
public abstract int getRemaining()
This method returns the number of unused bytes in the buffer.
Returns: the number of bytes unused in the buffer
public boolean isAutoFlush()
This method indicates whether the JspWriter is autoFlushing.
PUBLIC DRAFT
2-33 CORE API
PUBLIC DRAFT
Implicit Objects 2-34
form’s default character encoding, and these bytes are written in exactly the
manner of the java.io.Writer.write(int) method.
Parameters:
d - The double to be printed
Throws:
java.io.IOException
See Also: java.lang.Double
public abstract void print(float f)
Print a floating-point number. The string produced by
java.lang.String.valueOf(float) is translated into bytes according to the plat-
form’s default character encoding, and these bytes are written in exactly the
manner of the java.io.Writer.write(int) method.
Parameters:
f - The float to be printed
Throws:
java.io.IOException
See Also: java.lang.Float
public abstract void print(int i)
Print an integer. The string produced by java.lang.String.valueOf(int) is trans-
lated into bytes according to the platform’s default character encoding, and
these bytes are written in exactly the manner of the java.io.Writer.write(int)
method.
Parameters:
i - The int to be printed
Throws:
java.io.IOException
See Also: java.lang.Integer
public abstract void print(long l)
Print a long integer. The string produced by java.lang.String.valueOf(long) is
translated into bytes according to the platform’s default character encoding,
and these bytes are written in exactly the manner of the
java.io.Writer.write(int) method.
Parameters:
l - The long to be printed
Throws:
java.io.IOException
See Also: java.lang.Long
PUBLIC DRAFT
2-35 CORE API
PUBLIC DRAFT
Implicit Objects 2-36
PUBLIC DRAFT
2-37 CORE API
Print a String and then terminate the line. This method behaves as though it
invokes public abstract void print(java.lang.String s) and then public abstract
void println() .
Throws:
java.io.IOException
PUBLIC DRAFT
Exceptions 2-38
JSP.11.4 Exceptions
The JspException class is the base class for all JSP exceptions. The JspTag-
Exception is used by the tag extension mechanism.
JSP.11.4.1 JspException
Syntax
public class JspException extends java.lang.Exception
PUBLIC DRAFT
2-39 CORE API
Description
A generic exception known to the JSP engine; uncaught JspExceptions will result
in an invocation of the errorpage machinery.
JSP.11.4.1.1 Constructors
public JspException()
Construct a JspException
public JspException(java.lang.String msg)
Constructs a new JSP exception with the specified message. The message can
be written to the server log and/or displayed for the user.
Parameters:
msg - a String specifying the text of the exception message
public JspException(java.lang.String message, java.lang.Throwable rootCause)
Constructs a new JSP exception when the JSP needs to throw an exception
and include a message about the “root cause” exception that interfered with
its normal operation, including a description message.
Parameters:
message - a String containing the text of the exception message
rootCause - the Throwable exception that interfered with the servlet’s normal
operation, making this servlet exception necessary
public JspException(java.lang.Throwable rootCause)
Constructs a new JSP exception when the JSP needs to throw an exception
and include a message about the “root cause” exception that interfered with
its normal operation. The exception’s message is based on the localized mes-
sage of the underlying exception.
This method calls the getLocalizedMessage method on the Throwable excep-
tion to get a localized exception message. When subclassing JspException,
this method can be overridden to create an exception message designed for a
specific locale.
Parameters:
rootCause - the Throwable exception that interfered with the JSP’s normal
operation, making the JSP exception necessary
JSP.11.4.1.2 Methods
public java.lang.Throwable getRootCause()
Returns the exception that caused this JSP exception.
PUBLIC DRAFT
Exceptions 2-40
JSP.11.4.2 JspTagException
Syntax
public class JspTagException extends JspException
Description
Exception to be used by a Tag Handler to indicate some unrecoverable error. This
error is to be caught by the top level of the JSP page and will result in an error
page.
JSP.11.4.2.1 Constructors
public JspTagException()
No message
public JspTagException(java.lang.String msg)
Constructor with a message.
PUBLIC DRAFT
C H A P T E R JSP.12
Tag Extension API
This chapter describes the details of tag handlers and other tag extension
classes as well as methods that are available to access the Tag Library Descriptor
files. This complements a previous chapter that described the Tag Library Descrip-
tor files formats and their use in taglib directives.
This chapter includes content that is generated automatically from javadoc
embedded into the actual Java classes and interfaces. This allows the creation of a
single, authoritative, specification document.
Custom actions can be used by JSP authors and authoring tools to simplify
writing JSP pages. A custom action can be either an empty or a non-empty action.
An empty tag has no body. There are two equivalent syntaxes, one with
separate start and an end tag, and one where the start and end tags are combined.
The two following examples are identical:
<x:foo att=“myObject” />
<x:foo att=“myObject” ></foo>
A non-empty tag has a start tag, a body, and an end tag. A prototypical example
is of the form:
<x:foo att=“myObject” >
BODY
</x:foo/>
The JavaServer Pages(tm) (JSP) 1.2 specification provides a portable mecha-
nism for the description of tag libraries containing:
•A Tag Library Descriptor (TLD)
•A number of Tag handler classes defining request-time behavior
•A number of classes defining translation-time behavior
•Additional resources used by the classes
This chapter is organized in three sections. The first section presents the basic
tag handler classes. The second section describes the more complex tag handlers
that need to access their body evaluation. The last section looks at translation-time
issues.
2-41
Classic Tag Handlers 2-42
This section introduces the notion of a tag handler and describes the classic
types of tag handler.
JSP 2.0 introduces a new type of Tag Handler called a Simple Tag Handler,
which is described in a later section in this chapter. The protocol for Simple Tag
handlers is much more straightforward.
Tag Handler
A tag handler is a run-time, container-managed, object that evaluates custom
actions during the execution of a JSP page. A tag handler supports a protocol that
allows the JSP container to provide good integration of the server-side actions
within a JSP page.
A tag handler is created initially using a zero argument constructor on its
corresponding class; the method java.beans.Beans.instantiate() is not used.
A tag handler has some properties that are exposed to the page as attributes on
an action; these properties are managed by the JSP container (via generated code).
The setter methods used to set the properties are discovered using the JavaBeans
introspector machinery.
The protocol supported by a tag handler provides for passing of parameters,
the evaluation and reevaluation of the body of the action, and for getting access to
objects and other tag handlers in the JSP page.
A tag handler instance is responsible for processing one request at a time. It is
the responsability of the JSP container to enforce this.
Additional translation time information associated with the action indicates
the name of any scripting variables it may introduce, their types and their scope.
At specific moments, the JSP container will automatically synchronize the Page-
Context information with variables in the scripting language so they can be made
available directly through the scripting elements.
Properties
A tag handler has some properties. All tag handlers have a pageContext prop-
erty for the JSP page where the tag is located, and a parent property for the tag han-
dler to the closest enclosing action. Specific tag handler classes may have additional
properties.
All attributes of a custom action must be JavaBeans component properties,
although some properties may not be exposed as attributes. The attributes that are
visible to the JSP translator are exactly those listed in the Tag Library Descriptor
(TLD).
PUBLIC DRAFT
2-43 TAG EXTENSION API
Conversions
A tag handler implements an action; the JSP container must follow the type
conversions described in Section 2.13.2 when assigning values to the attributes of an
action.
PUBLIC DRAFT
Classic Tag Handlers 2-44
PUBLIC DRAFT
2-45 TAG EXTENSION API
JSP.12.1.1 Tag
Syntax
public interface Tag
Description
The interface of a simple tag handler that does not want to manipulate its body.
The Tag interface defines the basic protocol between a Tag handler and JSP page
implementation class. It defines the life cycle and the methods to be invoked at
start and end tag.
Properties
The Tag interface specifies the setter and getter methods for the core pageContext
and parent properties.
The JSP page implementation object invokes setPageContext and setParent, in
that order, before invoking doStartTag() or doEndTag().
Methods
There are two main actions: doStartTag and doEndTag. Once all appropriate
properties have been initialized, the doStartTag and doEndTag methods can be
invoked on the tag handler. Between these invocations, the tag handler is assumed
to hold a state that must be preserved. After the doEndTag invocation, the tag han-
dler is available for further invocations (and it is expected to have retained its
properties).
Lifecycle
Lifecycle details are described by the transition diagram below, with the follow-
ing comments:
•[1] This transition is intended to be for releasing long-term data. no guaran-
tees are assumed on whether any properties have been retained or not.
•[2] This transition happens if and only if the tag ends normally without rais-
ing an exception
•[3] Note that since there are no guarantees on the state of the properties, a
tag handler that had some optional properties set can only be reused if those
properties are set to a new (known) value. This means that tag handlers can
only be reused within the same “AttSet” (set of attributes that have been set).
PUBLIC DRAFT
Classic Tag Handlers 2-46
Once all invocations on the tag handler are completed, the release method is
invoked on it. Once a release method is invoked all properties, including parent
and pageContext, are assumed to have been reset to an unspecified value. The
page compiler guarantees that release() will be invoked on the Tag handler before
the handler is released to the GC.
Empty and Non-Empty Action
If the TagLibraryDescriptor file indicates that the action must always have an
empty action, by an <body-content> entry of “empty”, then the doStartTag()
PUBLIC DRAFT
2-47 TAG EXTENSION API
JSP.12.1.1.1 Fields
public static final int EVAL_BODY_INCLUDE
Evaluate body into existing out stream. Valid return value for doStartTag.
public static final int EVAL_PAGE
Continue evaluating the page. Valid return value for doEndTag().
public static final int SKIP_BODY
Skip body evaluation. Valid return value for doStartTag and doAfterBody.
public static final int SKIP_PAGE
Skip the rest of the page. Valid return value for doEndTag.
JSP.12.1.1.2 Methods
public int doEndTag()
Process the end tag for this instance. This method is invoked by the JSP page
implementation object on all Tag handlers.
This method will be called after returning from doStartTag. The body of the
action may or not have been evaluated, depending on the return value of
doStartTag.
If this method returns EVAL_PAGE, the rest of the page continues to be eval-
uated. If this method returns SKIP_PAGE, the rest of the page is not evalu-
ated, the request is completed, and the doEndTag() methods of enclosing tags
are not invoked. If this request was forwarded or included from another page
(or Servlet), only the current page evaluation is stopped.
The JSP container will resynchronize any variable values that are indicated as
so in TagExtraInfo after the invocation of doEndTag().
Throws:
JspException., JspException
public int doStartTag()
Process the start tag for this instance. This method is invoked by the JSP page
implementation object.
PUBLIC DRAFT
Classic Tag Handlers 2-48
The doStartTag method assumes that the properties pageContext and parent
have been set. It also assumes that any properties exposed as attributes have
been set too. When this method is invoked, the body has not yet been evalu-
ated.
This method returns Tag.EVAL_BODY_INCLUDE or Body-
Tag.EVAL_BODY_BUFFERED to indicate that the body of the action
should be evaluated or SKIP_BODY to indicate otherwise.
When a Tag returns EVAL_BODY_INCLUDE the result of evaluating the
body (if any) is included into the current “out” JspWriter as it happens and
then doEndTag() is invoked.
BodyTag.EVAL_BODY_BUFFERED is only valid if the tag handler imple-
ments BodyTag.
The JSP container will resynchronize any variable values that are indicated as
so in TagExtraInfo after the invocation of doStartTag().
Throws:
JspException., JspException
See Also: BodyTag
public Tag getParent()
Get the parent (closest enclosing tag handler) for this tag handler.
The getParent() method can be used to navigate the nested tag handler struc-
ture at runtime for cooperation among custom actions; for example, the find-
AncestorWithClass() method in TagSupport provides a convenient way of
doing this.
The current version of the specification only provides one formal way of indi-
cating the observable type of a tag handler: its tag handler implementation
class, described in the tag-class subelement of the tag element. This is
extended in an informal manner by allowing the tag library author to indicate
in the description subelement an observable type. The type should be a sub-
type of the tag handler implementation class or void. This addititional con-
straint can be exploited by a specialized container that knows about that
specific tag library, as in the case of the JSP standard tag library.
public void release()
Called on a Tag handler to release state. The page compiler guarantees that
JSP page implementation objects will invoke this method on all tag handlers,
but there may be multiple invocations on doStartTag and doEndTag in
between.
public void setPageContext(PageContext pc)
PUBLIC DRAFT
2-49 TAG EXTENSION API
Set the current page context. This method is invoked by the JSP page imple-
mentation object prior to doStartTag().
This value is *not* reset by doEndTag() and must be explicitly reset by a
page implementation if it changes between calls to doStartTag().
Parameters:
pc - The page context for this tag handler.
public void setParent(Tag t)
Set the parent (closest enclosing tag handler) of this tag handler. Invoked by
the JSP page implementation object prior to doStartTag().
This value is *not* reset by doEndTag() and must be explicitly reset by a
page implementation.
Parameters:
t - The parent tag, or null.
JSP.12.1.2 IterationTag
Syntax
public interface IterationTag extends Tag
Description
The IterationTag interface extends Tag by defining one additional method that
controls the reevaluation of its body.
A tag handler that implements IterationTag is treated as one that implements Tag
regarding the doStartTag() and doEndTag() methods. IterationTag provides a new
method: doAfterBody().
The doAfterBody() method is invoked after every body evaluation to control
whether the body will be reevaluated or not. If doAfterBody() returns Iteration-
Tag.EVAL_BODY_AGAIN, then the body will be reevaluated. If doAfterBody()
returns Tag.SKIP_BODY, then the body will be skipped and doEndTag() will be
evaluated instead.
PUBLIC DRAFT
Classic Tag Handlers 2-50
PUBLIC DRAFT
2-51 TAG EXTENSION API
JSP.12.1.2.1 Fields
public static final int EVAL_BODY_AGAIN
Request the reevaluation of some body. Returned from doAfterBody. For
compatibility with JSP 1.1, the value is carefully selected to be the same as
the, now deprecated, BodyTag.EVAL_BODY_TAG,
JSP.12.1.2.2 Methods
public int doAfterBody()
Process body (re)evaluation. This method is invoked by the JSP Page imple-
mentation object after every evaluation of the body into the BodyEvaluation
object. The method is not invoked if there is no body evaluation.
If doAfterBody returns EVAL_BODY_AGAIN, a new evaluation of the body
will happen (followed by another invocation of doAfterBody). If doAfter-
Body returns SKIP_BODY no more body evaluations will occur, the value of
out will be restored using the popBody method in pageContext, and then
doEndTag will be invoked.
The method re-invocations may be lead to different actions because there
might have been some changes to shared state, or because of external compu-
tation.
The JSP container will resynchronize any variable values that are indicated as
so in TagExtraInfo after the invocation of doAfterBody().
Returns: whether additional evaluations of the body are desired
Throws:
JspException
JSP.12.1.3 TryCatchFinally
Syntax
public interface TryCatchFinally
Description
The auxiliary interface of a Tag, IterationTag or BodyTag tag handler that wants
additional hooks for managing resources.
PUBLIC DRAFT
Classic Tag Handlers 2-52
JSP.12.1.3.1 Methods
public void doCatch(java.lang.Throwable t)
Invoked if a Throwable occurs while evaluating the BODY inside a tag or in
any of the following methods: Tag.doStartTag(), Tag.doEndTag(), Iteration-
Tag.doAfterBody() and BodyTag.doInitBody().
This method is not invoked if the Throwable occurs during one of the setter
methods.
This method may throw an exception (the same or a new one) that will be
propagated further the nest chain. If an exception is thrown, doFinally() will
be invoked.
This method is intended to be used to respond to an exceptional condition.
Parameters:
t - The throwable exception navigating through this tag.
Throws:
Throwable
public void doFinally()
Invoked in all cases after doEndTag() for any class implementing Tag,
IterationTag or BodyTag. This method is invoked even if an exception has
PUBLIC DRAFT
2-53 TAG EXTENSION API
JSP.12.1.4 TagSupport
Syntax
public class TagSupport implements IterationTag, java.io.Serializable
Description
A base class for defining new tag handlers implementing Tag.
The TagSupport class is a utility class intended to be used as the base class for
new tag handlers. The TagSupport class implements the Tag and IterationTag
interfaces and adds additional convenience methods including getter methods for
the properties in Tag. TagSupport has one static method that is included to facili-
tate coordination among cooperating tags.
Many tag handlers will extend TagSupport and only redefine a few methods.
JSP.12.1.4.1 Fields
protected java.lang.String id
protected PageContext pageContext
JSP.12.1.4.2 Constructors
public TagSupport()
Default constructor, all subclasses are required to define only a public con-
structor with the same signature, and to call the superclass constructor. This
constructor is called by the code generated by the JSP translator.
PUBLIC DRAFT
Classic Tag Handlers 2-54
JSP.12.1.4.3 Methods
public int doAfterBody()
Default processing for a body
Returns: SKIP_BODY
Throws:
JspException
See Also: public int doAfterBody()
public int doEndTag()
Default processing of the end tag returning EVAL_PAGE.
Throws:
JspException
See Also: public int doEndTag()
public int doStartTag()
Default processing of the start tag, returning SKIP_BODY.
Throws:
JspException
See Also: public int doStartTag()
public static final Tag findAncestorWithClass(Tag from, java.lang.Class klass)
Find the instance of a given class type that is closest to a given instance. This
method uses the getParent method from the Tag interface. This method is
used for coordination among cooperating tags.
The current version of the specification only provides one formal way of indi-
cating the observable type of a tag handler: its tag handler implementation
class, described in the tag-class subelement of the tag element. This is
extended in an informal manner by allowing the tag library author to indicate
in the description subelement an observable type. The type should be a sub-
type of the tag handler implementation class or void. This addititional con-
straint can be exploited by a specialized container that knows about that
specific tag library, as in the case of the JSP standard tag library.
When a tag library author provides information on the observable type of a
tag handler, client programmatic code should adhere to that constraint. Spe-
cifically, the Class passed to findAncestorWithClass should be a subtype of
the observable type.
Parameters:
from - The instance from where to start looking.
PUBLIC DRAFT
2-55 TAG EXTENSION API
PUBLIC DRAFT
Tag Handlers that want Access to their Body Content 2-56
PUBLIC DRAFT
2-57 TAG EXTENSION API
JSP.12.2.1 BodyContent
Syntax
public abstract class BodyContent extends JspWriter
Description
An encapsulation of the evaluation of the body of an action so it is available to a
tag handler. BodyContent is a subclass of JspWriter.
Note that the content of BodyContent is the result of evaluation, so it will not con-
tain actions and the like, but the result of their invocation.
BodyContent has methods to convert its contents into a String, to read its con-
tents, and to clear the contents.
The buffer size of a BodyContent object is unbounded. A BodyContent object
cannot be in autoFlush mode. It is not possible to invoke flush on a BodyContent
object, as there is no backing stream.
Instances of BodyContent are created by invoking the pushBody and popBody
methods of the PageContext class. A BodyContent is enclosed within another
JspWriter (maybe another BodyContent object) following the structure of their
associated actions.
A BodyContent is made available to a BodyTag through a setBodyContent() call.
The tag handler can use the object until after the call to doEndTag().
JSP.12.2.1.1 Constructors
protected BodyContent(JspWriter e)
Protected constructor. Unbounded buffer, no autoflushing.
JSP.12.2.1.2 Methods
public void clearBody()
Clear the body without throwing any exceptions.
public void flush()
Redefined flush() so it is not legal.
It is not valid to flush a BodyContent because there is no backing stream
behind it.
Overrides: public abstract void flush() in class JspWriter
Throws:
PUBLIC DRAFT
Tag Handlers that want Access to their Body Content 2-58
IOException
public JspWriter getEnclosingWriter()
Get the enclosing JspWriter.
Returns: the enclosing JspWriter passed at construction time
public abstract java.io.Reader getReader()
Return the value of this BodyContent as a Reader.
Returns: the value of this BodyContent as a Reader
public abstract java.lang.String getString()
Return the value of the BodyContent as a String.
Returns: the value of the BodyContent as a String
public abstract void writeOut(java.io.Writer out)
Write the contents of this BodyContent into a Writer. Subclasses may opti-
mize common invocation patterns.
Parameters:
out - The writer into which to place the contents of this body evaluation
Throws:
IOException
JSP.12.2.2 BodyTag
Syntax
public interface BodyTag extends IterationTag
Description
The BodyTag interface extends IterationTag by defining additional methods that
let a tag handler manipulate the content of evaluating its body.
It is the responsibility of the tag handler to manipulate the body content. For
example the tag handler may take the body content, convert it into a String using
the bodyContent.getString method and then use it. Or the tag handler may take
the body content and write it out into its enclosing JspWriter using the body-
Content.writeOut method.
PUBLIC DRAFT
2-59 TAG EXTENSION API
PUBLIC DRAFT
Tag Handlers that want Access to their Body Content 2-60
PUBLIC DRAFT
2-61 TAG EXTENSION API
JSP.12.2.2.1 Fields
public static final int EVAL_BODY_BUFFERED
Request the creation of new buffer, a BodyContent on which to evaluate the
body of this tag. Returned from doStartTag when it implements BodyTag.
This is an illegal return value for doStartTag when the class does not imple-
ment BodyTag.
public static final int EVAL_BODY_TAG
Deprecated. As of Java JSP API 1.2, use
BodyTag.EVAL_BODY_BUFFERED or
IterationTag.EVAL_BODY_AGAIN.
Deprecated constant that has the same value as EVAL_BODY_BUFFERED
and EVAL_BODY_AGAIN. This name has been marked as deprecated to
encourage the use of the two different terms, which are much more descrip-
tive.
JSP.12.2.2.2 Methods
public void doInitBody()
Prepare for evaluation of the body. This method is invoked by the JSP page
implementation object after setBodyContent and before the first time the
body is to be evaluated. This method will not be invoked for empty tags or for
non-empty tags whose doStartTag() method returns SKIP_BODY or
EVAL_BODY_INCLUDE.
The JSP container will resynchronize any variable values that are indicated as
so in TagExtraInfo after the invocation of doInitBody().
Throws:
JspException
public void setBodyContent(BodyContent b)
Set the bodyContent property. This method is invoked by the JSP page imple-
mentation object at most once per action invocation. This method will be
invoked before doInitBody. This method will not be invoked for empty tags
or for non-empty tags whose doStartTag() method returns SKIP_BODY or
EVAL_BODY_INCLUDE.
When setBodyContent is invoked, the value of the implicit object out has
already been changed in the pageContext object. The BodyContent object
PUBLIC DRAFT
Tag Handlers that want Access to their Body Content 2-62
passed will have not data on it but may have been reused (and cleared) from
some previous invocation.
The BodyContent object is available and with the appropriate content until
after the invocation of the doEndTag method, at which case it may be reused.
Parameters:
b - the BodyContent
JSP.12.2.3 BodyTagSupport
Syntax
public class BodyTagSupport extends TagSupport implements BodyTag
Description
A base class for defining tag handlers implementing BodyTag.
The BodyTagSupport class implements the BodyTag interface and adds addi-
tional convenience methods including getter methods for the bodyContent prop-
erty and methods to get at the previous out JspWriter.
Many tag handlers will extend BodyTagSupport and only redefine a few methods.
JSP.12.2.3.1 Fields
protected BodyContent bodyContent
JSP.12.2.3.2 Constructors
public BodyTagSupport()
Default constructor, all subclasses are required to only define a public con-
structor with the same signature, and to call the superclass constructor. This
constructor is called by the code generated by the JSP translator.
JSP.12.2.3.3 Methods
public int doAfterBody()
After the body evaluation: do not reevaluate and continue with the page. By
default nothing is done with the bodyContent data (if any).
Overrides: public int doAfterBody() in class TagSupport
PUBLIC DRAFT
2-63 TAG EXTENSION API
Returns: SKIP_BODY
Throws:
JspException
public int doEndTag()
Default processing of the end tag returning EVAL_PAGE.
Overrides: public int doEndTag() in class TagSupport
Returns: EVAL_PAGE
Throws:
JspException
public void doInitBody()
Prepare for evaluation of the body just before the first body evaluation: no
action.
Throws:
JspException
public int doStartTag()
Default processing of the start tag returning EVAL_BODY_BUFFERED
Overrides: public int doStartTag() in class TagSupport
Returns: EVAL_BODY_BUFFERED;
Throws:
JspException
public BodyContent getBodyContent()
Get current bodyContent.
Returns: the body content.
public JspWriter getPreviousOut()
Get surrounding out JspWriter.
Returns: the enclosing JspWriter, from the bodyContent.
public void release()
Release state.
Overrides: public void release() in class TagSupport
public void setBodyContent(BodyContent b)
Prepare for evaluation of the body: stash the bodyContent away.
Parameters:
b - the BodyContent
PUBLIC DRAFT
Dynamic Attributes 2-64
Any tag handler can optionally extend the DynamicAttribute interface to indicate
that it supports dynamic attributes. See the JSP Fragments chapter for more details
on how Dynamic Attributes work.
JSP.12.3.1 DynamicAttributes
Syntax
public interface DynamicAttributes
Description
For a tag to declare that it accepts dynamic attributes, it must implement this
interface. The entry for the tag in the Tag Library Descriptor must also be config-
ured to indicate dynamic attributes are accepted.
For any attribute that is not declared in the Tag Library Descriptor for this tag,
instead of getting an error at translation time, the setDynamicAttribute() method is
called, with the name and value of the attribute. It is the responsibility of the tag
to remember the names and values of the dynamic attributes.
JSP.12.3.1.1 Methods
public void setDynamicAttribute(java.lang.String uri, java.lang.String localName,
java.lang.Object value)
Called when a tag declared to accept dynamic attributes is passed an attribute
that is not declared in the Tag Library Descriptor.
Parameters:
uri - the namespace of the attribute, nor null if in the default namespace.
localName - the name of the attribute being set.
value - the value of the attribute
Throws:
AttributeNotSupportedException - if the tag handler wishes to signal that it
does not accept the given attribute.
JSP.12.3.2 AttributeNotSupportedException
Syntax
public class AttributeNotSupportedException extends java.lang.Exception
PUBLIC DRAFT
2-65 TAG EXTENSION API
Description
Thrown by a tag handler that wants to indicate that the provided dynamic attribute
is not supported by this tag.
JSP.12.3.2.1 Constructors
public AttributeNotSupportedException()
Creates an AttributeNotSupportedException with no message.
public AttributeNotSupportedException(java.lang.String message)
Creates an AttributeNotSupportedException with the provided message.
Below is a somewhat complete example of the way one JSP container could
choose to do some tag handler management. There are many other strategies that
could be followed, with different pay offs.
The example is as below. In this example, we are assuming that x:iterate is an
iterative tag, while x:doit and x:foobar are simple tag. We will also assume that
x:iterate and x:foobar implement the TryCatchFinally interface, while x:doit does
not.
<x:iterate src=“foo”>
<x:doit att1=“one” att2=“<%= 1 + 1 %>” />
<x:foobar />
<x:doit att1=“one” att2=“<%= 2 + 2 %>” />
</x:iterate>
<x:doit att1=“one” att2=“<%= 3 + 3 %>” />
The particular code shown below assumes there is some pool of tag handlers
that are managed (details not described, although pool managing is simpler when
there are no optional attributes), and attemps to reuse tag handlers if possible. The
code also “hoists” setting of properties to reduce the cost when appropriate, e.g.
inside an iteration.
PUBLIC DRAFT
Annotated Tag Handler Management Example 2-66
PUBLIC DRAFT
2-67 TAG EXTENSION API
// third invocation
// this tag handler could be reused from the previous ones.
d = get tag from pool or new();
d.setPageContext(pc);
d.setParent(null);
d.setAtt1(“one”);
d.setAtt2(3+3);
if ((b1 = d.doStartTag()) == EVAL_BODY_INCLUDE) {
// nothing
} else if (b1 != SKIP_BODY) {
// Q? protocol error
}
if ((b1 = d.doEndTag()) == SKIP_PAGE) {
break page; // be done with it.
} else if (b1 != EVAL_PAGE) {
// Q? protocol error
}
} catch (Throwable t) {
PUBLIC DRAFT
Cooperating Actions 2-68
Actions can cooperate with other actions and with scripting code in a number of
ways.
PageContext
Often two actions in a JSP page will want to cooperate, perhaps by one action
creating some server-side object that needs to be access by another. One mechanism
for doing this is by giving the object a name within the JSP page; the first action will
create the object and associate the name to it while the second action will use the
name to retrieve the object.
For example, in the following JSP fragment the foo action might create a
server-side object and give it the name “myObject”. Then the bar action might
access that server-side object and take some action.
<x:foo id=“myObject” />
<x:bar ref=“myObjet” />
In a JSP implementation, the mapping “name”->value is kept by the implicit
object pageContext. This object is passed around through the Tag handler instances
so it can be used to communicate information: all it is needed is to know the name
under which the information is stored into the pageContext.
PUBLIC DRAFT
2-69 TAG EXTENSION API
This section presents the API to implement Simple Tag Handlers and JSP Frag-
ments. Simple Tag Handlers present a much simpler invocation protocol than do
Classic Tag Handlers.
Instead of invoking doStartTag() and doEndTag() and interpreting return values
to have the controller decide when and how many times to invoke the body of a
tag, Simple Tag Handlers encapsulate the tag body as a JSP Fragment, and pass it
in to a single doTag() method. This presents a much simpler invocation protocol
making it easier to design powerful tags.
See the JSP Fragments section for more details.
JSP.12.6.1 SimpleTag
Syntax
public interface SimpleTag
Description
Interface for defining “simple tag handlers.”
To support body content, the setJspBody() and getJspBody() methods are pro-
vided. The container invokes the setJspBody() method with a JspFragment object
encapsulating the body of the tag. The tag handler implementation can call get-
JspBody().invoke() to evaluate the body as many times as it needs.
JSP.12.6.1.1 Methods
public int doTag()
Used for an action declared to have an empty body. The single doTag()
method replaces the doStartTag() and doEndTag() methods inherited from the
Tag interface.
Returns: SKIP_PAGE to abort the processing, or EVAL_PAGE * to
continue.
Throws:
PUBLIC DRAFT
Simple Tag Handlers 2-70
JspException
public java.lang.Object getParent()
Returns the parent of this tag, for collaboration purposes.
public void setJspBody(JspFragment jspBody)
Provides the body of this tag as a JspFragment object, able to be invoked zero
or more times by the tag handler.
This method is invoked by the JSP page implementation object prior to
doTag().
Parameters:
body - The fragment encapsulating the body of this tag.
public void setJspContext(JspContext pc)
Stores the provided page context in the protected jspContext field.
See Also: Tag#setJspContext
public void setParent(java.lang.Object parent)
Sets the parent of this tag, for collaboration purposes.
JSP.12.6.2 JspFragment
Syntax
public interface JspFragment
Description
Encapsulates a portion of JSP code in an object that can be invoked as many times
as needed. JSP Fragments are defined using JSP syntax as the body of a tag or the
body of a <jsp:attribute> standard action, during a tag invocation.
The definition of the JSP fragment must only contain template text and JSP action
elements. It must not contain, for example, scriptlets or scriptlet expressions. At
translation time, the container generates an implementation of the JspFragment
interface capable of executing the defined fragment.
A tag handler can invoke the fragment zero or more times, or pass it along to
other tags, before returning. JSP fragments accept parameters from the invoker,
which are exposed as Expression Language variables to the JSP code that com-
poses the fragment. This allows the tag handler to parameterize the body each
time it is invoked.
Note that tag library developers and page authors should not generate Jsp-
Fragment implementations manually.
PUBLIC DRAFT
2-71 TAG EXTENSION API
JSP.12.6.2.1 Methods
public void invoke(java.io.Writer out, java.util.Map params)
Executes the fragment and directs all output to the given Writer, or the Jsp-
Writer returned by the getOut() method of the JspContext associated with the
fragment if out is null. The method accepts a parameter map, containing the
body-input parameters passed to the body by its invoker (e.g. a tag handler).
Parameters:
out - The Writer to output the fragment to, or null if output should be sent to
JspContext.getOut().
params - specifies the set of parameters to pass to the fragment. Keys in this
map are parameter names, and the values are parameter values. This allows
the invoker to parameterize a fragment invocation.
Throws:
JspException
JSP.12.6.3 TagAdapter
Syntax
public class TagAdapter implements Tag
Description
Wraps any Object and exposes it using a Tag interface. This is used to allow col-
laboration between classic Tag handlers and SimpleTag handlers.
Because SimpleTag does not extend Tag, and because Tag.setParent() only
accepts a Tag instance, a classic tag handler (one that implements Tag) cannot
have a SimpleTag as its parent. To remedy this, a TagAdapter is created to wrap
the SimpleTag parent, and the adapter is passed to setParent() instead. A classic
Tag Handler can call getAdaptee() to retrieve the encapsulated SimpleTag
instance.
PUBLIC DRAFT
Simple Tag Handlers 2-72
JSP.12.6.3.1 Constructors
public TagAdapter(java.lang.Object adaptee, Tag parentTag)
Creates a new TagAdapter that wraps the given tag and returns the given par-
ent tag when getParent() is called.
JSP.12.6.3.2 Methods
public int doEndTag()
Must not be called.
Throws:
UnsupportedOperationException, JspException
public int doStartTag()
Must not be called.
Throws:
UnsupportedOperationException, JspException
public java.lang.Object getAdaptee()
Gets the tag that is being adapted to the Tag interface. This should be an
instance of SimpleTag in JSP 2.0, but room is left for other kinds of tags in
future spec versions.
public Tag getParent()
Returns the value passed to setParent(). This will either be the enclosing Tag
(if parent implements Tag), or an adapter to the enclosing Tag (if parent does
not implement Tag).
public void release()
Must not be called.
Throws:
UnsupportedOperationException
public void setAdaptee(java.lang.Object adaptee)
Sets the tag that is being adapted to the Tag interface. This should be an
instance of SimpleTag in JSP 2.0, but room is left for other kinds of tags in
future spec versions.
public void setPageContext(PageContext pc)
Must not be called.
Throws:
UnsupportedOperationException
public void setParent(Tag parentTag)
PUBLIC DRAFT
2-73 TAG EXTENSION API
Scripting Variables
JSP supports scripting variables that can be declared within a scriptlet and can
be used in another. JSP actions also can be used to define scripting variables so they
can used in scripting elements, or in other actions. This is very useful in some cases;
for example, the jsp:useBean standard action may define an object which can later
be used through a scripting variable.
In some cases the information on scripting variables can be described directly
into the TLD using elements. A special case is typical interpretation of the
"id“ attribute. In other cases the logic that decides whether an action instance
will define a scripting variable may be quite complex and the name of a TagExtra-
Info class is instead given in the TLD. The getVariableInfo method of this class is
used at translation time to obtain information on each variable that will be created
at request time when this action is executed. The method is passed a TagData
instance that contains the translation-time attribute values.
Validation
The TLD file contains several pieces of information that is used to do syntactic
validation at translation-time. It also contains two extensible validation mecha-
PUBLIC DRAFT
Translation-time Classes 2-74
nisms: a TagLibraryValidator class can be used to validate a complete JSP page, and a
TagExtraInfo class can be used to validate a specific action. In some cases, additional
request-time validation will be done dynamically within the methods in the Tag
instance. If an error is discovered, an instance of JspTagException can be thrown. If
uncaught, this object will invoke the errorpage mechanism of JSP.
The TagLibraryValidator is an addition to the JSP 1.2 specification and is very
open ended, being strictly more powerful than the TagExtraInfo mechanism. A
JSP page is presented via the PageData object, which abstracts the XML view of
the JSP page.
A PageData instance will provides an InputStream (read-only) on the page.
Later specifications may add other views on the page (DOM, SAX, JDOM are all
candidates), for now these views can be generated from the InputStream and
perhaps can be cached for improved performance (recall the view of the page is
just read-only).
A JSP container may optionally support a jsp:id attribute to provide higher
quality validation errors. When supported, the container will track the JSP pages
as passed to the container, and will assign to each element a unique “id”, which is
passed as the value of the jsp:id attribute. Each XML element in the XML view
available will be extended with this attribute. The TagLibraryValidator can then
use the attribute in one or more ValidationMessage objects. The container then, in
turn, can use these values to provide more precise information on the location of
an error.
Validation Details
In detail, validation is done as follows:
First, the JSP page is parsed using the information in the TLD. At this stage
valid mandatory and optional attributes are checked.
Second, for all taglib directives in the page, and in the lexical order in which
they appear, their associated validator class (if any) is invoked. This involves
several substeps.
The first substep is to obtain an initialized validator instance by either:
•construct a new instance and invoke setInitParameters() on it, or
•obtain an existing instance that is not being used, invoke release() on it, and
then invoke setInitParameters() on it, or
•locate an existing instance that is not being used on which the desired set-
InitParameters() has already been invoked
The class name is as indicated in the <validator-class> element, and the Map
passed through setInitParameters() is as described in the <init-params> element. All
TagLibraryValidator classes are supposed to keep their initParameters until new
ones are set, or until release() is invoked on them.
PUBLIC DRAFT
2-75 TAG EXTENSION API
JSP.12.7.1 TagLibraryInfo
Syntax
public abstract class TagLibraryInfo
Description
Translation-time information associated with a taglib directive, and its underlying
TLD file. Most of the information is directly from the TLD, except for the prefix
and the uri values used in the taglib directive
JSP.12.7.1.1 Fields
protected java.lang.String info
protected java.lang.String jspversion
protected java.lang.String prefix
protected java.lang.String shortname
protected TagInfo[] tags
protected java.lang.String tlibversion
protected java.lang.String uri
protected java.lang.String urn
JSP.12.7.1.2 Constructors
protected TagLibraryInfo(java.lang.String prefix, java.lang.String uri)
Constructor. This will invoke the constructors for TagInfo, and TagAttribute-
Info after parsing the TLD file.
Parameters:
prefix - the prefix actually used by the taglib directive
PUBLIC DRAFT
Translation-time Classes 2-76
JSP.12.7.1.3 Methods
public java.lang.String getInfoString()
Information (documentation) for this TLD.
public java.lang.String getPrefixString()
The prefix assigned to this taglib from the <%taglib directive
public java.lang.String getReliableURN()
The “reliable” URN indicated in the TLD. This may be used by authoring
tools as a global identifier (the uri attribute) to use when creating a taglib
directive for this library.
public java.lang.String getRequiredVersion()
A string describing the required version of the JSP container.
public java.lang.String getShortName()
The preferred short name (prefix) as indicated in the TLD. This may be used
by authoring tools as the preferred prefix to use when creating an include
directive for this library.
public TagInfo getTag(java.lang.String shortname)
Get the TagInfo for a given tag name, looking through all the tags in this tag
library.
Parameters:
shortname - The short name (no prefix) of the tag
public TagInfo[] getTags()
An array describing the tags that are defined in this tag library.
public java.lang.String getURI()
The value of the uri attribute from the <%@ taglib directive for this library.
JSP.12.7.2 TagInfo
Syntax
public class TagInfo
Description
Tag information for a tag in a Tag Library; This class is instantiated from the Tag
Library Descriptor file (TLD) and is available only at translation time.
PUBLIC DRAFT
2-77 TAG EXTENSION API
JSP.12.7.2.1 Fields
public static final java.lang.String BODY_CONTENT_EMPTY
static constant for getBodyContent() when it is empty
public static final java.lang.String BODY_CONTENT_JSP
static constant for getBodyContent() when it is JSP
public static final java.lang.String BODY_CONTENT_TAG_DEPENDENT
static constant for getBodyContent() when it is Tag dependent
JSP.12.7.2.2 Constructors
public TagInfo(java.lang.String tagName, java.lang.String tagClassName,
java.lang.String bodycontent, java.lang.String infoString,
TagLibraryInfo taglib, TagExtraInfo tagExtraInfo,
TagAttributeInfo[] attributeInfo)
Constructor for TagInfo from data in the JSP 1.1 format for TLD. This class
is to be instantiated only from the TagLibrary code under request from some
JSP code that is parsing a TLD (Tag Library Descriptor). Note that, since
TagLibibraryInfo reflects both TLD information and taglib directive informa-
tion, a TagInfo instance is dependent on a taglib directive. This is probably a
design error, which may be fixed in the future.
Parameters:
tagName - The name of this tag
tagClassName - The name of the tag handler class
bodycontent - Information on the body content of these tags
infoString - The (optional) string information for this tag
taglib - The instance of the tag library that contains us.
tagExtraInfo - The instance providing extra Tag info. May be null
attributeInfo - An array of AttributeInfo data from descriptor. May be null;
public TagInfo(java.lang.String tagName, java.lang.String tagClassName,
java.lang.String bodycontent, java.lang.String infoString,
TagLibraryInfo taglib, TagExtraInfo tagExtraInfo,
TagAttributeInfo[] attributeInfo, java.lang.String displayName,
java.lang.String smallIcon, java.lang.String largeIcon, TagVariableInfo[] tvi)
Constructor for TagInfo from data in the JSP 1.2 format for TLD. This class
is to be instantiated only from the TagLibrary code under request from some
JSP code that is parsing a TLD (Tag Library Descriptor). Note that, since
TagLibibraryInfo reflects both TLD information and taglib directive informa-
PUBLIC DRAFT
Translation-time Classes 2-78
JSP.12.7.2.3 Methods
public TagAttributeInfo[] getAttributes()
Attribute information (in the TLD) on this tag. The return is an array describ-
ing the attributes of this tag, as indicated in the TLD. A null return means no
attributes.
Returns: The array of TagAttributeInfo for this tag.
public java.lang.String getBodyContent()
The bodycontent information for this tag.
Returns: the body content string.
public java.lang.String getDisplayName()
Get the displayName
Returns: A short name to be displayed by tools
public java.lang.String getInfoString()
The information string for the tag.
Returns: the info string
public java.lang.String getLargeIcon()
Get the path to the large icon
Returns: Path to a large icon to be displayed by tools
PUBLIC DRAFT
2-79 TAG EXTENSION API
PUBLIC DRAFT
Translation-time Classes 2-80
JSP.12.7.3 TagAttributeInfo
Syntax
public class TagAttributeInfo
Description
Information on the attributes of a Tag, available at translation time. This class is
instantiated from the Tag Library Descriptor file (TLD).
Only the information needed to generate code is included here. Other information
like SCHEMA for validation belongs elsewhere.
JSP.12.7.3.1 Fields
public static final java.lang.String ID
“id” is wired in to be ID. There is no real benefit in having it be something
else IDREFs are not handled any differently.
JSP.12.7.3.2 Constructors
public TagAttributeInfo(java.lang.String name, boolean required,
java.lang.String type, boolean reqTime)
PUBLIC DRAFT
2-81 TAG EXTENSION API
JSP.12.7.3.3 Methods
public boolean canBeRequestTime()
Whether this attribute can hold a request-time value.
Returns: if the attribute can hold a request-time value.
public static TagAttributeInfo getIdAttribute(TagAttributeInfo[] a)
Convenience static method that goes through an array of TagAttributeInfo
objects and looks for “id”.
Parameters:
a - An array of TagAttributeInfo
Returns: The TagAttributeInfo reference with name “id”
public java.lang.String getName()
The name of this attribute.
Returns: the name of the attribute
public java.lang.String getTypeName()
The type (as a String) of this attribute.
Returns: the type of the attribute
public boolean isRequired()
Whether this attribute is required.
Returns: if the attribute is required.
public java.lang.String toString()
Overrides: java.lang.Object.toString() in class java.lang.Object
PUBLIC DRAFT
Translation-time Classes 2-82
JSP.12.7.4 PageData
Syntax
public abstract class PageData
Description
Translation-time information on a JSP page. The information corresponds to the
XML view of the JSP page.
Objects of this type are generated by the JSP translator, e.g. when being pased to
a TagLibraryValidator instance.
JSP.12.7.4.1 Constructors
public PageData()
JSP.12.7.4.2 Methods
public abstract java.io.InputStream getInputStream()
Returns an input stream on the XML view of a JSP page. Recall tht the XML
view of a JSP page has the include directives expanded.
Returns: An input stream on the document.
JSP.12.7.5 TagLibraryValidator
Syntax
public abstract class TagLibraryValidator
Description
Translation-time validator class for a JSP page. A validator operates on the XML
document associated with the JSP page.
The TLD file associates a TagLibraryValidator class and some init arguments
with a tag library.
The JSP container is reponsible for locating an appropriate instance of the appro-
priate subclass by
•new a fresh instance, or reuse an available one
•invoke the setInitParams(Map) method on the instance
PUBLIC DRAFT
2-83 TAG EXTENSION API
JSP.12.7.5.1 Constructors
public TagLibraryValidator()
JSP.12.7.5.2 Methods
public java.util.Map getInitParameters()
Get the init parameters data as an immutable Map. Parameter names are keys,
and parameter values are the values.
Returns: The init parameters as an immutable map.
public void release()
Release any data kept by this instance for validation purposes
public void setInitParameters(java.util.Map map)
Set the init data in the TLD for this validator. Parameter names are keys, and
parameter values are the values.
Parameters:
initMap - A Map describing the init parameters
public ValidationMessage[] validate(java.lang.String prefix, java.lang.String uri,
PageData page)
Validate a JSP page. This will get invoked once per directive in the JSP page.
This method will return null if the page is valid; otherwise the method should
PUBLIC DRAFT
Translation-time Classes 2-84
JSP.12.7.6 ValidationMessage
Syntax
public class ValidationMessage
Description
A validation message from a TagLibraryValidator.
A JSP container may (optionally) support a jsp:id attribute to provide higher qual-
ity validation errors. When supported, the container will track the JSP pages as
passed to the container, and will assign to each element a unique “id”, which is
passed as the value of the jsp:id attribute. Each XML element in the XML view
available will be extended with this attribute. The TagLibraryValidator can then
use the attribute in one or more ValidationMessage objects. The container then, in
turn, can use these values to provide more precise information on the location of
an error.
JSP.12.7.6.1 Constructors
public ValidationMessage(java.lang.String id, java.lang.String message)
Create a ValidationMessage. The message String should be non-null. The
value of id may be null, if the message is not specific to any XML element, or
if no jsp:id attributes were passed on. If non-null, the value of id must be the
value of a jsp:id attribute for the PageData passed into the validate() method.
Parameters:
id - Either null, or the value of a jsp:id attribute.
message - A localized validation message.
JSP.12.7.6.2 Methods
public java.lang.String getId()
PUBLIC DRAFT
2-85 TAG EXTENSION API
JSP.12.7.7 TagExtraInfo
Syntax
public abstract class TagExtraInfo
Description
Optional class provided by the tag library author to describe additional transla-
tion-time information not described in the TLD. The TagExtraInfo class is men-
tioned in the Tag Library Descriptor file (TLD).
It is the responsibility of the JSP translator that the initial value to be returned by
calls to getTagInfo() corresponds to a TagInfo object for the tag being translated.
If an explicit call to setTagInfo() is done, then the object passed will be returned
in subsequent calls to getTagInfo().
The only way to affect the value returned by getTagInfo() is through a setTag-
Info() call, and thus, TagExtraInfo.setTagInfo() is to be called by the JSP transla-
tor, with a TagInfo object that corresponds to the tag being translated. The call
should happen before any invocation on isValid() and before any invocation on
getVariableInfo().
JSP.12.7.7.1 Constructors
public TagExtraInfo()
JSP.12.7.7.2 Methods
public final TagInfo getTagInfo()
Get the TagInfo for this class.
Returns: the taginfo instance this instance is extending
public VariableInfo[] getVariableInfo(TagData data)
PUBLIC DRAFT
Translation-time Classes 2-86
information on scripting variables defined by the tag associated with this Tag-
ExtraInfo instance. Request-time attributes are indicated as such in the Tag-
Data parameter.
Parameters:
data - The TagData instance.
Returns: An array of VariableInfo data.
public boolean isValid(TagData data)
Translation-time validation of the attributes. Request-time attributes are indi-
cated as such in the TagData parameter.
Parameters:
data - The TagData instance.
Returns: Whether this tag instance is valid.
public final void setTagInfo(TagInfo tagInfo)
Set the TagInfo for this class.
Parameters:
tagInfo - The TagInfo this instance is extending
JSP.12.7.8 TagData
Syntax
public class TagData implements java.lang.Cloneable
Description
The (translation-time only) attribute/value information for a tag instance.
JSP.12.7.8.1 Fields
public static final java.lang.Object REQUEST_TIME_VALUE
Distinguished value for an attribute to indicate its value is a request-time
expression (which is not yet available because TagData instances are used at
translation-time).
PUBLIC DRAFT
2-87 TAG EXTENSION API
JSP.12.7.8.2 Constructors
public TagData(java.util.Hashtable attrs)
Constructor for a TagData. If you already have the attributes in a hashtable,
use this constructor.
Parameters:
attrs - A hashtable to get the values from.
public TagData(java.lang.Object[][] atts)
Constructor for TagData.
A typical constructor may be
static final Object[][] att = {{“connection”, “conn0”},
{“id”, “query0”}};
static final TagData td = new TagData(att);
All values must be Strings except for those holding the distinguished object
REQUEST_TIME_VALUE.
Parameters:
atts - the static attribute and values. May be null.
JSP.12.7.8.3 Methods
public java.lang.Object getAttribute(java.lang.String attName)
The value of the attribute. Returns the distinguished object
REQUEST_TIME_VALUE if the value is request time. Returns null if the
attribute is not set.
Returns: the attribute’s value object
public java.util.Enumeration getAttributes()
Enumerates the attributes.
Returns: An enumeration of the attributes in a TagData
public java.lang.String getAttributeString(java.lang.String attName)
Get the value for a given attribute.
Returns: the attribute value string
public java.lang.String getId()
The value of the id attribute, if available.
Returns: the value of the id attribute or null
public void setAttribute(java.lang.String attName, java.lang.Object value)
Set the value of an attribute.
PUBLIC DRAFT
Translation-time Classes 2-88
Parameters:
attName - the name of the attribute
value - the value.
JSP.12.7.9 VariableInfo
Syntax
public class VariableInfo
Description
Information on the scripting variables that are created/modified by a tag (at run-
time). This information is provided by TagExtraInfo classes and it is used by the
translation phase of JSP.
Scripting variables generated by a custom action may have scope values of page,
request, session, and application.
The class name (VariableInfo.getClassName) in the returned objects are used to
determine the types of the scripting variables. Because of this, a custom action
cannot create a scripting variable of a primitive type. The workaround is to use
“boxed” types.
The class name may be a Fully Qualified Class Name, or a short class name.
If a Fully Qualified Class Name is provided, it should refer to a class that should
be in the CLASSPATH for the Web Application (see Servlet 2.3 specification -
essentially it is WEB-INF/lib and WEB-INF/classes). Failure to be so will lead to
a translation-time error.
If a short class name is given in the VariableInfo objects, then the class name must
be that of a public class in the context of the import directives of the page where
the custom action appears (will check if there is a JLS verbiage to refer to). The
class must also be in the CLASSPATH for the Web Application (see Servlet 2.3
specification - essentially it is WEB-INF/lib and WEB-INF/classes). Failure to be
so will lead to a translation-time error.
Usage Comments
Frequently a fully qualified class name will refer to a class that is known to the tag
library and thus, delivered in the same JAR file as the tag handlers. In most other
remaining cases it will refer to a class that is in the platform on which the JSP
processor is built (like J2EE). Using fully qualified class names in this manner
makes the usage relatively resistant to configuration errors.
PUBLIC DRAFT
2-89 TAG EXTENSION API
A short name is usually generated by the tag library based on some attributes
passed through from the custom action user (the author), and it is thus less robust:
for instance a missing import directive in the referring JSP page will lead to an
invalid short name class and a translation error.
Synchronization Protocol
The result of the invocation on getVariableInfo is an array of VariableInfo objects.
Each such object describes a scripting variable by providing its name, its type,
whether the variable is new or not, and what its scope is. Scope is best described
through a picture:
The scope value for a variable implies what methods may affect its value and thus
where synchronization is needed:
•for NESTED, after doInitBody and doAfterBody for a tag handler imple-
menting BodyTag, and after doStartTag otherwise.
•for AT_BEGIN, after doInitBody, doAfterBody, and doEndTag for a tag
handler implementing BodyTag, and doStartTag and doEndTag otherwise.
•for AT_END, after doEndTag method.
Scripting variable information can also be encoded directly for most cases into
the Tag Library Descriptor using the <variable> subelement of the <tag> element.
See the JSP specification.
PUBLIC DRAFT
Translation-time Classes 2-90
JSP.12.7.9.1 Fields
public static final int AT_BEGIN
Scope information that scripting variable is visible after start tag
public static final int AT_END
Scope information that scripting variable is visible after end tag
public static final int NESTED
Scope information that scripting variable is visible only within the start/end
tags
JSP.12.7.9.2 Constructors
public VariableInfo(java.lang.String varName, java.lang.String className,
boolean declare, int scope)
Constructor These objects can be created (at translation time) by the Tag-
ExtraInfo instances.
Parameters:
id - The name of the scripting variable
className - The name of the scripting variable
declare - If true, it is a new variable (in some languages this will require a
declaration)
scope - Indication on the lexical scope of the variable
JSP.12.7.9.3 Methods
public java.lang.String getClassName()
public boolean getDeclare()
public int getScope()
public java.lang.String getVarName()
JSP.12.7.10 TagVariableInfo
Syntax
public class TagVariableInfo
PUBLIC DRAFT
2-91 TAG EXTENSION API
Description
Variable information for a tag in a Tag Library; This class is instantiated from the
Tag Library Descriptor file (TLD) and is available only at translation time. This
object should be immutable. This information is only available in JSP 1.2 format
JSP.12.7.10.1 Constructors
public TagVariableInfo(java.lang.String nameGiven,
java.lang.String nameFromAttribute, java.lang.String className,
boolean declare, int scope)
Constructor for TagVariableInfo
Parameters:
nameGiven - value of <name-given>
nameFromAttribute - value of <name-from-attribute>
className - value of <variable-class>
declare - value of <declare>
scope - value of <scope>
JSP.12.7.10.2 Methods
public java.lang.String getClassName()
The body of the <variable-class> element.
Returns: The name of the class of the variable
public boolean getDeclare()
The body of the <declare> element
Returns: Whether the variable is to be declared or not
public java.lang.String getNameFromAttribute()
The body of the <name-from-attribute> element. This is the name of an
attribute whose (translation-time) value will give the name of the variable.
One of <name-given> or <name-from-attribute> is required.
Returns: The attribute whose value defines the variable name
public java.lang.String getNameGiven()
The body of the <name-given> element
Returns: The variable name as a constant
public int getScope()
The body of the <scope> element
PUBLIC DRAFT
Translation-time Classes 2-92
PUBLIC DRAFT
2-93 TAG EXTENSION API
PUBLIC DRAFT
C H A P T E R JSP.13
Expression Language API
JSP.13.1.1 ExpressionEvaluator
Syntax
public interface ExpressionEvaluator
Description
The interface for an expression-language validator and evaluator. Classes that
implement an expression language expose their functionality via this interface.
2-94
2-95 EXPRESSION LANGUAGE API
The validate() and evaluate() methods must be thread-safe. That is, multiple
threads may call these methods on the same ExpressionEvaluator object simulta-
neously. Implementations should synchronize access if they depend on transient
state. Implementations should not, however, assume that only one object of each
ExpressionEvaluator type will be instantiated; global caching should therefore be
static.
JSP.13.1.1.1 Methods
public java.lang.Object evaluate(java.lang.String attributeName,
java.lang.String expression, java.lang.Class expectedType, Tag tag,
PageContext pageContext)
Evaluates the expression at request time.
Throws:
JspException
public java.lang.String validate(java.lang.String attributeName,
java.lang.String expression)
Translation time validation of an expression. This method will return a null
String if the expression is valid; otherwise an error message.
JSP.13.1.2 VariableResolver
Syntax
public interface VariableResolver
Description
This class is used to customize the way the evaluator resolves variable references.
For example, instances of this class can implement their own variable lookup
mechanisms, or introduce the notion of “implicit variables” which override any
other variables. An instance of this class should be passed to the evaluator’s con-
structor.
Whenever the evaluator is invoked, it is passed a “context” Object from the appli-
cation. For example, in a JSP environment, the “context” is a PageContext. That
context object is eventually passed to this class, so that this class has a context in
which to resolve variables.
JSP.13.1.2.1 Methods
public java.lang.Object resolveVariable(java.lang.String pName,
java.lang.Object pContext)
PUBLIC DRAFT
Exceptions 2-96
Resolves the specified variable within the given context. Returns null if the
variable is not found.
Throws:
ELException
JSP.13.2 Exceptions
JSP.13.2.1 ELException
Syntax
public class ELException extends java.lang.Exception
Description
Represents any of the exception conditions that arise during the operation evalua-
tion of the evaluator.
JSP.13.2.1.1 Constructors
public ELException()
Constructor
public ELException(java.lang.String pMessage)
Constructor
public ELException(java.lang.String pMessage,
java.lang.Throwable pRootCause)
Constructor
public ELException(java.lang.Throwable pRootCause)
Constructor
JSP.13.2.1.2 Methods
public java.lang.Throwable getRootCause()
Returns the root cause
public java.lang.String toString()
PUBLIC DRAFT
2-97 EXPRESSION LANGUAGE API
String representation
Overrides: java.lang.Throwable.toString() in class java.lang.Throwable
PUBLIC DRAFT
Exceptions 2-98
PUBLIC DRAFT
PART III
T he next Appendices provide details.
Only Appendices X, Y, and C are normative. Appendices U, Z, and W are
non-normative.
The Appendices are
This appendix shows two simple examples of packaging a JSP page into a
WAR for delivery into a Web container. In the first example, the JSP page is deliv-
ered in source form. This is likely to be the most common example. In the second
example the JSP page is compiled into a Servlet that uses only Servlet 2.4 and JSP
2.0 API calls; the Servlet is then packaged into a WAR with a deployment descriptor
such that it looks as the original JSP page to any client.
This appendix is non normative. Actually, strictly speaking, the appendix
relates more to the Servlet 2.4 capabilities than to the JSP 2.0 capabilities. The
appendix is included here as this is a feature that JSP page authors and JSP page
authoring tools are interested in.
The JSP page can be packaged into a WAR file by just placing it at location "/
HelloWorld.jsp" the default JSP page extension mapping will pick it up. The
web.xml is trivial:
<!DOCTYPE webapp
SYSTEM "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<webapp>
<session-config>
<session-timeout> 1 </session-timeout>
</session-config>
</webapp>
As an alternative, we will show how one can compile the JSP page into a Servlet
class to run in a JSP container.
The JSP page is compiled into a Servlet with some implementation dependent
name _jsp_HelloWorld_XXX_Impl. The Servlet code only depends on the JSP 2.0
and Servlet 2.4 APIs, as follows:
imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;
class _jsp_HelloWorld_XXX_Impl
extends_PlatformDependent_Jsp_Super_Impl {
public void _jspInit() {
// ...
}
PUBLIC DRAFT
3-4
{
Object page= this;
HttpSessionsession= request.getSession();
ServletConfigconfig= getServletConfig();
ServletContextapplication = config.getServletContext();
PageContextpageContext
= _factory.getPageContext(this,
request,
response,
(String)NULL,
true,
JspWriter.DEFAULT_BUFFER,
true
);
JspWriterout= pageContext.getOut();
// page context creates initial JspWriter "out"
try {
out.println("<p>");
out.println("Hello World");
out.println("</p>");
} catch (Exception e) {
pageContext.handlePageException(e);
} finally {
_factory.releasePageContext(pageContext);
}
}
}
The Servlet is made to look as a JSP page with the following web.xml:
PUBLIC DRAFT
3-5 PACKAGING JSP PAGES
<!DOCTYPE webapp
SYSTEM "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<webapp>
<servlet>
<servlet-name> HelloWorld </servlet-name>
<servlet-class> _jsp_HelloWorld_XXX_Impl.class </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> HelloWorld </servlet-name>
<url-pattern> /HelloWorld.jsp </url-pattern>
</servlet-mapping>
<session-config>
<session-timeout> 1 </session-timeout>
</session-config>
</webapp>
/WEB-INF/web.xml
/WEB-INF/classes/_jsp_HelloWorld_XXX_Impl.class
Note that if the Servlet class generated for the JSP page had depended on
some support classes, they would have to be included in the WAR.
PUBLIC DRAFT
A P P E N D I X JSP.B
DTD and Schemas for XML
Syntax
T his appendix includes the DTD and XSchema for JSP pages in XML syntax.
This appendix is non-normative.
As indicated in Section JSP.6.4, a DTD is not a good description to be used
for validating a document that is using namespaces like a JSP page in XML
syntax, but its familiarity with many readers makes it nevertheless useful.
<!--
This DTD is not conditional on any parameter entities in the
internal subset and does not export any general entities.
-->
<!-- used for object, applet, img, input and iframe -->
<!ENTITY % ImgAlign “(top|middle|bottom|left|right)”>
PUBLIC DRAFT
3-8
<!ENTITY % Actions
“jsp:useBean
|jsp:setProperty
|jsp:getProperty
|jsp:include
|jsp:forward
|jsp:plugin”
>
<!ATTLIST jsp:directive.page
PUBLIC DRAFT
3-9
<!-- the jsp:directive.include element only appears in JSP documents and does
not appear in XML views of JSP pages -->
PUBLIC DRAFT
3-10
>
PUBLIC DRAFT
3-11
<xsd:schema
xmlns = "http://java.sun.com/JSP/Page"
xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
xmlns:jsp = "http://java.sun.com/JSP/Page"
targetNamespace = "http://java.sun.com/JSP/Page"
elementFormDefault = "qualified"
attributeFormDefault = "unqualified">
<xsd:annotation>
<xsd:documentation>
XML Schema for JSP 1.2.
PUBLIC DRAFT
3-12
PUBLIC DRAFT
3-13
<!--
There should be a constraint for jsp:id to be unique within all elements
in the document.
-->
PUBLIC DRAFT
3-14
<xsd:annotation>
<xsd:documentation>
TypeName is one or more Java identifiers separated by dots
with no whitespace.
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&TypeName;"/>
</xsd:restriction>
</xsd:simpleType>
PUBLIC DRAFT
3-15
</xsd:simpleType>
PUBLIC DRAFT
3-16
PUBLIC DRAFT
3-17
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/JSP/Page xsd-file-location"
PUBLIC DRAFT
3-18
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "language" default = "java" type = "xsd:string"/>
<xsd:attribute name = "extends" type = "TypeName"/>
<xsd:attribute name = "contentType"
default = "text/xml; UTF-8" type = "ContentType"/>
<xsd:attribute name = "pageEncoding"
use = "optional" type = "PageEncoding"/>
<xsd:attribute name = "import" type = "ImportList"/>
<xsd:attribute name = "session" default = "true" type = "Bool"/>
<xsd:attribute name = "buffer" default = "8kb" type = "BufferSize"/>
<xsd:attribute name = "autoFlush" default = "true" type = "Bool"/>
<xsd:attribute name = "isThreadSafe" default = "true" type = "Bool"/>
<xsd:attribute name = "info" type = "xsd:string"/>
<xsd:attribute name = "errorPage" type = "RelativeURL"/>
<xsd:attribute name = "isErrorPage" default = "false" type = "Bool"/>
</xsd:complexType>
</xsd:element>
PUBLIC DRAFT
3-19
</xsd:element>
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="Body">
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "id" use = "required" type = "Identifier"/>
<xsd:attribute name = "class" type = "TypeName"/>
<xsd:attribute name = "type" type = "TypeName"/>
<xsd:attribute name = "beanName" type = "TypeName"/>
<xsd:attribute name = "scope" default = "page" type = "Scope"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
PUBLIC DRAFT
3-20
name="Identifier" property="*"
name="Identifier" property="Identfiier" param="string"
name="Identifier" property="Identifier" value="string"
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "name" use = "required" type = "Identifier"/>
<xsd:attribute name = "property" use = "required" type = "SetProp"/>
<xsd:attribute name = "param" type = "xsd:string"/>
<xsd:attribute name = "value" type = "xsd:string"/>
</xsd:complexType>
</xsd:element>
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "name" use = "required" type = "Identifier"/>
<xsd:attribute name = "property" use = "required" type = "Identifier"/>
</xsd:complexType>
</xsd:element>
PUBLIC DRAFT
3-21
PUBLIC DRAFT
3-22
</xsd:schema>
PUBLIC DRAFT
A P P E N D I X JSP.C
DTD for TagLibrary
Descriptor, JSP 1.2
This appendix includes the DTD for a tag library descriptor using JSP 1.2.
All JSP 1.2 containers are required to accept such a TLD.
This is the same DTD as "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd",
except for some formatting changes to extract comments and make them more
readable.
<!--
This is the DTD defining the JavaServer Pages 1.2 Tag Library descriptor (.tld)
(XML) file format/syntax.
A Tag Library is a JAR file containing a valid instance of a Tag Library Descriptor
file, along with the appropriate implementation classes and other resources re-
quired to implement the actions defined therein. When deployed inside a JAR file,
the tag library descriptor files must be in the META-INF directory, or a subdirec-
tory of it. When deployed directly into a web application, the tag library descriptor
files must always be in the WEB-INF directory, or some subdirectory of it.
Packaged tag libraries must have at least one tag library descriptor file. The JSP
1.1 specification allowed for only a single TLD, in META-INF/taglib.tld, but in JSP
1.2 multiple tag libraries are allowed.
<!--
All JSP 1.2 tag library descriptors must include a DOCTYPE of the following form:
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
-->
<!--
The taglib element is the document root, it defines:
description a simple string describing the “use” of this taglib, should be user
discernable
-->
PUBLIC DRAFT
3-25 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2
<!ATTLIST taglib
id ID #IMPLIED
xmlns CDATA #FIXED “http://java.sun.com/JSP/TagLibraryDescriptor”>
<!--
The value of the tlib-version element describes this version (number) of the tagl-
ibrary. This element is mandatory.
<!--
The value of the jsp-version element describes the JSP version (number) this
taglibrary requires in order to function. This element is mandatory. The value that
should be used for JSP 1.2 is "1.2" (no quotes).
<!--
The value of the short-name element is a name that could be used by a JSP au-
thoring tool to create names with a mnemonic value; for example, it may be used
as the prefered prefix value in taglib directives.
Do not use white space, and do not start with digits or underscore.
<!--
The value of the uri element is a public URI that uniquely identifies the exact se-
mantics of this taglibrary.
-->
PUBLIC DRAFT
3-26
<!--
The value of the description element is an arbitrary text string describing the tag
library.
-->
<!--
The validator element provides information on an optional validator that can be
used to validate the conformance of a JSP page to using this tag library.
-->
<!--
The validator-class element defines the TagLibraryValidator class that can be
used to validate the conformance of a JSP page to using this tag library.
-->
<!--
The init-param element contains a name/value pair as an
initialization param.
-->
<!--
The param-name element contains the name of a parameter.
-->
<!--
The param-value element contains the value of a parameter.
-->
PUBLIC DRAFT
3-27 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2
<!--
The listener element defines an optional event listener object to be instantiated
and
registered automatically.
-->
<!--
The listener-class element declares a class in the application that must be regis-
tered as a web application listener bean.
See the Servlet 2.3 specification for details.
-->
<!--
The tag element defines an action in this tag library. The tag element has one at-
tribute, id.
The tag element may have several subelements defining:
-->
PUBLIC DRAFT
3-28
<!--
The tag-class element indicates the subclass of javax.serlvet.jsp.tagext.Tag that
implements the request time semantics for this tag. This element is required.
<!--
The tei-class element indicates the subclass of javax.servlet.jsp.tagext.TagEx-
traInfo for this tag. The class is instantiated at translation time. This element is
optional.
<!--
The body-content element provides provides information on the content of the
body of this tag. This element is primarily intended for use by page composition
tools.
There are currently three values specified:
tagdependent The body of the tag is interpreted by the tag implementation it-
self, and is most likely in a different “langage”, e.g embedded
SQL statements.
PUBLIC DRAFT
3-29 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2
<!--
The display-name element contains a short name that is intended to be displayed
by tools.
-->
<!--
The large-icon element contains the name of a file containing a large (32 x 32)
icon image. The icon can be used by tools. The file name is a relative path within
the tag library.
The image must be either in the JPEG or GIF format, and the file name must end
with the suffix “.jpg” or “.gif” respectively.
-->
<!--
The small-icon element contains the name of a file containing a small (16 x 16)
icon image. The icon can be used by tools. The file name is a relative path within
the tag library.
The image must be either in the JPEG or GIF format, and the file name must end
with the suffix “.jpg” or “.gif” respectively.
-->
<!--
The example element provides an informal description of an example of the use
of a tag.
-->
<!--
The variable element provides information on the scripting variables defined by
this tag.
It is a (translation time) error for an action that has one or more variable subele-
ments to have a TagExtraInfo class that returns a non-null object.
The subelements of variable are of the form:
PUBLIC DRAFT
3-30
-->
<!--
The name-given element provides the name for the scripting variable.
One of name-given or name-from-attribute is required.
-->
<!--
The value of the name-from-attribute element is the name of an attribute whose
(translation-time) value will give the name of the variable.
One of name-given or name-from-attribute is required.
-->
<!--
The variable-class element is the name of the class for the scripting variable.
This element is optional; the default is java.lang.String.
-->
<!--
The value of the declare element indicates whether the scripting variable is to be
defined or not. See TagExtraInfo for details.
PUBLIC DRAFT
3-31 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2
<!--
The value of the scope element describes the scope of the scripting variable.
See TagExtraInfo for details.
This element is optional and the default value is the string “NESTED”. The other
legal values are “AT_BEGIN” and “AT_END”.
-->
<!--
The attribute element defines an attribute for the nesting tag.
The attributre element may have several subelements defining:
-->
<!--
The name element defines the canonical name of a tag or attribute being defined
<!--
The value of the required element indicates if the nesting attribute is required or
optional. This attribute is optional and its default value is false.
PUBLIC DRAFT
3-32
<!--
The value of the rtexpvalue element indicates if the value of the attribute may be
dynamically calculated at request time, as opposed to a static value determined
at translation time. This attribute is optional and its default value is false
<!--
The value of the type element describes the Java type of the attributes value.
For static values (those determined at translation time) the type is always ja-
va.lang.String.
-->
PUBLIC DRAFT
3-33 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2
PUBLIC DRAFT
A P P E N D I X JSP.D
DTD for TagLibrary
Descriptor, JSP 1.1
T his appendix includes the DTD for a tag library descriptor using JSP 1.1.
All JSP 1.2 containers are required to accept such a TLD.
This is the same DTD as "http://java.sun.com/dtd/web-jsptaglibrary_1_1.dtd",
except for some formatting changes to extract comments and make them more
readable.
<!--
This is the DTD defining the JavaServer Pages 1.1 Tag Library descriptor (.tld)
(XML) file format/syntax.
A Tag Library is a JAR file containing a valid instance of a Tag Library Descriptor
(taglib.tld) file in the META-INF subdirectory, along with the appropriate imple-
menting classes, and other resources required toimplement the tags defined
therein.
<!--
The taglib tag is the document root, it defines:
<!--
Describes this version (number) of the taglibrary (dewey decimal)
#PCDATA ::= [0-9]*{ “.”[0-9] }0..3
-->
<!--
Describes the JSP version (number) this taglibrary requires in order to function
(dewey decimal)
The default is 1.1
<!--
Defines a short (default) shortname to be used for tags and variable names used/
created by this tag library. Do not use white space, and do not start with digits or
underscore.
PUBLIC DRAFT
3-36
<!--
Defines a public URI that uniquely identifies this version of the taglibrary Leave it
empty if it does not apply.
-->
<!--
Defines an arbitrary text string descirbing the tag library
-->
<!--
The tag defines a unique tag in this tag library, defining:
- the unique tag/element name
- the subclass of javax.servlet.jsp.tagext.Tag implementation class
- an optional subclass of javax.servlet.jsp.tagext.TagExtraInfo
- the body content type (hint)
- optional tag-specific information
- any attributes
-->
<!--
Defines the subclass of javax.serlvet.jsp.tagext.Tag that implements the request
time semantics for this tag. (required)
<!--
Defines the subclass of javax.servlet.jsp.tagext.TagExtraInfo for this tag. (option-
al)
If this is not given, the class is not consulted at translation time.
PUBLIC DRAFT
3-37
<!--
Provides a hint as to the content of the body of this tag. Primarily intended for use
by page composition tools.
There are currently three values specified:
tagdependent The body of the tag is interpreted by the tag implementation
itself, and is most likely in a different “langage”, e.g embedded SQL
statements.
JSP The body of the tag contains nested JSP syntax
empty The body must be empty. The default (if not defined) is JSP
<!--
The attribute tag defines an attribute for the nesting tag
An attribute definition is composed of:
- the attributes name (required)
- if the attribute is required or optional (optional)
- if the attributes value may be dynamically calculated at runtime
by a scriptlet expression (optional)
-->
<!--
Defines the canonical name of a tag or attribute being defined
<!--
Defines if the nesting attribute is required or optional.
PUBLIC DRAFT
3-38
If not present then the default is “false”, i.e the attribute is optional.
-->
<!--
Defines if the nesting attribute can have scriptlet expressions as a value, i.e the
value of the attribute may be dynamically calculated at request time, as opposed
to a static value determined at translation time.
If not present then the default is “false”, i.e the attribute has a static value
-->
PUBLIC DRAFT
A P P E N D I X JSP.E
Changes
This appendix lists the changes in the JavaServer Pages specification. This
appendix is non-normative.
• Moved all the JSP configuration description into its own chapter.
• Reordered the EBNF description to be at the end of JSP 1.3.
• Restored some pieces in the Syntax chapter that were lost in an editing opera-
tion. The only substantive piece was the description of the <include-prelude>
and <include-coda> elements, which are now in the JSP configuration chapter.
• Added details on how to implement functions in EL.
• Upgraded major version from JSP 1.3 to JSP 2.0, added section to the Preface
explaining change.
• Added directive examples to JSP Fragments chapter.
• Moved section describing passing attribute values via <jsp:attribute> and
<jsp:body> to syntax chapter and moved definitions of these two standard ac-
tions to Standard Actions chapter, from JSP Fragments chapter.
PUBLIC DRAFT
3-42
• A new chapter on JSP fragments and supporting technologies such as the .tag
mechanism and simple tag handlers:
■
JSP fragments allow a portion of JSP code to be encapsulated into a Java ob-
ject which can be passed around and evaluated zero or more times.
■
The .tag mechanism allows page authors to use JSP syntax to write Custom
Actions.
■
Simple tag handlers integrates tightly with JSP fragments and allows for a
much easier and more natural invocation protocol for tag extensions.
PUBLIC DRAFT
3-43
JSP.E.4Changes Between JSP 1.2 Final Draft and JSP 2.0 ED1
PUBLIC DRAFT
3-44
This is the final version approved by JCP Executive Comittee; the document
was updated to reflect that status. All change bars were reset.
PUBLIC DRAFT
3-45
statements about the jsp:useBean standard action. This has been made explicit and
the sections were moved to Chapter 5 to reflect that.
Sections JSP.2.13.3 and JSP.2.13.4, and Chapter 4 were affected.
• Reafirmed that, in a JSP page in XML syntax, the URI for jsp core actions is
important, not the prefix.
• Clarify that <?xml ... ?> is not required (as indicated by the XML spec).
• Clarified further the interpretation of whitespace on JSP documents.
PUBLIC DRAFT
3-46
Change bars are used in almost all chapters to indicate changes between PFD 1b
and PFD 2. The exception are Chapters 11 and 12 which are generated automati-
cally from the Java sources and have no change bars. Most changes are semantical,
but some of them are editorial.
PUBLIC DRAFT
3-47
PUBLIC DRAFT
3-48
• Add a comment to the DTD for the TLD indicating that a DOCTYPE is needed
and what its value is. No changes to the value.
• Removed the paragraph at the end of Section JSP.7.3.9 that used to contain
non-normative comments on the future of "well kwown URIs".
• Corrected the description of the valid values that can be passed to the flush at-
tribute of the include action in Section JSP.5.4.
• Clarified that <jsp:param> can only appear within <jsp:forward>, <jsp:in-
clude>, and <jsp:params>.
• Clarified that <jsp:params> and <jsp:fallback> can only appear within
<jsp:plugin>.
PUBLIC DRAFT
3-49
• Resolved a conflict in Section JSP.5.4 between the Servlet and the JSP specifi-
cation regarding how to treat modifications to headers in included actions.
• Section 10.1.1 in PFD1 incorrectly described the valid return values for
doStartTag() in tag handlers that implement the BodyTag interface. The cor-
rect valid values are SKIP_BODY, EVAL_BODY_INCLUDE and
EVAL_BODY_BUFFER. Section now indicates this.
PFD 1b is a draft that has mostly formating and a few editorial changes. This
draft is shown only to make it simpler to correlate changes between later drafts and
the previous drafts.
Change bars are used to indicate changes between PFD 1 and PFD 1b.
The following changes ocurred between the Public Draft 1 and the Proposed
Final Draft versions of the JSP 1.2 specification.
E.8.30 Deletions
E.8.31 Additions
PUBLIC DRAFT
3-50
E.8.32 Clarifications
• A tag handler object can be created with a simple “new()”; it needs not be a
fully fledged Beans, supporting the complete behavior of the ja-
va.beans.Beans.instantiate() method.
• Removed the “recommendation” that the <uri> element in a TLD be a URL to
anything.
• Clarified that extension dependency information in packaged tag libraries
should be honored.
• Clarified invocation and lifecycle of TagLibraryValidator.
• Clarified where TLDs may appear in a packaged JAR file.
• Clarified when are response.getWriter().
E.8.33 Changes
PUBLIC DRAFT
3-51
The following changes ocurred between the JSP 1.1 and JSP 1.2 Public Draft 1.
• Chapter 8 and 10 are now generated automatically from the javadoc sources.
• Created a new document to allow longer descriptions of uses of the technolo-
gy.
• Created a new I18N chapter to capture Servlet 2.3 implications and others
(mostly empty for PD1).
• Removed Implementation Notes and Future appendices, as they have not been
updated yet.
PUBLIC DRAFT
3-52
E.9.37 Clarifications
E.9.38 Changes
The JSP 1.1 specification builds on the JSP 1.0 specification. The following
changes ocurred between the JSP 1.0 final specification and the JSP 1.1 final specifi-
cation.
E.10.39 Additions
PUBLIC DRAFT
3-53
E.10.40 Changes
• Use Servlet 2.2 instead of Servlet 2.1 (as clarified in Appendix B), including
distributable JSP pages.
• jsp:plugin no longer can be implemented by just sending the contents of
jsp:fallback to the client.
• Reserved all request parameters starting with "jsp".
PUBLIC DRAFT
A P P E N D I X JSP.F
Glossary
action An element in a JSP page that can act on implicit objects and other
server-side objects or can define new scripting variables. Actions follow the
XML syntax for elements with a start tag, a body and an end tag; if the body is
empty it can also use the empty tag syntax. The tag must use a prefix.
action, standard An action that is defined in the JSP specification and is always
available to a JSP file without being imported.
action, custom An action described in a portable manner by a tag library descrip-
tor and a collection of Java classes and imported into a JSP page by a taglib
directive.
Application Assembler A person that combines JSP pages, servlet classes,
HTML content, tag libraries, and other Web content into a deployable Web
application.
component contract The contract between a component and its container,
including life cycle management of the component and the APIs and proto-
cols that the container must support.
Component Provider A vendor that provides a component either as Java classes
or as JSP page source.
distributed container A JSP container that can run a Web application that is
tagged as distributable and is spread across multiple Java virtual machines
that might be running on different hosts.
JSP page, frontA JSP page that receives an HTTP request directly from the cli-
ent. It creates, updates, and/or accesses some server-side data and then for-
wards the request to a presentation JSP page.
JSP page, presentation A JSP page that is intended for presentation purposes
only. It accesses and/or updates some server-side data and incorporates fixed
template data to create content that is sent to the client.
PUBLIC DRAFT
3-56
JSP page implementation class The Java programming language class, a Servlet,
that is the runtime representation of a JSP page and which receives the request
object and updates the response object. The page implementation class can
use the services provided by the JSP container, including both the Servlet and
the JSP APIs.
JSP page implementation object The instance of the JSP page implementation
class that receives the request object and updates the response object.
scripting element A declaration, scriptlet, or expression, whose tag syntax is
defined by the JSP specification, and whose content is written according to the
scripting language used in the JSP page. The JSP specification describes the
syntax and semantics for the case where the language page attribute is "java".
scriptlet An scripting element containing any code fragment that is valid in the
scripting language used in the JSP page. The JSP specification describes what
is a valid scriptlet for the case where the language page attribute is "java".
Syntactically a scriptlet is delimited by the <% and %> characters.
tag A piece of text between a left angle bracket and a right angle bracket that has
a name, can have attributes, and is part of an element in a JSP page. Tag
names are known to the JSP translator, either because the name is part of the
JSP specification (in the case of a standard action), or because it has been
introduced using a Tag Library (in the case of custom action).
tag handler A Java class that implements the Tag or the BodyTag interfaces and
that is the run-time representation of a custom action.
tag handler A JavaBean component that implements the Tag or BodyTag inter-
faces and is the run-time representation of a custom action.
tag library A collection of custom actions described by a tag library descriptor
and Java classes.
tag library descriptor An XML document describing a tag library.
Tag Library Provider A vendor that provides a tag library. Typical examples
may be a JSP container vendor, a development group within a corporation, a
component vendor, or a service vendor that wants to provide easier use of
their services.
web application An application built for the Internet, an intranet, or an extranet.
web application, distributable A Web application that is written so that it can be
deployed in a Web container distributed across multiple Java virtual machines
PUBLIC DRAFT
3-57
running on the same host or different hosts. The deployment descriptor for
such an application uses the distributable element.
Web Application Deployer A person who deploys a Web application in a Web
container, specifying at least the root prefix for the Web application, and in a
J2EE environment, the security and resource mappings.
web component A servlet class or JSP page that runs in a JSP container and pro-
vides services in response to requests.
Web Container Provider A vendor that provides a servlet and JSP container that
support the corresponding component contracts.
PUBLIC DRAFT