JavaServer Pages™ Specification V1.2
JavaServer Pages™ Specification V1.2
Specification
Version 1.2
please send comments to [email protected]
Version: 1.2
Status: FCS
Release: September 17, 2001
Copyright 2001 Sun Microsystems, Inc.
901 San Antonio Road, Palo Alto, California 94303, 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 Speci-
fication 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 Guidelines as set forth
in the Terms of Use on Sun’s website. 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.
Sun hereby grants you a fully-paid, non-exclusive, non-transferable, world-
wide, limited license (without the right to sublicense), under Sun’s intellectual
property rights that are essential to practice the Specification, to internally prac-
tice the Specification for the purpose of designing and developing your Java
applets and applications intended to run on the Java platform or creating a clean
room implementation of the Specification that: (i) includes a complete implemen-
tation of the current version of the Specification, without subsetting or superset-
ting; (ii) implements all of the interfaces and functionality of the Specification
without subsetting or supersetting; (iii) includes a complete implementation of
any optional components (as defined by the Specification) which you choose to
implement, without subsetting or supersetting; (iv) implements all of the inter-
faces and functionality of such optional components, without subsetting or super-
setting; (v) does not add any additional packages, classes or interfaces to the
"java.*" or "javax.*" packages or subpackages or other packages defined by the
Specification; (vi) satisfies all testing requirements available from Sun relating to
the most recently published version of the Specification six (6) months prior to
any release of the clean room implementation or upgrade thereto; (vii) does not
derive from any Sun source code or binary code materials; and (viii) does not
JSP 1.2
4
include any Sun source code or binary code materials without an appropriate and
separate license from Sun. The Specification contains the proprietary information
of Sun and may only be used in accordance with the license terms set forth herein.
This license will terminate immediately without notice from Sun if you fail to
comply with any provision of this license. Upon termination or expiration of this
license, 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 trade-
marks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other
countries.
DISCLAIMER OF WARRANTIES
THE SPECIFICATION IS PROVIDED "AS IS". SUN MAKES NO REPRE-
SENTATIONS OR WARRANTIES, EITHER EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANT-
ABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGE-
MENT 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 PAT-
ENTS, COPYRIGHTS, TRADE SECRETS OR OTHER RIGHTS. This docu-
ment does not represent any commitment to release or implement any portion of
the Specification in any product.
THE SPECIFICATION COULD INCLUDE TECHNICAL INACCURA-
CIES 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 SPECIFI-
CATION 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 Specifica-
tion.
LIMITATION OF LIABILITY
TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL
SUN OR ITS LICENSORS BE LIABLE FOR ANY DAMAGES, INCLUDING
JSP 1.2
5
REPORT
You may wish to report any ambiguities, inconsistencies or inaccuracies you
may find in connection with your use 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#95719/Form ID#011801)
JSP 1.2
6
JSP 1.2
Contents
Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
JSP.S.1 The Java Community Process . . . . . . . . . . . . . . . . . . . . . 15
JSP.S.2 The JCP and this Specification . . . . . . . . . . . . . . . . . . . . 15
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
JSP.P.1 Relation To JSP 1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
JSP.P.2 Licensing of Specification . . . . . . . . . . . . . . . . . . . . . . . 18
JSP.P.3 Who should read this document . . . . . . . . . . . . . . . . . . . 18
JSP.P.4 Related Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
JSP.P.5 Historical Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
JSP.P.6 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
JSP.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
JSP.1.1 The JavaServer Pages™ Technology . . . . . . . . . . . . . . . 23
JSP.1.1.1 General Concepts . . . . . . . . . . . . . . . . . . . . . . . . 23
JSP.1.1.2 Benefits of the JavaServer Pages Technology . . 24
JSP.1.2 Basic Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
JSP.1.2.1 What is a JSP Page? . . . . . . . . . . . . . . . . . . . . . . 25
JSP.1.2.2 Web Applications . . . . . . . . . . . . . . . . . . . . . . . 26
JSP.1.2.3 Components and Containers . . . . . . . . . . . . . . . 26
JSP.1.2.4 Translation and Execution Steps . . . . . . . . . . . . 27
JSP.1.2.5 Role in the Java 2 Platform, Enterprise Edition . 27
JSP.2 Core Syntax and Semantics . . . . . . . . . . . . . . . . . . . . . . . . 29
JSP.2.1 What is a JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
JSP.2.1.1 Web Containers and Web Components . . . . . . . 29
JSP.2.1.2 XML Document for a JSP Page . . . . . . . . . . . . . 30
JSP.2.1.3 Translation and Execution Phases . . . . . . . . . . . 30
JSP.2.1.4 Events in JSP Pages . . . . . . . . . . . . . . . . . . . . . . 30
JSP.2.1.5 Compiling JSP Pages . . . . . . . . . . . . . . . . . . . . . 31
JSP.2.1.5.1 JSP Page Packaging . . . . . . . . . . . . . . . . 31
JSP.2.1.6 Debugging JSP Pages . . . . . . . . . . . . . . . . . . . . 32
JSP.2.1.7 Naming Conventions for JSP Files . . . . . . . . . . 32
JSP.2.2 Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
JSP.2.2.1 Relative URL Specifications . . . . . . . . . . . . . . . 33
7
8
This is the JSP 1.2 specification, developed by the expert group JSR053 under
the Java Community Process (more details at http://jcp.org/jsr/detail/53.jsp).
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 1.2 and Servlet 2.3 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.
15
16
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.
JSP 1.2 extends JavaServer Pages™ 1.1 Specification (JSP 1.1) in the following
ways:
17
18
Details on the conditions under which this document is distributed are described
in the license on page 2.
Implementors of JSP containers and authors of JSP pages may find the follow-
ing documents worth consulting for additional information:
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.
JSP.P.6 Acknowledgments
Abamson, Nic Ferrier, Olli Blackburn, Paul Bonfanti, Peter Petersen, Petr Jiricka,
Pier Paolo Fumagalli, Pierre Delisle, Ramesh Mandava, Rod Magnuson, Sam
Pullara, Satoshi Kikuchi, Scott Ferguson, Scott Snyder, Simeon Simeonov,
Stephanie Bodoff, Stefano Mazzocchi, Tim Ampe, Tom Reilly, Vince Bonfanti.
We want to thank the community that implemented the reference
implementation, and the vendors that have implemented the spec, the authoring
tools, and the tag librarys.
Special mention is due to Scott Ferguson, Bob Foster, Stefano Mazzocchi and
Ricardo Rocha for their contributions to chapter 5. Bob Foster deserves credit for
for the DTD & XSchema, and the Cocoon community for Cocoon & XSP. Our
thanks to Jess Holle for insisting on the topics in Chapter JSP.3.
We want to thank all the authors of books on JSP, and the creators of the web
sites that are tracking and facilitating the creation of the JSP community.
The editor wants to give special thanks to many individuals within the Java
Platform Group, and especially to James, Jon, Mala, Jeff, Connie and Graham.
Lastly, we thank the software developers, web authors and members of the
general public who have read this specification, used the reference
implementation, and shared their experience. You are the reason the JavaServer
Pages technology exists.
• 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.
23
24 OVERVIEW
• Encapsulation of Functionality
JSP technology provides two related mechanisms for the encapsulation of
functionality: JavaBeans component architecture, and tag libraries.
• 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
natural division of labor.
A subset of the developer community may be engaged in developing reusable
components intended to be used by authors.
This section introduces basic concepts that will be defined formally later in the
specification.
paradigms for authoring dynamic content. The key features of JavaServer Pages
are:
• Standard directives
• Standard actions
• Scripting elements
• Tag Extension mechanism
• Template content
The JavaServer Pages specification inherits from the Servlet specification the
concepts of web applications, ServletContexts, sessions, requests and responses.
See the Java Servlet 2.3 specification for more details.
This chapter describes the core syntax and semantics for the JavaServer Pages
1.2 specification (JSP 1.2).
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.8
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.
29
30 CORE SYNTAX AND SEMANTICS
In JSP 1.2 only init and destroy events can be described in the JSP page.
When the first request is delivered to a JSP page, a jspInit() method, if present,
will be called to prepare the page. Similarly, a JSP container may invoke a JSP’s
jspDestroy() method to reclaim the resources used by the JSP page at any time
when a request is not being serviced. This is the same life-cycle as for servlets.
• 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.
1. A JSP page delivered in source form (probably the most common case).
1. 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.
• “.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.
Web applications are described in more detail in the Servlet 2.3 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
application. The deployment descriptor is described in detail in the Servlet 2.3
specification.
JSP 1.2 requires that these resources be implicitly associated with and
accessible through a unique ServletContext instance available as the implicit appli-
cation object (Section JSP.2.8).
The application to which a JSP page belongs is reflected in the application
object, and has impact on the semantics of the following elements:
A page relative path is a path that does not start with a “/”. It is to be
interpreted as relative to the current JSP page or the current JSP file depending on
where the path is being used: for an include directive (Section JSP.2.10.3) where
the path is used in a file attribute, the interpretation is relative to the JSP file; for an
jsp:include action (Section JSP.4.4) where the path is used in a page attribute, the
interpretation is relative to the JSP page. In both cases the current page (or file) is
denoted by some path starting with “/” that is then modified by the new
specification to produce a path starting with “/”. The new path is interpreted
through the ServletContext object. See Section JSP.2.10.4 for exact details on this
interpretation.
The JSP specification uniformly interprets paths in the context of the web
server where the JSP page is deployed. The specification goes through a mapping
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.
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.
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>
The result is
The next two tables show another example, with input and output.,
The result is
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.
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.2.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.
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 <\%
■
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.5.
the scripting language used (see Chapter JSP.6). Most details are not language spe-
cific and are described in this chapter.
The content of a JSP page is devoted largely to describing the data that is
written into the output stream of the response. (The JSP container usually sends
this data back to the client.) The description is based on a JspWriter object that is
exposed through the implicit object out (see Section JSP.2.8.3, “Implicit Objects).
Its value varies:
• 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.2.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.3.
• 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.
A JSP page can also describe what should happen when some specific events
occur. In JSP 1.2, 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.8.1.1.1).
JSP.2.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.
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.2.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.
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.
declared implicitly at the beginning of the page. All scripting languages are required
to provide access to these objects. Implicit objects are available to tag handlers
through the pageContext object, see below.
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.2-1.
Variable
Name Type Semantics & Scope
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.
See Section JSP.7.6.1 for some non-normative conventions for the
introduction of new implicit objects.
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.2.6, “Quoting and Escape Conventions.
JSP.2.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.5 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.
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 %>
Table JSP.2-1
Table JSP.2-1
Table JSP.2-1
Table JSP.2-1
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” prefix=”tagPrefix” %>
Table JSP.2-1
Table JSP.2-1
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.
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
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.
can also be used to do things like iterations and conditional execution of other
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.6.
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.5.2.
JSP.2.11.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
of initialization should be done with care in the presence of multiple requests
on the page. The third declaration declares a method global to the page.
Syntax
<%! declaration(s) %>
JSP.2.11.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.6).
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.
Syntax
<% scriptlet %>
JSP.2.11.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 %>
JSP.2.12 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 4.
New actions are defined according to the mechanisms described in Chapters 7
and 10 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.2.13.2.
Many values are fixed ‘translation-time values’, but JSP 1.2 also provides a
mechanism for describing values that are computed at request time, the rules are
described in Section JSP.2.13.1.
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 4 have page translation-
time semantics, but the following attributes accept request-time attribute
expressions:
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.4.2 describes the mechanism used for
the setProperty standard action.
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
ftp://venera.isi.edu/in-notes/iana/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
63
64 LOCALIZATION ISSUES
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.
The default value for TYPE is “text/html” and the default value for the
character encoding is ISO-8859-1.
A registry of content type names is kept by IANA. See:
ftp://venera.isi.edu/in-notes/iana/assignments/media-types/media-types
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 encodings 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.
Dynamic setting of content type relies on an underlying invocation on
response.setContentType(). That method can be invoked as long as no content has
been been sent to the response stream. 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 pages 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.
This chapter describes the standard actions of JavaServer Pages 1.2 (JSP 1.2).
JSP.4.1 <jsp:useBean>
67
68 STANDARD ACTIONS
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.6
provides details for the case where the language attribute is ”java”.
<%
/*
* 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.4-1
Table JSP.4-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.
1. 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.
2. If the object is found, the variable’s value is initialized with a reference to the
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.
3. If the jsp:useBean element had a non-empty body it is ignored. This completes
the processing of this jsp:useBean action.
4. 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.
5. 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.
6. 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.
7. 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.
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.
Table JSP.4-1
JSP.4.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.2.13.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.2.13.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.2.13.2.3.
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 />
prop_expr ::=
property="*" |
property=”propertyName”|
property=”propertyName” param="parameterName"|
property=”propertyName” value=”propertyValue”
Table JSP.4-2
1.
See syntax for expression scriptlet “<%= ... %>”
Table JSP.4-2
JSP.4.3 <jsp:getProperty>
Examples
<jsp:getProperty name=”user” property=”name” />
Syntax
<jsp:getProperty name=”name” property=”propertyName” />
Table JSP.4-3
name The name of the object instance from which the property is
obtained.
property Names the property to get.
JSP.4.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.2-1 for a summary
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”/>
• 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.
Table JSP.4-4
JSP.4.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” />
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.4-5
JSP.4.6 <jsp:param>
JSP.4.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.
JSP.4.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>
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.4-1
Table JSP.4-1
JSP.4.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.4.7.
JSP.4.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.4.7.
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.
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 1.2 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).
81
82 JSP DOCUMENTS
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.
<jsp:root
xmlns:jsp=”http://java.sun.com/JSP/Page”
xmlns:prefix1=”URI-for-taglib1”
xmlns:prefix2=”URI-for-taglib2”... >
version="1.2">
JSP page
</jsp:root>
• jsp:useBean
• jsp:setProperty
• jsp:getProperty
• jsp:include
• jsp:forward
• jsp:param
• jsp:params
• jsp:plugin
• jsp:text
The semantics and constraints are as in Chapter JSP.4, and the interpretation
of the scripting elements is as in Chapter JSP.6. 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.
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.5.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.
• Convert declarations, scriptlets and expressions into valid XML elements as
described in Section JSP.5.2.2 and following sections.
• Convert request-time attribute expressions as in Section JSP.5.3.11.
• Convert JSP quotations to XML quotations.
<%@ page ... %> <jsp:directive.page ... />. Optionally add jsp:id
In more detail:
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.5.3.7 Declarations
Declarations are translated into a jsp:declaration element. For example, the sec-
ond example from Section JSP.2.11.1:
JSP.5.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.5.3.9 Expressions
In the XML document corresponding to JSP pages, directives are represented
using the jsp:expression element:
In a JSP container that supports the jsp:id attribute, 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 10 for more details.
JSP.5.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.
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
<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="1.2">
<mytags:iterator count="4">
<foo> </foo>
</mytags:iterator>
</jsp:root>
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.
93
94 SCRIPTING
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 {
(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.2.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:
JSP.6.4.2 Scriptlets
A scriptlet is transformed into its code fragment.:
JSP.6.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.6.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.
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 variabl
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.10.
JSP.7.1 Introduction
97
98 TAG EXTENSIONS
A Tab 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
the XML syntax.
The first step is to parse the JSP page. The page that is parsed is as expanded
by the processing of include directives. Information in the TLD is used in this
step, including the identification of custom tags, so there is some processing
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.
• 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 opportu-
nity to process the buffer before the first evaluation of the body into the buffer.
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 has 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, Itera-
tionTag or BodyTag .
This type of action can be implemented with a tag handler that implements the
Tag interface. The tag handler needs to use only the doStartTag() method which
is invoked when the start tag is encountered. It can access the attributes of the tag
and information about the state of the JSP page. The information is passed to the
Tag object through setter method calls, prior to the call to doStartTag().
Since simple actions with empty tag bodies are common, the Tag Library
Descriptor can be used to indicate that the tag is always intended to be empty.
This indication leads to better error checking at translation time, and to better code
quality in the JSP page implementation class.
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.
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.
It is a fatal translation error for the taglib directive to appear after actions
using the prefix introduced by it.
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.
<taglib>
The taglib element provides 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:
<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.2.2.1. There should be no entries in
web.xml with the same taglib-uri value.
<taglib-location>
A taglib-location contains the location (as a resource) of the Tag Library
Description File for the tag library.
• 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.
These implicit map entries correspond to libraries that are known to the
container, who is responsible for providing their implementation, either through
tag handlers, or via the mechanism described in Section JSP.7.3.9.
• 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.
<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:
indirectly those indicated through the use of the class-path attribute in the META-
INF/MANIFEST file of these JAR files.
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"
>
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
<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>
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
<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
automatically.
<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.3 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:
<!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:
tagdependent The body of the action is passed verbatim to be interpreted by the
tag handler itself, and is most likely in a different “language”, e.g.
embedded SQL statements. The body of the action may be empty.
No quoting is performed.
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:
<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:
<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:
<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.
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.
JSP.7.5 Validation
There are a number of reasons why the structure of a JSP page should conform
to some validation rules:
This chapter describes the contracts between a JSP container and a JSP page.
The precompilation protocol (see Section JSP.8.4) is also presented here.
The information in this chapter is independent of the Scripting Language used
in the JSP page. Chapter JSP.6 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.
123
124 JSP CONTAINER
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.2.8.3.
The involved contracts are shown in Figure J2EE.8.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 emprove performance, for example.
The JSP page implementation class will implement Servlet and the Servlet
protocol will be used to deliver requests to the class.
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.
In the following code examples, Code Example 8.1 illustrates a generic HTTP
superclass named ExampleHttpSuper. Code Example 8.2 shows a subclass named
_jsp1344 that extends ExampleHttpSuper and is the class generated from the JSP
page. By using separate _jsp1344 and ExampleHttpSuper classes, the JSP page
translator does not need to discover whether the JSP page includes a declaration
with jspInit() or jspDestroy(). This significantly simplifies the implementation.
Code Example 8.1 A Generic HTTP Superclass
imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;
/**
* An example of a superclass for an HTTP JSP class
*/
/**
* The entry point into service.
*/
_jspService(request, resonse);
/**
* abstract method to be provided by the JSP processor in the subclass
* Must be defined in subclass.
*/
Code Example 8.2 The Java Class Generated From a JSP Page
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)
*/
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.8.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:
import javax.servlet.jsp.JspWriter;
JSP.8.4 Precompilation
A JSP page that is using the HTTP protocol will receive HTTP requests. JSP
1.2 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).
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).
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.9.1.1 JspPage
Syntax
public interface JspPage extends javax.servlet.Servlet
135
136 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.9.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.
JSP.9.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.9.1.2.2 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
JSP.9.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.9.1.3.3 Constructors
public JspFactory()
JSP.9.1.3.4 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.
JSP.9.1.4 JspEngineInfo
Syntax
public abstract class JspEngineInfo
Description
The JspEngineInfo is an abstract class that provides information on the current
JSP engine.
JSP.9.1.4.5 Constructors
public JspEngineInfo()
JSP.9.1.4.6 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.9.2.1 PageContext
Syntax
public abstract class PageContext
Description
A PageContext instance provides access to all the namespaces associated with a
JSP page, provides access to several page attributes, as well as a layer above the
implementation details. Implicit objects are added the pageContext automatically.
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 following methods provide support for forwarding, inclusion and error
handling: forward(), include(), and handlePageException().
JSP.9.2.1.7 Fields
public static final java.lang.String APPLICATION
Name used to store ServletContext in PageContext name table.
public static final int APPLICATION_SCOPE
JSP.9.2.1.8 Constructors
public PageContext()
JSP.9.2.1.9 Methods
public abstract java.lang.Object findAttribute(java.lang.String name)
Searches for the named attribute in page, request, session (if valid), and
application scope(s) in order and returns the value associated or null.
Returns: the value associated or null
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
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.Object getAttribute(java.lang.String name)
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
any output to the client, or to modify any ServletResponse state after invok-
ing this call.
Parameters:
t - the throwable to be handled
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.
JSP.9.2.2 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.
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
JSP.9.2.2.10 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.9.2.2.11 Constructors
protected JspWriter(int bufferSize, boolean autoFlush)
protected constructor.
JSP.9.2.2.12 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()
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()
Throws:
java.io.IOException
See Also: java.lang.Object.toString()
public abstract void print(java.lang.String s)
Print a string. If the argument is null then the string “null” is printed. Other-
wise, the string’s characters are converted 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:
s - The String to be printed
Throws:
java.io.IOException
public abstract void println()
Terminate the current line by writing the line separator string. The line sepa-
rator string is defined by the system property line.separator, and is not neces-
sarily a single newline character (’\n’).
Throws:
java.io.IOException
public abstract void println(boolean x)
Print a boolean value and then terminate the line. This method behaves as
though it invokes public abstract void print(boolean b) and then public abstract
void println() .
Throws:
java.io.IOException
public abstract void println(char x)
Print a character and then terminate the line. This method behaves as though
it invokes public abstract void print(char c) and then public abstract void
println() .
Throws:
java.io.IOException
public abstract void println(char[] x)
Print an array of characters and then terminate the line. This method behaves
as though it invokes print(char[]) and then println().
Throws:
java.io.IOException
public abstract void println(double x)
JSP.9.4 Exceptions
The JspException class is the base class for all JSP exceptions. The JspTag-
Exception is used by the tag extension mechanism.
JSP.9.4.1 JspException
Syntax
public class JspException extends java.lang.Exception
Description
A generic exception known to the JSP engine; uncaught JspExceptions will result
in an invocation of the errorpage machinery.
JSP.9.4.1.13 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.9.4.1.14 Methods
public java.lang.Throwable getRootCause()
Returns the exception that caused this JSP exception.
Returns: the Throwable that caused this JSP exception
JSP.9.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.9.4.2.15 Constructors
public JspTagException()
No message
public JspTagException(java.lang.String msg)
Constructor with a message.
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.
159
160 TAG EXTENSION API
This section introduces the notion of a tag handler and describes the simplest
types of tag handler.
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).
All properties of a tag handler instance exposed as attributes will be initialized
by the container using the appropriate setter methods before the instance can be
used to perform the action methods. It is the responsibility of the JSP container to
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.
cate that a tag can only be used to write empty actions; when used, non-empty
actions using that tag will produce a translation error.
A non-empty action has a body.
JSP.10.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
handler 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).
•Check the TryCatchFinally interface for additional details related to excep-
tion handling and resource management.
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()
method must return SKIP_BODY. Otherwise, the doStartTag() method may
return SKIP_BODY or EVAL_BODY_INCLUDE.
If SKIP_BODY is returned the body, if present, is not evaluated.
JSP.10.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.10.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 and the request is completed. If this request was forwarded or included
from another page (or Servlet), only the current page evaluation is completed.
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.
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.
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.10.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.
Properties There are no new properties in addition to those in Tag.
Methods There is one new methods: doAfterBody().
Lifecycle
Lifecycle details are described by the transition diagram below. Exceptions that
are thrown during the computation of doStartTag(), BODY and doAfterBody()
interrupt the execution sequence and are propagated up the stack, unless the tag
handler implements the TryCatchFinally interface; see that interface for details.
JSP.10.1.2.3 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.10.1.2.4 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
doAfterBody 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.10.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.
JSP.10.1.3.5 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
occurred in the BODY of the tag, or in any of the following methods:
JSP.10.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.10.1.4.6 Fields
protected java.lang.String id
protected PageContext pageContext
JSP.10.1.4.7 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.
JSP.10.1.4.8 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
indicating the observable type of a tag handler: its tag handler implementa-
tion 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.
JSP.10.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.10.2.1.9 Constructors
protected BodyContent(JspWriter e)
Protected constructor. Unbounded buffer, no autoflushing.
JSP.10.2.1.10 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:
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.10.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.
If the TagLibraryDescriptor file indicates that the action must always have an
empty action, by an <body-content> entry of “empty”, then the doStartTag()
method must return SKIP_BODY. Otherwise, the doStartTag() method may
return SKIP_BODY, EVAL_BODY_INCLUDE, or EVAL_BODY_BUFFERED.
If SKIP_BODY is returned the body is not evaluated, and doEndTag() is invoked.
JSP.10.2.2.11 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.10.2.2.12 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
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.10.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.10.2.3.13 Fields
protected BodyContent bodyContent
JSP.10.2.3.14 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.10.2.3.15 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
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
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.
// 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) {
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.
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-
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.
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.
The second substep is to perform the actual validation. This is done by
invoking the validate() method with a prefix, uri, and PageData that correspond to
the taglib directive instance being validated and the PageData representing the
page.
The last substep is to invoke the release() method on the validator tag when it
is no longer needed. This method releases all resources.
Finally, after checking all the tag library validator classes, the TagExtraInfo
classes for all tags will be consulted by invoking their isValid method. The order of
invocation of this methods is undefined.
JSP.10.5.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.10.5.1.16 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.10.5.1.17 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
uri - the URI actually used by the taglib directive
JSP.10.5.1.18 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.10.5.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.
JSP.10.5.2.19 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.10.5.2.20 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-
JSP.10.5.2.21 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
JSP.10.5.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.10.5.3.22 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.10.5.3.23 Constructors
public TagAttributeInfo(java.lang.String name, boolean required,
java.lang.String type, boolean reqTime)
JSP.10.5.3.24 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
JSP.10.5.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.10.5.4.25 Constructors
public PageData()
JSP.10.5.4.26 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.10.5.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
JSP.10.5.5.27 Constructors
public TagLibraryValidator()
JSP.10.5.5.28 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
JSP.10.5.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.10.5.6.29 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.10.5.6.30 Methods
public java.lang.String getId()
JSP.10.5.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.10.5.7.31 Constructors
public TagExtraInfo()
JSP.10.5.7.32 Methods
public final TagInfo getTagInfo()
Get the TagInfo for this class.
Returns: the taginfo instance this instance is extending
public VariableInfo[] getVariableInfo(TagData data)
JSP.10.5.8 TagData
Syntax
public class TagData implements java.lang.Cloneable
Description
The (translation-time only) attribute/value information for a tag instance.
JSP.10.5.8.33 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).
JSP.10.5.8.34 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.10.5.8.35 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.
Parameters:
attName - the name of the attribute
value - the value.
JSP.10.5.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 man-
ner makes the usage relatively resistant to configuration errors.
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.
JavaServer Pages 1.2 Specification
Translation-time Classes 203
JSP.10.5.9.36 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.10.5.9.37 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.10.5.9.38 Methods
public java.lang.String getClassName()
public boolean getDeclare()
public int getScope()
public java.lang.String getVarName()
JSP.10.5.10 TagVariableInfo
Syntax
public class TagVariableInfo
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.10.5.10.39 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.10.5.10.40 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
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.3 and JSP
1.2 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.3 capabilities than to the JSP 1.2 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:
207
208 PACKAGING JSP PAGES
<!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 Serv-
let 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 1.2
and Servlet 2.3 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() {
// ...
}
{
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:
<!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.
T his appendix includes the DTD and XSchema for JSP pages in XML syntax.
This appendix is non-normative.
As indicated in Section JSP.5.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.
-->
207
208
<!-- used for object, applet, img, input and iframe -->
<!ENTITY % ImgAlign “(top|middle|bottom|left|right)”>
<!ENTITY % Actions
“jsp:useBean
|jsp:setProperty
|jsp:getProperty
|jsp:include
|jsp:forward
|jsp:plugin”
>
<!-- the jsp:directive.include element only appears in JSP documents and does
not appear in XML views of JSP pages -->
<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.
<!--
There should be a constraint for jsp:id to be unique within all elements
in the document.
-->
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&Length;"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:simpleType>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/JSP/Page xsd-file-location"
<xsd:annotation>
<xsd:documentation>
Verbatim template text.
</xsd:documentation>
</xsd:annotation>
</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>
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>
</xsd:schema>
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
(taglib.tld) file in the META-INF subdirectory, along with the appropriate imple-
mentation classes and other resources required to implement the actions defined
therein.
Use is subject to license terms.
-->
225
226 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2
<!--
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
-->
<!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.
-->
<!--
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.
-->
<!--
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:
-->
<!--
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.
<!--
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:
-->
<!--
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.
This element is optional and is the default is true.
-->
<!--
The value of the scope element describes the scope of the scripting variable.
<!--
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.
<!--
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.
-->
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:
237
238
<!--
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.
<!--
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.
<!--
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.
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
-->
This appendix lists the changes in the JavaServer Pages specification. This
appendix is non-normative.
This is the final version approved by JCP Executive Comittee; the document
was updated to reflect that status. All change bars were reset.
243
244
could only return SKIP_BODY; the correct statement is that tags whose body-
content is "empty" can only return SKIP_BODY.
• 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.
Change bars are used in almost all chapters to indicate changes between PFD 1b
and PFD 2. The exception are Chapters 9 and 10 which are generated automatically
from the Java sources and have no change bars. Most changes are semantical, but
some of them are editorial.
• 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.4.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>.
• Resolved a conflict in Section JSP.4.4 between the Servlet and the JSP speci-
fication 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.4.1 Deletions
E.4.2 Additions
E.4.3 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.4.4 Changes
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.
E.5.4 Clarifications
E.5.5 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 speci-
fication.
E.6.1 Additions
E.6.2 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".
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.
249
250
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.
JSP page implementation class The Java programming language class, a Serv-
let, 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.