Sei sulla pagina 1di 374

PUBLIC DRAFT

JavaServer Pages™
Specification
Version2.0
(originally1.3)

please send comments to jsp-spec-comments@eng.sun.com

f t
D ra
b l ic
P u
Tuesday, June 18, 2002
Mark Roth
Eduardo Pelegrí-Llopart

4150 Network Circle


Santa Clara, CA 95054, USA
650 960-1300 fax: 650 969-9131
iii

Java ServerPagesTM Specification (“Specification”)

Version: 2.0
Status: Pre-FCS
Release: June 18, 2002
Copyright 2002 Sun Microsystems, Inc.
4150 Network Circle, Santa Clara, California 95054, U.S.A
All rights reserved.

NOTICE
The Specification is protected by copyright and the information described
therein may be protected by one or more U.S. patents, foreign patents, or pending
applications. Except as provided under the following license, no part of the
Specification may be reproduced in any form by any means without the prior
written authorization of Sun Microsystems, Inc. (“Sun”) and its licensors, if any.
Any use of the Specification and the information described therein will be
governed by the terms and conditions of this license and the Export Control and
General Terms as set forth in Sun’s website Legal Terms. By viewing,
downloading or otherwise copying the Specification, you agree that you have
read, understood, and will comply with all of the terms and conditions set forth
herein.
Subject to the terms and conditions of this license, Sun hereby grants you a
fully-paid, non-exclusive, non-transferable, worldwide, limited license (without
the right to sublicense) under Sun’s intellectual property rights to review the
Specification internally for the purposes of evaluation only. Other than this limited
license, you acquire no right, title or interest in or to the Specification or any other
Sun intellectual property. The Specification contains the proprietary and
confidential information of Sun and may only be used in accordance with the
license terms set forth herein. This license will expire ninety (90) days from the
date of Release listed above and will terminate immediately without notice from
Sun if you fail to comply with any provision of this license. Upon termination,
you must cease use of or destroy the Specification.

TRADEMARKS
No right, title, or interest in or to any trademarks, service marks, or trade
names of Sun or Sun’s licensors is granted hereunder. Sun, Sun Microsystems, the
Sun logo, Java, the Java Coffee Cup logo, JSP, and JavaServer Pages are

PUBLIC DRAFT
iv

trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and


other countries.

DISCLAIMER OF WARRANTIES
THE SPECIFICATION IS PROVIDED “AS IS” AND IS EXPERIMENTAL
AND MAY CONTAIN DEFECTS OR DEFICIENCIES WHICH CANNOT OR
WILL NOT BE CORRECTED BY SUN. SUN MAKES NO
REPRESENTATIONS OR WARRANTIES, EITHER EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO, WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-
INFRINGEMENT THAT THE CONTENTS OF THE SPECIFICATION ARE
SUITABLE FOR ANY PURPOSE OR THAT ANY PRACTICE OR
IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY
THIRD PARTY PATENTS, COPYRIGHTS, TRADE SECRETS OR OTHER
RIGHTS. This document does not represent any commitment to release or
implement any portion of the Specification in any product.
THE SPECIFICATION COULD INCLUDE TECHNICAL
INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE
PERIODICALLY ADDED TO THE INFORMATION THEREIN; THESE
CHANGES WILL BE INCORPORATED INTO NEW VERSIONS OF THE
SPECIFICATION, IF ANY. SUN MAY MAKE IMPROVEMENTS AND/OR
CHANGES TO THE PRODUCT(S) AND/OR THE PROGRAM(S)
DESCRIBED IN THE SPECIFICATION AT ANY TIME. Any use of such
changes in the Specification will be governed by the then-current license for the
applicable version of the Specification.

LIMITATION OF LIABILITY
TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL
SUN OR ITS LICENSORS BE LIABLE FOR ANY DAMAGES, INCLUDING
WITHOUT LIMITATION, LOST REVENUE, PROFITS OR DATA, OR FOR
SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
OF LIABILITY, ARISING OUT OF OR RELATED TO ANY FURNISHING,
PRACTICING, MODIFYING OR ANY USE OF THE SPECIFICATION, EVEN
IF SUN AND/OR ITS LICENSORS HAVE BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
You will indemnify, hold harmless, and defend Sun and its licensors from any
claims based on your use of the Specification for any purposes other than those of

PUBLIC DRAFT
v

internal evaluation, and from any claims that later versions or releases of any
Specification furnished to you are incompatible with the Specification provided to
you under this license.

RESTRICTED RIGHTS LEGEND


If this Software is being acquired by or on behalf of the U.S. Government or
by a U.S. Government prime contractor or subcontractor (at any tier), then the
Government’s rights in the Software and accompanying documentation shall be
only as set forth in this license; this is in accordance with 48 C.F.R. 227.7201
through 227.7202-4 (for Department of Defense (DoD) acquisitions) and with 48
C.F.R. 2.101 and 12.212 (for non-DoD acquisitions).

REPORT
You may wish to report any ambiguities, inconsistencies or inaccuracies you
may find in connection with your evaluation of the Specification (“Feedback”). To
the extent that you provide Sun with any Feedback, you hereby: (i) agree that such
Feedback is provided on a non-proprietary and non-confidential basis, and (ii)
grant Sun a perpetual, non-exclusive, worldwide, fully paid-up, irrevocable
license, with the right to sublicense through multiple levels of sublicensees, to
incorporate, disclose, and use without limitation the Feedback for any purpose
related to the Specification and future versions, implementations, and test suites
thereof.
LFI#113874/Form ID#01180

PUBLIC DRAFT
vi

PUBLIC DRAFT
Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
The JavaServer Pages™ Technology . . . . . . . . . . . . . . . . . . . . . . xxv
Basic Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxviii
Users of JavaServer Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxx

PART I. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1
JSP.1 Core Syntax and Semantics . . . . . . . . . . . . . . . . . . . . . . . 1-2
JSP.1.1 What is a JSP Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
JSP.1.1.1 Web Containers and Web Components . . . . . . 1-2
JSP.1.1.2 XML Document for a JSP Page . . . . . . . . . . . . 1-3
JSP.1.1.3 Translation and Execution Phases . . . . . . . . . . 1-3
JSP.1.1.4 Events in JSP Pages . . . . . . . . . . . . . . . . . . . . . 1-4
JSP.1.1.5 JSP Configuration Information . . . . . . . . . . . . 1-4
JSP.1.1.6 Naming Conventions for JSP Files . . . . . . . . . 1-4
JSP.1.1.7 Compiling JSP Pages . . . . . . . . . . . . . . . . . . . . 1-5
JSP.1.1.8 Debugging JSP Pages . . . . . . . . . . . . . . . . . . . 1-6
JSP.1.2 Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
JSP.1.2.1 Relative URL Specifications . . . . . . . . . . . . . . 1-7
JSP.1.3 Syntactic Elements of a JSP Page . . . . . . . . . . . . . . . . . 1-8
JSP.1.3.1 Elements and Template Data . . . . . . . . . . . . . . 1-8
JSP.1.3.2 Element Syntax . . . . . . . . . . . . . . . . . . . . . . . . 1-8
JSP.1.3.3 Start and End Tags . . . . . . . . . . . . . . . . . . . . . . 1-9
JSP.1.3.4 Empty Elements . . . . . . . . . . . . . . . . . . . . . . . . 1-9
JSP.1.3.5 Attribute Values Using XML Attributes . . . . 1-10
JSP.1.3.6 Attribute Values Using XML Elements . . . . . 1-10
JSP.1.3.7 Valid Names for Actions and Attributes . . . . 1-11
JSP.1.3.8 White Space . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
JSP.1.3.9 Standard JSP Syntax Grammar . . . . . . . . . . . 1-13
JSP.1.4 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-25
JSP.1.4.1 Translation Time Processing Errors . . . . . . . . 1-25
JSP.1.4.2 Request Time Processing Errors . . . . . . . . . . 1-25

PUBLIC DRAFT vii


viii

JSP.1.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-26


JSP.1.5.1 Generating Comments in Output to Client . . . 1-26
JSP.1.5.2 JSP Comments . . . . . . . . . . . . . . . . . . . . . . . . 1-26
JSP.1.6 Quoting and Escape Conventions . . . . . . . . . . . . . . . . 1-27
JSP.1.7 Overall Semantics of a JSP Page . . . . . . . . . . . . . . . . . 1-29
JSP.1.8 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30
JSP.1.8.1 Objects and Variables . . . . . . . . . . . . . . . . . . . 1-30
JSP.1.8.2 Objects and Scopes . . . . . . . . . . . . . . . . . . . . . 1-30
JSP.1.8.3 Implicit Objects . . . . . . . . . . . . . . . . . . . . . . . . 1-32
JSP.1.8.4 The pageContext Object . . . . . . . . . . . . . . . . . 1-34
JSP.1.9 Template Text Semantics . . . . . . . . . . . . . . . . . . . . . . . 1-34
JSP.1.10 Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-34
JSP.1.10.1 The page Directive . . . . . . . . . . . . . . . . . . . . . 1-34
JSP.1.10.2 Page property: isScriptingEnabled . . . . . . . . . . . 1-36
JSP.1.10.3 Page property: isELEnabled . . . . . . . . . . . . . . . 1-36
JSP.1.10.4 The taglib Directive . . . . . . . . . . . . . . . . . . . . 1-41
JSP.1.10.5 The include Directive . . . . . . . . . . . . . . . . . . . 1-42
JSP.1.10.6 Implicit Includes . . . . . . . . . . . . . . . . . . . . . . . 1-43
JSP.1.10.7 Including Data in JSP Pages . . . . . . . . . . . . . . 1-43
JSP.1.10.8 Additional Directives for Tag Files . . . . . . . . 1-44
JSP.1.11 EL Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-44
JSP.1.12 Scripting Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-44
JSP.1.12.1 Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . 1-45
JSP.1.12.2 Scriptlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-46
JSP.1.12.3 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-47
JSP.1.13 Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-48
JSP.1.14 Tag Attribute Interpretation Semantics . . . . . . . . . . . . 1-48
JSP.1.14.1 Request Time Attribute Values . . . . . . . . . . . . 1-48
JSP.1.14.2 Type Conversions . . . . . . . . . . . . . . . . . . . . . . 1-49
JSP.2 Expression Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-51
JSP.2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-51
JSP.2.2 Expressions and Attribute Values . . . . . . . . . . . . . . . . 1-52
JSP.2.2.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-53
JSP.2.3 Expressions and Template Text . . . . . . . . . . . . . . . . . . 1-53
JSP.2.3.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-53
JSP.2.4 Deactivating EL Evaluation . . . . . . . . . . . . . . . . . . . . . 1-54
JSP.2.5 Desabling Scripting Elements . . . . . . . . . . . . . . . . . . . 1-54
JSP.2.6 General Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-55
JSP.2.6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-55

PUBLIC DRAFT
ix

JSP.2.6.2 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-55


JSP.2.6.3 Errors, Warnings, Default Values . . . . . . . . . 1-55
JSP.2.6.4 Operators "[]" and "." . . . . . . . . . . . . . . . . . . . 1-56
JSP.2.6.5 Arithmetic Operators . . . . . . . . . . . . . . . . . . . 1-57
JSP.2.6.6 Logical Operators . . . . . . . . . . . . . . . . . . . . . . 1-60
JSP.2.6.7 Empty Operator - empty A . . . . . . . . . . . . . . 1-60
JSP.2.6.8 Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-61
JSP.2.6.9 Operator Precedence . . . . . . . . . . . . . . . . . . . 1-61
JSP.2.7 Reserved Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-61
JSP.2.8 Named Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-61
JSP.2.9 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-62
JSP.2.9.1 Invocation Syntax . . . . . . . . . . . . . . . . . . . . . 1-62
JSP.2.9.2 Tag Library Descriptor Information . . . . . . . 1-63
JSP.2.9.3 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
JSP.2.9.4 Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
JSP.2.10 Implicit Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-65
JSP.2.11 Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-66
JSP.2.11.1 Coerce A to String . . . . . . . . . . . . . . . . . . . . . 1-66
JSP.2.11.2 Coerce A to primitive Number type N . . . . . . 1-67
JSP.2.11.3 Coerce A to Character . . . . . . . . . . . . . . . . . . 1-67
JSP.2.11.4 Coerce A to Boolean . . . . . . . . . . . . . . . . . . . 1-68
JSP.2.11.5 Coerce A to any other type T . . . . . . . . . . . . . 1-68
JSP.2.12 API to Expression Evaluator . . . . . . . . . . . . . . . . . . . . 1-68
JSP.2.12.1 ExpressionEvaluator Interface . . . . . . . . . . . . 1-69
JSP.2.12.2 VariableResolver Interface . . . . . . . . . . . . . . 1-69
JSP.2.12.3 Constructor Classes and Other Types . . . . . . 1-70
JSP.2.13 Collected Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-70
JSP.3 JSP Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-74
JSP.3.1 JSP configuration information in web.xml . . . . . . . . . 1-74
JSP.3.1.1 <jsp-config> . . . . . . . . . . . . . . . . . . . . . . . . . . 1-74
JSP.3.2 Taglib map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-75
JSP.3.2.1 <taglib> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-75
JSP.3.2.2 <taglib-uri> . . . . . . . . . . . . . . . . . . . . . . . . . . 1-75
JSP.3.2.3 <taglib-location> . . . . . . . . . . . . . . . . . . . . . . 1-75
JSP.3.3 JSP Property Groups . . . . . . . . . . . . . . . . . . . . . . . . . . 1-76
JSP.3.3.1 <jsp-property-group> . . . . . . . . . . . . . . . . . . . 1-76
JSP.3.3.2 Enabling EL Evaluation . . . . . . . . . . . . . . . . . 1-77
JSP.3.3.3 Enabling Scripting . . . . . . . . . . . . . . . . . . . . . 1-77
JSP.3.3.4 Declaring Page Encodings . . . . . . . . . . . . . . . 1-78

PUBLIC DRAFT
x

JSP.3.3.5 Defining Implicit Includes . . . . . . . . . . . . . . . 1-78


JSP.4 Localization Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-80
JSP.4.1 Page Character Encoding . . . . . . . . . . . . . . . . . . . . . . . 1-80
JSP.4.2 Static Content Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-82
JSP.4.3 Dynamic Content Type and Character Encoding . . . . 1-82
JSP.4.4 Delivering Localized Content . . . . . . . . . . . . . . . . . . . 1-83
JSP.5 Standard Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-84
JSP.5.1 <jsp:useBean> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-84
JSP.5.2 <jsp:setProperty> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-91
JSP.5.3 <jsp:getProperty> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-93
JSP.5.4 <jsp:include> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-94
JSP.5.5 <jsp:forward> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-96
JSP.5.6 <jsp:param> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-97
JSP.5.6.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-97
JSP.5.7 <jsp:plugin> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-98
JSP.5.8 <jsp:params> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-100
JSP.5.9 <jsp:fallback> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-100
JSP.5.10 <jsp:attribute> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-100
JSP.5.11 <jsp:body> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-101
JSP.5.12 Additional Standard Actions . . . . . . . . . . . . . . . . . . . 1-102
JSP.6 JSP Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-103
JSP.6.1 Uses for XML Syntax for JSP Pages . . . . . . . . . . . . . 1-103
JSP.6.2 JSP Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-104
JSP.6.2.1 Semantic Model . . . . . . . . . . . . . . . . . . . . . . 1-105
JSP.6.2.2 The jsp:root element . . . . . . . . . . . . . . . . . . . 1-105
JSP.6.2.3 The jsp:directive.page element . . . . . . . . . . . 1-106
JSP.6.2.4 The jsp:directive.include element . . . . . . . . . 1-106
JSP.6.2.5 The jsp:declaration element . . . . . . . . . . . . . 1-106
JSP.6.2.6 The jsp:scriptlet element . . . . . . . . . . . . . . . . 1-107
JSP.6.2.7 The jsp:expression element . . . . . . . . . . . . . . 1-107
JSP.6.2.8 Standard and custom action elements . . . . . . 1-107
JSP.6.2.9 Request-Time Attributes . . . . . . . . . . . . . . . . 1-108
JSP.6.2.10 The jsp:text element . . . . . . . . . . . . . . . . . . . 1-108
JSP.6.2.11 Other XML elements . . . . . . . . . . . . . . . . . . 1-108
JSP.6.3 XML View of a JSP Page . . . . . . . . . . . . . . . . . . . . . 1-109
JSP.6.3.1 JSP Documents . . . . . . . . . . . . . . . . . . . . . . . 1-109
JSP.6.3.2 JSP pages in JSP syntax . . . . . . . . . . . . . . . . 1-109
JSP.6.3.3 JSP comments . . . . . . . . . . . . . . . . . . . . . . . . 1-111
PUBLIC DRAFT
xi

JSP.6.3.4 The page directive . . . . . . . . . . . . . . . . . . . . 1-111


JSP.6.3.5 The taglib directive . . . . . . . . . . . . . . . . . . . 1-111
JSP.6.3.6 The include directive . . . . . . . . . . . . . . . . . . 1-111
JSP.6.3.7 Declarations . . . . . . . . . . . . . . . . . . . . . . . . . 1-111
JSP.6.3.8 Scriptlets . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-112
JSP.6.3.9 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 1-112
JSP.6.3.10 Standard and Custom Actions . . . . . . . . . . . 1-112
JSP.6.3.11 Request-Time Attribute Expressions . . . . . . 1-112
JSP.6.3.12 Template Text and XML Elements . . . . . . . 1-112
JSP.6.3.13 The jsp:id Attribute . . . . . . . . . . . . . . . . . . . 1-113
JSP.6.4 Validating an XML View of a JSP page . . . . . . . . . . 1-113
JSP.6.5 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-114
JSP.6.5.1 A JSP page and its corresponding JSP document 1-
114
JSP.6.5.2 A JSP document . . . . . . . . . . . . . . . . . . . . . . 1-115
JSP.7 Tag Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-116
JSP.7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-116
JSP.7.1.1 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-117
JSP.7.1.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-117
JSP.7.1.3 Simple Examples . . . . . . . . . . . . . . . . . . . . . 1-119
JSP.7.2 Tag Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-121
JSP.7.2.1 Packaged Tag Libraries . . . . . . . . . . . . . . . . 1-122
JSP.7.2.2 Location of Java Classes . . . . . . . . . . . . . . . 1-122
JSP.7.2.3 Tag Library directive . . . . . . . . . . . . . . . . . . 1-122
JSP.7.3 The Tag Library Descriptor . . . . . . . . . . . . . . . . . . . 1-123
JSP.7.3.1 Identifying Tag Library Descriptors . . . . . . 1-124
JSP.7.3.2 TLD resource path . . . . . . . . . . . . . . . . . . . . 1-124
JSP.7.3.3 Taglib map in web.xml . . . . . . . . . . . . . . . . 1-124
JSP.7.3.4 Implicit Map entries from TLDs . . . . . . . . . 1-124
JSP.7.3.5 Implicit Map entries from the Container . . . 1-125
JSP.7.3.6 Determining the TLD Resource Path . . . . . . 1-125
JSP.7.3.7 Translation-Time Class Loader . . . . . . . . . . 1-127
JSP.7.3.8 Assembling a Web Application . . . . . . . . . . 1-127
JSP.7.3.9 Well-Known URIs . . . . . . . . . . . . . . . . . . . . 1-127
JSP.7.4 The Tag Library Descriptor Format . . . . . . . . . . . . . 1-128
JSP.7.5 Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-137
JSP.7.5.1 Translation-Time Mechanisms . . . . . . . . . . 1-137
JSP.7.5.2 Request-Time Errors . . . . . . . . . . . . . . . . . . 1-138
JSP.7.6 Conventions and Other Issues . . . . . . . . . . . . . . . . . . 1-138

PUBLIC DRAFT
xii

JSP.7.6.1 How to Define New Implicit Objects . . . . . . 1-138


JSP.7.6.2 Access to Vendor-Specific information . . . . 1-139
JSP.7.6.3 Customizing a Tag Library . . . . . . . . . . . . . . 1-139
JSP.8 JSP Fragments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-141
JSP.8.1 Custom Action Invocation . . . . . . . . . . . . . . . . . . . . . 1-141
JSP.8.1.1 JSP Fragments . . . . . . . . . . . . . . . . . . . . . . . . 1-142
JSP.8.1.2 Attributes With Dynamic Names . . . . . . . . . 1-142
JSP.8.2 Simple Tag Extensions . . . . . . . . . . . . . . . . . . . . . . . 1-144
JSP.8.2.1 Genericness of SimpleTag Extensions . . . . . 1-145
JSP.8.2.2 Declaring Simple Tag Extensions in the TLD 1-145
JSP.8.2.3 The javax.servlet.jsp.tagext.SimpleTag Interface . . 1-
148
JSP.8.2.4 SimpleTag Collaboration . . . . . . . . . . . . . . . 1-148
JSP.8.2.5 Packaging Simple Tag Handlers . . . . . . . . . . 1-149
JSP.8.2.6 Lifecycle of Simple Tag Handlers . . . . . . . . 1-149
JSP.8.3 Defining and Invoking JSP Fragments . . . . . . . . . . . 1-151
JSP.8.3.1 The javax.servlet.jsp.tagext.JspFragment interface 1-
151
JSP.8.3.2 Writing JSP Fragments using JSP Syntax . . 1-152
JSP.8.3.3 The <jsp:invoke> Standard Action . . . . . . . . . 1-152
JSP.8.3.4 The <jsp:doBody> Standard Action . . . . . . . . 1-154
JSP.8.3.5 Lifecycle of JSP Fragments . . . . . . . . . . . . . 1-155
JSP.8.4 Tag Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-157
JSP.8.4.1 Syntax of Tag Files . . . . . . . . . . . . . . . . . . . . 1-158
JSP.8.4.2 Semantics of Tag Files . . . . . . . . . . . . . . . . . 1-158
JSP.8.4.3 Packaging Tag Files . . . . . . . . . . . . . . . . . . . 1-159
JSP.8.4.4 Tag File Directives . . . . . . . . . . . . . . . . . . . . 1-162
JSP.8.4.5 The tag Directive . . . . . . . . . . . . . . . . . . . . . . 1-162
JSP.8.4.6 The attribute Directive . . . . . . . . . . . . . . . . . 1-164
JSP.8.4.7 The variable Directive . . . . . . . . . . . . . . . . . . 1-166
JSP.8.4.8 The fragment-input Directive . . . . . . . . . . . . 1-167
JSP.8.4.9 XML View of a Tag File . . . . . . . . . . . . . . . 1-169
JSP.8.5 Example Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-170
JSP.8.5.1 Sample Source Files . . . . . . . . . . . . . . . . . . . 1-171
JSP.8.5.2 Sample Generated Files . . . . . . . . . . . . . . . . 1-172
JSP.9 Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-181
JSP.9.1 Overall Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-181
JSP.9.1.1 Valid JSP Page . . . . . . . . . . . . . . . . . . . . . . . 1-181

PUBLIC DRAFT
xiii

JSP.9.1.2 Reserved Names . . . . . . . . . . . . . . . . . . . . . . 1-182


JSP.9.1.3 Implementation Flexibility . . . . . . . . . . . . . 1-182
JSP.9.2 Declarations Section . . . . . . . . . . . . . . . . . . . . . . . . . 1-183
JSP.9.3 Initialization Section . . . . . . . . . . . . . . . . . . . . . . . . . 1-183
JSP.9.4 Main Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-183
JSP.9.4.1 Template Data . . . . . . . . . . . . . . . . . . . . . . . 1-183
JSP.9.4.2 Scriptlets . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-184
JSP.9.4.3 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 1-184
JSP.9.4.4 Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-184

PART II . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1
JSP.10 JSP Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
JSP.10.1 JSP Page Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
JSP.10.1.1 Protocol Seen by the Web Server . . . . . . . . . . 2-2
JSP.10.2 JSP Page Implementation Class . . . . . . . . . . . . . . . . . . 2-4
JSP.10.2.1 API Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
JSP.10.2.2 Request and Response Parameters . . . . . . . . . . 2-6
JSP.10.2.3 Omitting the extends Attribute . . . . . . . . . . . . . 2-6
JSP.10.2.4 Using the extends Attribute . . . . . . . . . . . . . . 2-10
JSP.10.3 Buffering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
JSP.10.4 Precompilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
JSP.10.4.1 Request Parameter Names . . . . . . . . . . . . . . . 2-11
JSP.10.4.2 Precompilation Protocol . . . . . . . . . . . . . . . . . 2-12
JSP.10.5 Debugging Requirements . . . . . . . . . . . . . . . . . . . . . . 2-12
JSP.11 Core API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
JSP.11.1 JSP Page Implementation Object Contract . . . . . . . . . 2-14
JSP.11.1.1 JspPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
JSP.11.1.2 HttpJspPage . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
JSP.11.1.3 JspFactory . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
JSP.11.1.4 JspEngineInfo . . . . . . . . . . . . . . . . . . . . . . . . 2-18
JSP.11.2 Implicit Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
JSP.11.2.1 JspContext . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
JSP.11.2.2 PageContext . . . . . . . . . . . . . . . . . . . . . . . . . . 2-23
JSP.11.2.3 JspWriter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-29
JSP.11.3 An Implementation Example . . . . . . . . . . . . . . . . . . . 2-37
JSP.11.4 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-37
JSP.11.4.1 JspException . . . . . . . . . . . . . . . . . . . . . . . . . 2-37
JSP.11.4.2 JspTagException . . . . . . . . . . . . . . . . . . . . . . 2-39

PUBLIC DRAFT
xiv

JSP.12 Tag Extension API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-41


JSP.12.1 Classic Tag Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . 2-42
JSP.12.1.1 Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-45
JSP.12.1.2 IterationTag . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-49
JSP.12.1.3 TryCatchFinally . . . . . . . . . . . . . . . . . . . . . . . 2-51
JSP.12.1.4 TagSupport . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-53
JSP.12.2 Tag Handlers that want Access to their Body Content 2-56
JSP.12.2.1 BodyContent . . . . . . . . . . . . . . . . . . . . . . . . . . 2-57
JSP.12.2.2 BodyTag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-58
JSP.12.2.3 BodyTagSupport . . . . . . . . . . . . . . . . . . . . . . . 2-62
JSP.12.3 Dynamic Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-64
JSP.12.3.1 DynamicAttributes . . . . . . . . . . . . . . . . . . . . . 2-64
JSP.12.3.2 AttributeNotSupportedException . . . . . . . . . . 2-64
JSP.12.4 Annotated Tag Handler Management Example . . . . . . 2-65
JSP.12.5 Cooperating Actions . . . . . . . . . . . . . . . . . . . . . . . . . . 2-68
JSP.12.6 Simple Tag Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . 2-69
JSP.12.6.1 SimpleTag . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-69
JSP.12.6.2 JspFragment . . . . . . . . . . . . . . . . . . . . . . . . . . 2-70
JSP.12.6.3 TagAdapter . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-71
JSP.12.7 Translation-time Classes . . . . . . . . . . . . . . . . . . . . . . . 2-73
JSP.12.7.1 TagLibraryInfo . . . . . . . . . . . . . . . . . . . . . . . . 2-75
JSP.12.7.2 TagInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-76
JSP.12.7.3 TagAttributeInfo . . . . . . . . . . . . . . . . . . . . . . . 2-80
JSP.12.7.4 PageData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-82
JSP.12.7.5 TagLibraryValidator . . . . . . . . . . . . . . . . . . . . 2-82
JSP.12.7.6 ValidationMessage . . . . . . . . . . . . . . . . . . . . . 2-84
JSP.12.7.7 TagExtraInfo . . . . . . . . . . . . . . . . . . . . . . . . . . 2-85
JSP.12.7.8 TagData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-86
JSP.12.7.9 VariableInfo . . . . . . . . . . . . . . . . . . . . . . . . . . 2-88
JSP.12.7.10 TagVariableInfo . . . . . . . . . . . . . . . . . . . . . . . 2-90
JSP.13 Expression Language API . . . . . . . . . . . . . . . . . . . . . . . . 2-94
JSP.13.1 Expression Evaluator . . . . . . . . . . . . . . . . . . . . . . . . . . 2-94
JSP.13.1.1 ExpressionEvaluator . . . . . . . . . . . . . . . . . . . . 2-94
JSP.13.1.2 VariableResolver . . . . . . . . . . . . . . . . . . . . . . . 2-95
JSP.13.2 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-96
JSP.13.2.1 ELException . . . . . . . . . . . . . . . . . . . . . . . . . . 2-96

PART III . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-1

PUBLIC DRAFT
xv

JSP.A Packaging JSP Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2


JSP.A.1 A very simple JSP page . . . . . . . . . . . . . . . . . . . . . . . . 3-2
JSP.A.2 The JSP page packaged as source in a WAR file . . . . . 3-2
JSP.A.3 The Servlet for the compiled JSP page . . . . . . . . . . . . . 3-3
JSP.A.4 The Web Application Descriptor . . . . . . . . . . . . . . . . . 3-4
JSP.A.5 The WAR for the compiled JSP page . . . . . . . . . . . . . . 3-5
JSP.B DTD and Schemas for XML Syntax . . . . . . . . . . . . . . . . 3-6
JSP.B.1 DTD for JSP documents . . . . . . . . . . . . . . . . . . . . . . . . 3-6
JSP.B.2 XSchema Description of JSP documents . . . . . . . . . . 3-11
JSP.C DTD for TagLibrary Descriptor, JSP 1.2 . . . . . . . . . . . 3-23
JSP.C.1 DTD for TagLibrary Descriptor Files . . . . . . . . . . . . . 3-23
JSP.D DTD for TagLibrary Descriptor, JSP 1.1 . . . . . . . . . . . 3-34
JSP.D.1 DTD for TagLibrary Descriptor Files . . . . . . . . . . . . . 3-34
JSP.E Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-39
JSP.E.1 Changes between JSP 2.0 CD2 and JSP 2.0 PD1 . . . . 3-39
JSP.E.2 Changes between JSP 2.0 CD1 and JSP 2.0 CD2 . . . . 3-39
E.2.1 Between CD2c and CD2 . . . . . . . . . . . . . . . . . 3-39
E.2.2 Between CD2b and CD2c . . . . . . . . . . . . . . . . 3-40
E.2.3 Between CD2a and CD2b . . . . . . . . . . . . . . . . 3-41
E.2.4 Changes between CD1 and CD2a . . . . . . . . . . 3-41
JSP.E.3 Changes between JSP 2.0 ED1 and JSP 2.0 CD1 . . . . 3-42
E.3.5 JSP Fragments, .tag Files, and Simple Tag Handlers
3-42
E.3.6 Expression Language Added . . . . . . . . . . . . . 3-42
E.3.7 EBNF Fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-42
E.3.8 I18N Clarifications . . . . . . . . . . . . . . . . . . . . . 3-42
E.3.9 Other Changes . . . . . . . . . . . . . . . . . . . . . . . . . 3-43
JSP.E.4 Changes Between JSP 1.2 Final Draft and JSP 2.0 ED1 3-
43
E.4.10 Typographical Fixes and Version Numbers . . 3-43
E.4.11 Added EBNF Grammar for JSP Standard Syntax 3-
43
E.4.12 Added Users of JavaServer Pages Section . . . 3-43
E.4.13 Added Placeholders for Expression Language and
Custom Actions Using JSP . . . . . . . . . . . . . . . 3-43
E.4.14 Added Requirement for Debugging Support . 3-44
PUBLIC DRAFT
xvi

JSP.E.5 Changes Between PFD 2 and Final Draft . . . . . . . . . . 3-44


E.5.15 Added jsp:id mechanism . . . . . . . . . . . . . . . . . 3-44
E.5.16 Other Small Changes . . . . . . . . . . . . . . . . . . . . 3-44
E.5.17 Clarification of role of id . . . . . . . . . . . . . . . . . 3-44
E.5.18 Clarifications on Multiple Requests and Threading
3-45
E.5.19 Clarifications on JSP Documents . . . . . . . . . . . 3-45
E.5.20 Clarifications on Well Known Tag Libraries . . 3-45
E.5.21 Clarified Impact of Blocks . . . . . . . . . . . . . . . . 3-46
E.5.22 Other Small Clarifications . . . . . . . . . . . . . . . . 3-46
JSP.E.6 Changes Between 1.2 PFD 1b and PFD 2 . . . . . . . . . . 3-46
E.6.23 Added elements to Tag Library Descriptor . . . 3-47
E.6.24 Changed the way version information is encoded into
TLD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-47
E.6.25 Assigning String literals to Object attributes . . 3-47
E.6.26 Clarification on valid names for prefix, action and at-
tributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-47
E.6.27 Clarification of details of empty actions . . . . . 3-47
E.6.28 Corrections related to XML syntax . . . . . . . . . 3-48
E.6.29 Other changes . . . . . . . . . . . . . . . . . . . . . . . . . . 3-48
JSP.E.7 Changes Between 1.2 PFD and 1.2 PFD 1b . . . . . . . . 3-49
JSP.E.8 Changes Between 1.2 PD1 and 1.2 PFD . . . . . . . . . . . 3-49
E.8.30 Deletions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-49
E.8.31 Additions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-49
E.8.32 Clarifications . . . . . . . . . . . . . . . . . . . . . . . . . . 3-50
E.8.33 Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-50
JSP.E.9 Changes Between 1.1 and 1.2 PD1 . . . . . . . . . . . . . . . 3-51
E.9.34 Organizational Changes . . . . . . . . . . . . . . . . . . 3-51
E.9.35 New Document . . . . . . . . . . . . . . . . . . . . . . . . 3-51
E.9.36 Additions to API . . . . . . . . . . . . . . . . . . . . . . . 3-51
E.9.37 Clarifications . . . . . . . . . . . . . . . . . . . . . . . . . . 3-52
E.9.38 Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-52
JSP.E.10 Changes Between 1.0 and 1.1 . . . . . . . . . . . . . . . . . . . 3-52
E.10.39 Additions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-52
E.10.40 Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-53
JSP.F Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-54

PUBLIC DRAFT
Preface

This document is the JavaServer Pages™ 2.0 Specification (JSP 2.0).


This specification is being developed following the Java Community Process
(JCP). Comments from Experts, Participants, and the Public will be reviewed and
improvements will be incorporated into the specification where applicable.
The original Java Specification Request (JSR-152) listed the version number
of the specifcation as 1.3. The scope and content of the specification effort has not
changed, but the Expert Group realized that the new features would have a deep
impact in the development model of JSP applications and decided that 2.0 would
more appropriatedly reflect that impact.

Relation To JSP 1.2

JSP 2.0 extends JavaServer Pages™ 1.2 Specification (JSP 1.2) in the following
ways:

• Requiring the Java 2 platform, version 1.4 or later.


• Using the Servlet 2.4 specification for its web semantics.
• Adding a simple Expression Language (EL) that can be used to easily access
data from the JSP pages. The EL simplifies writing script-less JSP pages that
do not use Java scriptlets or Java expressions and thus have a more controlled
interaction with the rest of the Web Application.
• Adding an API for invoking the EL. This API will likely be used in the imple-
mentation of the EL in JSP 1.3 and JSTL but we expect it to also be used in
other technologies like JavaServer Faces.

PUBLIC DRAFT xvii


xviii

• Adding new syntax elements for defining custom actions using the JSP tech-
nology directly. These elements are delivered into .tag files which can be au-
thored by developers and page authors alike to provide encapsulation and
reusability of common actions.
• Adding a new Simple Invocation Protocol that exploits what we expect to be
the prevalent use of script-less pages. The simple invocation protocol avoids
the complex “inverted closure” mechanism of the classic invocation protocol
introducted in JSP 1.1 and is used for implementing the tag files.
We expect to add a number of other features before the Proposed Final Draft.
The Expert Group has already discussed most of them but some of them are better
understood than others; among the former are:

• Improve the XML syntax of JSP using namespaces rather than requiring all
documents to use jsp:root.
• Conversion of the TLD to XML schema.
• Making the JSP technology usable as a general templating mechanism sepa-
rate from Servlets.
• Adding additional information to the TLD so page authoring tools can pro-
vide a better user experience.

Major Version Number Upgrade (JSP 2.0)

In combination with the JSP Standard Tag Library, the new features introduced
in this specification (such as a built-in expression language, a new invocation proto-
col and JSP fragments) will have a substantial impact on the methodology page
authors will use to write JSPs. The impact is strong enough that the expert group felt
it was appropriate the upgrade the major version number of the JSP specification to
JSP 2.0.
Among other benefits, we believe this version number upgrade will help draw
developer’s attention to these new features. It will also allow one to more easily
differentiate between the two different programming models (JSP 1.x style vs.
JSP 2.x style).

PUBLIC DRAFT
xix

Licensing of Specification

Details on the conditions under which this document is distributed are described
in the license on page 2.

Who should read this document

This document is the authoritative JSP 2.0 specification. It is intended to pro-


vide requirements for implementations of JSP processing, and support by web con-
tainers in web servers and application servers. As an authoritative document, it
covers material that pertains to a wide-range audience, including Page Authors, Tag
Library Developers, Deployers, Container Vendors and Tool Vendors.
This document is not intended to be a user’s guide. We expect other
documents will be created that will cater to different readerships.

Organization of this Document

This document comprises of a number of Chapters and Appendices that are


organized into 3 parts. Additionally, the document contains a Preface (this section),
a Status and an Overview.
Part I contains several chapters that describe are intended for all JSP Page
Authors. These chapters provide the general structure of the language, including
the expresion language, fragments and scripting.
Part II contains detailed chapters on the JSP container engine and the API in
full detail. The information in this part is more advanced.
Finally, Part III contains all the appendices.

Related Documents

Implementors of JSP containers and authors of JSP pages may find the follow-
ing documents worth consulting for additional information:

Table JSP.P-1 Some Related Web Sites

JSP home page http://java.sun.com/products/jsp

Servlet home page http://java.sun.com/products/servlet

Java 2 Platform, Standard Edition http://java.sun.com/products/jdk/1.4

PUBLIC DRAFT
xx

Table JSP.P-1 Some Related Web Sites

JSP home page http://java.sun.com/products/jsp

Servlet home page http://java.sun.com/products/servlet

Java 2 Platform, Enterprise Edition http://java.sun.com/j2ee


XML in the Java Platform home http://java.sun.com/xml
page

JavaBeans™ technology home page http://java.sun.com/beans

XML home page at W3C http://www.w3.org/XML

HTML home page at W3C http://www.w3.org/MarkUp

XML.org home page http://www.xml.org

JSR-045 home page (Debugging http://jcp.org/jsr/detail/45.jsp


Support for Other Languages)

Historical Note

The following individuals were pioneers who did ground-breaking work in the
Java platform areas related to this specification: James Gosling’s work on a Web
Server in Java in 1994/1995, became the foundation for servlets. A larger project
emerged in 1996 with Pavani Diwanji as lead engineer and with many other key
members listed below. From this project came Sun’s Java Web Server product.
Things started to move quickly in 1999. The servlet expert group, with James
Davidson as lead, delivered the Servlet 2.1 specification in January and the Servlet
2.2 specification in December, while the JSP group, with Larry Cable and
Eduardo Pelegri-Llopart as leads, delivered JSP 1.0 in June and JSP 1.1 in
December.
The year 2000 saw a lot of activity, with many implementations of containers,
tools, books, and training that target JSP 1.1, Servlet 2.2, and the Java 2 Enterprise
Edition platform. Tag libraries were an area of intense development, as were
varying approaches to organizing all these features together. The adoption of JSP
technology has continued in the year 2001, with many talks at the “Web, Services
and beyond” track at JavaOne being dedicated to the technology.
Tracking the industry in a printed document is at best difficult; the industry
pages at the web site at http://java.sun.com/products/jsp do a better job.

PUBLIC DRAFT
xxi

Note – More history will go here.. - Including some on JSP 1.2, and JSP 2.0

Acknowledgments

Note – In progress...

PUBLIC DRAFT
xxii

PUBLIC DRAFT
Status

This is the Public Draft for the JSP 2.0 specification, developed by the expert
group JSR-152 under the Java Community Process (more details at http://jcp.org/
jsr/detail/152.jsp).
The original Java Specification Request (JSR-152) listed the version number
of the specification as 1.3. The scope and content of the specification effort has
not changed, but the Expert Group realized that the new features would have a
deep impact in the development model of JSP applications and decided that 2.0
would more appropriatedly reflect that impact.
In the tradition of previous JSP specifications, we plan an early access
implementation of this draft to get practical experience that we can incorporate
into later Public Drafts. This approach has been very succesful in delivering
usable features.

The Java Community Process

The JCP produces a specification using three communities: an expert commu-


nity (the expert group), the participants of the JCP, and the public-at-large. The
expert group is responsible for the authoring of the specification through a collection
of drafts. Specification drafts move from the expert community, through the partici-
pants, to the public, gaining in detail and completeness, always feeding received
comments back to the expert group; the final draft is submitted for approval by the
Executive Committee. The expert group lead is responsible for facilitating the work-
ings of the expert group, for authoring the specification, and for delivering the refer-
ence implementation and the conformance test suite.

PUBLIC DRAFT xxiii


xxiv

The JCP and this Specification

The JCP is designed to be a very flexible process so each expert group can
address the requirements of the specific communities it serves. The reference imple-
mentation for JSP 2.0 and Servlet 2.4 uses code that is being developed as an open
source project under an agreement with the Apache Software Foundation.
This specification includes chapters that are derived directly from the javadoc
comments in the API classes, but, were there to be any discrepancies, this
specification has precedence over the javadoc comments.
The JCP process provides a mechanism for updating the specification through
a maintenance process using Erratas. If they are available, the erratas will have
precedence over this specification.
Appendices C and D are normative; the other appendices are non-normative.

PUBLIC DRAFT
Overview

This is an overview of the JavaServer Pages technology.


The JavaServer Pages™ Technology

JavaServer Pages™ is the Java™ 2 Platform, Enterprise Edition (J2EE) technol-


ogy for building applications for generating dynamic web content, such as HTML,
DHTML, XHTML and XML. The JavaServer Pages technology enables the easy
authoring of web pages that create dynamic content with maximum power and flex-
ibility.

General Concepts
The JavaServer Pages technology provides the means for textual specification of
the creation of a dynamic response to a request. The technology builds on the fol-
lowing concepts:

• Template Data
A substantial portion of most dynamic content is fixed or template content.
Text or XML fragments are typical template data. JSP technology supports
natural manipulation of template data.

• Addition of Dynamic Data


JSP technology provides a simple, yet powerful, way to add dynamic data to
template data.

PUBLIC DRAFT xxv


xxvi

• Encapsulation of Functionality
JSP technology provides two related mechanisms for the encapsulation of
functionality: JavaBeans component architecture, and tag libraries delivering
custom actions, functions, listener classes and validation.

• Good Tool Support


Good tool support leads to significantly improved productivity. Accordingly,
JSP technology has features that enable the creation of good authoring tools.

Careful development of these concepts yields a flexible and powerful server-


side technology.

Benefits of the JavaServer Pages Technology


JavaServer Pages technology offers the following benefits:

• Write Once, Run Anywhere™ properties


JSP technology is platform independent in its dynamic web pages, its web
servers, and its underlying server components. JSP pages may be authored on
any platform, run on any web server or web enabled application server, and
accessed from any web browser. Server components can be built on any plat-
form and run on any server.

• High quality tool support


Platform independence allows the JSP user to choose best-of-breed tools.
Additionally, an explicit goal of the JavaServer Pages design is to enable the
creation of high quality portable tools.

• Separation of Roles
JSP supports the separation of developer and author roles: Developers write
components that interact with server-side objects. Authors put static data and
dynamic content together to create presentations suited for their intended
audiences.
Each group may do their job without knowing the job of the other. Each role
emphasizes different abilities and, although these abilities may be present in
the same individual, they most commonly will not be. Separation allows a nat-
ural division of labor.
A subset of the developer community may be engaged in developing reusable
components intended to be used by authors.

PUBLIC DRAFT
xxvii

• Reuse of components and tag libraries


The JavaServer Pages technology emphasizes the use of reusable components
such as JavaBeans™ components, Enterprise JavaBeans™ components, and tag
libraries. These components can be used with interactive tools for component
development and page composition, yielding considerable development time
savings. In addition, they provide the cross-platform power and flexibility of
the Java programming language or other scripting languages.

• Separation of dynamic and static content


The JavaServer Pages technology enables the separation of static content in a
template from dynamic content that is inserted into the static template. This
greatly simplifies the creation of content. The separation is supported by
beans specifically designed for the interaction with server-side objects, and by
the tag extension mechanism.

• Support for actions, expressions and scripting


The JavaServer Pages technology supports scripting elements as well as
actions. Actions encapsulate useful functionality in a convenient form that
can be manipulated by tools. Expressions are used to access data. Scripts can
be used to glue together this functionality in a per-page manner.
The JSP 2.0 specification adds a simple expression language (EL) to the Java-
based scripts. Expressions in the EL directly express page author concepts
like properties in beans and provide more controlled access to the Web Appli-
cation data. Functions defined through the tag library mechanism can be
accessed in the EL.
The JSP 2.0 specification also adds a mechanism by which page authors can
write actions using the JSP technology directly. This greatly increases the
ease with which action abstractions can be created.

• Web access layer for N-tier enterprise application architecture(s)


The JavaServer Pages technology is an integral part of the Java 2 Platform
Enterprise Edition (J2EE). The J2EE platform brings Java technology to
enterprise computing. You can now develop powerful middle-tier server
applications that include a web site using JavaServer Pages technology as a
front end to Enterprise JavaBeans components in a J2EE compliant environ-
ment.

PUBLIC DRAFT
xxviii

Basic Concepts

This section introduces basic concepts that will be defined formally later in the
specification.

What is a JSP Page?


A JSP page is a text-based document that describes how to process a request to
create a response. The description intermixes template data with dynamic actions
and leverages on the Java 2 Platform. JSP technology supports a number of different
paradigms for authoring dynamic content. The key features of JavaServer Pages
are:

• Standard directives
• Standard actions
• Scripting elements
• Tag Extension mechanism
• Template content

Web Applications
The concept of a web application is inherited from the Servlet specification. A
web application can be composed from:

• Java Runtime Environment(s) running in the server (required)


• JSP page(s) that handle requests and generate dynamic content
• Servlet(s) that handle requests and generate dynamic content
• Server-side JavaBeans components that encapsulate behavior and state
• Static HTML, DHTML, XHTML, XML and similar pages.
• Client-side Java Applets, JavaBeans components, and arbitrary Java class files
• Java Runtime Environment(s) running in client(s) (downloadable via the Plu-
gin and Java Web Start technology)

PUBLIC DRAFT
xxix

The JavaServer Pages specification inherits from the Servlet specification the
concepts of web applications, ServletContexts, sessions, requests and responses.
See the Java Servlet 2.4 specification for more details.

Components and Containers


JSP pages and servlet classes are collectively referred to as web components.
JSP pages are delivered to a Container that provides the services indicated in the
JSP Component Contract.
The separation of components from containers allows reuse of components,
with quality-of-service features provided by the container.

Translation and Execution Steps


JSP pages are textual components. They go through two phases: a translation
phase, and a request phase. Translation is done once per page. The request phase is
done once per request.
The JSP page is translated to create a servlet class, the JSP page
implementation class, that is instantiated at request time. The instantiated JSP
page object handles requests and creates responses.

Note – Separation/Delegation would go here

JSP pages may be translated prior to their use, providing the web application,
with a servlet class that can serve as the textual representation of the JSP page.
The translation may also be done by the JSP container at deployment time, or
on-demand as the requests reach an untranslated JSP page.

Deployment Descriptor and Global Information


The JSP pages delivered in a Web Application may require some JSP configura-
tion information; this information is delivered through JSP-specific elements in the
web.xml deployment descriptor, rooted on the <jsp-config> element. Configuration
information includes <taglib> elements in mapping of tag libraries and <jsp-prop-
erty-group> elements used to provide properties of collections of JSP files. The
properties that can be indicated this way include pageEncoding information, EL
evaluation activation, automatic includes before and after pages, and whether script-
ing is enabled in a given page.

PUBLIC DRAFT
xxx

Role in the Java 2 Platform, Enterprise Edition


With a few exceptions, integration of JSP pages within the J2EE 1.4 platform is
inherited from the Servlet 2.4 specification since translation turns JSPs into servlets.

Note – Role of XML - We need a good description here.

Users of JavaServer Pages

There are six classes of users that interact with JavaServer Pages technology.
This section describes each class of user, enumerates the technologies each must be
familiar with, and identifies which sections of this specification are most relevant to
each user class. The intent is to ensure that JavaServer Pages remains a practical and
easy-to-use technology for each class of user, even as the language continues to
grow.

Page Authors
Page Authors are application component providers that use JavaServer Pages to
develop the presentation component of a web application. It is expected that they
will not make use of the scripting capabilities of JavaServer Pages, but rather limit
their use to standard and custom actions. Therefore, it is assumed that they know the
target language (e.g. HTML or XML), and basic XML concepts, but they need not
know Java at all.
The following sections are most relevant to this class of user:

• Chapter JSP.1, “Core Syntax and Semantics”, except for Section JSP.1.12,
“Scripting Elements” and Section JSP.1.14, “Tag Attribute Interpretation Se-
mantics” which both talk about scripting.
• Chapter JSP.2, “Expression Language”
• Chapter JSP.3, “JSP Configuration”
• Chapter JSP.4, “Localization Issues”
• Chapter JSP.5, “Standard Actions”
• Chapter JSP.6, “JSP Documents”, except for sections that discuss declara-
tions, scriplets, expressions, and request-time attributes, and except for
Section JSP.6.4, “Validating an XML View of a JSP page”.

PUBLIC DRAFT
xxxi

• Section JSP.7.1.1, “Goals” and Section JSP.7.1.2, “Overview” of


Chapter JSP.7, “Tag Extensions”.
• Chapter JSP.8, “JSP Fragments”
• Appendices JSP.A, JSP.E, and JSP.F.

Advanced Page Authors


Like Page Authors, Advanced Page Authors are also application component
providers that use JavaServer Pages to develop the presentation component of a web
application. These authors have a better understanding of XML and also know Java.
Though they are recommended to avoid it where possible, these authors do have
scripting at their disposal and should be able to read and understand JSPs that make
use of scripting.
The following sections are most relevant to this class of user:

• Chapters JSP.1, JSP.2, JSP.3, JSP.4 and JSP.5.


• Chapter JSP.6, “JSP Documents”, except for Section JSP.6.4, “Validating an
XML View of a JSP page”.
• Section JSP.9.1.1, “Valid JSP Page” and Section JSP.9.1.2, “Reserved
Names” of Chapter JSP.9, “Scripting”.
• Section JSP.7.1.1, “Goals” and Section JSP.7.1.2, “Overview” of
Chapter JSP.7, “Tag Extensions”.
• Chapter JSP.8, “JSP Fragments”
• Section JSP.10.4, “Precompilation” of Chapter JSP.10, “JSP Container”
• Chapter JSP.11, “Core API”
• Appendices JSP.A, JSP.B, JSP.E, and JSP.F.

Tag Library Developers


Tag Library Developers are application component providers who write tag
libraries that provide increased functionality to Page Authors and Advanced Page
Authors. They have an advanced understanding of the target language, XML and
Java.
The following sections are most relevant to this class of user:

PUBLIC DRAFT
xxxii

• Chapters JSP.1, JSP.2, JSP.3, JSP.4 and JSP.5.


• Chapter JSP.6, “JSP Documents”, except for Section JSP.6.4, “Validating an
XML View of a JSP page”.
• Section JSP.9.1.1, “Valid JSP Page” and Section JSP.9.1.2, “Reserved
Names” of Chapter JSP.9, “Scripting”.
• Chapter JSP.7, “Tag Extensions”
• Chapter JSP.8, “JSP Fragments”
• Section JSP.10.4, “Precompilation” of Chapter JSP.10, “JSP Container”
• Chapter JSP.11, “Core API” and Chapter JSP.12, “Tag Extension API”
• All Appendices.

Deployers
A deployer is an expert in a specific operational environment who is responsible
for configuring a web application for, and deploying the web application to, that
environment. The deployer does not need to understand the target language or Java,
but must have an understanding of XML or use tools that provide the ability to read
deployment descriptors.
The following sections are most relevant to this class of user:

• Section JSP.1.1, “What is a JSP Page” and Section JSP.1.2, “Web Applica-
tions” of Chapter JSP.1, “Core Syntax and Semantics”
• Chapter JSP.3, “JSP Configuration”
• Chapter JSP.4, “Localization Issues”
• Chapter JSP.10, “JSP Container”
• All Appendices.

Container Developers / Tool Vendors


Container Developers develop containers that host JavaServer Pages. Tool Ven-
dors write development tools to assist Page Authors, Advanced Page Authors, Tag
Library Developers and Deployers. Both Container Developers and Tool Vendors
must know both XML and Java, and must know all the requirements and technical
details of JavaServer Pages. Therefore, this entire specification is relevant to both
classes of user.

PUBLIC DRAFT
xxxiii

Note –

PUBLIC DRAFT
PART I
T he next chapters form the core of the JSP specification. These chapters pro-
vide information for Page authors, Tag Library developers, deployers and Container
and Tool vendors.
The chapter of this part are

• Core Syntax and Semantics


• Expression Language
• Configuration Information
• Localization Issues
• Standard Actions
• JSP Documents
• Tag Extensions
• JSP Fragments
• Scripting

Note – Should there be a separate chapter on Localization Issues?

Note – The XML syntax part of the JSP Documents should be integrated with
the Core Syntax Chapter. The XML view part should probably go to Part II.

Note – Most of the JSP fragments chapter moves elsewhere; the rest becomes
a chapter focused on Tag files which probably moves ahead.

PUBLIC DRAFT 1-1


C H A P T E R JSP.1
Core Syntax and Semantics

This chapter describes the core syntax and semantics for the JavaServer Pages
2.0 specification (JSP 2.0).

JSP.1.1 What is a JSP Page

A JSP page is a textual document that describes how to create a response object
from a request object for a given protocol. The processing of the JSP page may
involve creating and/or using other objects.
A JSP page defines a JSP page implementation class that implements the
semantics of the JSP page. This class is a subclass of Servlet (see Chapter JSP.10
for details). At request time a request intended for the JSP page is delivered to the
JSP page implementation object for processing.
HTTP is the default protocol for requests and responses. Additional request/
response protocols may be supported by JSP containers (See below). The default
request and response objects are of type HttpServletRequest and HttpServletRe-
sponse respectively.

JSP.1.1.1 Web Containers and Web Components


A JSP container is a system-level entity that provides life-cycle management
and runtime support for JSP pages and Servlet components. Requests sent to a JSP
page are delivered by the JSP container to the appropriate JSP page implementation
object. The term web container is synonymous with JSP container.
A web component is either a servlet or a JSP page. The servlet element in a
web.xml deployment descriptor is used to describe both types of web
components. JSP page components are defined implicitly in the deployment

PUBLIC DRAFT 1-2


1-3 CORE SYNTAX AND SEMANTICS

descriptor through the use of an implicit .jsp extension mapping, or explicitly


through the use of a jsp-group element.

JSP.1.1.2 XML Document for a JSP Page


JSP pages have an equivalent XML document. The XML view of a JSP page is
exposed to the translation phase (see below).
A JSP page can be written directly as an XML document. Beginning with
JSP 1.2, the XML document can be delivered to a JSP container for processing.
It is not valid to mix standard syntax and XML syntax in the same source file.
However, a JSP page in either syntax can include a JSP page in either syntax via a
directive.

Note – This will be revisited after incorporating the XML syntax changes.

JSP.1.1.3 Translation and Execution Phases


A JSP container manages two phases of a JSP page’s life. In the translation
phase, the container determines a JSP page implementation class that corresponds to
the JSP page. In the execution phase the container manages one or more instances of
this class in response to requests and other events.
During the translation phase the container locates or creates the JSP page
implementation class that corresponds to a given JSP page. This process is
determined by the semantics of the JSP page. The container interprets the
standard directives and actions, and the custom actions referencing tag libraries
used in the page. A tag library may optionally provide a validation method to
validate that a JSP page is correctly using the library.
A JSP container has flexibility in the details of the JSP page implementation
class that can be used to address quality-of-service --most notably performance--
issues.
During the execution phase the JSP container delivers events to the JSP page
implementation object. The container is responsible for instantiating request and
response objects and invoking the appropriate JSP page implementation object.
Upon completion of processing, the response object is received by the container
for communication to the client. The details of the contract between the JSP page
implementation class and the JSP container are described in Chapter JSP.10.
The translation of a JSP source page into its implementation class can occur at
any time between initial deployment of the JSP page into the JSP container and
the receipt and processing of a client request for the target JSP page.

PUBLIC DRAFT
What is a JSP Page 1-4

Section JSP.1.1.7 describes how to perform the translation phase ahead of


deployment.

JSP.1.1.4 Events in JSP Pages


A JSP page may indicate how some events are to be handled.
As of 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.

JSP.1.1.5 JSP Configuration Information


JSP pages may be extended with configuration information that is delivered in
the JSP configuration portion of the web.xml deployment description of the Web
Application. The JSP configuration information includes interpretation for the tag
libraries used in the JSP files and different property information for groups of JSP
files. The property information includes: page encoding information, whether the
EL evaluation and the scripting machinery is enabled, and prelude and coda auto-
matic inclusions. The JSP configuration information can also be used to indicate that
some resources in the Web Application are JSP files even if they do not conform to
the default “.jsp” extension.

Note – Remember to revisit this section to improve how it reads.

JSP.1.1.6 Naming Conventions for JSP Files


A JSP page is packaged as one or more files, often in a web application, and
delivered to a tool like a JSP container, a J2EE container, or an IDE. A complete JSP
page may be contained in a single file. In other cases, the top file will include other
files that contain complete JSP pages, or included fragments.
It is common for tools to need to differentiate JSP page files from other files.
In some cases, the tools also need to differentiate between top JSP files and
included fragments. For example, a fragment may not be a legal JSP page and
may not compile properly. Determining the type of file is also very useful from a
documentation and maintenance point of view, as people familiar with the “.c”
and “.h” convention in the C language know.

PUBLIC DRAFT
1-5 CORE SYNTAX AND SEMANTICS

By default the extension “.jsp” means a JSP page, but we recommend, but do
not mandate, to differentiate between top-level JSP pages and included pages so
that:

• “.jsp” files correspond to top level JSP files containing a JSP page.
• Included fragments not use the “.jsp” extension. Any other extension will do,
although “.jspf” and “.jsf” seem reasonable extensions and are offered as sug-
gestions.

The jsp-property-group element of web.xml can be used to indicate that some


group of files, perhaps not using either of the extensions above, are JSP pages.

Note – Does it make sense to have a property to differentiate between top-


level pages and included fragments?

JSP.1.1.7 Compiling JSP Pages


A JSP page may be compiled into its implementation class plus deployment
information during development. (A JSP page can also be compiled at deployment
time.) In this way JSP page authoring tools and JSP tag libraries may be used for
authoring servlets. The benefits of this approach include:

• 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.

Compilation of a JSP page in the context of a web application provides


resolution of relative URL specifications in include directives (and elsewhere),
taglib references, and translation-time actions used in custom actions.
A JSP page can also be compiled at deployment time.

JSP.1.1.7.1 JSP Page Packaging


When a JSP page implementation class depends on support classes (in addition
to the JSP 2.0 and Servlet 2.4 classes), the support classes are included in the pack-
aged WAR (as defined in the Servlet 2.4 specification) for portability across JSP
containers..

PUBLIC DRAFT
Web Applications 1-6

Appendix JSP.A contains two examples of the packaging of JSP pages in


WARs:

1. A JSP page delivered in source form (probably the most common case).
2. A JSP page translated into an implementation class plus deployment informa-
tion. The deployment information indicates support classes needed and the
mapping between the original URL path to the JSP page and the URL for the
JSP page implementation class for that page.

JSP.1.1.8 Debugging JSP Pages


In the past debugging tools provided by development environments have lacked
a standard format for conveying source map information allowing the debugger of
one vendor to be used with the JSP container of another. As of JSP 2.0, containers
must support JSR-045 (“Debugging Support for Other Languages”). Details can be
found in Section JSP.10.5, “Debugging Requirements”.

JSP.1.2 Web Applications

A web application is a collection of resources that are available at designated


URLs. A web application is made up of some of the following:

• Java runtime environment(s) running in the server (required)


• JSP page(s) that handle requests and generate dynamic content
• Servlet(s) that handle requests and generate dynamic content
• Server-side JavaBeans components that encapsulate behavior and state
• Static HTML, DHTML, XHTML, XML and similar pages.
• Resource files used by Java classes.
• Client-side Java Applets, JavaBeans components, and Java class files
• Java runtime environment(s) (downloadable via the Plugin and Java Web
Start) running in client(s)

Web applications are described in more detail in the Servlet 2.4 specification.
A web application contains a deployment descriptor web.xml that contains
information about the JSP pages, servlets, and other resources used in the web

PUBLIC DRAFT
1-7 CORE SYNTAX AND SEMANTICS

application. The deployment descriptor is described in detail in the Servlet 2.4


specification.
JSP 2.0 requires that these resources be implicitly associated with and
accessible through a unique ServletContext instance available as the implicit appli-
cation object (Section JSP.1.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:

• The include directive (Section JSP.1.10.5).


• The jsp:include action element (Section JSP.5.4).
• The jsp:forward action (Section JSP.5.5).

JSP 2.0 supports portable packaging and deployment of web applications


through the Servlet 2.4 specification. The JavaServer Pages specification inherits
from the Servlet specification the concepts of applications, ServletContexts,
Sessions, Requests and Responses.

JSP.1.2.1 Relative URL Specifications


Elements may use relative URL specifications, called “URI paths” in the Servlet
2.4 specification. These paths are as described in the RFC 2396 specification. We
refer to the path part of that specification, not the scheme nor authority parts. Some
examples are:
A context-relative path is a path that starts with a “/”. It is to be interpreted
as relative to the application to which the JSP page belongs, that is to say that its
ServletContext object provides the base context URL.
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.1.10.5) where
the path is used in a file attribute, the interpretation is relative to the JSP file; for an
jsp:include action (Section JSP.5.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.1.10.7 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

PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-8

translation. The semantics outlined here apply to the translation-time phase, and
to the request-time phase.

JSP.1.3 Syntactic Elements of a JSP Page

This section describes the basic syntax rules of JSP pages.

JSP.1.3.1 Elements and Template Data


A JSP page has elements and template data. An element is an instance of an ele-
ment type known to the JSP container. Template data is everything else: anything
that the JSP translator does not know about.
The type of an element describes its syntax and its semantics. If the element
has attributes, the type describes the attribute names, their valid types, and their
interpretation. If the element defines objects, the semantics includes what objects
it defines and their types.

JSP.1.3.2 Element Syntax


There are three types of elements: directive elements, scripting elements, and
action elements.

Note – Need to talk about Expression Language here, since an EL expression


can appear anywhere and that becomes a fourth type of element.

Directives
Directives provide global information that is conceptually valid independent
of any specific request received by the JSP page. They provide information for
the translation phase.
Directive elements have a syntax of the form <%@ directive...%>

Actions
Actions provide information for the request processing phase. The interpreta-
tion of an action may, and often will, depend on the details of the specific
request received by the JSP page. An Actions can either be standard, that is.
defined in this specification, or custom, that is provided via the portable tag
extension mechanism.

PUBLIC DRAFT
1-9 CORE SYNTAX AND SEMANTICS

Action elements follow the syntax of an XML element.: They have a start tag
including the element name, and may have attributes, an optional body, and a
matching end tag, or they be an empty tag possibly with attributes:

<mytag attr1=”attribute value”...>body</mytag>

and

<mytag attr1=”attribute value”.../>


<mytag attr1=”attribute value” ...></mytag>

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 <%= ... %>.

JSP.1.3.3 Start and End Tags


Elements that have distinct start and end tags (with enclosed body) must start
and end in the same file. The start tag cannot be on one file while the end tag is in
another.
The same rule applies to elements in the alternate syntax. For example, a
scriptlet has the syntax <% scriptlet %>. Both the opening <% characters and the
closing %> characters must be in the same physical file.
A scripting language may also impose constraints on the placement of start
and end tags relative to specific scripting constructs. For example, Chapter 9
shows that Java language blocks cannot separate a start and an end tag; see
Section JSP.9.4 for details.

JSP.1.3.4 Empty Elements


Following the XML specification, an element described using an empty tag is
indistinguishable from one using a start tag, an empty body, and an end tag
As examples, the following are all empty tags:
PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-10

<x:foo></x:foo>
<x:foo />
<x:foo/>
<x:foo><%-- any comment --%></x:foo>

While the following are all non-empty tags:

<foo> </foo>
<foo><%= expression %></foo>
<foo><% scriptlet %></foo>
<foo><bar/></foo>
<foo><!-- a comment --></foo>

JSP.1.3.5 Attribute Values Using XML Attributes


Following the XML specification, attribute values always appear quoted. Either
single or double quotes can be used to reduce the need for quoting quotes; the quota-
tion conventions available are described in Section JSP.1.6. There are two types of
attribute values, literals and request-time expressions (Section JSP.1.14.1) but the
quotation rules are the same.

JSP.1.3.6 Attribute Values Using XML Elements


Until JSP 2.0, tag handlers could be passed input two ways: through attribute
values and through the element body. Attribute values were always evaluated once
(if they were specified as an expression) and the result was passed to the tag
handler. The body could contain scripting elements and action elements and be
evaluated zero or more times on demand by the tag handler.
As of JSP 2.0, page authors can provide input in new ways using the
<jsp:attribute> standard action element. This action element body can contain
template text, EL expressions and action elements. Based on the configuration of
the tag being invoked, the body of the element either specifies a value that is
evaluated once and passed to the tag handler, or it specifies a “JSP fragment,”
which represents the body in a form that makes it possible for the tag handler to
evaluate it as many times as needed.
It is illegal JSP syntax, which must result in a translation error, to use both an
XML element attribute and a <jsp:attribute> standard action to pass the value of
the same attribute. Also, the body of the attribute standard action must be
scriptless. That is, it may only contain template text and JSP action elements. See
Section JSP.5.10 for more details on the <jsp:attribute> standard action.

PUBLIC DRAFT
1-11 CORE SYNTAX AND SEMANTICS

The following example uses an XML element attribute to define the value of
the param1 attribute, and uses an attribute standard action to define the value of
the param2 attribute. In this example, the value of param2 comes from the result
of a custom action invocation.

<mytag:paramTag param1=”value1”>
<jsp:attribute name=”param2”>
<mymath:add x=”2” y=”2”/>
</jsp:attribute>
</mytag:paramTag>

If a page author wishes to pass both an attribute standard action and a tag
body, the <jsp:body> standard action must be used to specify the body. A
translation error will result if the custom action invocation has <jsp:attribute>
elements but does not define the body using a <jsp:body> element. See
Section JSP.5.11 for more details on the <jsp:body> standard action.
The following example shows two equivalent tag invocations to the
hypothetical <mytag:formatBody> custom action. The first invocation uses an
XML element attribute to pass the values of the color and size attributes. The
second example uses an attribute standard action to pass the value of the color
attribute. Both examples have tag body containing simply the words “Template
Text”.

<mytag:tagWithBody color=”blue” size=”12”>


Template Text
</mytag:tagWithBody>

<mytag:tagWithBody size=”12”>
<jsp:attribute name=”color”>blue</jsp:attribute>
<jsp:body>
Template Text
</jsp:body>
</mytag:tagWithBody>

JSP.1.3.7 Valid Names for Actions and Attributes


The names for actions must follow the XML convention (ie. must be an NMTO-
KEN as indicated in the XML 1.0 specification). The names for attributes must be
follow the conventions described in the JavaBeans specification.
Attribute names that start with jsp, _jsp, java, or sun are reserved to this
specification.

PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-12

JSP.1.3.8 White Space


In HTML and XML white space is usually not significant, but there are excep-
tions. For example, an XML file may start with the characters <?xml, and, when it
does, it must do so with no leading whitespace characters.
This specification follows the whitespace behavior defined for XML. White
space within the body text of a document is not significant, but is preserved.
Next are two examples of JSP fragments with their associated output. Note
that directives generate no data and apply globally to the JSP page.

Table JSP.1-1 Example 1 - Input


LineNo Source Text
1 <?xml version=”1.0” ?>
2 <%@ page buffer=”8kb” %>
3 The rest of the document goes here

The result is

Table JSP.1-2 Example 1 - Output


LineNo Output Text
1 <?xml version=”1.0” ?>
2
3 The rest of the document goes here

The next two tables show another example, with input and output.,

Table JSP.1-3 Example 2 - Input


LineNo Source Text
1 <% response.setContentType(“....”);
2 whatever... %><?xml version=”1.0” ?>
3 <%@ page buffer=”8kb” %>
4 The rest of the document goes here

The result is

Table JSP.1-4 Example 2 - Output


LineNo Output Text
1 <?xml version=”1.0” ?>
2

PUBLIC DRAFT
1-13 CORE SYNTAX AND SEMANTICS

Table JSP.1-4 Example 2 - Output


4 The rest of the document goes here

JSP.1.3.9 Standard JSP Syntax Grammar


This section presents a simple EBNF grammar for the standard (i.e. non-XML)
JSP syntax. The grammar is intended to provide a concise syntax overview and to
resolve any syntax ambiguities present in this specification. Other sections may
apply further restrictions to this syntax, for example to restrict what represents a
valid attribute value for a page directive. In all other cases the grammar takes prece-
dence in resolving syntax questions.
The notation for this grammar is identical to that described by Chapter 6 of
the XML 1.0 specification, available at the following URL:

http://www.w3c.org/TR/2000/REC-xml-20001006#sec-notation

In addition, the following notes and rules apply:

• The root production for a JSP page is JSPPage.


• The prefix XML:: is used to refer to an EBNF definition in the XML 1.0 speci-
fication. Refer to http://www.w3.org/TR/REC-xml.
• Where applicable, to resolve grammar ambiguities, the first matching produc-
tion must always be followed. This is commonly known as the “greedy” algo-
rithm.
• If the <TRANSLATION_ERROR> production is followed, the page is invalid,
and the result will be a translation error.
• Many productions make use of XML-style attributes. These attributes can ap-
pear in any order, but no attribute can be repeated twice. To make XML at-
tributes easier to specify and read, the syntax “ATTR[attrset]” is used in the
EBNF to define a set of XML attributes that are recognized in a particular pro-
duction.

Within the square brackets (attrset) is listed a comma-separated list of case-


sensitive attribute names that are valid. Each attribute name represents a sin-
gle XML attribute. If the attribute name is prefixed with an ‘=’, the production
“Attribute” (defined below) must be matched (either a rtexprvalue or a static
value is accepted). If not, the production “NonRTAttribute” must be matched
(only static values are accepted). If the attribute name is prefixed with a ‘!’,

PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-14

the attribute is required and must appear in order for this production to be
matched. If an attribute that matches the “Attribute” production with a name
not listed appears adjacent to any of the other attributes, the production is not
matched.

For example, consider the production ATTR[ !name, =value, =!repeat ]. This
production is matched if and only if all of the following hold true:
• The name attribute appears extactly once and matches the NonRTAttribute
production.
• The value attribute appears at most once. If it appears, the Attribute pro-
duction must be matched.
• The repeat attribute appears exactly once and matches the Attribute pro-
duction.
• There must be no other attributes aside from name, value, or repeat.

For example, the following sample strings match the above:


• name=”somename” value=”somevalue” repeat=”2”
• repeat=”<%= x + y %>” name=”othername”

JSP.1.3.9.1 EBNF Grammar for Staandard JSP Syntax

JSPPage ::= Body

JSPTagDef ::= Body

Body ::= AllBody | ScriptlessBody


[ vc: ScriptlessBody ]

AllBody ::= ( ( ‘<%--’ JSPCommentBody )


| ( ‘<%@’ DirectiveBody )
| ( ‘<%!’ DeclarationBody )
| ( ‘<%=’ ExpressionBody )
| ( ‘${‘ ELExpressionBody )
| ( ‘<%’ ScriptletBody )
| ( ‘<jsp:’ StandardAction )
| ( ‘<‘ CustomAction
CustomActionBody )
| TemplateText
)*

PUBLIC DRAFT
1-15 CORE SYNTAX AND SEMANTICS

ScriptlessBody ::= ( ( ‘<%--’ JSPCommentBody )


| ( ‘<jsp:’ StandardAction )
| ( ‘<‘ CustomAction
CustomActionBody )
| TemplateText
)*

JSPCommentBody ::= ( Char* - ( Char* ‘--%>’ ) ) ‘--%>’


| <TRANSLATION_ERROR>

DirectiveBody ::= JSPDirectiveBody | TagDefDirectiveBody


[ vc: TagFileSpecificDirectives ]

JSPDirectiveBody ::= S?
( ( ‘page’ S PageDirectiveAttrList )
| ( ‘taglib’ S TagLibDirectiveAttrList )
| ( ‘include’ S IncludeDirectiveAttrList )
)
S? ‘%>’
| <TRANSLATION_ERROR>

TagDefDirectiveBody::= S?
( ( ‘tag’ S TagDirectiveAttrList )
| ( ‘taglib’ S TagLibDirectiveAttrList )
| ( ‘include’ S IncludeDirectiveAttrList )
| ( ‘attribute’ S AttributeDirectiveAttrList )
| ( ‘variable’ S VariableDirectiveAttrList )
| ( ‘fragment-input’ S
FragmentInputDirectiveAttrList
)
)
S? ‘%>’
| <TRANSLATION_ERROR>

PageDirectiveAttrList::= ATTR[ language, extends, import, session,


buffer, autoFlush, isThreadSafe,
info, errorPage, isErrorPage,
contentType, pageEncoding ]
[ vc: PageDirectiveUniqueAttr ]

TagLibDirectiveAttrList::= ATTR[ !uri, !prefix ]


| ATTR[ !tagdir, !prefix ]
[ vc: TagLibDirectiveUniquePrefix ]

IncludeDirectiveAttrList::=ATTR[ !file ]

PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-16

TagDirectiveAttrList ::= ATTR[ name, display-name, body-content,


dynamic-attributes, small-icon, large-icon,
description, example, pageEncoding]
[ vc: TagDirectiveUniqueAttr ]

AttributeDirectiveAttrList::=ATTR[ !name, required, fragment, rtexprvalue,


type, description ]
[ vc: UniqueAttributeName ]

VariableDirectiveAttrList::= ATTR[ !name-given, variable-class,


scope, declare, description ]
| ATTR[ !name-from-attribute, variable-class,
scope, declare, description ]
[ vc: UniqueVariableName ]

FragmentInputDirectiveAttrList::= ATTR[ !name, !fragment,


required, type, description ]
[ vc: UniqueFragmentInputName ]
[ vc: FragmentInputDefaultXORNamed ]
[ vc: FragmentInputAttrExists ]

DeclarationBody ::= ( Char* - ( Char* ‘%>’ ) ) ‘%>’


| <TRANSLATION_ERROR>

ExpressionBody ::= ( Char* - ( Char* ‘%>’ ) ) ‘%>’


| <TRANSLATION_ERROR>
[ vc: ExpressionBodyContent ]

ELExpressionBody ::= ELExpression ‘}’


| <TRANSLATION_ERROR>

ELExpression ::= [See Section JSP.2.13, production Expression]

ScriptletBody ::= ( Char* - ( Char* ‘%>’ ) ) ‘%>’


| <TRANSLATION_ERROR>

PUBLIC DRAFT
1-17 CORE SYNTAX AND SEMANTICS

StandardAction ::= ( ‘useBean’ StdActionContent )


| ( ‘setProperty’ StdActionContent )
| ( ‘getProperty’ StdActionContent )
| ( ‘include’ StdActionContent )
| ( ‘forward’ StdActionContent )
| ( ‘plugin’ StdActionContent )
| ( ‘invoke’ StdActionContent )
| ( ‘doBody’ StdActionContent )
| <TRANSLATION_ERROR>
[ vc: TagFileSpecificActions ]

StdActionContent ::= Attributes StdActionBody


[ vc: StdActionAttributesValid ]

StdActionBody ::= EmptyBody


| OptionalBody
| ParamBody
| PluginBody
[ vc: StdActionBodyMatch ]

EmptyBody ::= ‘/>’


| ( ‘>’ ETag )
| ( ‘>’ S? ‘<jsp:attribute’ NamedAttributes S? ETag )

ActionBody ::= ( ‘>’ S? ( ‘<jsp:attribute’NamedAttributes )?


‘<jsp:body’
( JspBodyBody |<TRANSLATION_ERROR> )
S? ETag
)
| ( ‘>’ Body ETag )

ScriptlessActionBody::= ( ‘>’ S? ( ‘<jsp:attribute’NamedAttributes )?


‘<jsp:body’
( JspBodyBody | <TRANSLATION_ERROR> )
S? ETag
)
| ( ‘>’ ScriptlessBody ETag )

OptionalBody ::= EmptyBody | ActionBody

ScriptlessOptionalBody::=EmptyBody | ScriptlessActionBody

PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-18

ParamBody ::= EmptyBody


| ( ‘>’ S? ( ‘<jsp:attribute’ NamedAttributes )?
‘<jsp:body’
(JspBodyParam | <TRANSLATION_ERROR>)
S? ETag
)
| ( ‘>’ Param* ETag )

PluginBody ::= EmptyBody


| ( ‘>’ S? ( ‘<jsp:attribute’ NamedAttributes )?
‘<jsp:body’
( JspBodyPluginTags
| <TRANSLATION_ERROR>
)
S? ETag
)
| ( ‘>’ PluginTags ETag )

NamedAttributes ::= AttributeBody S? ( ‘<jsp:attribute’ AttributeBody )*

AttributeBody ::= ATTR[ !name, trim ] S? AttributeBodyRequired

AttributeEmptyBody ::= ‘/>’


| ‘></jsp:attribute>’
| <TRANSLATION_ERROR>

AttributeBodyRequired::=‘>’(ScriptlessBody - ‘’)‘</jsp:attribute>’

JspBodyBody ::= ( ATTR[ !value ] S? JspBodyEmptyBody )


| ( S? ‘>’ ( ScriptlessBody - ‘’ ) ‘</jsp:body>’ )

JspBodyEmptyBody ::= ‘/>’


| ‘></jsp:body>’
| <TRANSLATION_ERROR>

JspBodyParam ::= S? ‘>’ Param* ‘</jsp:body>’

JspBodyPluginTags ::= S? ‘>’ PluginTags ‘</jsp:body>’

PluginTags ::= Params? S? Fallback? S?

Params ::= ’<jsp:params/>’


| ( ’<jsp:params>’ S? Param* ’</jsp:params>’ )

PUBLIC DRAFT
1-19 CORE SYNTAX AND SEMANTICS

Fallback ::= ’<jsp:fallback/>’


| ( ’<jsp:fallback>’
( Char* - ( Char* ’<’ ) )
’</jsp:fallback>’
)

Param ::= ’<jsp:param’ S ATTR[ !name, =!value] S? ‘/>’ S?

Attributes ::= ( S Attribute )* S?


[ vc: UniqueAttSpec ]

CustomAction ::= TagPrefix ’:’ CustomActionName


[vc: CustomActionMatchesAndValid]

TagPrefix ::= Name

CustomActionName ::= Name

CustomActionBody ::= ( Attributes CustomActionEnd )


| <TRANSLATION_ERROR>

CustomActionEnd ::= ‘/>’


| ( ‘>’ ( CustomActionTagDependent
| CustomActionJSPContent
| CustomActionScriptlessContent
)
)

CustomActionTagDependent::= Char* ETag


[vc: CustomActionTagDependentMatch]

CustomActionJSPContent::= OptionalBody
[ vc: CustomActionJSPContentMatch ]

CustomActionScriptlessContent::= ScriptlessOptionalBody
[ vc: CustomActionScriptlessContentMatch ]

TemplateText ::= ‘<‘


| ( Char* - ( Char* ‘<‘ ) )

ETag ::= ‘</’ Name S? ‘>’


[ vc: ETagMatch ]

PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-20

Attribute ::= Name Eq


( ‘”<%=’ RTAttributeValueDouble
| “‘<%=” RTAttributeValueSingle
| ‘”’ AttributeValueDouble
| “‘” AttributeValueSingle
)

NonRTAttribute ::= Name Eq


( ‘”’ AttributeValueDouble
| “‘” AttributeValueSingle
)

AnyAttributeValue ::= AttributeValue | RTAttributeValue

AttributeValue ::= AttributeValueDouble | AttributeValueSingle

RTAttributeValue ::= RTAttributeValueDouble | RTAttributeValueSingle

AttributeValueDouble::= ( QuotedChar - ‘”’ )*


( ‘”’ | <TRANSLATION_ERROR> )

AttributeValueSingle ::= ( QuotedChar - “‘” )*


( “‘” | <TRANSLATION_ERROR> )

RTAttributeValueDouble::= ( ( QuotedChar - ‘”’ )* -


( ( QuotedChar - ’"’ )* ’%>’ )
)
( ’%>"’ | <TRANSLATION_ERROR> )
[ vc: ExpressionBodyContent ]

RTAttributeValueSingle::= ( ( QuotedChar - “‘” )* -


( ( QuotedChar - “‘” )* ’%>’ )
)
( "%>’" | <TRANSLATION_ERROR> )
[ vc: ExpressionBodyContent ]

Name ::= XML::Name

Char ::= XML::Char

PUBLIC DRAFT
1-21 CORE SYNTAX AND SEMANTICS

QuotedChar ::= ’&apos;’


| ’&quot;’
| ’\\’
| ‘\”’
| "\’"
| ( ‘${‘
( ELExpressionBody
| <TRANSLATION_ERROR>
)
)
| Char

S ::= XML::S

Eq ::= XML::Eq

JSP.1.3.9.2 Validity Constraints


The following validity constraints are referenced in the above grammar using the syn-
tax [ vc: ValidityConstraint ], and must be followed:

• ScriptlessBody - The AllBody production cannot be followed if one of our par-


ent nodes in the parse tree is a ScriptlessBody production. That is, once we
have followed the ScriptlessBody production, until that production is complete
we cannot choose the AllBody production.
• TagFileSpecificDirectives - The JSPDirectiveBody production must be fol-
lowed if the root production is JSPPage (i.e. this is a JSP page). The TagDef-
DirectiveBody production must be followed if the root production is
JSPTagDef (i.e. this is a tag file).
• PageDirectiveUniqueAttr - A translation error will result if there is more
than one occurrence of any attribute/value defined by this directive in a given
translation unit with the exception of the “import” attribute (see
Section JSP.1.10.1)
• TagLibDirectiveUniquePrefix - A translation error will result if the prefix
AttributeValue has already previously been encountered as a potential TagPre-
fix in this translation unit.

• TagDirectiveUniqueAttr - A translation error will result if there is more than


one occurrence of any attribute/value defined by the tag directive in a given
translation unit.

PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-22

• UniqueAttributeName - A translation error will result if there are two or


more attribute directives with the same value for the name attribute in the
same translation unit.
• UniqueVariableName - A translation error must occur if more than one vari-
able directive appears in the same translation unit with the same value for the
name-given or name-from-attribute attributes.

• UniqueFragmentInputName - A translation error must occur if more than


one fragment-input directive appears in the same translation unit with the
same value for both the name and fragment attributes.
• FragmentInputDefaultXORNamed - A translation error must occur if two
fragment-input directives exist in the same translation unit, such that the frag-
ment attribute is specified for one directive but not for the other.

• FragmentInputAttrExists - A translation error must result if a fragment-in-


put directive appears with a fragment attribute specified with value B, but no
attribute directive appears in the same translation unit, prior to the fragment-
input directive, with a name attribute equal to B.

• TagFileSpecificActions - The invoke and doBody standard actions are only


matched if the JSPTagDef production was followed (i.e. if this is a tag file in-
stead of a JSP page).
• ExpressionBodyContent - A translation error will result if the body content
minus the closing delimiter (%>) does not represent a well-formed expression
in the scripting language selected for the JSP page.
• StdActionAttributesValid - An attribute is considered “provided” for this
standard action if either the Attribute production or the AttributeBody produc-
tion is followed in the context of the enclosing StandardAction production. A
translation error will result if any of the following conditions is true:

The set of attributes “provided” for this standard action does not match one
of the valid attribute combinations specified in Table JSP.1-5.

The same attribute is “provided” more than once, as determined by the at-
tribute name.

An attribute is “provided” using the AttributeBody production that does not
accept a runtime expression value, as indicated by the ‘=’ prefix in Table
JSP.1-5.

PUBLIC DRAFT
1-23 CORE SYNTAX AND SEMANTICS

• StdActionBodyMatch - The StdActionBody production will only be matched


if the production listed for this standard action in the “Body Production” col-
umn in Table JSP.1-5 is followed.
• UniqueAttSpec - A translation error will result if the same attribute name ap-
pears more than once.
• CustomActionMatchesAndValid - Following the rules in Section JSP.7.3 for
determining the relevant set of tags and tag libraries, assume the following:

Let U be the URI indicated by the ‘uri’ AttributeValue of the previously en-
countered TagLibDirectiveAttrList with ‘prefix’ matching the TagPrefix for
this potential custom action, or nil if no such TagLibDirectiveAttrList was en-
countered in this translation unit.

If U is not nil, let L be the <taglib> element in the relevant TLD entry such
that L.uri is equal to U.
Then:

If, after being parsed, the CustomAction production is matched (not yet tak-
ing into account the following rules), TagPrefix is considered a "potential
TagPrefix in this translation unit" for the purposes of the TagLibDirectiveU-
niquePrefix validity constraint.

The CustomAction production will not be matched if U is nil or if the TagPre-
fix does not match the ‘prefix’ AttributeValue of a TagLibDirectiveAttrList pre-
viously encountered in this translation unit.

Otherwise, if the CustomAction production is matched, a translation error
will result if there does not exist a <tag> element T in a relevant TLD such
that L.T.name is equal to CustomActionName.
• CustomActionTagDependentMatch - Assume the definition of L from the
CustomActionMatchesAndValid validity constraint above. The CustomAction-
TagDependent production is not matched if there does not exist a <tag> ele-
ment T in a relevant TLD such that L.T.body-content contains the value
‘tagdependent’.
• CustomActionJSPContentMatch - Assume the definition of L from the Cus-
tomActionMatchesAndValid validity constraint above. The CustomActionJSP-
Content production is not matched if there exists a <tag> element T in a
relevant TLD such that L.T.body-content does not contain the value ‘JSP’.
• CustomActionScriptlessContentMatch - Assume the definition of L from
the CustomActionMatchesAndValid validity constraint above. The CustomAc-
tionScriptlessContent production is not matched if there does not exist a <tag>

PUBLIC DRAFT
Syntactic Elements of a JSP Page 1-24

element T in a relevant TLD such that L.T.body-content contains the value


‘scriptless’.
• ETagMatch - A translation error will result if the Name for this ETag does
not match the name of the starting tag at the corresponding nesting level. This
is similar to the way XML is defined.

JSP.1.3.9.3 Standard Action Attributes


Table JSP.1-5 specifies, for each standard action element, the bodies and the
attribute combinations that are valid. The value in the “Body Production” column
specifies a production name that must be matched for the body of the standard
action to be considered valid. The value in the “Valid Attribute Combinations”
column uses the same syntax as the attrset notation described at the start of
Section JSP.1.3.9, and indicates which attributes can be provided. Note that for
some valid attribute combinations, there are differing body productions. The first
attribute combination to be matched selects the valid body production for this
standard action invocation.

Table JSP.1-5 Valid body content and attributes for Standard Actions
Element Body Production Valid Attribute Combinations

jsp:useBean OptionalBody ( !id, scope, !class )


OptionalBody ( !id, scope, !type )
OptionalBody ( !id, scope, !class, !type )
OptionalBody ( !id, scope, =!beanName, !type )

jsp:setProperty EmptyBody ( !name, !property, param )


EmptyBody ( !name, !property, =!value )
EmptyBody
jsp:getProperty EmptyBody ( !name, !property )

jsp:include ParamBody ( =!page, flush )

jsp:forward ParamBody ( =!page )

jsp:plugin PluginBody ( !type, !code, !codebase, align,


archive, =height, hspace,
jreversion, name, vspace, title,
=width, nspluginurl, iepluginurl )

PUBLIC DRAFT
1-25 CORE SYNTAX AND SEMANTICS

Table JSP.1-5 Valid body content and attributes for Standard Actions
jsp:invoke EmptyBody ( !fragment, !varReader, scope)
ParamBody ( !fragment )

jsp:doBody EmptyBody ( varReader!, scope )


ParamBody ()

JSP.1.4 Error Handling

Errors may occur at translation time or at request time. This section describes
how errors are treated by a compliant implementation.

JSP.1.4.1 Translation Time Processing Errors


The translation of a JSP page source into a corresponding JSP page implemen-
tation class by a JSP container can occur at any time between initial deployment of
the JSP page into the JSP container and the receipt and processing of a client request
for the target JSP page. If translation occurs prior to the receipt of a client request for
the target JSP page, error processing and notification is implementation dependent
and not covered by this specification. Fatal translation failures shall result in the fail-
ure of subsequent client requests for the translation target with the appropriate error
specification: For HTTP protocols the error status code 500 (Server Error) is
returned.

JSP.1.4.2 Request Time Processing Errors


During the processing of client requests, errors can occur in either the body of
the JSP page implementation class, or in some other code (Java or other implemen-
tation programming language) called from the body of the JSP page implementation
class. Runtime errors occurring are realized in the page implementation, using the
Java programming language exception mechanism to signal their occurrence to
caller(s) of the offending behavior1.

1.
Note that this is independent of scripting language. This specification re-
quires that unhandled errors occurring in a scripting language environ-
ment used in a JSP container implementation to be signalled to the JSP
page implementation class via the Java programming language exception
mechanism.

PUBLIC DRAFT
Comments 1-26

These exceptions may be caught and handled (as appropriate) in the body of
the JSP page implementation class.
Any uncaught exceptions thrown in the body of the JSP page implementation
class result in the forwarding of the client request and uncaught exception to the
errorPage URL specified by the JSP page (or the implementation default behavior,
if none is specified).
The offending java.lang.Throwable describing the error that occurred is stored
in the javax.ServletRequest instance for the client request using the setAttribute()
method, using the name “javax.servlet.jsp.jspException”. Names starting with the
prefixes “java” and “javax” are reserved by the different specifications of the Java
platform. The “javax.servlet” prefix is reserved and used by the Servlet and JSP
specifications.
If the errorPage attribute of a page directive names a URL that refers to
another JSP, and that JSP indicates that it is an error page (by setting the page
directive’s isErrorPage attribute to true) then the “exception” implicit scripting
language variable of that page is initialized to the offending Throwable reference

JSP.1.5 Comments

There are two types of comments in a JSP page: comments to the JSP page
itself, documenting what the page is doing; and comments that are intended to
appear in the generated document sent to the client.

JSP.1.5.1 Generating Comments in Output to Client


In order to generate comments that appear in the response output stream to the
requesting client, the HTML and XML comment syntax is used, as follows:

<!-- comments ... -->

These comments are treated as uninterpreted template text by the JSP


container. If the generated comment is to have dynamic data, this can be obtained
through an expression syntax, as in:

<!-- comments <%= expression %> more comments ... -->

JSP.1.5.2 JSP Comments


A JSP comment is of the form

PUBLIC DRAFT
1-27 CORE SYNTAX AND SEMANTICS

<%-- anything but a closing --%> ... --%>

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:

<% /** this is a comment ... **/ %>

JSP.1.6 Quoting and Escape Conventions

Note – Add EL quoting material here.

The following quoting conventions apply to JSP pages.

Quoting in Scripting Elements



A literal %> is quoted by %\>

Quoting in Template Text



A literal <% is quoted by <\%

Quoting in Attributes
Quotation is done consistently regardless of whether the attribute value is a
literal or a request-time attribute expression. Quoting can be used in attribute
values regardless of whether they are delimited using single or double quotes. It is
only required as described below.


A ‘ is quoted as \’. This is required within a single quote-delimited attribute
value.

A “ is quoted as \”. This is required within a double quote-delimited attribute
value.

A \ is quoted as \\

A %> is quoted as %\>

A <% is quoted as <\%

PUBLIC DRAFT
Quoting and Escape Conventions 1-28


The entities &apos; and &quot; are available to describe single and double
quotes.

Examples
The following line shows an illegal attribute values.

• <mytags:tag value="<%= "hi!" %>" />


The following line shows a legal scriptlet, but perhaps with an intended value.
The result is “Joe said %\>” not “Joe said %>”.

• <%= "Joe said %\\>" %>


The next lines are all legal quotations.

• <%= "Joe said %/>" %>


• <%= "Joe said %\>" %>
• <% String joes_statement = "hi!"; %>
<%= "Joe said \"" + joes_statement + "\"." %>
<x:tag value='<%="Joe said \\"" + joes_statement + "\\"."%>'/>
• <x:tag value='<%= "hi!" %>' />
• <x:tag value="<%= \"hi!\" %>" />
• <x:tag value='<%= \"name\" %>' />
• <x:tag value="<%= \"Joe said 'hello'\" %>"/>
• <x:tag value="<%= \"Joe said \\\"hello\\\" \" %>"/>
• <x:tag value="end expression %\>"/>
• <% String s="abc"; %>
<x:tag value="<%= s + \"def\" + \"jkl\" + 'm' + \'n\' %>" />
<x:tag value='<%= s + \"def\" + "jkl" + \'m\' + \'n\' %>' />

XML Representation
The quoting conventions are different from those of XML. See Chapter JSP.6.

PUBLIC DRAFT
1-29 CORE SYNTAX AND SEMANTICS

JSP.1.7 Overall Semantics of a JSP Page

A JSP page implementation class defines a _jspService() method mapping from


the request to the response object. Some details of this transformation are specific to
the scripting language used (see Chapter JSP.9). 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.1.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.1.10.1, “The page Directive””). This is the initial out object. JSP
page authors are prohibited from writing directly to either the PrintWriter or
OutputStream associated with the ServletResponse.

• The JSP container should not invoke response.getWriter() until the time when
the first portion of the content is to be sent to the client. This enables a number
of uses of JSP, including using JSP as a language to ‘glue’ actions that deliver
binary content, or reliably forwarding to a servlet, or change dynamically the
content type of the respose before generating content. See Chapter JSP.4.
• Within the body of some actions, out may be temporarily re-assigned to a dif-
ferent (nested) instance of JspWriter object. Whether this is the case depends
on the details of the action’s semantics. Typically the content of these tempo-
rary streams is appended to the stream previously referred to by out, and out is
subsequently re-assigned to refer to the previous (nesting) stream. Such nest-
ed streams are always buffered, and require explicit flushing to a nesting
stream or their contents will be discarded.
• If the initial out JspWriter object is buffered, then depending upon the value of
the autoFlush attribute of the page directive, the content of that buffer will ei-
ther be automatically flushed out to the ServletResponse output stream to ob-
viate overflow, or an exception shall be thrown to signal buffer overflow. If the
initial out JspWriter is unbuffered, then content written to it will be passed di-
rectly through to the ServletResponse output stream.

PUBLIC DRAFT
Objects 1-30

A JSP page can also describe what should happen when some specific events
occur. In JSP 2.0, the only events that can be described are the initialization and
the destruction of the page. These events are described using “well-known method
names” in declaration elements. (See Section JSP.10.1.1.1).

JSP.1.8 Objects

A JSP page can access, create, and modify server-side objects. Objects can be
made visible to actions and to scripting elements. An object has a scope describing
what entities can access the object.
Actions can access objects using a name in the PageContext object.
An object exposed through a scripting variable has a scope within the page.
Scripting elements can access some objects directly via a scripting variable.
Some implicit objects are visible via scripting variables in any JSP page.

Note – Add material on the EL here. Arrange emphasis on scripting.

JSP.1.8.1 Objects and Variables


An object may be made accessible to code in the scripting elements through a
scripting language variable. An element can define scripting variables that will con-
tain, at process request-time, a reference to the object defined by the element,
although other references may exist depending on the scope of the object.
An element type indicates the name and type of such variables although
details on the name of the variable may depend on the Scripting Language. The
scripting language may also affect how different features of the object are
exposed. For example, in the JavaBeans specification, properties are exposed via
getter and setter methods, while these properties are available directly as variables
in the JavaScript™ programming language.
The exact rules for the visibility of the variables are scripting language
specific. Chapter JSP.1.1 defines the rules for when the language attribute of the
page directive is “java”.

JSP.1.8.2 Objects and Scopes


A JSP page can create and/or access some Java objects when processing a
request. The JSP specification indicates that some objects are created implicitly,
perhaps as a result of a directive (see Section JSP.1.8.3, “Implicit Objects”). Other

PUBLIC DRAFT
1-31 CORE SYNTAX AND SEMANTICS

objects are created explicitly through actions, or created directly using scripting
code. Created objects have a scope attribute defining where there is a reference to
the object and when that reference is removed.
The created objects may also be visible directly to scripting elements through
scripting-level variables (see Section JSP.1.8.3, “Implicit Objects”).
Each action and declaration defines, as part of its semantics, what objects it
creates, with what scope attribute, and whether they are available to the scripting
elements.
Objects are created within a JSP page instance that is responding to a request
object. There are several scopes:

• page - Objects with page scope are accessible only within the page where they
are created. All references to such an object shall be released after the response
is sent back to the client from the JSP page or the request is forwarded some-
where else. References to objects with page scope are stored in the pageCon-
text object.

• request - Objects with request scope are accessible from pages processing the
same request where they were created. References to the object shall be re-
leased after the request is processed. In particular, if the request is forwarded
to a resource in the same runtime, the object is still reachable. References to
objects with request scope are stored in the request object.
• session - Objects with session scope are accessible from pages processing re-
quests that are in the same session as the one in which they were created. It is
not legal to define an object with session scope from within a page that is not
session-aware (see Section JSP.1.10.1, “The page Directive”). All references
to the object shall be released after the associated session ends. References to
objects with session scope are stored in the session object associated with the
page activation.
• application - Objects with application scope are accessible from pages pro-
cessing requests that are in the same application as they one in which they were
created. Objects with application scope can be defined (and reached) from pag-
es that are not session-aware. References to objects with application scope are
stored in the application object associated with a page activation. The
application object is the servlet context obtained from the servlet configuration
object. All references to the object shall be released when the runtime environ-
ment reclaims the ServletContext.

PUBLIC DRAFT
Objects 1-32

A name should refer to a unique object at all points in the execution, that is all
the different scopes really should behave as a single name space. A JSP container
implementation may or may not enforce this rule explicitly due to performance
reasons.

JSP.1.8.3 Implicit Objects


JSP page authors have access to certain implicit objects that are always avail-
able for use within scriptlets and expressions through scripting variables that are
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.

Note – The EG is exploring parametrizing the set of implicit objects so that


the JSP technology can be used outside of Servlets.

Each implicit object has a class or interface type defined in a core Java
technology or Java Servlet API package, as shown in Table JSP.1-6.

Table JSP.1-6 Implicit Objects Available in JSP Pages

Variable
Name Type Semantics & Scope

request protocol dependent subtype of: The request triggering


javax.servlet.ServletRequest the service invocation.
e.g: request scope.
javax.servlet.http.HttpServletRequest

response protocol dependent subtype of: The response to the


javax.servlet.ServletResponse, e.g: request.
javax.servlet.http.HttpServletResponse page scope.
pageContext javax.servlet.jsp.PageContext The page context for this
JSP page.
page scope.
session javax.servlet.http.HttpSession The session object
created for the requesting
client (if any).
This variable is only
valid for Http protocols.
session scope

PUBLIC DRAFT
1-33 CORE SYNTAX AND SEMANTICS

Table JSP.1-6 Implicit Objects Available in JSP Pages

Variable
Name Type Semantics & Scope

application javax.servlet.ServletContext The servlet context


obtained from the servlet
configuration object
(as in the call
getServletConfig().
getContext() )
application scope
out javax.servlet.jsp.JspWriter An object that writes into
the output stream.
page scope
config javax.servlet.ServletConfig The ServletConfig
for this JSP page
page scope
page java.lang.Object The instance of this
page’s implementation
class processing the
current requesta
page scope
a. When the scripting language is “java” then “page” is a synonym for “this” in
the body of the page.

In addition, the exception implicit object can be accessed in an error page, as


described in Table JSP.1-7.

Table JSP.1-7 Implicit Objects Available in Error Pages

Variable
Name Type Semantics & Scope

exception java.lang.Throwable The uncaught Throwable


that resulted in the error
page being invoked.
page scope.

Object names with prefixes jsp, _jsp, jspx and _jspx, in any combination of
upper and lower case, are reserved by the JSP specification.

PUBLIC DRAFT
Template Text Semantics 1-34

See Section JSP.7.6.1 for some non-normative conventions for the


introduction of new implicit objects.

JSP.1.8.4 The pageContext Object


A PageContext is an object that provides a context to store references to objects
used by the page, encapsulates implementation-dependent features, and provides
convenience methods. A JSP page implementation class can use a PageContext to
run unmodified in any compliant JSP container while taking advantage of imple-
mentation-specific improvements like high performance JspWriters.

Note – If we make JSP files not depend on Servlets, we may want to expose
the JspContext object, not the PageContext object.

See Chapter JSP.11 for more details.

JSP.1.9 Template Text Semantics

The semantics of template (or uninterpreted) Text is very simple: the template
text is passed through to the current out JspWriter implicit object, after applying the
substitutions of Section JSP.1.6, “Quoting and Escape Conventions”.

JSP.1.10 Directives

Directives are messages to the JSP container. Directives have this syntax:

<%@ directive { attr=”value” }* %>

There may be optional white space after the “<%@” and before “%>”.
This syntax is easy to type and concise but it is not XML-compatible.
Chapter JSP.6 describes the mapping of directives into XML elements.
Directives do not produce any output into the current out stream.
There are three directives: the page and the taglib directives are described
next, while the include directive is described in the next chapter.

JSP.1.10.1 The page Directive


The page directive defines a number of page dependent properties and commu-
nicates these to the JSP container.

PUBLIC DRAFT
1-35 CORE SYNTAX AND SEMANTICS

A translation unit (JSP source file and any files included via the include
directive) can contain more than one instance of the page directive, all the
attributes will apply to the complete translation unit (i.e. page directives are
position independent). However, there shall be only one occurrence of any
attribute/value defined by this directive in a given translation unit with the
exception of the “import” attribute; multiple uses of this attribute are cumulative
(with ordered set union semantics). Other such multiple attribute/value
(re)definitions result in a fatal translation error.
The attribute/value namespace is reserved for use by this, and subsequent, JSP
specification(s).
Unrecognized attributes or values result in fatal translation errors.

Examples
The following directive provides some user-visible information on this JSP
page:

<%@ page info=”my latest JSP Example” %>

The following directive requests no buffering, indicates that the page is thread
safe, and provides an error page.

<%@ page buffer=”none” isThreadSafe=”yes” errorPage=”/oops.jsp” %>

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.

<%@ page language=”java” import=”com.myco.*” buffer=”16kb” %>

Syntax
<%@ page page_directive_attr_list %>

PUBLIC DRAFT
Directives 1-36

page_directive_attr_list ::= { language=”scriptingLanguage”}


{ extends=”className” }
{ import=”importList” }
{ session=”true|false” }
{ buffer=”none|sizekb” }
{ autoFlush=”true|false” }
{ isThreadSafe=”true|false” }
{ info=”info_text” }
{ errorPage=”error_url” }
{ isErrorPage=”true|false” }
{ contentType=”ctinfo” }
{ pageEncoding=”peinfo” }

Note – Need to update treatment of pageEncoding to reflect the page-encod-


ing element. See Localization chapter for now.

JSP.1.10.2 Page property: isScriptingEnabled


Scripting elements in a page can be disabled using the page directive, through
the isScriptingEnabled attribute. This attribute can have two values:
true - to enable scripting elements
false - to disable scripting elements
The default is true.
When disabled, declarations, scriptlets and scripting expressions are all dis-
abled for this page. The corresponding JSP configuration element is scripting-
enabled.

JSP.1.10.3 Page property: isELEnabled


The EL evaluation for a page can be changed using the page directive, through
the isELEnabled attribute. This attribute can have two values:
true - to activate EL evaluation
false - to deactivate EL evaluation
The default value varies depending on the web.xml version - see the EL
chapter. When disabled, ${} will not be interpreted by the container. The
corresponding JSP configuration element is el-evaluation.

PUBLIC DRAFT
1-37 CORE SYNTAX AND SEMANTICS

The details of the attributes are as follows:

Table JSP.1-8

language Defines the scripting language to be used in the scriptlets,


expression scriptlets, and declarations within the body of the
translation unit (the JSP page and any files included using
the include directive below).
In JSP 2.0, the only defined and required scripting language
value for this attribute is “java”.
This specification only describes the semantics of scripts for
when the value of the language attribute is “java”.
When “java” is the value of the scripting language, the Java
Programming Language source code fragments used within
the translation unit are required to conform to the Java
Programming Language Specification in the way indicated
in Chapter JSP.9.
All scripting languages must provide some implicit objects
that a JSP page author can use in declarations, scriptlets, and
expressions. The specific objects that can be used are defined
in Section JSP.1.8.3, “Implicit Objects”.”
All scripting languages must support the Java Runtime
Environment (JRE). All scripting languages must expose the
Java technology object model to the script environment,
especially implicit variables, JavaBeans component
properties, and public methods.
Future versions of the JSP specification may define
additional values for the language attribute and all such
values are reserved.
It is a fatal translation error for a directive with a non-”java”
language attribute to appear after the first scripting element
has been encountered.
extends The value is a fully qualified Java programming language
class name, that names the superclass of the class to which
this JSP page is transformed (see Chapter JSP.10).
This attribute should not be used without careful
consideration as it restricts the ability of the JSP container to
provide specialized superclasses that may improve on the
quality of rendered service. See Section JSP.7.6.1 for an
alternate way to introduce objects into a JSP page that does
not have this drawback.

PUBLIC DRAFT
Directives 1-38

Table JSP.1-8

import An import attribute describes the types that are available to


the scripting environment. The value is as in an import
declaration in the Java programming language, i.e. a (comma
separated) list of either a fully qualified Java programming
language type name denoting that type, or of a package name
followed by the “.*” string, denoting all the public types
declared in that package. The import list shall be imported
by the translated JSP page implementation and is thus
available to the scripting environment.
The default import list is java.lang.*, javax.servlet.*,
javax.servlet.jsp.* and javax.servlet.http.*.
This value is currently only defined when the value of the
language directive is “java”.
session Indicates that the page requires participation in an (http)
session.
If “true” then the implicit script language variable named
“session” of type javax.servlet.http.HttpSession references the
current/new session for the page.
If “false” then the page does not participate in a session; the
“session” implicit variable is unavailable, and any reference
to it within the body of the JSP page is illegal and shall result
in a fatal translation error.
Default is “true”.
buffer Specifies the buffering model for the initial “out” JspWriter to
handle content output from the page.
If “none”, then there is no buffering and all output is written
directly through to the ServletResponse PrintWriter.
The size can only be specified in kilobytes, and the suffix
“kb” is mandatory.
If a buffer size is specified then output is buffered with a
buffer size not less than that specified.
Depending upon the value of the “autoFlush” attribute, the
contents of this buffer is either automatically flushed, or an
exception is raised, when overflow would occur.
The default is buffered with an implementation buffer size of
not less than 8kb.

PUBLIC DRAFT
1-39 CORE SYNTAX AND SEMANTICS

Table JSP.1-8

autoFlush Specifies whether the buffered output should be flushed


automatically (“true” value) when the buffer is filled, or
whether an exception should be raised (“false” value) to
indicate buffer overflow.
The default is “true”.
Note: it is illegal to set autoFlush to “false” when
“buffer=none”.
isThreadSafe Indicates the level of thread safety implemented in the page.
If “false” then the JSP container shall dispatch multiple
outstanding client requests, one at a time, in the order they
were received, to the page implementation for processing.
If “true” then the JSP container may choose to dispatch
multiple outstanding client requests to the page
simultaneously.
Page authors using “true” must ensure that they properly
synchronize access to the shared state of the page.
Default is “true”.
Note that even if the isThreadSafe attribute is “false” the JSP
page author must ensure that accesses to any shared objects
are properly synchronized., The objects may be shared in
either the ServletContext or the HttpSession.
info Defines an arbitrary string that is incorporated into the
translated page, that can subsequently be obtained from the
page’s implementation of Servlet.getServletInfo() method.
isErrorPage Indicates if the current JSP page is intended to be the URL
target of another JSP page’s errorPage.
If “true”, then the implicit script language variable
“exception” is defined and its value is a reference to the
offending Throwable from the source JSP page in error.
If “false” then the “exception” implicit variable is
unavailable, and any reference to it within the body of the
JSP page is illegal and shall result in a fatal translation error.
Default is “false”

PUBLIC DRAFT
Directives 1-40

Table JSP.1-8

errorPage Defines a URL to a resource to which any Java programming


language Throwable object(s) thrown but not caught by the
page implementation are forwarded for error processing.
The provided URL spec is as in Section JSP.1.2.1.
If the URL names another JSP page then, when invoked that
JSP page’s exception implicit script variable shall contain a
reference to the originating uncaught Throwable.
The default URL is implementation dependent.
Note the Throwable object is transferred by the throwing
page implementation to the error page implementation by
saving the object reference on the common ServletRequest
object using the setAttribute() method, with a name of
“javax.servlet.jsp.jspException”.
Note: if autoFlush=true then if the contents of the initial Jsp-
Writer has been flushed to the ServletResponse output stream
then any subsequent attempt to dispatch an uncaught
exception from the offending page to an errorPage may fail.
When an error page is also indicated in the web.xml
descriptor, the JSP error page applies first, then the web.xml
page.
contentType Defines the character encoding for the JSP page and for the
response of the JSP page and the MIME type for the
response of the JSP page.
Values are either of the form “TYPE” or “TYPE;
charset=CHARSET” with an optional white space after the
“;”. CHARSET, if present, must be the IANA value for a
character encoding. TYPE is a MIME type, see the IANA
registry for useful values.
The default value for TYPE is “text/html” for JSP Pages in
standard syntax, or "text/xml" for JSP Documents in XML
syntax. If CHARSET is not specified, but the page encoding
for the JSP page is specified, CHARSET defaults to the
specified page encoding. Otherwise, if neither CHARSET
nor the page encoding for the JSP page is specified, the
default value for CHARSET is ISO-8859-1 for JSP Pages in
standard syntax, or UTF-8 for JSP Pages in XML syntax.
See Chapter 4 for complete details on character encodings.

PUBLIC DRAFT
1-41 CORE SYNTAX AND SEMANTICS

Table JSP.1-8

pageEncoding Defines the character encoding for the JSP page.


Values is of the form “CHARSET” which must be the IANA
value for a character encoding.
The CHARSET value of contentType is used as default if
present, or ISO-8859-1 otherwise.
See Chapter 4 for complete details on character encodings.

JSP.1.10.4 The taglib Directive


The set of significant tags a JSP container interprets can be extended through a
“tag library”.
The taglib directive in a JSP page declares that the page uses a tag library,
uniquely identifies the tag library using a URI and associates a tag prefix that will
distinguish usage of the actions in the library.
If a JSP container implementation cannot locate a tag library description, a
fatal translation error shall result.
It is a fatal translation error for the taglib directive to appear after actions
using the prefix.
A tag library may include a validation method that will be consulted to
determine if a JSP page is correctly using the tag library functionality.
See Chapter JSP.7 for more specification details. And see Section JSP.7.2.3
for an implementation note.

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.

<%@ taglib uri=”http://www.mycorp/supertags” prefix=”super” %>


...
<super:doMagic>
...
</super:doMagic>

Syntax
<%@ taglib ( uri=”tagLibraryURI” | tagdir=”tagDir” ) prefix=”tagPrefix” %>

PUBLIC DRAFT
Directives 1-42

where the attributes are:

Table JSP.1-9

uri Either an absolute URI or a relative URI specification that


uniquely identifies the tag library descriptor associated with
this prefix.
The URI is used to locate a description of the tag library as
indicated in Chapter 7.
tagdir Indicates this prefix is to be used to identify tag extensions
installed in the /WEB-INF/tags/ directory or a subdirectory. If
a tld is present in the specified directory, it is used.
Otherwise, an implicit tag library is used. See
Section JSP.8.4.3 for more details. A translation error must
occur if the value does not start with “/WEB-INF/tags/” and
point to a directory that exists within the web application. A
translation error must result if used in conjunction with the
uri attribute.

prefix Defines the prefix string in <prefix>:<tagname> that is


used to distinguish a custom action, e.g <myPrefix:myTag>.
Prefixes starting with jsp:, jspx:, java:, javax:, servlet:, sun:,
and sunw: are reserved.
A prefix must follow the naming convention specified in the
XML namespaces specification.
Empty prefixes are illegal in this version of the specification.

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.

JSP.1.10.5 The include Directive


The include directive is used to substitute text and/or code at JSP page transla-
tion-time. The <%@ include file=”relativeURLspec” %> directive inserts the text of
the specified resource into the .jsp file. The included file is subject to the access con-
trol available to the JSP container. The file attribute is as in Section JSP.1.2.1.
A JSP container can include a mechanism for being notified if an included file
changes, so the container can recompile the JSP page. However, the JSP 2.0
specification does not have a way of directing the JSP container that included files
have changed.

PUBLIC DRAFT
1-43 CORE SYNTAX AND SEMANTICS

Examples
The following example requests the inclusion, at translation time, of a copy-
right file. The file may have elements which will be processed too.

<%@ include file=”copyright.html” %>

Syntax
<%@ include file="relativeURLspec" %>

JSP.1.10.6 Implicit Includes


Many JSP pages start with a list of taglib directives that activate the use of tag
libraries within the page. In some cases, these are the only tag libraries that are sup-
posed to be used by the JSP page authors. These, and other common conventions are
greately facilitated by two JSP configuration elements: include-prelude and include-
coda. Full description of the mechanism is in Section JSP.3.3.5.

JSP.1.10.7 Including Data in JSP Pages


Including data is a significant part of the tasks in a JSP page. Accordingly, the
JSP 2.0 specification has two include mechanisms suited to different tasks. A sum-
mary of their semantics is shown in Table JSP.1-10.

Table JSP.1-10 Summary of Include Mechanisms in JSP 2.0

Syntax Spec Object Description Section

Include Directive - Translation-time


<%@ include file=... %> file- static Content is parsed JSP.1.10.5
relative by JSP container.
Include Action - Request-time
<jsp:include page= /> page- static Content is not JSP.5.4
relative and dynamic parsed; it is
included in place.

The Spec column describes what type of specification is valid to appear in the
given element. The JSP specification requires a relative URL spec. The reference
is resolved by the web/application server and its URL map is involved. Include

PUBLIC DRAFT
EL Elements 1-44

directives are interpreted relative to the current JSP file; jsp:include actions are
interpreted relative to the current JSP page.
An include directive regards a resource like a JSP page as a static object; i.e.
the bytes in the JSP page are included. An include action regards a resource like a
JSP page as a dynamic object; i.e. the request is sent to that object and the result of
processing it is included.
Implicit include directives can also be requested for a collection of pages
through the use of the <include-prelude> and <include-coda> elements of the JSP
configuration section of web.xml.

JSP.1.10.8 Additional Directives for Tag Files


Additional directives are available when editing a tag file. See Section JSP.8.4.4,
“Tag File Directives” for details.

JSP.1.11 EL Elements

Note – A section talking about the use of EL at the top level of a page, in the
body of tags, and in attribute values.

Note – Describe how to disable them using page directives and JSP configura-
tion information.

JSP.1.12 Scripting Elements

Scripting elements are commonly used to manipulate objects and to perform


computation that affects the content generated.
There are three classes of scripting elements: declarations, scriptlets and
expressions. The scripting language used in the current page is given by the value
of the language directive (see Section JSP.1.10.1, “The page Directive”). In JSP
2.0, the only value defined is “java”.
Declarations are used to declare scripting language constructs that are
available to all other scripting elements. Scriptlets are used to describe actions to
be performed in response to some request. Scriptlets that are program fragments
can also be used to do things like iterations and conditional execution of other

PUBLIC DRAFT
1-45 CORE SYNTAX AND SEMANTICS

elements in the JSP page. Expressions are complete expressions in the scripting
language that get evaluated at response time; commonly, the result is converted
into a string and inserted into the output stream.
All JSP containers must support scripting elements based on the Java
programming language. Additionally, JSP containers may also support other
scripting languages. All such scripting languages must support:

• Manipulation of Java objects.


• Invocation of methods on Java objects.
• Catching of Java language exceptions.

The precise definition of the semantics for scripting done using elements
based on the Java programming language is given in Chapter JSP.9.
The semantics for other scripting languages are not precisely defined in this
version of the specification, which means that portability across implementations
cannot be guaranteed. Precise definitions may be given for other languages in the
future.
Each scripting element has a “<%”-based syntax as follows:

<%! this is a declaration %>


<% this is a scriptlet %>
<%= this is an expression %>

White space is optional after “<%!”, “<%”, and “<%=”, and before “%>”.
The equivalent XML elements for these scripting elements are described in
Section JSP.6.2.

JSP.1.12.1 Declarations
Declarations are used to declare variables and methods in the scripting language
used in a JSP page. A declaration should be a complete declarative statement, or
sequence thereof, according to the syntax of the scripting language specified.
Declarations do not produce any output into the current out stream.
Declarations are initialized when the JSP page is initialized and are made
available to other declarations, scriptlets, and expressions.

Examples
For example, the first declaration below declares an integer, global to the
page. The second declaration does the same and initializes it to zero. This type

PUBLIC DRAFT
Scripting Elements 1-46

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.

<%! int i; %>

<%! int i = 0; %>

<%! public String f(int i) { if (i<3) return(“...”); ... } %>

Syntax
<%! declaration(s) %>

JSP.1.12.2 Scriptlets
Scriptlets can contain any code fragments that are valid for the scripting lan-
guage specified in the language directive. Whether the code fragment is legal
depends on the details of the scripting language (see Chapter JSP.9).
Scriptlets are executed at request-processing time. Whether or not they
produce any output into the out stream depends on the code in the scriptlet.
Scriptlets can have side-effects, modifying the objects visible to them.
When all scriptlet fragments in a given translation unit are combined in the
order they appear in the JSP page, they must yield a valid statement, or sequence
of statements, in the specified scripting language.
To use the %> character sequence as literal characters in a scriptlet, rather
than to end the scriptlet, escape them by typing %\>.

Examples
Here is a simple example where the page changed dynamically depending on
the time of day.

<% if (Calendar.getInstance().get(Calendar.AM_PM) == Calendar.AM) {%>


Good Morning
<% } else { %>
Good Afternoon
<% } %>

A scriptlet can also have a local variable declaration, for example the following
scriptlet just declares and initializes an integer, and later displays its value and incre-
ments it.

PUBLIC DRAFT
1-47 CORE SYNTAX AND SEMANTICS

<% int i; i= 0; %>


Hi, the value of i is <% i++ %>

Syntax
<% scriptlet %>

JSP.1.12.3 Expressions
An expression element in a JSP page is a scripting language expression that is
evaluated and the result is coerced to a String. The result is subsequently emitted
into the current out JspWriter object.
If the result of the expression cannot be coerced to a String the following
must happen: If the problem is detected at translation time, a translation time error
shall occur. If the coercion cannot be detected during translation, a ClassCastEx-
ception shall be raised at request time.
A scripting language may support side-effects in expressions when the
expression is evaluated. Expressions are evaluated left-to-right in the JSP page. If
an expression appears in more than one run-time attribute, they are evaluated left-
to-right in the tag. An expression might change the value of the out object,
although this is not something to be done lightly.
The expression must be a complete expression in the scripting language in
which it is written.
Expressions are evaluated at HTTP processing time. The value of an
expression is converted to a String and inserted at the proper position in the .jsp
file.

Examples
This example inserts the current date.

<%= (new java.util.Date()).toLocaleString() %>

Syntax
<%= expression %>

PUBLIC DRAFT
Actions 1-48

JSP.1.13 Actions

Actions may affect the current out stream and use, modify and/or create objects.
Actions may depend on the details of the specific request object received by the JSP
page.
The JSP specification includes some actions that are standard and must be
implemented by all conforming JSP containers; these actions are described in
Chapter 5.
New actions are defined according to the mechanisms described in Chapters 7
and 12 and are introduced using the taglib directive.
The syntax for action elements is based on XML. Actions can be empty or
non-empty.

JSP.1.14 Tag Attribute Interpretation Semantics

The interpretation of all actions start by evaluating the values given to its
attributes left to right, and assigning the values to the attributes. In the process some
conversions may be applicable; the rules for them are described in
Section JSP.1.14.2.
Many values are fixed ‘translation-time values’, but JSP 2.0 also provides a
mechanism for describing values that are computed at request time, the rules are
described in Section JSP.1.14.1.

JSP.1.14.1 Request Time Attribute Values


An attribute value of the form “<%= scriptlet_expr %>” or
‘<%= scriptlet_expr %>’ denotes a request-time attribute value. The value denoted
is that of the scriptlet expression involved. Request-time attribute values can only
be used in actions and cannot be used in directives. If there are more than one such
attribute in a tag, the expressions are evaluated left-to-right.
Quotation is done as in any other attribute value (Section JSP.1.6).
Only attribute values can be denoted this way ( the name of the attribute is
always an explicit name). The expression must appear by itself (multiple
expressions, and mixing of expressions and string constants are not permitted).
Multiple operations must be performed within the expression. Type conversions
are described in Section JSP.1.14.2.
By default, all attributes have page translation-time semantics. Attempting to
specify a scriptlet expression as the value for an attribute that (by default or
otherwise) has page translation time semantics is illegal, and will result in a fatal

PUBLIC DRAFT
1-49 CORE SYNTAX AND SEMANTICS

translation error. The type of an action element indicates whether a given attribute
will accept request-time attribute values.
Most attributes in the standard actions from Chapter 5 have page translation-
time semantics, but the following attributes accept request-time attribute
expressions:

• The value attribute of jsp:setProperty (Section JSP.5.2).


• The beanName attribute of jsp:useBean (Section JSP.5.1).
• The page attribute of jsp:include (Section JSP.5.4).
• The page attribute of jsp:forward (Section JSP.5.5).
• The value attribute of jsp:param (Section JSP.5.6).
• The height and width attributes of jsp:plugin (Section JSP.5.7).

JSP.1.14.2 Type Conversions


We describe two cases for type conversions

JSP.1.14.2.1 Conversions from String values


A string value can be used to describe a value of a non-String type through a
conversion. Whether the conversion is possible, and, if so, what is it, depends on
a target type.
String values can be used to assign values to a type that has a PropertyEditor
class as indicated in the JavaBeans specification. When that is the case, the setAs-
Text(String) method is used. A conversion failure arises if the method throws an
IllegalArgumentException.
String values can also be used to assign to the types as listed in Table JSP.1-
11. The conversion applied is that shown in the table.
A conversion failure leads to an error, whether at translation time or request-
time.

Table JSP.1-11 Conversions from string values to target type

Target Type Source String Value


Bean Property Use setAsText(string-literal)
boolean or As indicated in java.lang.Boolean.valueOf(String)
Boolean

PUBLIC DRAFT
Tag Attribute Interpretation Semantics 1-50

Table JSP.1-11 Conversions from string values to target type

byte or Byte As indicated in java.lang.Byte.valueOf(String)


char or Character As indicated in String.charAt(0)
double or Double As indicated in java.lang.Double.valueOf(String)
int or Integer As indicated in java.lang.Integer.valueOf(String)
float or Float As indicated in java.lang.Float.valueOf(String)
long or Long As indicated in java.lang.Long.valueOf(String)
short of Short As indicated in java.lang.Short.valueOf(String)
Object As if new String(string-literal)

These conversions are part of the generic mechanism used to assign values
to attributes of actions: when an attribute value that is not a request-time
attribute is assigned to a given attribute, the conversion described here is used,
using the type of the attribute as the target type. The type of each attribute of the
standard actions is described in this specification, while the types of the
attributes of a custom action are described in its associated Tag Library Descrip-
tor.
A given action may also define additional ways where type/value conver-
sions are used. In particular, Section JSP.5.2 describes the mechanism used for
the setProperty standard action.

JSP.1.14.2.2 Conversions from request-time expressions


Request-time expressions can be assigned to properties of any type. No
automatic conversions will be performed.

PUBLIC DRAFT
C H A P T E R JSP.2
Expression Language

The JSP expression language (EL) has been developed in collaboration with
the JSP Standard Tag Library (JSTL) Expert Group (JSR-052) and it is used in both
specifications.
This chapter describes the expression language for JSP 2.0. Ideally, this
version of the expression language will be compatible with that used in JSTL 1.0,
but the JSR-052 EG has agreed to incorporate any changes the JSR-152 decides
there are required into a maintenance release of JSTL 1.0.

JSP.2.1 Overview

The EL is a simple language based on:

• Available namespace (the PageContext attributes)


• Nested properties and accessors to collections
• Relational, logical and arithmetic operators.
• Extensible functions mapping into static methods in Java classes.
• A set of implicit objects

Note – The expert group is investigating a mechanism to provide type infor-


mation. This could be used to provide better errors as well as better performance.

The EL is inspired by both ECMAScript and the XPath expression languages.


Both expert groups were very reluctant to design yet another expression language
and tried to use each of these languages but both were found to fall short in

PUBLIC DRAFT 1-51


Expressions and Attribute Values 1-52

different areas. The feedback received from users of JSTL 1.0 has been very
positive.
The only intrinsic dependencies on JSP or Servlet concepts are in the set of
implicit objects; the EL concept and machinery can be reused in other contexts
and this is made more feasible through the EL evaluation API that is described
later in this chapter.
The EL is available in attribute values for standard and custom actions and
within template text; in both cases the EL is invoked consistently via the construct
${expr}.
The addition of the EL to the JSP technology facilitates much the writing of
script-less JSP pages. These pages can use EL expressions but can’t use Java
scriptlets, Java expressions, or Java declaration elements. This usage pattern can
be enforced through the isScriptingEnabled page directive and also through the
scripting-enabled JSP configuration element.

JSP.2.2 Expressions and Attribute Values

EL expressions can be used in any attribute that can accept a run-time expres-
sion, be it a standard action or a custom action (see the section below on backward
compatibility issues).
There are three use cases for expressions in attribute values:

• The attribute value contains a single expression construct


<some:tag value="${expr}"/>
In this case, the expression is evaluated and the result is coerced to the at-
tribute's expected type according to the type conversion rules described later.
• The attribute value contains one or more expressions separated or surrounded
by text:
<some:tag value="some${expr}${expr}text${expr}"/>
In this case, the expressions are evaluated from left to right, coerced to Strings
(according to the type conversion rules described later), and concatenated
with any intervening text. The resulting String is then coerced to the at-
tribute's expected type according to the type conversion rules described later.
• The attribute value contains only text:
<some:tag value="sometext"/>

PUBLIC DRAFT
1-53 EXPRESSION LANGUAGE

In this case, the attribute's String value is coerced to the attribute's expected
type according to the type conversion rules described later. These rules are
equivalent to the JSP 1.2 conversions, except that empty strings are treated
differently.

JSP.2.2.1 Examples
The following shows a conditional action that uses the EL to test whether a
property of a bean is less than 3.

<c:if test="${bean1.a < 3}">


...
</c:if>

Note that the normal JSP coercion mechanism already allows for:

<mytags:if test="true" />

There may be literal values that include the character sequence "${". If that is
the case, a literal with that value can be used as shown here:

<mytags:example code="an expression is ${'${'}expr}" />

The resulting attribute value would then be the string “an expression is
${expr}”.

JSP.2.3 Expressions and Template Text

The EL can be used directly in template text, be it inside the body of a custom or
standard actions or in template text outside of any action. Exceptions are if the body
of the tag is tagdependent, or if EL is turned off (usually for compatibility issues)
explicitly through a directive or implicitly; see the next section.
The semantics of an EL is the same as with Java expressions: the value is
computed and inserted into the current output.

JSP.2.3.1 Examples
The following shows a custom action where two EL expressions are used to
access bean properties:

PUBLIC DRAFT
Deactivating EL Evaluation 1-54

<c:wombat>
One value is ${bean1.a} and another is ${bean2.a.c}
</c:if>

JSP.2.4 Deactivating EL Evaluation

Since the syntactic pattern ${expr} was not reserved in the JSP specifications
before JSP 1.2, there may be situations where such a pattern appears but the inten-
tion is not to activate EL expression evaluation but rather to pass through the pattern
verbatim. To address this, the EL evaluation machinery can be deactivated as indi-
cated in this section.
Each JSP page has a default EL evaluation mode that may be true or false.
The default mode for JSP pages in a Web Application delivered using a
web.xml using the Servlet 2.3 format is false; this provides for backward
compatibility.
The default mode for JSP pages in a Web Application delivered using a
web.xml using the Servlet 2.4 format is true; this provides automatically the
default that most applications want.
The default can be changed by setting the value of the elEvaluation property of
the page, either through a page directive, or through the JSP configuration
information for the web application using the el-evaluation element.

JSP.2.5 Desabling Scripting Elements

With the addition of the EL some JSP page authors, or page authoring groups,
may want to follow a methodology where scripting elements are not allowed. Previ-
ous versions of JSP enabled this through the notion of a TagLibraryValidator that
would verify that the elements are not present. JSP 2.0 makes this slightly easier
through a page directive to disable scripting elements and a corresponding JSP con-
figuration element.
Disabling scripting elements can be done through using the isScriptingEnabled
page directive and through the isScriptingEnabled element of the JSP
configuration.

PUBLIC DRAFT
1-55 EXPRESSION LANGUAGE

JSP.2.6 General Syntax

JSP.2.6.1 Overview
The syntax is quite simple. Variables are accessed by name. A generalized []
operator can be used to access maps, lists, arrays of objects and properties of a Java-
Beans object; the operator can be nested arbitrarily. The "." operator can be used as
a convenient shorthand for property access when the property name follows the con-
ventions of java identifiers, but the [] operator allows for more generalized access.
Relational comparisons are allowed using the standard Java relational
operators. Comparisons may be made against other values, or against boolean (for
equality comparisons only), String, integer, or floating point literals.
Arithmetic operators can be used to compute integer and floating point vlaues.
Logical operators are available.

JSP.2.6.2 Literals
There are literals for boolean, integer, floating point, string, null.

• Boolean - true and false


• Integer - As defined by the IntegerLiteral construct in Section JSP.2.13
• Floating point - As defined by the FloatingPointLiteral construct in
Section JSP.2.13
• String - With single and double quotes - " is escaped as \", ' is escaped as \',
and \ is escaped as \\ . Quotes only need to be escaped in a string value en-
closed in the same type of quote
• Null - null

JSP.2.6.3 Errors, Warnings, Default Values


JSP pages are mostly used in presentation, and in that usage, experience sug-
gests that it is most important to be able to provide as good a presentation as possi-
ble, even when there are simple errors in the page. To meet this requirement, the EL
does not provide warnings, just 'default values' and 'errors'. Default values are type-
correct values that are assigned to a subexpression when there is some problem. An
error is an exception thrown (to be handled by the standard JSP machinery).

PUBLIC DRAFT
General Syntax 1-56

Note – The details of error handling, which are tightly coupled with default-
ing and with the API to the EL evaluation, are still being investigated in the expert
group.

JSP.2.6.4 Operators "[]" and "."

Note – The EG has received some requests for customizing - through the API
- the interpretation of “.” for non-JSP uses of the EL. We still have not discussed
this.

The EL follows ECMAScript in unifying the treatment of the "." and "[]" opera-
tors.
expr-a.identifier-b is equivalent to a["identifier-b"]; that
is, the identifier identifier-b is used to construct a literal whose value is the
identifier, and then the "[]" operator is used with that value.
To evaluate expr-a[expr-b]:

• Evaluate expr-a into value-a


• if value-a is null, return null.
• Evaluate expr-b into value-b
• if value-b is null, return null.
• if value-a is a Map, List or array

if value-a is a Map
• if !value-a.containsKey(value-b) then return null.
• otherwise, return value-a.get(value-b)

if value-a is a List or array
• coerce value-b to int (using coercion rules);
• if coercion couldn't be performed: error
• then, if value-a.get(value-b) or Array.get(value-a,
value-b) throws ArrayIndexOutOfBoundsException or
IndexOutOfBoundsException: return null
• otherwise, if value-a.get(value-b) or Array.get(value-a,
value-b) throws other exception, error
• otherwise, return value-a.get(value-b) or

PUBLIC DRAFT
1-57 EXPRESSION LANGUAGE

Array.get(value-a, value-b), as appropriate.


• Otherwise (a JavaBeans object), coerce value-b to String

If value-b is a readable property of value-a
• if getter throws an exception: error
• otherwise: return result of getter call

otherwise: error

JSP.2.6.5 Arithmetic Operators


Arithmetic is provided to act on integer (long) and floating point values. There
are 5 operators:

• Addition: "+"
• Substraction: "-"
• Multiplication: "*"
• Division: "/" and "div"
• Remainder (modulo): "%" and "mod"

The last two operators are available in both syntaxes to be consistent with
XPath and ECMAScript.
The evaluation of arithmetic operators is described in the following sections.
A and B are the evaluation of subexpressions

JSP.2.6.5.1 Binary operators - A {+,-,*} B

• If A and B are null, - return 0


• If A or B is Float, Double, or a String containing ".", "e", or "E", coerce
both A and B to Double and apply operator
• Otherwise coerce both A and B to Long and apply operator
• If operator results in exception, error

JSP.2.6.5.2 Binary operator - A {/} B

• If A and B are null, - return 0


• Coerce both A and B to Double and apply operator

PUBLIC DRAFT
General Syntax 1-58

• If operator results in exception, error

JSP.2.6.5.3 Binary operator - A {%} B

• If A and B are null, return 0


• If A or B is Float, Double, or a String containing ".", "e", or "E", coerce
both A and B to Double and apply operator
• Otherwise coerce both A and B to Long and apply operator
• If operator results in exception, error

JSP.2.6.5.4 Unary minus operator - -A

• If A is null, return 0
• If A is a String

If A contains ".", "e", or "E", coerce to a Double and apply operator

Otherwise, coerce to a Long and apply operator

If operator results in exception, error
• If A is Byte, Short, Integer, Long, Float, Double

Retain type, apply operator

If operator results in exception, error
• Otherwise, error

JSP.2.6.5.5 Relational Operators


The relational operators are:

• "==" and “eq”


• "!=" and “ne”
• "<" and "lt"
• ">" and "gt"
• "<=" and "le"
• ">=" and "ge"

PUBLIC DRAFT
1-59 EXPRESSION LANGUAGE

The second versions of the last 4 operators are made available to avoid having
to use entity references in XML syntax and have the exact same behavior, i.e. "<"
behaves the same as "lt" and so on.
The evaluation of relational operators is described in the following sections.

JSP.2.6.5.6 A {<,>,<=,>=,lt,gt,le,ge} B

• If A==B, if operator is <=, le, >= or ge return true otherwise return false
• If A is null or B is null, return false
• If A or B is Float or Double coerce both A and B to Double apply oper-
ator
• If A or B is Byte, Short, Character, Integer, Long coerce both A
and B to Long and apply operator
• If A or B is String coerce both A and B to String, compare lexically
• If A is Comparable if A.compareTo (B) throws exception error otherwise use
result of A.compareTo(B)
• If B is Comparable if B.compareTo (A) throws exception error otherwise use
result of B.compareTo(A)
• Otherwise, error

JSP.2.6.5.7 A {==,!=,eq,ne} B

• If A==B, apply operator


• If A is null or B is null return false for ==, true for !=
• If A or B is Float or Double coerce both A and B to Double apply oper-
ator
• If A or B is Byte, Short, Character, Integer, Long coerce both A
and B to Long apply operator
• If A or B is Boolean coerce both A and B to Boolean apply operator
• If A or B is String coerce both A and B to String, compare lexically
• Otherwise if an error occurs while calling A.equals(B), error
• Otherwise, apply operator to result of A.equals(B)

PUBLIC DRAFT
General Syntax 1-60

JSP.2.6.6 Logical Operators


The logical operators are:

• && and and


• || and or
• ! and not

The evaluation of logical operators is described in the following sections.

JSP.2.6.6.1 Binary operator - A {&&,||,and,or} B

• Coerce both A and B to Boolean, apply operator


The operator stops as soon as expression can be determined, i.e., A and B and
C and D – if B is false, then only A and B is evaluated.

JSP.2.6.6.2 Unary not operator - {!,not} A

• Coerce A to Boolean, apply operator

JSP.2.6.7 Empty Operator - empty A


The empty operator is a prefix operator that can be used to determine if a value
is null or empty.
To evaluate empty A

• If A is null, return true,


• Otherwise, if A is the empty string, then return true.
• Otherwise, if A is an empty array, then return true.
• Otherwise, if A is an empty Map, return true
• Otherwise, if A is an empty List, return true,
• Otherwise return false.

Note – Other types may be added.

PUBLIC DRAFT
1-61 EXPRESSION LANGUAGE

JSP.2.6.8 Parentheses
Parentheses can be used to change precedence, as in: "${ ( a * (b + c)
) }"

JSP.2.6.9 Operator Precedence


Highest to lowest, left-to-right.

• [] .
• ()
• - (unary) not ! empty
• * / div % mod
• + - (binary)
• < > <= >= lt gt le ge
• == != eq ne
• && and
• || or

JSP.2.7 Reserved Words

The following words are reserved for the language and should not be used as
identifiers without being quoted.
and eq gt true instanceof
or ne le false empty
not lt ge null div mod
Note that many of these words are not in the language now, but they may be in
the future, so developers should avoid using these words now.

JSP.2.8 Named Variables

A core concept in the EL is the evaluation of an identifier. The EL API provides


a mechanism to plug in a VariableResolver into the EL evaluation machinery, but in
the context of the JSP evaluation, the EL evaluates an identifier by looking up its
value as an attribute, according to the behavior of PageContext.findAt-
tribute(String). For example:

PUBLIC DRAFT
Functions 1-62

${product}

This expression will look for the attribute named "product", searching the
page, request, session, and application scopes, and will return its value. If the
attribute is not found, null is returned.
Note that an identifier that matches one of the implicit objects described in the
next section will return that implicit object instead of an attribute value.

JSP.2.9 Functions

Note – The EG is exploring this functionality and would like to get feedback
on its usefulness; if the feedback is not conclusive we will drop this functionality
from JSP 2.0.

The EL has qualified functions, reusing the notion of qualification from XML
namespaces (& attributes), XSL functions, and JSP custom actions. Functions are
mapped into public static methods in Java classes. In JSP 2.0 the map is specified
in the TLD.

Note – The TLD description has not yet been updated with the new elements
described here.

JSP.2.9.1 Invocation Syntax


The full syntax is that of qualified n-ary functions:

ns:f(a1,a2... an)

As with the rest of EL, this element can appear in attributes and directly in
template text.
An alternate syntax:

f(a1,a2... an)

is valid within attribute values of custom actions. This is equivalent to


“ns.f(...)”, where "ns" is the prefix of the custom action

PUBLIC DRAFT
1-63 EXPRESSION LANGUAGE

JSP.2.9.2 Tag Library Descriptor Information


Each tag library may include zero or more n-ary (static) functions. The TLD
associated with a tag library lists the functions.
Each such function is given a name (as seen in the EL), and a static method in
a specific class that will implement the function.
JSP 2.0 does not support function overloads, but supports different functions
with same name but different number of arguments.
The following elements are added to the Tag Library Descriptor file

JSP.2.9.2.1 function element


The function element is an optional child of the taglib element and can appear
multiple times. It is used to provide information on each function in the tag library
that is to be exposed to the EL.

<!ELEMENT taglib (.... tag*, function*)>

<!ELEMENT function (name, function-class, function-signature, display-name?,


small-icon?, large-icon?, description?, example?)>

The name, display-name, small-icon, large-icon, description, and example


elements have the same semantics as elsewhere in the TLD. The function-class
and function-signature elements are new and described below.

Note – Small-icon and large-icon are included for completeness; it could be


argued that they are not needed since EL is a textual language. Feedback appreci-
ated.

JSP.2.9.2.2 function-class element


The function-class element is a mandatory child of the function element. It
provides the name of the Java class that is to be used to implement the function.
The class must be a public non-abstract class; failure shall generate a
translation-time error.

<!ELEMENT function-class (#PCDATA) >

PUBLIC DRAFT
Functions 1-64

JSP.2.9.2.3 function-signature element


The function-signature element is a mandatory child of the function element.
It provides the signature, as in the Java Language Specification, of the Java class
that is to be used to implement the function.
The value of this element must be a public static method in the class described
in the function-class element; failure shall generate a translation-time error.
A tag library can have two or more function elements in the same tag library
with the same value for their name element as long as their function-signature
values have different number of arguments. If two functions have the same name
and the same number of elements, a translation-time error shall be generated.

<!ELEMENT function-signature (#PCDATA) >

JSP.2.9.3 Example
The following TLD fragment describes a function with name nickname that is
intended to fetch the nickname of the user:

<taglib>
...
<function>
<name>nickname</name>
<function-class>mypkg.MyFunctions</function-class>
<function-signature>String nickName(String)</function-signature>
</function>
</taglib>

The following EL fragment shows the invocation of the function:

<h2>Dear ${nickname(user)}</h2>

JSP.2.9.4 Semantics

• If the function has no namespace associated, then, if the function is used in an


attribute value, assume the namespace as that of the custom action; if the
function is used elsewhere, this shall be a translation time error.
Let “ns” be the namespace associated with the function, and “f” be the
namespace associated with the function.
• Locate the TLD associated with "ns". If none can be found, this shall be a
translation-time error.

PUBLIC DRAFT
1-65 EXPRESSION LANGUAGE

• Locate the function element with a name subelement with value “f" in that
TLD. If none can be found, this shall be a translation-time error.
• Locate the public class with name equal to the value of the function-class ele-
ment. Locate the public static method with name and signature equal to the
value of the function-signature element. If any of these don’t exist, a transla-
tion-time error shall occur..
• Evaluate each argument to the corresponding type indicated in the signature
• Evaluate the public static Java method. The resulting type is that of the return
value in the function-signature element.

JSP.2.10 Implicit Objects

The EL defines a set of implicit objects which depends on the context in which
the EL is being used. When an expression references one of these objects by name,
the appropriate object is returned instead of the corresponding attribute. For exam-
ple in the context of JSP pages, ${pageContext} returns the PageContext object,
even if there is an existing pageContext attribute containing some other value.
The following implicit objects are available to EL expressions used in JSP
pages:

• pageContext - the PageContext object


• pageScope - a Map that maps page-scoped attribute names to their values
• requestScope - a Map that maps request-scoped attribute names to their val-
ues
• sessionScope - a Map that maps session-scoped attribute names to their val-
ues
• applicationScope - a Map that maps application-scoped attribute names to
their values
• param - a Map that maps parameter names to a single String parameter value
(obtained by calling ServletRequest.getParameter(String name))
• paramValues - a Map that maps parameter names to a String[] of all values for
that parameter (obtained by calling ServletRequest.getParameterValues(String
name))

PUBLIC DRAFT
Type Conversion 1-66

• header - a Map that maps header names to a single String header value (ob-
tained by calling ServletRequest.getHeader(String name))
• headerValues - a Map that maps header names to a String[] of all values for
that header (obtained by calling ServletRequest.getHeaders(String))
• cookie - a Map that maps cookie names to a single Cookie object. Cookies
are retrieved according to the semantics of HttpServletRequest.getCookies(). If
the same name is shared by multiple cookies, an implementation must use the
first one encountered in the array of Cookie objects returned by the getCook-
ies() method. However, users of the cookie implicit object must be aware that
the ordering of cookies is currently unspecified in the Servlet specification.
• initParam - a Map that maps context initialization parameter names to their
String parameter value (obtained by calling ServletContext.getInitParame-
ter(String name))

The following table shows some examples of using these implicit objects:

Expression Result
The request's URI (obtained from
${pageContext.request.requestURI}
HttpServletRequest)
The session-scoped attribute named profile
${sessionScope.profile}
(null if not found)
The String value of the productId
${param.productId}
parameter, or null if not found
The String[] containing all values of the
${paramValues.productId}
productId parameter, or null if not found

JSP.2.11 Type Conversion

Every expression is evaluated in the context of an expected type. The result of


the expression evaluation may not match the expected type exactly, so the rules
described in the following sections are applied:

JSP.2.11.1 Coerce A to String

• If A is String: return A
• Otherwise, if A is null: return "".

PUBLIC DRAFT
1-67 EXPRESSION LANGUAGE

• Otherwise, if A.toString() throws exception, error


• Otherwise, return A.toString()
• Otherwise, if A is a primitive type, return a String as in the java expression
""+A

JSP.2.11.2 Coerce A to primitive Number type N

• If A is null or "", return 0.


• If A is Character, convert to short, apply following rules.
• If A is Boolean, then error.
• If A is Number type N, return A
• If A is Number with less precision than N, coerce quietly
• If A is Number with greater precision than N, coerce quietly
• If A is String, and new N.valueOf(A) throws exception, then error.
• If A is String, and N.valueOf(A) does not throw exception, return it.
• Otherwise, error.

JSP.2.11.3 Coerce A to Character

• If A is null or "", return (char) 0


• If A is Character, return A
• If A is Boolean, error
• If A is Number with less precision than short, coerce quietly – return
(char) A
• If A is Number with greater precision than short, coerce quietly – return
(char) A
• If A is String, return A.charAt (0)
• Otherwise, error

PUBLIC DRAFT
API to Expression Evaluator 1-68

JSP.2.11.4 Coerce A to Boolean

• If A is null or "", return false


• Otherwise, if A is Boolean, return A
• Otherwise, if A is String, and Boolean.valueOf(A) throws exception,
error.
• Otherwise. if A is String return Boolean.valueOf(A)
• Otherwise, error

JSP.2.11.5 Coerce A to any other type T

• If A is null, return null


• If A is assignable to T, coerce quietly
• If A is a primitive type, return a boxed object with equivalent value, as fol-
lows:
• If A is an int, return new Integer(A)
• If A is a float, return new Float(A)
• If A is String, and T has no PropertyEditor
• If A is "", return null
• Otherwise error
• If A is String and T's PropertyEditor throws exception
• If A is "", return null
• Otherwise, error
• Otherwise, apply T's PropertyEditor.
• Otherwise, error

JSP.2.12 API to Expression Evaluator

The EL specification provides an API to an EL expression evaluator. This API


can be used by an implementation of JSP to evaluate the expressions, but other
implementations, like open-coding into Java bytecodes, are allowed. The

PUBLIC DRAFT
1-69 EXPRESSION LANGUAGE

ExpressionEvaluator object can be obtained by an invocation on the


JspContext.getExpressionEvaluator() method on the corresponding object.
More details on the Expression Evaluator API are available in Chapter JSP.13

JSP.2.12.1 ExpressionEvaluator Interface


The main interface is ExpressionEvaluator which provides a main method of
the form:

public interface ExpressionEvaluator {


/*
* Translation time validation of an expression.
* This method will return a null String if the expression
* is valid; otherwise an error message.
*/
public String validate(String attributeName,
String expression);
/**
* Evaluates the expression at request time.
*/
public Object evaluate(String attributeName,
String expression,
Class expectedType,
Tag tag,
PageContext pageContext)
throws JspException;
}

JSP.2.12.2 VariableResolver Interface


This interface can be used to customize how to resolve a 'variable' in the EL

public interface VariableResolver {


/**
* Resolves the specified variable within the given context.
* Returns null if the variable is not found.
**/
public Object resolveVariable (String pName,
Object pContext)
throws ELException;
}

PUBLIC DRAFT
Collected Syntax 1-70

JSP.2.12.3 Constructor Classes and Other Types


The API will also provide:

• A mechanism to instantiate an EL evaluator, including a way to modify the


JSP-specific VariableResolver.
• A mechanism to a better handle run-time error, probably tied to defaulting.

Note – The EL API will be completed before making an implementation


available as an Early Access. The specification will then be updated to reflect that
experience.

JSP.2.13 Collected Syntax

The following are the constructs supported by the EL:

Expression ::=- Expression BinaryOp Expression


| UnaryExpression

BinaryOp ::=- 'and'


| ‘&&’
| ‘or’
| ‘||’
| '+'
| '-'
| '*'
| '/'
| 'div'
| '%'
| 'mod'
| '>'
| 'gt'
| '<'
| 'lt'
| '>='
| 'ge'
| '<='
| 'le'
| '=='

PUBLIC DRAFT
1-71 EXPRESSION LANGUAGE

| ‘eq’
| '‘!=’
| ‘ne’

UnaryExpression ::=- UnaryOp UnaryExpression


| Value

UnaryOp ::=- '-'


| ‘not’

Value ::=- ValuePrefix


| Value ValueSuffix

ValuePrefix ::=- Literal


| '(' Expression ')'
| Identifier except for ImplicitObject
| ImplicitObject

ValueSuffix ::=- ‘.’Identifier


| [Expression]

Identifier ::=- Java language identifier

ImplicitObject ::=- 'pageContext'


| ‘pageScope’
| 'requestScope'
| 'sessionScope'
| 'applicationScope'
| 'param'
| 'paramValues'
| 'header'
| 'headerValues'
| 'initParam'
| 'cookie'

Literal ::=- BooleanLiteral


| IntegerLiteral
| FloatingPointLiteral
| StringLiteral
| NullLiteral

BooleanLiteral ::=- 'true'


| ‘false’

StringLiteral ::=- '([^'\]|\'|\\)*'


| "([^'\]|\'|\\)*"
i.e., a string of any characters enclosed
by single or double quotes, where \ is
used to escape ', ", and \. It is possible

PUBLIC DRAFT
Collected Syntax 1-72

to use single quotes within double


quotes, and vice versa, without
escaping.

IntegerLiteral ::=- ["+","-"] ["1"-"9"] (["0"-"9"])*

FloatingPointLiteral ::=- (["+","-"])? (["0"-"9"])+ "." (["0"-"9"])* (["e","E"]


(["+","-"])? (["0"-"9"])+)?
| (["+","-"])? "." (["0"-"9"])+ (["e","E"] (["+","-
"])? (["0"-"9"])+)?
| (["+","-"])? (["0"-"9"])+ ["e","E"] (["+","-"])?
(["0"-"9"])+

NullLiteral ::=- 'null'

Notes:

• An identifier is constrained to be a Java identifier - i.e., no "-", no "/", etc. with-


out quoting.
• A String only recognizes a limited set of escape sequences, and \ may not
appear unescaped. This may eventually be expanded, but once again, this is
the minimum.
• The definitions for integer and floating point literals are pretty much taken
from the Java definitions.
• The relational operator for equality is "==" (double equals).

PUBLIC DRAFT
1-73 EXPRESSION LANGUAGE

PUBLIC DRAFT
C H A P T E R JSP.3
JSP Configuration

This chapter describes the JSP configuration information.


JSP.3.1 JSP configuration information in web.xml

A Web Application can include general JSP configuration information in its


web.xml file that is to be used by the JSP container. The information is described
through the jsp-config element and its subelements.

Note – The Expert Group is exploring whether to allow JSP configuration


information to be in a separate file, outside of web.xml

JSP.3.1.1 <jsp-config>
A jsp-config is a subelement of web-app that is used to provide global
configuration information for the JSP files in a Web Application.

<!ELEMENT web-app .... jsp-config? .... >

<!ELEMENT jsp-config (taglib* jsp-property-group*)>


<!ATTLIST jsp-config id ID #IMPLIED>

A jsp-config has two subelements: taglib and jsp-property-group, defining the


taglib mapping and groups of JSP files.

PUBLIC DRAFT 1-74


1-75 JSP CONFIGURATION

JSP.3.2 Taglib map

The web.xml file can include an explicit taglib map between URIs and TLD
resource paths described using the taglib elements of the Web Application Deploy-
ment descriptor in WEB-INF/web.xml, as described in the Servlet 2.3 spec and in
“http://java.sun.com/j2ee/dtds/web-app_2_3.dtd”.

Note – The above needs updating to reflect the new separation between the
two specifications.

A taglib element is a subelement of the jsp-config element. A taglib element


has two subelements: taglib-uri and taglib-location.

JSP.3.2.1 <taglib>
A taglib is a subelement of jsp-config that can be used to provide information
on a tag library that is used by a JSP page within the Web Application.
A taglib element has two subelements and one attribute:

<!ELEMENT taglib ( taglib-uri, taglib-location ) >


<!ATTLIST taglib id ID #IMPLIED>

JSP.3.2.2 <taglib-uri>
A taglib-uri element describes a URI identifying a tag library used in the web
application.

<!ELEMENT taglib-uri (#PCDATA) >


PCDATA ::= a URI spec.

The body of the taglib-uri element may be either an absolute URI specifica-
tion, or a relative URI as in Section JSP.1.2.1. There should be no entries in
web.xml with the same taglib-uri value.

JSP.3.2.3 <taglib-location>
A taglib-location contains the location (as a resource) of the Tag Library
Description File for the tag library.

<!ELEMENT taglib-location (#PCDATA) >

PUBLIC DRAFT
JSP Property Groups 1-76

PCDATA ::= a resource location, as indicated in Section JSP.1.2.1, where to


find the Tag Library Descriptor file.

JSP.3.3 JSP Property Groups

A JSP property group is a collection of properties that apply to a set of JSP files.
Currently all the properties correspond to page directives.
The applicability of a JSP property group is defined through one or more URL
patterns; all the properties in the group apply to the resources in the Web
Application that match any of the URL patterns. There is an implicit property: that
of being a JSP file.

Note – There is no mechanism to indicate that a resource is not a JSP file; that
means that all .jsp resources are JSP files, unless overridden by the servlet map-
pings. Please provide feedback if you feel an explicit property is needed.

Note – Need to clarify how to resolve overlaps on being a JSP file between
servlet mappings and JSP configuration info.

If a resource matches URL patterns in more than one group, the pattern that is
most specific (following the same rules as in the Servlet specification) applies.

JSP.3.3.1 <jsp-property-group>
A jsp-property-group is a subelement of jsp-config:

<!ELEMENT jsp-property-group (url-pattern+ el-evaluation? page-encoding?


scripting-enabled? include-prelude* include-coda*)>
<!ATTLIST jsp-property-group id ID #IMPLIED>

The properties that can currently be described in a jsp-property-group include;



Resource being a JSP file (implicit).

Control enabling of EL evaluation.

Control enabling of Scripting elements.

Indicate pageEncoding information.

Prelude and Coda automatic includes.

PUBLIC DRAFT
1-77 JSP CONFIGURATION

JSP.3.3.2 Enabling EL Evaluation


The JSP configuration element el-evaluation can be used to easily set the
elEvaluation property of a group of JSP pages defined using the jsp-property-group
element.
The el-evaluation element is a subelement of jsp-property-group (see 3.3.1). It
has no subelements. Its valid values are true and false.

<!ELEMENT el-evaluation (#PCDATA) >


<!ATTLIST el-evaluation id ID #IMPLIED>

For example, the following web.xml fragment defines a group that activates
EL evaluation for all JSP pages delivered using the “.jsp” extension:

<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-evaluation>true</el-evaluation>
</jsp-property-group>

JSP.3.3.3 Enabling Scripting


The JSP configuration element scripting-enabled can be used to easily set the
isScriptingEnabled property of a group of JSP pages defined using the jsp-property-
group element.
The scripting-enabled element is a subelement of jsp-property-group (see
3.3.1). It has no subelements. Its valid values are true and false.

<!ELEMENT scripting-enabled (#PCDATA) >


<!ATTLIST scripting-enabled id ID #IMPLIED>

For example, the following web.xml fragment defines a group that disables
scripting elements for all JSP pages delivered using the “.jsp” extension:

<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-enabled>false</scripting-enabled>
</jsp-property-group>

PUBLIC DRAFT
JSP Property Groups 1-78

JSP.3.3.4 Declaring Page Encodings


The JSP configuration element page-encoding can be used to easily set the
pageEncoding property of a group of JSP pages defined using the jsp-property-
group element.
The page-encoding element is a subelement of jsp-property-group (see 3.3.1).
It has no subelements. Its valid values are those of the pageEncoding page
directive. It is a translation-time error to define the pageEncoding of a JSP page
through one value in the JSP configuration element and then give it a different
value in a pageEncoding directive, but it is legal to give it the same value.

<!ELEMENT page-encoding (#PCDATA) >


<!ATTLIST page-encoding id ID #IMPLIED>

For example, the following web.xml fragment defines a group that explicitly
assigns ISO-8859-1 to all JSP pages delivered using the “.jsp” extension:

<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>ISO-8859-1</page-encoding>
</jsp-property-group>

JSP.3.3.5 Defining Implicit Includes


The include-prelude element is an optional subelement of jsp-property-group.
It has no subelements. Its value is a context-relative path that must correspond to
an element in the Web Application. When the element is present, the given path
will be automatically included (as in an include directive) at the beginning of the
JSP page in the jsp-property-group. When there are more than one include-prelude
element in a group, they are to be included in the order they appear. When more
than one jsp-property-group applies to a JSP page, the corresponding include-
prelude elements will be processed in the same order as they appear in the JSP
configuration section of web.xml.
The include-coda element is an optional subelement of jsp-property-group. It
has no subelements. Its value is a context-relative path that must correspond to an
element in the Web Application. When the element is present, the given path will
be automatically included (as in an include directive) at the end of the JSP page in
the jsp-property-group. When there are more than one include-coda element in a
group, they are to be included in the order they appear. When more than one jsp-
property-group applies to a JSP page, the corresponding include-coda elements

PUBLIC DRAFT
1-79 JSP CONFIGURATION

will be processed in the same order as they appear in the JSP configuration section
of web.xml.

<!ELEMENT include-prelude (#PCDATA) >


<!ATTLIST include-prelude id ID #IMPLIED>

<!ELEMENT include-coda (#PCDATA) >


<!ATTLIST include-coda id ID #IMPLIED>

For example, the following web.xml fragment defines two groups. Together
they indicate that JSP pages in directory foo/ have /preludes/p1.jsp and /preludes/
p2.jsp at the beginning and /codas/c1.jsp and /codas/c2.jsp at the end, in that order,
while other .jsp files only have /preludes/p1.jsp at the beginning and /codas/c1.jsp
at the end .

<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<include-prelude>/preludes/p1.jsp</include-prelude>
<include-coda>/codas/c1.jsp</include-coda>
</jsp-property-group>
<jsp-property-group>
<url-pattern>two/*.jsp</url-pattern>
<include-prelude>/preludes/p2.jsp</include-prelude>
<include-coda>/codas/c2.jsp</include-coda>
</jsp-property-group>

PUBLIC DRAFT
C H A P T E R JSP.4
Localization Issues

This chapter describes requirements for localization with JavaServer Pages


2.0 (JSP 2.0).

JSP.4.1 Page Character Encoding

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

A JSP page uses a character encoding. The encoding can be described


explicitly using the pageEncoding attribute of the page directive. The character
encoding defaults to the encoding indicated in the contentType attribute of the
page directive if it is given, or to ISO-8859-1 otherwise. ISO-8859-1 is also
known as latin-1.
The valid names for describing character encodings in JSP 2.0 are those of
IANA. They are described at:

http://www.iana.org/assignments/character-sets

The pageEncoding attribute should be used only when the character encoding
of a JSP page is organized so that ASCII characters stand for themselves. The

PUBLIC DRAFT 1-80


1-81 LOCALIZATION ISSUES

directive containing the pageEncoding attribute should appear as early as possible


in the JSP page.
A JSP container may use some implementation-dependent heuristics and/or
structure to determine what the expected character encoding of a JSP page is and
verify that the contentType attribute is as expected.
A JSP container will raise a translation-time error if an unsupported character
encoding is requested.
Table JSP.4-1 clarifies the relationship between the declared page encoding
and content type and the input JSP page character encoding.

Table JSP.4-1 Effects of declared page encoding and content type on JSP
source encoding and output content type.

pageEncoding contentType
Page Directive Page Directive Input JSP
Attribute Attribute Source
(<encoding>) (<contentType>) Encoding Output Content Type

specified specified <encoding> <contentType>

specified not specified <encoding> "<defaultType>;


charset=<encoding>"

not specified specified <contentType <contentType>


charset>

not specified not specified <defaultInput "<defaultType>;


Encoding> charset=<default
InputEncoding>"

Where:

• <defaultType> is "text/html" for JSP Pages in standard syntax, or "text/xml" for


JSP Documents in XML syntax.
• <defaultEncoding> is "ISO-8859-1" for JSP Pages in standard syntax, or
"UTF-8" for JSP Documents in XML syntax.
• <defaultInputEncoding> is "ISO-8859-1" for JSP Pages in standard syntax, or
"UTF-8" or "UTF-16" for JSP Documents in XML syntax (depending on the
type detected as per the rules in the XML specification). Note that, in the case
of include directives, the default input encoding is derived from the initial
page, not from any of the included pages.

PUBLIC DRAFT
Static Content Type 1-82

Also see Chapter 3 for information on using the page-encoding element in the
JSP configuration to indicate the encoding of a JSP page.

JSP.4.2 Static Content Type

Most JSP pages are written to deliver a response using a specific content type
and character encoding. A JSP page can use the contentType attribute of the page
directive to indicate the content type of the response it provides to requests.
When used this way, a given page will always provide the same content type.
If a page determines that the response should be of a different content type, it
should do so “early”, determine what other JSP page or servlet will handle this
request, and forward the request to the other JSP page or servlet.
For JSP Pages in standard syntax, the default value for TYPE is "text/html"
and the default value for the character encoding is ISO-8859-1. For JSP
Documents in XML syntax, the default value for TYPE is "text/xml" and the
default value for the character encoding is UTF-8. Table JSP.4-1 clarifies the
relationship between the declared page encoding and content type and the output
content type used.
A registry of content type names is kept by IANA. See:

http://www.iana.org/assignments/media-types/index.html

The contentType attribute must only be used when the character encoding is
organized such that ASCII characters stand for themselves, at least until the con-
tentType attribute is found. The directive containing the contentType attribute
should appear as early as possible in the JSP page.

JSP.4.3 Dynamic Content Type and Character Encoding

Some JSP pages are designed so they can deliver content using different
content types (and character sets) depending on request time input. These pages
may be organized as custom actions or scriptlets that determine the response
content type and provide glue into other code actually generating the content of
the response.
The initial content type for the response (including the character set) is
determined as shown in the "Output Content Type" column in Table JSP.4-1. In all
cases, the container must call response.setContentType() with the initial content
type before processing the page.

PUBLIC DRAFT
1-83 LOCALIZATION ISSUES

The content type (and character set) can then be changed dynamically by
calling setContentType() or setLocale() on the response object. The most recent
call takes precedence. Changing the content type can be done up until the point
where the response is committed. Data is sent to the response stream on buffer
flushes for buffered pages, or on encountering the first content (beware of
whitespace) on unbuffered pages. Whitespace is notoriously tricky for JSP Pages
in JSP syntax, but much more manageable for JSP Documents in XML syntax.

JSP.4.4 Delivering Localized Content

The JSP specification does not mandate any specific approach for structuring
localized content, and different approaches are possible. Two common approaches
are to use a template taglib and pull localized strings from a resource repository, or
to use-per-locale JSP pages. Each approach has benefits and drawbacks. Some users
have been using transformations on JSP documents to do simple replacement of ele-
ments by localized strings, thus maintaining JSP syntax with no performance cost at
run-time. Combinations of these approaches also make sense.
There are a number of different efforts that are exploring how to best do
localization. We expect JSR-052, the standard JSP tag library, to address some of
these issues.

PUBLIC DRAFT
C H A P T E R JSP.5
Standard Actions

This chapter describes the standard actions of JavaServer Pages 2.0 (JSP 2.0).
Note – In principle, we intend to allow EL expressions whenever a Java
expression is allowed in a standard action. We will be adding this in more detail as
part of a later draft.

JSP.5.1 <jsp:useBean>

A jsp:useBean action associates an instance of a Java programming language


object defined within a given scope and available with a given id with a newly
declared scripting variable of the same id.

Note – The details of how useBean interacts with a script-less page will be
added in a later draft. Essentially, it will only make the object available through
the EL, but we need to check the details.

The jsp:useBean action is quite flexible; its exact semantics depends on the
attributes given. The basic semantic tries to find an existing object using id and
scope. If the object is not found it will attempt to create the object using the other
attributes.
It is also possible to use this action to give a local name to an object defined
elsewhere, as in another JSP page or in a Servlet. This can be done by using the
type attribute and not providing class or beanName attributes.
At least one of type and class must be present, and it is not valid to provide
both class and beanName. If type and class are present, class must be assignable

PUBLIC DRAFT 1-84


1-85 STANDARD ACTIONS

to type (in the Java platform sense). For it not to be assignable is a translation-
time error.
The attribute beanName specifies the name of a Bean, as specified in the
JavaBeans specification. It is used as an argument to the instantiate() method in
the java.beans.Beans class. It must be of the form “a.b.c”, which may be either a
class, or the name of a resource of the form “a/b/c.ser” that will be resolved in the
current ClassLoader. If this is not true, a request-time exception, as indicated in
the semantics of instantiate() will be raised. The value of this attribute can be a
request-time attribute expression.
More detail on the role of id and scope is given next.

The id Attribute
The id=”name” attribute/value tuple in a jsp:useBean element has special mean-
ing to a JSP container, at page translation time and at client request processing time.
In particular:

•the name must be unique within the translation unit, and identifies the particular
element in which it appears to the JSP container and page.
Duplicate id’s found in the same translation unit shall result in a fatal transla-
tion error.

•The JSP container will associate an object (a JavaBean component) with the
named value and accessed via that name in various contexts through the page-
context object described later in this specification.
The name is also used to expose a variable (name) in the page’s scripting lan-
guage environment. The scope of the scripting language variable is dependent
upon the scoping rules and capabilities of the scripting language used in the
page.
Note that this implies the name value syntax must comply with the variable
naming syntax rules of the scripting language used in the page. Chapter JSP.9
provides details for the case where the language attribute is ”java”.

An example of the scope rules just mentioned is shown next:

PUBLIC DRAFT
<jsp:useBean> 1-86

<% { // introduce a new block %>


...
<jsp:useBean id=”customer” class=”com.myco.Customer” />

<%
/*
* 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)
%>

The scope Attribute


The scope=”page|request|session|application” attribute/value tuple is associ-
ated with, and modifies the behavior of the id attribute described above (it has
both translation time and client request processing time semantics). In partic-
ular it describes the namespace, the implicit lifecycle of the object reference
associated with the name, and the APIs used to access this association, as fol-
lows:

Table JSP.5-1

page The named object is available from the javax.serv-


let.jsp.PageContext for the current page.
This reference must be discarded upon completion of the
current request by the page body.
It is illegal to change the instance object associated so that
its runtime type is a subset of the type of the current object
previously associated.

PUBLIC DRAFT
1-87 STANDARD ACTIONS

Table JSP.5-1

request The named object is available from the current page’s Serv-
letRequest object using the getAttribute(name) method.
This reference must be discarded upon completion of the
current client request.
It is illegal to change the value of an instance object so asso-
ciated so that its runtime type is a subset of the type(s) of
the object previously so associated.
session The named object is available from the current page’s
HttpSession object (which can in turn be obtained from the
ServletRequest object) using the getAttribute(name) method.
This reference must be discarded upon invalidation of the
current session.
It is Illegal to change the value of an instance object so
associated so that its new runtime type is a subset of the
type(s) of the object previously so associated.
Note it is a fatal translation error to attempt to use session
scope when the JSP page so attempting has declared, via the
<%@ page ... %> directive (see later) that it does not partic-
ipate in a session.
application The named object is available from the current page’s Serv-
letContext object using the getAttribute(name) method.
This reference shall be discarded upon reclamation of the
ServletContext.
It is Illegal to change the value of an instance object so
associated, such that its new runtime type is a subset of the
type(s) of the object previously so associated.

Semantics
The actions performed in a jsp:useBean action are:

1. An attempt to locate an object based on the attribute values id and scope. The
inspection is done synchronized per scope namespace to avoid non-determin-
istic behavior.
2. A scripting language variable of the specified type (if given) or class (if type
is not given) is defined with the given id in the current lexical scope of the
scripting language.
3. If the object is found, the variable’s value is initialized with a reference to the

PUBLIC DRAFT
<jsp:useBean> 1-88

located object, cast to the specified type. If the cast fails, a java.lang.ClassCas-
tException shall occur. This completes the processing of this jsp:useBean ac-
tion.
4. If the jsp:useBean element had a non-empty body it is ignored. This completes
the processing of this jsp:useBean action.
5. If the object is not found in the specified scope and neither class nor beanName
are given, a java.lang.InstantiationException shall occur. This completes the
processing of this jsp:useBean action.
6. If the object is not found in the specified scope, and the class specified names
a non-abstract class that defines a public no-args constructor, then the class is
instantiated. The new object reference is associated with the scripting variable
and with the specified name in the specified scope using the appropriate scope
dependent association mechanism (see PageContext). After this, step 7 is per-
formed.
If the object is not found, and the class is either abstract, an interface, or no
public no-args constructor is defined therein, then a java.lang.InstantiationEx-
ception shall occur. This completes the processing of this jsp:useBean action.

7. If the object is not found in the specified scope; and beanName is given, then
the method instantiate() of java.beans.Beans will be invoked with the Class-
Loader of the Servlet object and the beanName as arguments. If the method
succeeds, the new object reference is associated the with the scripting variable
and with the specified name in the specified scope using the appropriate scope
dependent association mechanism (see PageContext). After this, step 7 is per-
formed.
8. If the jsp:useBean element has a non-empty body, the body is processed. The
variable is initialized and available within the scope of the body. The text of
the body is treated as elsewhere. Any template text will be passed through to
the out stream. Scriptlets and action tags will be evaluated.
A common use of a non-empty body is to complete initializing the created in-
stance. In that case the body will likely contain jsp:setProperty actions and
scriptlets that are evaluated. This completes the processing of this useBean ac-
tion.

Examples
In the following example, a Bean with name “connection” of type
“com.myco.myapp.Connection” is available after actions on this element,
either because it was already created and found, or because it is newly cre-
ated.

PUBLIC DRAFT
1-89 STANDARD ACTIONS

<jsp:useBean id=”connection” class=”com.myco.myapp.Connection” />

In the next example, the timeout property is set to 33 if the Bean was instanti-
ated.

<jsp:useBean id=”connection” class=”com.myco.myapp.Connection”>


<jsp:setProperty name=”connection” property=”timeout” value=”33”>
</jsp:useBean>

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.

<jsp:useBean id=”wombat” type=”my.WombatType” scope=”session”/>

Syntax
This action may or not have a body. If the action has no body, it is of the form:

<jsp:useBean id="name" scope="page|request|session|application" typeSpec />

typeSpec ::= class=”className” |


class=”className” type=”typeName” |
type=”typeName” class=”className” |
beanName=”beanName” type=”typeName” |
type=”typeName” beanName=”beanName” |
type=”typeName”

If the action has a body, it is of the form:

<jsp:useBean id="name" scope="page|request|session|application" typeSpec >


body
</jsp:useBean>

In this case, the body will be invoked if the Bean denoted by the action is
created. Typically, the body will contain either scriptlets or jsp:setProperty tags
that will be used to modify the newly created object, but the contents of the body
are not restricted.

PUBLIC DRAFT
<jsp:useBean> 1-90

The <jsp:useBean> tag has the following attributes:

Table JSP.5-2

id The name used to identify the object instance in the


specified scope’s namespace, and also the scripting variable
name declared and initialized with that object reference.
The name specified is case sensitive and shall conform to
the current scripting language variable-naming conventions.
scope The scope within which the reference is available. The
default value is page. See the description of the scope
attribute defined earlier herein
class The fully qualified name of the class that defines the
implementation of the object. The class name is case
sensitive.
If the class and beanName attributes are not specified the
object must be present in the given scope.
beanName The name of a Bean, as expected by the instantiate()
method of the java.beans.Beans class.
This attribute can accept a request-time attribute expression
as a value.
type If specified, it defines the type of the scripting variable
defined.
This allows the type of the scripting variable to be distinct
from, but related to, the type of the implementation class
specified.
The type is required to be either the class itself, a superclass
of the class, or an interface implemented by the class
specified.
The object referenced is required to be of this type,
otherwise a java.lang.ClassCastException shall occur at
request time when the assignment of the object referenced
to the scripting variable is attempted.
If unspecified, the value is the same as the value of the
class attribute.

PUBLIC DRAFT
1-91 STANDARD ACTIONS

JSP.5.2 <jsp:setProperty>

The jsp:setProperty action sets the values of properties in a Bean. The name
attribute that denotes the Bean must be defined before this action appears.
There are two variants of the jsp:setProperty action. Both variants set the
values of one or more properties in the Bean based on the type of the properties.
The usual Bean introspection is done to discover what properties are present, and,
for each, its name, whether it is simple or indexed, its type, and the setter and
getter methods. Introspection also indicates if a given property type has a Proper-
tyEditor class.
Properties in a Bean can be set from one or more parameters in the request
object, from a String constant, or from a computed request-time expression.
Simple and indexed properties can be set using jsp:setProperty.
When assigning from a parameter in the request object, the conversions
described in Section JSP.1.14.2.1 are applied, using the target property to
determine the target type.
When assigning from a value given as a String constant, the conversions
described in Section JSP.1.14.2.1 are applied, using the target property to
determine the target type.
When assigning from a value given as a request-time attribute, no type
conversions are applied, as indicated in Section JSP.1.14.2.2.
When assigning values to indexed properties the value must be an array; the
rules described in the previous paragraph apply to the elements.
A conversion failure leads to an error, whether at translation time or request-
time.

Examples
The following two elements set a value from the request parameter values.

<jsp:setProperty name=”request” property=”*” />


<jsp:setProperty name=”user” property=”user” param=”username” />

The following element sets a property from a value

<jsp:setProperty name=”results” property=”row” value=”<%= i+1 %>” />

Syntax
<jsp:setProperty name="beanName" prop_expr />

PUBLIC DRAFT
<jsp:setProperty> 1-92

prop_expr ::=
property="*" |
property=”propertyName”|
property=”propertyName” param="parameterName"|
property=”propertyName” value=”propertyValue”

propertyValue ::= string

The value propertyValue can also be a request-time attribute value, as


described in Section JSP.1.14.1.

propertyValue ::= expr_scriptlet1

The <jsp:setProperty> element has the following attributes:

Table JSP.5-3

name The name of a Bean instance defined by a <jsp:useBean>


element or some other element. The Bean instance must
contain the property you want to set. The defining element
must appear before the <jsp:setProperty> element in the
same file.
property The name of the Bean property whose value you want to set
If you set propertyName to * then the tag will iterate over
the current ServletRequest parameters, matching parameter
names and value type(s) to property names and setter
method type(s), setting each matched property to the value
of the matching parameter. If a parameter has a value of "",
the corresponding property is not modified.
param The name of the request parameter whose value you want to
give to a Bean property. The name of the request parameter
usually comes from a web form
If you omit param, the request parameter name is assumed
to be the same as the Bean property name
If the param is not set in the Request object, or if it has the
value of ““, the jsp:setProperty element has no effect (a
noop).
An action may not have both param and value attributes.

1.
See syntax for expression scriptlet “<%= ... %>”

PUBLIC DRAFT
1-93 STANDARD ACTIONS

Table JSP.5-3

value The value to assign to the given property.


This attribute can accept a request-time attribute expression
as a value.
An action may not have both param and value attributes.

JSP.5.3 <jsp:getProperty>

An <jsp:getProperty> action places the value of a Bean instance property, con-


verted to a String, into the implicit out object, from which you can display the value
as output. The Bean instance must be defined as indicated in the name attribute
before this point in the page (usually via a jsp:useBean action).
The conversion to String is done as in the println() methods, i.e. the toString()
method of the object is used for Object instances, and the primitive types are
converted directly.
If the object is not found, a request-time exception is raised.
The value of the name attribute in jsp:setProperty and jsp:getProperty will
refer to an object that is obtained from the pageContext object through its findAt-
tribute() method.
The object named by the name must have been “introduced” to the JSP
processor using either the jsp:useBean action or a custom action with an
associated VariableInfo entry for this name.
Note: a consequence of the previous paragraph is that objects that are stored
in, say, the session by a front component are not automatically visible to jsp:set-
Property and jsp:getProperty actions in that page unless a jsp:useBean action, or
some other action, makes them visible.
If the JSP processor can ascertain that there is an alternate way guaranteed to
access the same object, it can use that information. For example it may use a
scripting variable, but it must guarantee that no intervening code has invalidated
the copy held by the scripting variable. The truth is always the value held by the
pageContext object.

Examples
<jsp:getProperty name=”user” property=”name” />

Syntax
<jsp:getProperty name=”name” property=”propertyName” />

PUBLIC DRAFT
<jsp:include> 1-94

The attributes are:

Table JSP.5-4

name The name of the object instance from which the property is
obtained.
property Names the property to get.

JSP.5.4 <jsp:include>

A <jsp:include .../> element provides for the inclusion of static and dynamic
resources in the same context as the current page. See Table JSP.1-10 for a sum-
mary of include facilities.
Inclusion is into the current value of out. The resource is specified using a
relativeURLspec that is interpreted in the context of the web server (i.e. it is
mapped).
The page attribute of both the jsp:include and the jsp:forward actions are
interpreted relative to the current JSP page, while the file attribute in an include
directive is interpreted relative to the current JSP file. See below for some
examples of combinations of this.
An included page only has access to the JspWriter object and it cannot set
headers. This precludes invoking methods like setCookie(). Attempts to invoke
these methods will be ignored. The constraint is equivalent to the one imposed on
the include() method of the RequestDispatcher class.
A jsp:include action may have jsp:param subelements that can provide values
for some parameters in the request to be used for the inclusion.
Request processing resumes in the calling JSP page, once the inclusion is
completed.
The flush attribute controls flushing. If true, then, if the page output is
buffered and the flush attribute is given a 'true' value, then the buffer is flushed
prior to the inclusion, otherwise the buffer is not flushed. The default value for the
flush attribute is 'false'

Examples
<jsp:include page=”/templates/copyright.html”/>

PUBLIC DRAFT
1-95 STANDARD ACTIONS

The above example is a simple inclusion of an object. The path is interpreted


in the context of the Web Application. It is likely a static object, but it could be
mapped into, for instance, a Servlet via web.xml.
For an example of a more complex set of inclusions, consider the following
four situations built using four JSP files: A.jsp, C.jsp, dir/B.jsp and dir/C.jsp:

• 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

<jsp:include page=”urlSpec” flush="true|false">


{ <jsp:param .... /> }*
</jsp:include>

The first syntax just does a request-time inclusion. In the second case, the
values in the param subelements are used to augment the request for the purposes
of the inclusion.

PUBLIC DRAFT
<jsp:forward> 1-96

The valid attributes are:

Table JSP.5-5

page The URL is a relative urlSpec is as in Section JSP.1.2.1.


Relative paths are interpreted relative to the current JSP
page.

Accepts a request-time attribute value (which must


evaluate to a String that is a relative URL specification).
flush Optional boolean attribute. If the value is “true”, the
buffer is flushed now. The default value is “false”.

JSP.5.5 <jsp:forward>

A <jsp:forward page=”urlSpec” /> element allows the runtime dispatch of the


current request to a static resource, a JSP page or a Java servlet class in the same
context as the current page. A jsp:forward effectively terminates the execution of the
current page. The relative urlSpec is as in Section JSP.1.2.1.
The request object will be adjusted according to the value of the page
attribute.
A jsp:forward action may have jsp:param subelements that can provide values
for some parameters in the request to be used for the forwarding.
If the page output is buffered, the buffer is cleared prior to forwarding.
If the page output is buffered and the buffer was flushed, an attempt to
forward the request will result in an IllegalStateException.
If the page output was unbuffered and anything has been written to it, an
attempt to forward the request will result in an IllegalStateException.

Examples
The following element might be used to forward to a static page based on
some dynamic condition.

<% String whereTo = “/templates/”+someValue; %>


<jsp:forward page=’<%= whereTo %>’ />

Syntax
<jsp:forward page=”relativeURLspec” />

PUBLIC DRAFT
1-97 STANDARD ACTIONS

and

<jsp:forward page=”urlSpec”>
{ <jsp:param .... /> }*
</jsp:forward>

This tag allows the page author to cause the current request processing to be
effected by the specified attributes as follows:

Table JSP.5-6

page The URL is a relative urlSpec is as in Section JSP.1.2.1.


Relative paths are interpreted relative to the current JSP
page.
Accepts a request-time attribute value (which must evaluate
to a String that is a relative URL specification).

JSP.5.6 <jsp:param>

The jsp:param element is used to provide key/value information. This element


is used in the jsp:include, jsp:forward and jsp:params elements. A translation error
shall occur if the element is used elsewhere.
When doing jsp:include or jsp:forward, the included page or forwarded page
will see the original request object, with the original parameters augmented with
the new parameters, with new values taking precedence over existing values when
applicable. The scope of the new parameters is the jsp:include or jsp:forward call;
i.e. in the case of an jsp:include the new parameters (and values) will not apply
after the include. This is the same behavior as in the ServletRequest include and
forward methods (see Section 8.1.1 in the Servlet 2.2 specification).
For example, if the request has a parameter A=foo and a parameter A=bar is
specified for forward, the forwarded request shall have A=bar,foo. Note that the
new param has precedence.

JSP.5.6.1 Syntax

<jsp:param name="name" value="value" />

This action has two mandatory attributes: name and value. Name indicates
the name of the parameter, and value, which may be a request-time expression,
indicates its value.

PUBLIC DRAFT
<jsp:plugin> 1-98

JSP.5.7 <jsp:plugin>

The plugin action enables a JSP page author to generate HTML that contains
the appropriate client browser dependent constructs (OBJECT or EMBED) that will
result in the download of the Java Plugin software (if required) and subsequent exe-
cution of the Applet or JavaBeans component specified therein.
The <jsp:plugin> tag is replaced by either an <object> or <embed> tag, as
appropriate for the requesting user agent, and emitted into the output stream of the
response. The attributes of the <jsp:plugin> tag provide configuration data for the
presentation of the element, as indicated in the table below.
The <jsp:param> elements indicate the parameters to the Applet or JavaBeans
component.
The <jsp:fallback> element indicates the content to be used by the client
browser if the plugin cannot be started (either because OBJECT or EMBED is not
supported by the client browser or due to some other problem). If the plugin can
start but the Applet or JavaBeans component cannot be found or started, a plugin
specific message will be presented to the user, most likely a popup window
reporting a ClassNotFoundException.
The actual plugin code need not be bundled with the JSP container and a
reference to Sun’s plugin location can be used instead, although some vendors
will choose to include the plugin for the benefit of their customers.

Examples
<jsp:plugin type=”applet” code=”Molecule.class” codebase=”/html” >
<jsp:params>
<jsp:param
name=”molecule”
value=”molecules/benzene.mol”/>
</jsp:params>
<jsp:fallback>
<p> unable to start plugin </p>
</jsp:fallback>
</jsp:plugin>

PUBLIC DRAFT
1-99 STANDARD ACTIONS

Syntax
<jsp:plugintype="bean|applet"
code="objectCode"
codebase="objectCodebase"
{ align="alignment" }
{ archive="archiveList" }
{ height="height" }
{ hspace="hspace" }
{ jreversion="jreversion" }
{ name="componentName" }
{ vspace="vspace" }
{ width="width" }
{ nspluginurl="url" }
{ iepluginurl="url" }>

{ <jsp:params>
{ <jsp:param name="paramName" value=”paramValue" /> }+
</jsp:params> }

{ <jsp:fallback> arbitrary_text </jsp:fallback> }


</jsp:plugin>

Table JSP.5-7

type Identifies the type of the component; a Bean, or an Applet.


code As defined by HTML spec
codebase As defined by HTML spec
align As defined by HTML spec
archive As defined by HTML spec
height As defined by HTML spec.
Accepts a run-time expression value.
hspace As defined by HTML spec.
jreversion Identifies the spec version number of the JRE the
component requires in order to operate; the default is: “1.2”
name As defined by HTML spec

PUBLIC DRAFT
<jsp:params> 1-100

Table JSP.5-7

vspace As defined by HTML spec


title As defined by the HTML spec
width As defined by HTML spec.
Accepts a run-time expression value.
nspluginurl URL where JRE plugin can be downloaded for Netscape
Navigator, default is implementation defined.
iepluginurl URL where JRE plugin can be downloaded for IE, default
is implementation defined.

JSP.5.8 <jsp:params>

The jsp:params action is part of the jsp:plugin action and can only occur as a
direct child of a <jsp:plugin> element. Using the jsp:params element in any other
context shall result in a translation-time error.
The semantics and syntax of jsp:params are described in Section JSP.5.7.

JSP.5.9 <jsp:fallback>

The jsp:fallback action is part of the jsp:plugin action and can only occur as a
direct child of a <jsp:plugin> element. Using the jsp:fallback element in any other
context shall result in a translation-time error.
The semantics and syntax of jsp:fallback are described in Section JSP.5.7.

JSP.5.10 <jsp:attribute>

The <jsp:attribute> standard action allows the page author to define the value
of a tag handler attribute in the body of an XML element instead of in the value of
an XML attribute. The action may only appear as a subelement of a standard or
custom action invocation.
The <jsp:attribute> action accepts a name attribute and a trim attribute. The
name attribute associates the action with one of the attributes the tag handler is
declared to accept. The optional trim attribute determines whether the whitespace
appearning at the beginning and at the end of the element body should be
discarded or not. By default, the leading and trailing whitespace is discarded.

PUBLIC DRAFT
1-101 STANDARD ACTIONS

The following is an example of using the <jsp:attribute> standard action to


define an attribute that is evaluated by the container prior to the custom action
invocation. This example assumes the name attribute is declared with type
java.lang.String in the TLD.

<mytag:highlight>
<jsp:attribute name=”text”>
Inline definition.
</jsp:attribute>
</mytag:highlight>

It is also legal to use the <jsp:attribute> standard action to supply attribute


values to standard actions, for any standard action attribute that accepts a runtime
expression value.
See Section JSP.1.3.9, “Standard JSP Syntax Grammar” for the formal syntax
definition of the <jsp:attribute> standard action.
The attributes are:

Table JSP.5-8 Attributes for the <jsp:attribute> standard action

name (required) The name must match the name of an attribute


for the tag being invoked, as declared in the Tag Library
Descriptor for a custom action, or as specified for a standard
action, or a translation error will result. A translation error
will result if both an XML element attribute and a
<jsp:attribute> element are used to specify the value for the
same attribute.
trim (optional) Valid values are “true” and “false”. If “true”, the
whitespace, including spaces, carriage returns, line feeds,
and tabs, that appears at the beginning and at the end of the
body of the <jsp:attribute> action will be ignored by the
JSP compiler. If “false” the whitespace is not ignored.
Defaults to “true”.

JSP.5.11 <jsp:body>

Normally, the body of a custom action invocation is defined implicitly as the


body of the XML element used to represent the invocation. The body of a custom
action can also be defined explicitly using the <jsp:body> standard action. This is
required if one or more <jsp:attribute> elements appear in the body of the tag.

PUBLIC DRAFT
Additional Standard Actions 1-102

The body standard action accepts one optional attribute. The value attribute
allows the page author to pass in an object of type
javax.servlet.jsp.tagext.JspFragment as the value of the body of this tag. If the
<jsp:body> action is present in the body of a custom action invocation, the page
author must either supply a body to the action, or supply a value attribute. A
translation error must result if both or neither are supplied.
If one or more <jsp:attribute> elements appear in the body of a tag invocation
but no <jsp:body> element appears, it is the equivalent of the tag having an empty
body.
It is also legal to use the <jsp:body> standard action to supply bodies to
standard actions, for any standard action that accepts a body.
The attribute is:

Table JSP.5-9 Attribute for the <jsp:body> standard action

value (optional) Allows the page author to provide the value of


the body as an attribute value instead of as the value of the
body of the standard action. The value of this attribute must
evaluate to an instance of javax.servlet.jsp.tagext.JspFrag-
ment, otherwise a JspException must result. If this attribute
is specified and the action has a body, a translation error
must result. If this attribute is not specified and the action
has no body, a translation error must result.

Accepts a request-time attribute value.

JSP.5.12 Additional Standard Actions

Additional Standard Actions are defined for tag files. See the following sections
for more details:

• Section JSP.8.3.3, “The <jsp:invoke> Standard Action”


• Section JSP.8.3.4, “The <jsp:doBody> Standard Action”

PUBLIC DRAFT
C H A P T E R JSP.6
JSP Documents

This chapter defines an XML syntax for JSP pages and the interpretation of
the pages written in this syntax. We use the term JSP document to refer to a JSP
page in XML syntax.
This chapter also defines a mapping between any JSP page and an XML
description of the page, its XML view. The XML view is defined for JSP pages
written in JSP and in XML syntax.

Note – We will drop the requirement that jsp:root is needed in a JSP docu-
ment, moving from "jsp as documents" to "jsp as namespace". That change will
make the XML syntax much easier to use.

JSP.6.1 Uses for XML Syntax for JSP Pages

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

PUBLIC DRAFT 1-103


JSP Documents 1-104

Validation of the JSP page is supported in the JSP 2.0 specification through a
TagLibraryValidator class associated with a tag library. The validator class acts on
a PageData object that represents the XML view of the JSP page (see, for
example, Section JSP.7.5.1.2).
A JSP page in either syntax can include via a directive a JSP page in either
syntax. It is not valid, however, to intermix standard JSP syntax and XML syntax
inside the same source file.

JSP.6.2 JSP Documents

A JSP document is a namespace-aware XML document. Namespaces are used


to identify the core syntax and the tag libraries used in the page and all JSP-related
namespaces are introduced in the root of the XML document.
The core syntax is identified through its own URI. Although in this chapter
the prefix jsp is used, any prefix is valid as long as the correct URI identifying the
core syntax is used.
A JSP document uses the same file extension (.jsp) as a JSP page in JSP
syntax. The container can distinguish the two because a JSP document is an XML
document with a jsp:root top element, and a jsp:root cannot appear in a JSP page
in JSP syntax.
Many XML elements in a JSP document correspond to JSP language elements,
but it is possible to include XML elements that describe template directly. Those
elements may have qualified names (and thus be in a namespace), or be unqualified.
A JSP page in XML syntax can use the following elements:

• a jsp:root element that is used to introduce the namespace for custom tags in
the page.
• JSP directive elements
• JSP scripting elements
• JSP standard action elements
• JSP custom action elements
• jsp:text elements corresponding to template data.
• other XML fragments also corresponding to template data.

PUBLIC DRAFT
1-105 JSP DOCUMENTS

JSP.6.2.1 Semantic Model


The semantic model of a JSP document is unchanged from that of a JSP page
in JSP syntax: JSP pages generate a response stream of characters from template
data and dynamic elements. Template data can be described explicitly through a
jsp:text element, or implicitly through an XML fragment. Dynamic elements are
scripting elements, standard actions or custom actions. Scripting elements are
represented as XML elements with the exception of request-time expressions,
which are represented through special attribute syntax.
To clearly explain the processing of whitespace, we follow the structure of the
XSLT specification. The first step in processing a JSP document is to identify the
nodes of the document. Then, all textual nodes that have only white space are
dropped from the document; the only exception are nodes in a jsp:text element,
which are kept verbatim. The resulting nodes are interpreted as described in the
following sections. Template data is either passed directly to the response or it is
mediated through (standard or custom) actions.
Following the XML specification (and the XSLT specification), whitespace
characters are #x20, #x9, #xD or #xA..

JSP.6.2.2 The jsp:root element


A JSP document has jsp:root as its root element. The root element has a xmlns
attribute that enables the use of the standard elements defined in the JSP 2.0 specifi-
cation.
In addition, the root is where namespace attributes of taglibs will be inserted.
All tag libraries used within the JSP document are represented in the root element
through additional xmlns attributes. The root element has one mandatory
attribute, the version of the JSP specification the page is using. No other attributes
are defined in this element.

<jsp:root
xmlns:jsp=”http://java.sun.com/JSP/Page”
xmlns:prefix1=”URI-for-taglib1”
xmlns:prefix2=”URI-for-taglib2”... >
version="2.0">
JSP page
</jsp:root>

An xmlns attribute for a custom tag library of the form xml:prefix=’uri’


identifies the tag library through the uri value. The uri value may be of one of two
forms, either a “uri” or of the form “urn:jsptld:path”.

PUBLIC DRAFT
JSP Documents 1-106

If the uri value is of the form “urn:jsptld:path”, then the TLD is determined
following the mechanism described in Section JSP.7.3.2.
If the uri value is a plain “uri”, then a path is determined by consulting the
mapping indicated in web.xml extended using the implicit maps in the packaged
tag libraries (Sections JSP.7.3.3 and JSP.7.3.4), as indicated in Section JSP.7.3.6.

JSP.6.2.3 The jsp:directive.page element


The jsp:directive.page element defines a number of page dependent properties
and communicates these to the JSP container. This element must be a child of the
root element and appear at the beginning of the JSP document. Its syntax is:

<jsp:directive.page page_directive_attr_list />

Where page_directive_attr_list is as described in Section JSP.1.10.1.


The interpretation of a jsp:directive.page element is as described in
Section JSP.1.10.1, and its scope is the JSP document and any fragments included
through an include directive.

JSP.6.2.4 The jsp:directive.include element


The jsp:directive.include element is used to substitute text and/or code at JSP
page translation-time. This element can appear anywhere within a JSP document. Its
syntax is:

<jsp:directive.include file="relativeURLspec” />

The interpretation of a jsp:directive.include element is as in Section JSP.1.10.5.


The XML view of a JSP page does not contain jsp:directive.include elements,
rather the included file is expanded in-place. This is done to simplify validation.

JSP.6.2.5 The jsp:declaration element


The jsp:declaration element is used to declare scripting language constructs that
are available to all other scripting elements. A jsp:declaration element has no
attributes and its body is the declaration itself. Its syntax is:

<jsp:declaration> declaration goes here </jsp:declaration>

The interpretation of a jsp:declaration element is as in Section JSP.1.12.1.

PUBLIC DRAFT
1-107 JSP DOCUMENTS

JSP.6.2.6 The jsp:scriptlet element


The jsp:scriptlet element is used to describe actions to be performed in response
to some request. Scriptlets that are program fragments. A jsp:scriptlet element has
no attributes and its body is the program fragment that comprises the scriptlet. Its
syntax is:

<jsp:scriptlet> code fragment goes here </jsp:scriptlet>

The interpretation of a jsp:scriptlet element is as in Section JSP.1.12.2.

JSP.6.2.7 The jsp:expression element


The jsp:expression element is used to describe complete expressions in the
scripting language that get evaluated at response time. A jsp:expression element has
no attributes and its body is the expression. Its syntax is:

<jsp:expression> expression goes here </jsp:expression>

The interpretation of a jsp:expression element is as in Section JSP.1.12.3.

JSP.6.2.8 Standard and custom action elements


A JSP document may use the standard actions described in Chapter JSP.5. Since
the syntax of those actions is already based on XML, the description in that chapter
suffices, except that in a JSP document template text can be described either
through a jsp:text element or through an XML element that is neither a standard
nor a custom action (see Section JSP.6.2.11). For completeness, the action ele-
ments are:

• jsp:useBean
• jsp:setProperty
• jsp:getProperty
• jsp:include
• jsp:forward
• jsp:param
• jsp:params
• jsp:plugin
• jsp:text

PUBLIC DRAFT
JSP Documents 1-108

The semantics and constraints are as in Chapter JSP.5, and the interpretation
of the scripting elements is as in Chapter JSP.9. Tag libraries introduce new
elements through an xmlns attribute on a jsp:root element and their syntax and
semantics are as in Chapter JSP.7.

JSP.6.2.9 Request-Time Attributes


An action element that can accept a request time attribute (Section JSP.1.14.1)
can accept an argument for that attribute of the form “%= text %” (white space
around text is not needed, and note the missing ‘<‘ and ‘>’). The text, after any
applicable quoting as in any other XML document, is an expression to be evaluated
as in Section JSP.1.14.1.

JSP.6.2.10 The jsp:text element


A jsp:text element can be used to enclose template data in the XML representa-
tion. A jsp:text element has no attributes and can appear anywhere that template data
can. Its syntax is:

<jsp:text> template data </jsp:text>

The interpretation of a jsp:text element is to pass its content through to the


current value of out. This is very similar to the XSLT xsl:text element.

JSP.6.2.11 Other XML elements


The XML syntax for JSP pages also allows an XML element that represents
neither a standard action nor a custom action to appear anywhere where a jsp:text
may appear.
The interpretation of such an XML element is to pass its textual
representation to the current value of out, after the whitespace processing
described in Section JSP.6.2.1.
As an example, if the relevant fragment of the JSP document is.

Table JSP.6-1 Example 1 - Input


LineNo Source Text
1 <hello><jsp:scriptlet>i=3;</jsp:scriptlet>
2 <hi>
3 <jsp:text> hi you all
4 </jsp:text><jsp:expression>i</jsp:expression>

PUBLIC DRAFT
1-109 JSP DOCUMENTS

Table JSP.6-1 Example 1 - Input


5 </hi>
6 </hello>

The result is

Table JSP.6-2 Example 1 - Output


LineNo Output Text
1 <hello> <hi> hi you all
2 3 </hi></hello>

Note the treatment of whitespace.

JSP.6.3 XML View of a JSP Page

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.

JSP.6.3.1 JSP Documents


The XML view of a JSP page written in XML syntax is very close to the
original JSP page. Only two transformations are performed:

• Expand all include directives into the JSP fragments they include.
• If the JSP container supports the jsp:id attribute, add the attribute. See
Section JSP.6.3.13.

JSP.6.3.2 JSP pages in JSP syntax


The XML view of a JSP page written in XML syntax is defined by the
following transformation:

• Expand all include directives into the JSP fragments they include.
• Add a jsp:root element as the root, with appropriate xmlns:jsp attribute, and
convert the taglib directive into xmlns: attributes of the jsp:root element.

PUBLIC DRAFT
XML View of a JSP Page 1-110

• Convert declarations, scriptlets and expressions into valid XML elements as


described in Section JSP.6.2.2 and following sections.
• Convert request-time attribute expressions as in Section JSP.6.3.11.
• Convert JSP quotations to XML quotations.
• Create jsp:text elements for all template text.
• If the JSP container supports the jsp:id attribute, add the attribute. See
Section JSP.6.3.13.
Note that the XML view of a JSP page has no DOCTYPE information; see
Section JSP.6.4.
A quick overview of the transformation is shown in Table JSP.6-3:

Table JSP.6-3 XML view transformations

JSP page element XML view


<%-- comment --%> removed

<%@ page ... %> <jsp:directive.page ... />. Optionally add jsp:id

<%@ taglib ... %> jsp:root element is annotated with namespace


information. Optionally add jsp:id.
<%@ include ... %> expanded in place
<%! ... %> <jsp:declaration> .... </jsp:declaration>. Optionally add
jsp:id.

<% ... %> <jsp:scriptlet> ... </jsp:scriptlet>. Optionally add jsp:id.

<%= ... %> <jsp:expression> ... </jsp:expression>. Optionally add


jsp:id.

Standard action Replace with XML syntax (adjust request-time


expressions; optionally add jsp:id)
Custom action As is (adjust request-time expressions; optionally add
jsp:id)
template Replace with jsp:text. Optionally add jsp:id.

In more detail:

PUBLIC DRAFT
1-111 JSP DOCUMENTS

JSP.6.3.3 JSP comments


JSP comments (of the form <%-- comment --%>) are not passed through to the
XML view of a JSP page.

JSP.6.3.4 The page directive


A page directive of the form

<%@ page { attr=”value” }* %>

is translated into an element of the form:

<jsp:directive.page { attr=”value” }* />

JSP.6.3.5 The taglib directive


A taglib directive of the form

<%@ taglib uri=”uriValue” prefix=”prefix” %>

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.

JSP.6.3.6 The include directive


An include directive of the form

<%@ include file=”value” %>

is expanded into the JSP fragment indicated by value. This is done to allow for
validation of the page.

JSP.6.3.7 Declarations
Declarations are translated into a jsp:declaration element. For example, the sec-
ond example from Section JSP.1.12.1:

<%! public String f(int i) { if (i<3) return(“...”); ... } %>

is translated into the following.

PUBLIC DRAFT
XML View of a JSP Page 1-112

<jsp:declaration> <![CDATA[ public String f(int i) { if (i<3) return(“...”); } ]]> </


jsp:declaration>

Alternatively, we could use an &lt; and instead say:

<jsp:declaration> public String f(int i) { if (i&lt;3) return(“...”); } </jsp:declaration>

JSP.6.3.8 Scriptlets
Scriptlets are translated into a jsp:scriptlet element. In the XML document cor-
responding to JSP pages, directives are represented using the syntax:

<jsp:scriptlet> code fragment goes here </jsp:scriptlet>

JSP.6.3.9 Expressions
In the XML document corresponding to JSP pages, directives are represented
using the jsp:expression element:

<jsp:expression> expression goes here </jsp:expression>

JSP.6.3.10 Standard and Custom Actions


The syntax for both standard and action elements is based on XML. The trans-
formations needed are due to quoting conventions and the syntax of request-time
attribute expressions.

JSP.6.3.11 Request-Time Attribute Expressions


Request-time attribute expressions are of the form “<%= expression %>”.
Although this syntax is consistent with the syntax used elsewhere in a JSP page, it is
not a legal XML syntax. The XML mapping for these expressions is into values of
the form “%= expression %”, where the JSP specification quoting convention has
been converted to the XML quoting convention.

JSP.6.3.12 Template Text and XML Elements


All text that is uninterpreted by the JSP translator is converted into the body for
a jsp:text element. As a consequence no XML elements of the form described in
Section JSP.6.2.11 will appear in the XML view of a JSP page written in JSP syntax.

PUBLIC DRAFT
1-113 JSP DOCUMENTS

JSP.6.3.13 The jsp:id Attribute

Note – The details of jsp:id semantics still need to be discussed in the EG. A
specific proposal will be included in a later draft. Details include how ’unique’
will the id value be, and whether the value is available at run-time

A JSP container must support a jsp:id attribute. This attribute can only be
present in the XML view of a JSP page and can be used to improve the quality of
translation time error messages.
The XML view of any JSP page will have an additional jsp:id attribute added
to all XML elements. This attribute is given a value that is unique over all
elements in the XML view. See Chapter 12 for more details.

JSP.6.4 Validating an XML View of a JSP page

The XML view of a JSP page is a namespace-aware document and it cannot be


validated against a DTD except in the most simple cases. To reduce confusions and
possible unintended performance consequences, the XML view of a JSP page will
not include a DOCTYPE. Still, since DTDs can have some value as documentation,
Appendix JSP.C contains both a DTD and an XSchema description of JSP docu-
ments.
There are several mechanisms that are aware of namespaces that can be used
to do validation of XML views of JSP pages. The most popular mechanism is the
W3C XML Schema language, but others are also suited, including some very
simple ones that may check, for example, that only some elements are being used,
or, inversely, that they are not used. The TagLibraryValidator for a tag library
permits encapsulating this knowledge with a tag library.
The TagLibraryValidator acts on the XML view of the JSP page. If the page
was authored in JSP syntax, that view does not provide any detail on template data
(all being grouped inside jsp:text elements), but fine detail can be described when
using JSP documents1.

1.
Similarly, when applying an XSLT transformation to a JSP document,
XML fragments will be plainly visible, while the content of jsp:text
elements will not

PUBLIC DRAFT
Examples 1-114

JSP.6.5 Examples

This section presents two examples of JSP documents. The first shows a JSP
page in JSP syntax and its mapping to XML syntax. The second shows a JSP page
in XML syntax that includes XML fragments.

JSP.6.5.1 A JSP page and its corresponding JSP document


Here is an example of mapping between JSP and XML syntax.

JSP PAGE IN JSP SYNTAX


<html>
<title>positiveTagLib</title>
<body>

<%@ taglib uri="http://java.apache.org/tomcat/examples-taglib" prefix="eg" %>


<%@ taglib uri="/tomcat/taglib" prefix="test" %>
<%@ taglib uri="WEB-INF/tlds/my.tld" prefix="temp" %>

<eg:test toBrowser="true" att1="Working">


Positive Test taglib directive </eg:test>
</body>
</html>

PUBLIC DRAFT
1-115 JSP DOCUMENTS

XML VIEW OF JSP PAGE:


<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:eg="http://java.apache.org/tomcat/examples-taglib"
xmlns:test="urn:jsptld:/tomcat/taglib"
xmlns:temp="urn:jsptld:/WEB-INF/tlds/my.tld"
version="2.0">

<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.6.5.2 A JSP document


This is an example of a very simple JSP document that has some template XML
elements.

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:mytags="prefix1-URL"
version="2.0">
<mytags:iterator count="4">
<foo> </foo>
</mytags:iterator>
</jsp:root>

PUBLIC DRAFT
C H A P T E R JSP.7
Tag Extensions

This chapter describes the tag library facility for introducing new actions into
a JSP page. The tag library facility includes portable run-time support, a validation
mechanism, and authoring tool support.
This chapter provides an overview of the tag library concept. It describes the
Tag Library Descriptor, and the taglib directive. A detailed description of the
APIs involved follows in Chapter JSP.12.

Note – This draft describes the new Simple Invocation Protocol in its own
chapter, but the descriptions will be integrated through the specification for a later
draft.

JSP.7.1 Introduction

A Tag Library abstracts functionality used by a JSP page by defining a special-


ized (sub)language that enables a more natural use of that functionality within JSP
pages.
The actions introduced by the Tag Library can be used by the JSP page author
in JSP pages explicitly, when authoring the page manually, or implicitly, when
using an authoring tool. Tag Libraries are particularly useful to authoring tools
because they make intent explicit and the parameters expressed in the action
instance provide information to the tool.
Actions that are delivered as tag libraries are imported into a JSP page using
the taglib directive. They are available for use in the page using the prefix given
by the directive. An action can create new objects that can be passed to other
actions, or can be manipulated programmatically through a scripting element in
the JSP page.

PUBLIC DRAFT 1-116


1-117 TAG EXTENSIONS

Tag libraries are portable: they can be used in any legal JSP page regardless of
the scripting language used in that page.
The tag extension mechanism includes information to:

• Execute a JSP page that uses the tag library.


• Author or modify a JSP page.
• Validate the JSP page.
• Present the JSP page to the end user.

A Tag Library is described via the Tag Library Descriptor ( TLD), an XML
document that is described below.

JSP.7.1.1 Goals
The tag extension mechanism described in this chapter addresses the following
goals. It is designed to be:
Portable - An action described in a tag library must be usable in any JSP con-
tainer.
Simple - Unsophisticated users must be able to understand and use this mech-
anism. Vendors of JSP functionality must find it easy to make it available to
users as actions.
Expressive - The mechanism must support a wide range of actions, including
nested actions, scripting elements inside action bodies, and creation, use and
updating of scripting variables.
Usable from different scripting languages - Although the JSP specification
currently only defines the semantics for scripts in the Java programming lan-
guage, we want to leave open the possibility of other scripting languages.
Built upon existing concepts and machinery- We do not want to reinvent what
exists elsewhere. Also, we want to avoid future conflicts whenever we can
predict them.

JSP.7.1.2 Overview
The processing of a JSP page conceptually follows these steps:

Parsing
JSP pages can be authored using two different syntaxes: a JSP syntax and an
XML syntax. The semantics and validation of a JSP syntax page is described
with reference to the semantics and validation of an equivalent document in

PUBLIC DRAFT
Introduction 1-118

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
of the taglib directives in the JSP page.

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.

JSP.7.1.2.1 Tag Handlers


The semantics of a specific custom action in a tag library is described via a tag
handler class which is usually instantiated at runtime by the JSP page implementa-
tion class. When the tag library is well known to the JSP container
(Section JSP.7.3.9), the container can use alternative implementations as long as the
semantics are preserved.
A tag handler is a Java class that implements the Tag, IterationTag, or BodyTag
interface, and is the run-time representation of a custom action.
The JSP page implementation class instantiates a tag handler object, or reuses
an existing tag handler object, for each action in the JSP page. The handler object

PUBLIC DRAFT
1-119 TAG EXTENSIONS

is a Java object that implements the javax.servlet.jsp.tagext.Tag interface. The


handler object is responsible for the interaction between the JSP page and
additional server-side objects.
There are three main interfaces: Tag, IterationTag, and BodyTag.

• The Tag interface defines the basic methods needed in all tag handlers. These
methods include setter methods to initialize a tag handler with context data and
attribute values of the action, and the doStartTag() and doEndTag() methods.
• The IterationTag interface is an extension to Tag that provides the additional
method, doAfterBody(), invoked for the reevaluation of the body of the tag.
• The BodyTag interface is an extension of IterationTag with two new methods
for when the tag handler wants to manipulate the tag body: setBodyContent()
passes a buffer, the BodyContent object, and doInitBody() provides an oppor-
tunity to process the buffer before the first evaluation of the body into the buff-
er.

The use of interfaces simplifies making an existing Java object a tag handler.
There are also two support classes that can be used as base classes: TagSupport
and BodyTagSupport.
JSP 1.2 introduced a new interface designed to help maintain data integrity
and resource management in the presence of exceptions. The TryCatchFinally
interface is a “mix-in” interface that can be added to a class implementing any of
Tag, IterationTag or BodyTag.

JSP.7.1.2.2 Event Listeners


A tag library may include classes that are event listeners (see the Servlet 2.4
specification). The listeners classes are listed in the tag library descriptor and the
JSP container automatically instantiates them and registers them. A container is
required to locate all TLD files (see Section JSP.7.3.1 for details on how they are
identified), read their listener elements, and treat the event listeners as extensions of
those listed in web.xml.
The order in which the listeners are registered is undefined, but they are
registered before application start.

JSP.7.1.3 Simple Examples


As examples, we describe prototypical uses of tag extensions, briefly sketching
how they take advantage of these mechanisms.

PUBLIC DRAFT
Introduction 1-120

JSP.7.1.3.1 Simple Actions


The simplest type of action just does something, perhaps with parameters to
modify what the “something” is, and improve reusability.
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.2 Actions with a Body


Another set of simple actions require something to happen when the start tag is
found, and when the end tag is found. The Tag interface can also be used for these
actions. The doEndTag() is similar to the doStartTag() method except that it is
invoked when the end tag of the action is encountered. The result of the doEndTag
invocation indicates whether the remainder of the page is to be evaluated or not.

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.

JSP.7.1.3.5 Actions that Process their Body


Consider an action that evaluates its body many times, creating a stream of
response data. The IterationTag protocol is used for this.
If the result of the reinterpretation is to be further manipulated for whatever
reason, including just discarding it, we need a way to divert the output of
reevaluations. This is done through the creation of a BodyContent object and use
of the setBodyContent() method, which is part of the BodyTag interface. BodyTag
also provides the doInitBody() method which is invoked after setBodyContent()

PUBLIC DRAFT
1-121 TAG EXTENSIONS

and before the first body evaluation provides an opportunity to interact with the
body.

JSP.7.1.3.6 Cooperating Actions


Cooperating actions may offer the best way to describe a desired functionality.
For example, one action may be used to describe information leading to the creation
of a server-side object, while another action may use that object elsewhere in the
page. These actions may cooperate explicitly, via scripting variables: one action cre-
ates an object and gives it a name; the other refers to the object through the name.
Scripting variables are discussed briefly below.
Two actions can also cooperate implicitly. A flexible and convenient
mechanism for action cooperation uses the nested structure of the actions to
describe scoping. This is supported in the specification by providing each tag
handler with its parent tag handler (if any) through the setParent() method. The
findAncestorWithClass static method in TagSupport can then be used to locate a tag
handler, and, once located, to perform valid operations on the tag handler.

JSP.7.1.3.7 Actions Defining Scripting Variables


A custom action may create server-side objects and make them available to
scripting elements by creating or updating the scripting variables. The variables thus
affected are part of the semantics of the custom action and are the responsability of
the tag library author.
This information is used at JSP page translation time and can be described in
one of two ways: directly in the TLD for simple cases, or through subclasses of
TagExtraInfo. Either mechanism will indicate the names and types of the scripting
variables.
At request time the tag handler will associate objects with the scripting
variables through the pageContext object.
It is the responsibility of the JSP page translator to automatically supply the
code required to do the “synchronization” between the pageObject values and the
scripting variables.

JSP.7.2 Tag Libraries

A tag library is a collection of actions that encapsulate some functionality to be


used from within a JSP page. A tag library is made available to a JSP page through a
taglib directive that identifies the tag library via a URI (Universal Resource Identi-
fier).

PUBLIC DRAFT
Tag Libraries 1-122

The URI identifying a tag library may be any valid URI as long as it can be
used to uniquely identify the semantics of the tag library.
The URI identifying the tag library is associated with a Tag Library
Description (TLD) file and with tag handler classes as indicated in
Section JSP.7.3 below.

JSP.7.2.1 Packaged Tag Libraries


JSP page authoring tools and JSP containers are required to accept a tag library
that is packaged as a JAR file. When deployed in a JSP container, the standard JAR
conventions described in the Servlet 2.4 specification apply, including the conven-
tions for dependencies on extensions.
Packaged tag libraries must have at least one tag library descriptor file. The
JSP 1.1 specification allowed only a single TLD, in META-INF/taglib.tld, but as
of JSP 1.2 multiple tag libraries are allowed. See Section JSP.7.3.1 for how TLDs
are identified.

JSP.7.2.2 Location of Java Classes


A tag library contains classes for instantiation at translation time and classes for
instantiation at request time. The former include TagLibraryValidator and TagEx-
traInfo classes. The later include tag handler and event listener classes.
The usual conventions for Java classes apply: as part of a web application,
they must reside either in a JAR file in the WEB-INF/lib directory, or in a
directory in the WEB-INF/classes directory.
A JAR containing a packaged tag libraries can be dropped into the WEB-INF/
lib directory to make its classes available at request time (and also at translation
time, see Section JSP.7.3.7). The mapping between the URI and the TLD is
explained further below.

JSP.7.2.3 Tag Library directive


The taglib directive in a JSP page declares that the page uses a tag library,
uniquely identifies the tag library using a URI, and associates a tag prefix with usage
of the actions in the library.
A JSP container maps the URI used in the taglib directive into a Tag Library
Descriptor in two steps: it resolves the URI into a TLD resource path, and then
derives the TLD object from the TLD resource path.

PUBLIC DRAFT
1-123 TAG EXTENSIONS

If the JSP container cannot locate a TLD resource path for a given URI, a fatal
translation error shall result. Similarly, it is a fatal translation error for a uri
attribute value to resolve to two different TLD resource paths.
It is a fatal translation error for the taglib directive to appear after actions
using the prefix introduced by it.

JSP.7.3 The Tag Library Descriptor

Note – We expect an XML-Schema version of the TLD. This will allow for a
more extensible TLD that can be used as a true single-source document.

The Tag Library Descriptor (TLD) is an XML document that describes a tag
library. The TLD for a tag library is used by a JSP container to interpret pages that
include taglib directives referring to that tag library. The TLD is also used by JSP
page authoring tools that will generate JSP pages that use a library, and by authors
who do the same manually.
The TLD includes documentation on the library as a whole and on its
individual tags, version information on the JSP container and on the tag library,
and information on each of the actions defined in the tag library.
The TLD may name a TagLibraryValidator class that can validate that a JSP
page conforms to a set of constraints expected by the tag library.
Each action in the library is described by giving its name, the class of its tag
handler, information on any scripting variables created by the action, and
information on attributes of the action. Scripting variable information can be
given directly in the TLD or through a TagExtraInfo class. For each valid attribute
there is an indication about whether it is mandatory, whether it can accept request-
time expressions, and additional information.
A TLD file is useful for providing information on a tag library. It can be read
by tools without instantiating objects or loader classes. Our approach conforms to
the conventions used in other J2EE technologies.
The DTD for the tag library descriptor is organized so that interesting
elements have an optional ID attribute. This attribute can be used by other
documents, like vendor-specific documents, to provide annotations of the TLD
information.

PUBLIC DRAFT
The Tag Library Descriptor 1-124

JSP.7.3.1 Identifying Tag Library Descriptors


Tag library descriptor files have names that use the extension “.tld”, and the
extension indicates a tag library descriptor file. When deployed inside a JAR file,
the tag library descriptor files must be in the META-INF directory, or a
subdirectory of it. When deployed directly into a web application, the tag library
descriptor files must always be in the WEB-INF directory, or some subdirectory
of it.
The DTD for a TLD document is "http://java.sun.com/dtd/web-
jsptaglibrary_1_2.dtd"

JSP.7.3.2 TLD resource path


A URI in a taglib directive is mapped into a context relative path (as discussed
in Section JSP.1.2.1). The context relative path is a URL without a protocol and host
components that starts with “/” and is called the TLD resource path.
The TLD resource path is interpreted relative to the root of the web
application and should resolve to a TLD file directly, or to a JAR file that has a
TLD file at location META-INF/taglib.tld. If the TLD resource path is not one of
these two cases, a fatal translation error will occur.
The URI describing a tag library is mapped to a TLD resource path though a
taglib map, and a fallback interpretation that is to be used if the map does not
contain the URI. The taglib map is built from an explicit taglib map in web.xml
(described in Section JSP.7.3.3) that is extended with implicit entries deduced
from packaged tag libraries in the web application (described in
Section JSP.7.3.4), and implicit entries known to the JSP container. The fallback
interpretation is targetted to a casual use of the mechanism, as in the development
cycle of the Web Application; in that case the URI is interpreted as a direct path to
the TLD (see Section JSP.7.3.6.2).

JSP.7.3.3 Taglib map in web.xml


The web.xml file can include an explicit taglib map between URIs and TLD
resource paths described using the taglib elements of the Web Application Deploy-
ment descriptor in WEB-INF/web.xml. See Section JSP.3.2 for more details.

JSP.7.3.4 Implicit Map entries from TLDs


The taglib map described in web.xml is extended with new entries extracted
from TLD files in the Web Application. The new entries are computed as follows:

PUBLIC DRAFT
1-125 TAG EXTENSIONS

• Each TLD file is examined. If it has a <uri> element, then a new <taglib> ele-
ment is created, with a <taglib-uri> subelement whose value is that of the <uri>
elemement, and with a <taglib-location> subelement that refers to the TLD file.
• If the created <taglib> element has a different <taglib-uri> to any in the taglib
map, it is added.

This mechanism provides an automatic URI to TLD mapping as well as


supporting multiple TLDs within a packaged JAR. Note that this functionality
does not require explicitly naming the location of the TLD file, which would
require a mechanism like the jar: protocol.
Note also that the mechanism does not add duplicated entries.

JSP.7.3.5 Implicit Map entries from the Container


The container may also add additional entries to the taglib map. As in the previ-
ous case, the entries are only added for URIs that are not present in the map. Con-
ceptually the entries correspond to TLD describing these tag libraries.
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.

JSP.7.3.6 Determining the TLD Resource Path


The TLD resource path can be determined from the uri attribute of a taglib
directive as described below. In the explanation below an “absolute URI” is one that
starts with a protocol and host, while a“relative URI specification” is as in section
2.5.2, i.e. one without the protocol and host part.
All steps are described as if they were taken, but an implementation can use a
different implementation strategy as long as the result is preserved.

JSP.7.3.6.1 Computing TLD Locations


The taglib map generated in Sections JSP.7.3.3, JSP.7.3.4 and JSP.7.3.5 may
contain one or more <taglib></taglib> entries. Each entry is identified by a
TAGLIB_URI, which is the value of the <taglib-uri> subelement. This TAGLIB_URI may
be an absolute URI, or a relative URI spec starting with “/” or one not starting with
“/”. Each entry also defines a TAGLIB_LOCATION as follows:

PUBLIC DRAFT
The Tag Library Descriptor 1-126

• If the <taglib-location> subelement is some relative URI specification that


starts with a “/” the TAGLIB_LOCATION is this URI.
• If the <taglib-location> subelement is some relative URI specification that does
not start with “/”, the TAGLIB_LOCATION is the resolution of the URI relative to
/WEB-INF/web.xml (the result of this resolution is a relative URI specification
that starts with “/”).

JSP.7.3.6.2 Computing the TLD Resource Path


The following describes how to resolve a taglib directive to compute the TLD
resource path. It is based on the value of the uri attribute of the taglib directive.

• If uri is ABS_URI, an absolute URI


Look in the taglib map for an entry whose TAGLIB_URI is ABS_URI. If found, the
corresponding TAGLIB_LOCATION is the TLD resource path. If not found, a
translation error is raised.

• If uri is ROOT_REL_URI, a relative URI that starts with “/”


Look in the taglib map for an entry whose TAGLIB_URI is ROOT_REL_URI. If
found, the corresponding TAGLIB_LOCATION is the TLD resource path. If no such
entry is found, ROOT_REL_URI is the TLD resource path.

• 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.

JSP.7.3.6.3 Usage Considerations


The explicit web.xml map provides a explicit description of the tag libraries that
are being used in a web application.
The implicit map from TLDs means that a JAR file implementing a tag library
can be dropped in and used immediatedly through its stable URIs.
The use of relative URI specifications in the taglib map enables very short
names in the taglib directive. For example, if the map is:

PUBLIC DRAFT
1-127 TAG EXTENSIONS

<taglib>
<taglib-uri>/myPRlibrary</taglib-uri>
<taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib-location>
</taglib>

then it can be used as:

<%@ taglib uri=”/myPRlibrary” prefix=”x” %>

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:

<%@ taglib uri=”/WEB-INF/tlds/PRlibrary_1_4.tld” prefix=”x” %>

JSP.7.3.7 Translation-Time Class Loader


The set of classes available at translation time is the same as that available at
runtime: the classes in the underlying Java platform, those in the JSP container, and
those in the class files in WEB-INF/classes, in the JAR files in WEB-INF/lib, and,
indirectly those indicated through the use of the class-path attribute in the META-
INF/MANIFEST file of these JAR files.

JSP.7.3.8 Assembling a Web Application


As part of the process of assembling a web application, the Application Assem-
bler will create a WEB-INF/ directory, with appropriate lib/ and classes/ subdirecto-
ries, place JSP pages, Servlet classes, auxiliary classes, and tag libraries in the
proper places, and create a WEB-INF/web.xml that ties everything together.
Tag libraries that have been delivered in the standard JAR format can be
dropped directly into WEB-INF/lib. This automatically adds all the TLDs inside
the JAR, making their URIs advertised in their <uri> elements visible to the URI
to TLD map. The assembler may create taglib entries in web.xml for each of the
libraries that are to be used.
Part of the assembly (and later the deployment) may create and/or change
information that customizes a tag library; see Section JSP.7.6.3.

JSP.7.3.9 Well-Known URIs


A JSP container may “know of” some specific URIs and may provide alternate
implementations for the tag libraries described by these URIs, but the user must see

PUBLIC DRAFT
The Tag Library Descriptor Format 1-128

the behavior as that described by the required, portable tag library description
described by the URI.
A JSP container must always use the mapping specified for a URI in the
web.xml deployment descriptor if present. If the deployer wants to use the
platform-specific implementation of the well-known URI, the mapping for that
URI should be removed at deployment time.

JSP.7.4 The Tag Library Descriptor Format

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"
>

A taglib element also has several subelements that define:


tlib-version the version of the tag library implementation

jsp-version the mandatory version of JSP specification the tag library


depends upon

PUBLIC DRAFT
1-129 TAG EXTENSIONS

short-name a simple default short name that could be used by a JSP page
authoring tool to create names with a mnemonic value; for
example, the it may be used as the preferred prefix value in taglib
directives.

uri a uri uniquely identifying this taglib.

display-name The display-name element contains a short name that is intended


to be displayed by tools.

small-icon Optional small-icon that can be used by tools.

large-icon Optional large-icon that can be used by tools.

description a string describing the “use” of this taglib.

validator Optional TagLibraryValidator information.

listener Optional event listener specification

<!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:

<!ELEMENT tlib-version (#PCDATA) >


#PCDATA ::= [0-9]*{ “.”[0-9] }0..3

<jsp-version>
Describes the JSP specification version (number) this tag library requires in
order to function. This element is mandatory
The syntax is:

<!ELEMENT jsp-version (#PCDATA) >


#PCDATA ::= [0-9]*{ “.”[0-9] }0..3.

<short-name>
Defines a simple default short name that could be used by a JSP page author-
ing tool to create names with a mnemonic value; for example, the it may be
used as the preferred prefix value in taglib directives and/or to create prefixes
for IDs. Do not use white space, and do not start with digits or underscore.
The syntax is

PUBLIC DRAFT
The Tag Library Descriptor Format 1-130

<!ELEMENT short-name (#PCDATA) >


#PCDATA ::= NMTOKEN

<uri>
Defines a public URI that uniquely identifies this version of the tag library.

<!ELEMENT uri (#PCDATA) >

<description>
Defines an arbitrary text string describing the tag library, variable, attribute or
validator.

<!ELEMENT description (#PCDATA) >

<validator>
Defines an optional TagLibraryValidator that can be used to validate the con-
formance of a JSP page to using this tag library. A validator may have some
optional initialization parameters.
The validator may have several subelements defining:
validator-class the class implementing
javax.servlet.jsp.tagext.TagLibraryValidator
init-param optional initialization parameters

description an optional description of the validator.

The element syntax is as follows:

<!ELEMENT validator (validator-class, init-param*, description?) >

<validator-class>
Defines the class of the optional TagLibraryValidator.

<!ELEMENT validator-class (#PCDATA) >

<init-param>
Defines an initialization parameter.
The init-param may have several subelements defining:
param-name the name of the parameter

param-value the value of the parameter

description optional description of the parameter

The element syntax is as follows:

PUBLIC DRAFT
1-131 TAG EXTENSIONS

<!ELEMENT init-param (param-value, param-value, description?) >

<param-name>
The name of a parameter.

<!ELEMENT param-name (#PCDATA) >

<param-value>
The value of a parameter.

<!ELEMENT param-value (#PCDATA) >

<listener>
Defines an optional event listener object to be instantiated and registered auto-
matically.

<!ELEMENT listener (listener-class) >

<listener-class>
The listener-class element declares a class in the application that must be reg-
istered as a web application listener bean. See the Servlet 2.4 specification for
details.

<!ELEMENT listener-class (#PCDATA) >

<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:

<!ATTLIST tag id ID #IMPLIED >

The tag may have several subelements defining:


name the unique action name

tag-class the tag handler class implementing


javax.servlet.jsp.tagext.Tag

PUBLIC DRAFT
The Tag Library Descriptor Format 1-132

tei-class an optional subclass of


javax.servlet.jsp.tagext.TagExtraInfo
body-content the body content type

display-name A short name that is intended to be displayed by tools.

small-icon Optional large-icon that can be used by tools.

large-icon Optional large-icon that can be used by tools.

description Optional tag-specific information.

variable Optional scripting variable information.

attribute all attributes of this action

example optional example of the use of this tag.

The element syntax is as follows:

<!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:

<!ELEMENT tag-class (#PCDATA) >

#PCDATA ::= fully qualified Java class name.

<tei-class>
Defines the subclass of javax.servlet.jsp.tagext.TagExtraInfo for this tag. This
element is optional.
The syntax is:

<!ELEMENT tei-class (#PCDATA) >


#PCDATA ::= fully qualified Java class name

<body-content>
Provides a hint as to the content of the body of this action. Primarily intended
for use by page composition tools.
There are currently three values specified:

PUBLIC DRAFT
1-133 TAG EXTENSIONS

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.

empty The body must be empty

The default value is “JSP”.


The syntax is:

<!ELEMENT body-content (#PCDATA) >


#PCDATA ::= tagdependent | JSP | empty.

Values are case dependent.

<display-name>
The display-name elements contains a short name that is intended to be displayed by
tools.
The syntax is:

<!ELEMENT display-name (#PCDATA) >

<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:

<!ELEMENT large-icon (#PCDATA) >

<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:

<!ELEMENT small-icon (#PCDATA) >

PUBLIC DRAFT
The Tag Library Descriptor Format 1-134

<variable>
Provides information on the scripting variables defined by this tag. It is a
(translation-time) error for a tag that has one or more variable subelements to
have a TagExtraInfo class that returns a non-null object.
The subelements of variable are of the form:
name-given the variable name as a constant.

name-from-attribute
the name of an attribute whose (translation-time) value will give
the name of the variable. One of name-given or name-from-
attribute is required.

variable-class name of the class of the variable. java.lang.String is default.

declare whether the variable is declared or not. True is thedefault.

scope the scope of the scripting variable defined. NESTED is default.

description optional description of the variable.

The syntax is:

<!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:

<!ELEMENT name-given (#PCDATA) >

<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:

<!ELEMENT name-from-attribute (#PCDATA) >

<variable-class>
The optional name of the class for the scripting variable. The default is
java.lang.String.
The syntax is:

<!ELEMENT class (#PCDATA) >

PUBLIC DRAFT
1-135 TAG EXTENSIONS

<declare>
Whether the scripting variable is to be defined or not. See TagExtraInfo for
details. This element is optional and “true” is the default.
The syntax is:

<!ELEMENT declare #PCDATA) >

#PCDATA ::= true | false | yes | no

<scope>
The scope of the scripting variable. See TagExtraInfo for details. This ele-
ment is optional and “NESTED” is the default..
The syntax is:

<!ELEMENT scope #PCDATA) >


#PCDATA ::= NESTED | AT_BEGIN | AT_END

<attribute>
Provides information on an attribute of this action. Attribute defines an id
attribute for external linkage.

<!ATTLIST attribute id ID#IMPLIED>

The subelements of attribute are of the form:


name the attributes name (required)

required if the attribute is required or optional (optional)

rtexprvalue if the attributes value may be dynamically calculated at runtime


by a scriptlet expression (optional)

type the type of the attributes value (optional)

description optional description of the attribute

The syntax is:

<!ELEMENT attribute (name, required?,rtexprvalue?, type?, description?) >

<name>
Defines the canonical name of a tag or attribute being defined
The syntax is:

<!ELEMENT name (#PCDATA) >


#PCDATA ::= NMTOKEN

PUBLIC DRAFT
The Tag Library Descriptor Format 1-136

<required>
Defines if the nesting attribute is required or optional.
The syntax is:

<!ELEMENT required (#PCDATA) >


#PCDATA ::= true | false | yes | no

If not present then the default is “false”, i.e the attribute is optional.

<rtexprvalue>
Defines if the nesting attribute can have scriptlet expressions as a value, i.e the
value of the attribute may be dynamically calculated at request time, as
opposed to a static value determined at translation time.
The syntax is:

<!ELEMENT rtexprvalue (#PCDATA) >


#PCDATA ::= true | false | yes | no

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:

<!ELEMENT type (#PCDATA) >


#PCDATA ::= fully qualified Java class name of result type

An example is:

<type> java.lang.Object </type>

<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.

<!ELEMENT example (#PCDATA) >

PUBLIC DRAFT
1-137 TAG EXTENSIONS

JSP.7.5 Validation

There are a number of reasons why the structure of a JSP page should conform
to some validation rules:

• Request-time semantics; e.g. a subelement may require the information from


some enclosing element at request-time .
• Authoring-tool support; e.g. a tool may require an ordering in the actions.
• Methodological constraints; e.g. a development group may want to constrain
the way some features are used.

Validation can be done either at translation-time or at request-time. In general


translation-time validation provides a better user experience, and the JSP 2.0
specification provides a very flexible translation-time validation mechanism.

JSP.7.5.1 Translation-Time Mechanisms


Some translation-time validation is represented in the Tag Library Descriptor.
In some cases a TagExtraInfo class needs to be provided to supplement this informa-
tion.

JSP.7.5.1.1 Attribute Information


The Tag Library Descriptor contains the basic syntactic information. In particu-
lar, the attributes are described including their name, whether they are optional or
mandatory, and whether they accept request-time expressions. Additionally the
body-content element can be used to indicate that an action must be empty.
All constraints described in the TLD must be enforced. A tag library author
can assume that the tag handler instance corresponds to an action that satisfies all
constraints indicated in the TLD.

JSP.7.5.1.2 Validator Classes


A TagLibraryValidator class may be listed in the TLD for a tag library to request
that a JSP page be validated. The XML view of a JSP page is exposed through a
PageData class, and the validator class can do any checks the tag library author may
have found appropriate.

Note – jsp:id is mandatory in JSP 2.0 -- this needs to be updated accordingly.

PUBLIC DRAFT
Conventions and Other Issues 1-138

The JSP container may optionally uniquely identify all XML elements in the
XML view of a JSP page through a jsp:id attribute. This attribute can be used to
provide better information on the location of an error.
The validator class mechanism is new as of the JSP 1.2 specification. A
TagLibraryValidator can be passed some initialization parameters in the TLD. This
eases the reuse of validator classes. We expect that validator classes will be
written based on different XML schema mechanisms (DTDs, XSchema, Relaxx,
others). Standard validator classes may be incorporated into a later version of the
JSP specification if a clear schema standard appears at some point.

JSP.7.5.1.3 TagExtraInfo Class Validation


Additional translation-time validation can be done using the isValid method in
the TagExtraInfo class. The isValid method is invoked at translation-time and is
passed a TagData instance as its argument.
The isValid mechanism was the original validation mechanism introduced in
JSP 1.1 with the rest of the Tag Extension machinery. Tag libraries that are
designed to run in JSP 1.2 containers or higher should use the validator class
mechanism.

JSP.7.5.2 Request-Time Errors


In some cases, additional request-time validation will be done dynamically
within the methods in the tag handler. If an error is discovered, an instance of
JspException can be thrown. If uncaught, this object will invoke the errorpage
mechanism of the JSP specification.

JSP.7.6 Conventions and Other Issues

This section is not normative, although it reflects good design practices.

JSP.7.6.1 How to Define New Implicit Objects


We advocate the following style for the introduction of implicit objects:

• Define a tag library.


• Add an action called defineObjects to define the desired objects.

The JSP page can make these objects available as follows:

PUBLIC DRAFT
1-139 TAG EXTENSIONS

<%@ tablig prefix="me" uri="......" %>


<me:defineObjects />
.... start using the objects....

This approach has the advantage of requiring no new machinery and of


making very explicit the dependency.
In some cases there may be an implementation dependency in making these
objects available. For example, they may be providing access to some
functionality that exists only in a particular implementation. This can be done by
having the tag extension class test at run-time for the existence of some
implementation dependent feature and raise a run-time error (this, of course,
makes the page not J2EE compliant).
This mechanism, together with the access to metadata information allows for
vendors to innovate within the standard.
Note: if a feature is added to a JSP specification, and a vendor also provides
that feature through its vendor-specific mechanism, the standard mechanism, as
indicated in the JSP specification will “win”. This means that vendor-specific
mechanisms can slowly migrate into the specification as they prove their
usefulness.

JSP.7.6.2 Access to Vendor-Specific information


If a vendor wants to associate some information that is not described in the cur-
rent version of the TLD with some tag library, it can do so by inserting the informa-
tion in a document it controls, inserting the document in the WEB-INF portion of
the JAR file where the Tab Library resides, and using the standard Servlet 2.2 mech-
anisms to access that information.
The vendor can now use the ID machinery to refer to the element within the
TLD.

JSP.7.6.3 Customizing a Tag Library


A tag library can be customized at assembly and deployment time. For exam-
ple, a tag library that provides access to databases may be customized with login and
password information.
There is no convenient place in web.xml in the Servlet 2.2 spec for customiza-
tion information A standardized mechanism is probably going to be part of a forth-
coming JSP specification, but in the meantime the suggestion is that a tag library
author place this information in a well-known location at some resource in the

PUBLIC DRAFT
Conventions and Other Issues 1-140

WEB-INF/ portion of the Web Application and access it via the getResource() call
on the ServletContext.

PUBLIC DRAFT
C H A P T E R JSP.8
JSP Fragments

This chapter describes the details of JSP fragments and supporting mecha-
nisms including Simple Tag Extensions and tag files. The mechanisms in this chap-
ter can be used only when the body of a tag invocation does not contain scripting
elements such as scriptlets or scriptlet expressions. The body of the invocation may
still contain template text, expressions written using the Expression Language, and
action elements.
Also presented is a facility that allows page authors to author tag extensions
using only JSP syntax. When used together, these concepts have the ability to
simplify JSP development substantially.

Note – This chapter will be split and merged with other chapters such as
Chapter JSP.7, “Tag Extensions”. For now it is in its own chapter for easier tracking
of changes. Eventually, we expect this chapter to only specify tag files. The rest will
be integrated elsewhere.

JSP.8.1 Custom Action Invocation

This section describes additional syntax and semantics for custom action invo-
cation. JSP 2.0 introduces a new mechanism for passing attributes when invoking
custom actions, using the <jsp:attribute> and <jsp:body> standard actions. This
new mechanism is useful for passing attribute values that are inconvenient or impos-
sible to express using the XML element attribute syntax. In addition, it facilitates the
passing of JSP fragments, which allow for dynamic re-evaluation of attributes, simi-
lar to the way tag bodies are currently handled.

PUBLIC DRAFT 1-141


Custom Action Invocation 1-142

This section also specifies a mechanism to pass attributes with dynamic


names to tag extensions. This allows a tag library developer to implement tag
handlers that accept attributes with names that are not predetermined.

JSP.8.1.1 JSP Fragments


A tag library developer can instruct the JSP container to postpone the
evaluation of an attribute by making the type of the attribute
javax.servlet.jsp.tagext.JspFragment. When configured this way, the attribute
behaves much like the body of the tag, in that the tag handler can evaluate the
attribute zero or more times, at its discretion. This is called a JSP fragment.
A JSP fragment must only contain template text and JSP action elements. For
example, it cannot contain scriptlets or scriptlet expressions. At runtime, the
fragment is represented by an instance of the
javax.servlet.jsp.tagext.JspFragment interface. See Section JSP.8.3.1 for more
details on this interface.
JSP fragments are also used to define the body of custom action invocation to
a Simple Tag Handler.

JSP.8.1.2 Attributes With Dynamic Names


Prior to JSP 2.0, the name of every attribute that a tag handler accepted was pre-
determined at the time the tag handler was developed. It is sometimes useful, how-
ever, to be able to define a tag handler that accepts attributes with dynamic names
that are not known until the page author uses the tag. For example, it is time con-
suming and error-prone to anticipate what attributes a user may wish to pass to a tag
that mimics an HTML element. New to JSP 2.0 is the ability to declare that a tag
handler accepts additional attributes with dynamic names.

JSP.8.1.2.1 javax.servlet.jsp.tagext.DynamicAttributes
To declare that it accepts attributes with dynamic names, a tag handler must
implement the javax.servlet.jsp.tagext.DynamicAttributes interface, defined as fol-
lows:

public interface DynamicAttributes {


public void setDynamicAttribute(
String uri, String localName, Object value )
throws AttributeNotSupportedException;
}

PUBLIC DRAFT
1-143 JSP FRAGMENTS

The setDynamicAttribute() method accepts the following parameters:

• uri - The namespace of the attribute, or null if in the default namespace.


• localName - The name of the attribute being set.
• value - The value of the attribute.
If the tag handler wishes to signal that it does not accept the given attribute, it
can throw AttributeNotSupportedException. The container must catch this
exception and rethrow a JspException to the calling page before calling doStart-
Tag() or doTag(). If a message is provided in the AttributeNotSupportedExcep-
tion, the corresponding JspException must contain the same message.

JSP.8.1.2.2 javax.servlet.jsp.tagext.AttributeNotSupportedException
This exception is thrown by a tag handler that wants to indicate that the pro-
vided dynamic attribute is not supported by this tag. The exception is defined as fol-
lows:

public class AttributeNotSupportedException


extends Exception
{
public AttributeNotSupportedException();
public AttributeNotSupportedException( String message );
}

JSP.8.1.2.3 Declaring Dynamic Attribute Support in the TLD


In addition to implementing the javax.servlet.jsp.tagext.DynamicAttributes
interface, tag handlers that support dynamic attributes must declare that they do so
in the Tag Library Descriptor.
See Section for the changes made to the Tag Library Descriptor to support
dynamic attributes.
The TLD ultimately determines whether a tag handler accepts dynamic
attributes or not. If a tag handler declares that it supports dynamic attributes in the
TLD but it does not implement the javax.servlet.jsp.tagext.DynamicAttributes
interface, the tag handler must be considered invalid by the container.

JSP.8.1.2.4 Semantics of Dynamic Attributes


If the dynamic-attributes element for a tag being invoked contains the value
“true”, the following requirements apply:

PUBLIC DRAFT
Simple Tag Extensions 1-144

• For each attribute specified in the tag invocation that does not have a corre-
sponding attribute or fragment-attribute element in the TLD for this tag, a call
must be made to setDynamicAttribute(), passing in the namespace of the at-
tribute (or null if in the default namespace), the name of the attribute, and the
final value of the attribute.
• Attributes must be set in the order in which they appear in the invocation.
• The JSP container must recognize dynamic attributes that are passed to the tag
handler using the <jsp:attribute> standard action.
In the following example, assume attributes a and b are declared using the
attribute element in the TLD, attributes d1 and d2 are not declared, and the
dynamic-attributes element is set to “true”. The attributes are set in the order a,
then d1, then b, then d2, using the calls setA( “1” ), setDynamicAttribute( null,
“d1”, “2” ), setB( “3” ), and setDynamicAttribute( null, “d2”, “4” ).

<mytag:invokeDynamic a=”1” d1=”2”>


<jsp:attribute name=”b” value=”3”/>
<jsp:attribute name=”d2” value=”4”/>
</mytag:invokeDynamic>

JSP.8.2 Simple Tag Extensions

Version 1.1 of the JavaServer Pages specification introduced a tag library facil-
ity for defining custom actions that can be used in a JSP page. See Chapter JSP.7,
“Tag Extensions” for more details. The API and invocation protocol for this facility
is necessarily somewhat complex because scriptlets and scriptlet expressions in tag
bodies can rely on surrounding context defined using scriptlets in the enclosing
page.
With the advent of the Expression Language and JSP Standard Tag Library
(JSTL), it is now feasible to develop JSP pages that do not need scriptlets or
scriptlet expressions. This allows us to define a tag invocation protocol that is
easier to use for many use cases.
In that interest, JSP 2.0 introduces a new type of tag extension called a
“Simple Tag Extension.” Simple Tag Extensions can be written in one of two
ways:

• In Java, by defining a class that implements the javax.servlet.jsp.tagext.Sim-


pleTag interface. This class is intended for use by advanced page authors and

PUBLIC DRAFT
1-145 JSP FRAGMENTS

tag library developers who need the flexibility of the Java language in order to
write their tag handlers.
• In JSP, using tag files. This method can be used by page authors who do not
know Java. It can also be used by advanced page authors or tag library devel-
opers who know Java but are producing tag libraries that are presentation-cen-
tric or can take advantage of existing tag libraries.

JSP.8.2.1 Genericness of SimpleTag Extensions


In addition to being simpler to work with, Simple Tag Extensions are
designed to work in a wider variety of environments. Because they do not rely on
any Servlet APIs, Simple Tag Extensions can be used for contexts other than
request/response. This is facilitated by the JspContext interface, which PageCon-
text extends. JspContext provides generic services such as storing the JspWriter
and keeping track of scoped attributes, whereas PageContext has functionality
specific to serving JSPs in the context of Servlets. Whereas the Tag interface relies
on PageContext, SimpleTag only relies on JspContext.

JSP.8.2.2 Declaring Simple Tag Extensions in the TLD


The Tag Library Descriptor is an XML document that describes a tag library. As
of JSP 2.0, a tag library can contain Simple Tag Extensions. The following changes
are made to the Tag Library Descriptor to support Simple Tag Extensions. Also
shown here are the changes made to the TLD to support dynamic attributes (see
Section JSP.8.1.2 for more details), and tag files (see Section JSP.8.4.3 for more
details).

Note – The final TLD will be converted to XML Schema for JSP 2.0. Older
versions (JSP 1.2 and prior) will be supported for backwards compatibility.

1. Add “scriptless” to the possible values for the body-content element (only
comment is affected, but this may affect the XML Schema version). A body-
content of “scriptless” indicates the body only accepts template text and JSP
action elements.
2. Change tag-lib element to support tag-file (changes in bold):

PUBLIC DRAFT
Simple Tag Extensions 1-146

<!ELEMENT taglib (tlib-version, jsp-version, short-name, uri?,


display-name?, small-icon?, large-icon?, description?, validator?,
listener*, ( tag | tag-file )+) >

3. Change tag element to support fragment-attribute and dynamic-attributes


(changes in bold):

<!--
The tag element defines an action in this tag library. The tag element
has one attribute, id.
The tag element may have several subelements defining:

name The unique action name


tag-class The tag handler class implementing
javax.servlet.jsp.tagext.Tag.
tei-class An optional subclass of
javax.servlet.jsp.tagext.TagExtraInfo
body-content The body content type
display-name A short name that is intended to be
displayed by tools.
small-icon Optional small-icon that can be used by tools
large-icon Optional large-icon that can be used by tools
description Optional tag-specific information
variable Optional scripting variable information
attribute All attributes of this action that are
evaluated prior to invocation.
fragment-attribute All attributes of this action that implement
javax.servlet.jsp.tagext.JspFragment
and can be evaluated zero or more times
by the tag handler.
dynamic-attributes Whether this tag supports additional
attributes with dynamic names. If true,
the tag-class must implement the
javax.servlet.jsp.tagext.DynamicAttributes
interface. Defaults to false.
example Optional informal description of an
example of a use of this action.
-->
<!ELEMENT tag
( name, tag-class, tei-class?, fragment*, display-name?,
small-icon?, large-icon?, description?, variable*,
attribute*, fragment-attribute*, dynamic-attributes?, example? ) >

4. Add the fragment-attribute element.

PUBLIC DRAFT
1-147 JSP FRAGMENTS

<!--
Defines the details of an attribute of type
javax.servlet.jsp.tagext.JspFragment.

Attributes defined of this type can be evaluated zero or more times


by a tag handler.

name The name of the fragment attribute.


required True if this fragment is required, or false if optional.
Defaults to false.
description Describes the purpose of this fragment-attribute.
fragment-input The types of inputs that may be passed to this
fragment by the tag handler.
-->
<!ELEMENT fragment-attribute ( name, required?, description?,
fragment-input* ) >

5. Add the dynamic-attributes element.

<!--
Declares whether this tag handler supports dynamic attributes
or not. Valid values are “true” and “false”. Defaults to false.
-->
<!ELEMENT dynamic-attributes (#PCDATA)>

6. Add the fragment-input element.

<!--
Describes the details of a single parameter that may be passed
from a tag handler to a fragment, when the fragment is invoked.
This allows the page author to know what variables to expect from
the tag when passing in a fragment.

name The name of the parameter to the fragment.


type The type of parameter being passed.
description Describes the purposes of this fragment input.
-->
<!ELEMENT fragment-input ( name, type?, description? ) >

7. Add the tag-file element.

PUBLIC DRAFT
Simple Tag Extensions 1-148

<!--
Defines an action in this tag library that is implemented
as a .tag file.

The tag-file element has two required subelements:

name Theunique action name

path Where to find the .tag file implementing this


action, relative to the location of this TLD file.

-->
<!ELEMENT tag-file ( name, path ) >

8. Add the path element.

<!ELEMENT path #PCDATA >

JSP.8.2.3 The javax.servlet.jsp.tagext.SimpleTag Interface


The Tag Library Descriptor maps tag library declarations to their physical
underlying implementations. A Simple Tag Handler is represented in Java by a
class which implements the javax.servlet.jsp.tagext.SimpleTag interface. See the
SimpleTag API for details.
Unlike classic tag handlers, the SimpleTag interface does not extend Tag.
Instead of supporting doStartTag() and doEndTag(), the SimpleTag interface
provides a simple doTag() method, which is called once and only once for any
given tag invocation. All tag logic, iteration, body evaluations, etc. are to be
performed in this single method. Thus, simple tag handlers have the equivalent
power of IterationTag, but with a much simpler lifecycle and interface.
To support body content, the setJspBody() and getJspBody() methods are
provided. The container invokes the setJspBody() method with a JspFragment
object encapsulating the body of the tag. The tag handler implementation can call
getJspBody().invoke() to evaluate the body.

JSP.8.2.4 SimpleTag Collaboration


As described in Section JSP.8.2.6, “Lifecycle of Simple Tag Handlers”,
before a SimpleTag is invoked, the setParent() method is called to set the instance
nearest enclosing tag. This is similar to the way collaboration works for classic
tags, allowing nested tags to exchange information. Instead of assuming a Tag
interface for the parent tag, SimpleTag assumes only Object.
PUBLIC DRAFT
1-149 JSP FRAGMENTS

Because SimpleTag does not extend Tag, and because Tag.setParent() accepts
an object of type Tag, tag collaboration becomes complicated when classic
custom actions (i.e. those that implement the Tag interface) are nested inside Sim-
pleTag custom actions. The javax.servlet.jsp.tagext.TagAdapter class can wrap
any Object and expose it as a Tag instace. The original object can be retrieved
through its getAdaptee() method.
Whenever calling setParent() on a classic Tag in a case where the outer tag
does not implement Tag, the JSP Container must construct a new TagAdapter and
call setParent() on the classic Tag passing in the adapter. See the API for TagAda-
pter for more details.

JSP.8.2.5 Packaging Simple Tag Handlers


Simple tag handlers written in Java can be packaged alongside classic tag
handlers, and they follow the same packaging semantics as described in
Section JSP.7.2, “Tag Libraries”.

JSP.8.2.6 Lifecycle of Simple Tag Handlers


Throughout this section, tag handlers that extend javax.serv-
let.jsp.tagext.SimpleTag will be referred to as simple tag handlers, whereas all
other tag handlers will be referred to as classic tag handlers. This section
describes the lifecycle of simple tag handlers, from creation to invocation,
comparing it to that of classic tag handlers. For all semantics left unspecified by
this section, the semantics default to that of a classic tag handler.
Although simple tag handlers implement the Tag interface, the container must
follow a different lifecyle for them at runtime. When a simple tag handler is
invoked, the following steps occur (in order):

1. Just as with classic tag handlers, simple tag handlers are created initially using
a zero argument constructor on the corresponding implementation class. Un-
like classic tag handlers, this instance must never be pooled by the container.
A new instance must be created for each tag invocation.
2. The setJspContext() and setParent() methods are invoked on the tag handler,
as with classic tag handlers.
3. The attributes specified as XML element attributes (if any) are evaluated next,
in the order in which they are declared, according to the following rules (re-
ferred to as “evaluating an XML element attribute” below):

If the attribute is a rtexprvalue (e.g. “<%= 1+1 %>” in JSP syntax, or “%=

PUBLIC DRAFT
Simple Tag Extensions 1-150

1+1 %” in XML syntax), the expression is evaluated, and the result is con-
verted as per the rules in Section JSP.1.14.2, “Type Conversions”, and passed
to the bean property setter.

Otherwise, if the attribute contains any Expression Language expressions
(e.g. “Hello ${name}”), the expression is evaluated, and the result is convert-
ed and passed to the setter.

Otherwise, the attribute value is taken verbatim, converted, and passed to the
setter.
4. The value for each <jsp:attribute> element is evaluated, and the corresponding
setter methods are invoked for each, in the order in which they appear in the
body of the tag. If the tag accepts dynamic attributes, the setDynamicAt-
tribute() method is invoked as the setter.

If the value attribute is specified, the XML element attribute is evaluated ac-
cording to the “evaluating an XML element attribute” procedure defined
above.

Otherwise, if the attribute is not of type javax.servlet.jsp.tagext.JspFrag-
ment, the container evaluates the body of the <jsp:attribute> element. This
evaluation can be done in a container-specific manner. Container implemen-
tors should note that in the process of evaluating this body, other custom ac-
tions may be invoked.

Otherwise, if the attribute is of type javax.servlet.jsp.tagext.JspFragment,
an instance of a JspFragment object is created as per the lifecycle described
in Section JSP.8.3.4.
5. The value for the body of the tag is determined, and the setJspBody() method
is called on the tag handler. If the tag is declared to have a body-content of
“empty” then null is passed to setJspBody(). Otherwise, the body of the tag is
either the body of the <jsp:body> element, or the body of the custom action in-
vocation if no <jsp:body> element is present.

If the value attribute is specified, the XML element attribute is evaluated ac-
cording to the “evaluating an XML element attribute” procedure above, and
the result of the evaluation is converted and passed to the setter.

Otherwise, an instance of a JspFragment object is created as per the lifecycle
described in Section JSP.8.3.4. and it is passed to the setter.
6. The doTag() method is invoked.
7. The implementation of doTag() performs its function, potentially calling other
tag handlers and invoking fragments.
8. The doTag() method returns, and the tag handler instance is discarded. The ap-
propriate action is taken, depending on the return value:
PUBLIC DRAFT
1-151 JSP FRAGMENTS


If EVAL_PAGE is returned, normal execution resumes at the next step and
the page continues to be evaluated.

If SKIP_PAGE is returned, the rest of the page is not evaluated and the re-
quest is completed. If this request was forwarded or included from another
page (or Servlet), only the current page evaluation stops.
9. For each tag scripting variable declared with scopes AT_BEGIN or AT_END,
the appropriate scripting variables and scoped attributes are declared, as with
classic tag handlers.
See Section JSP.8.3.4, “The <jsp:doBody> Standard Action” for the
lifecycle details of a JSP fragment. Check the TryCatchFinally interface for
additional details related to exception handling and resource management.

JSP.8.3 Defining and Invoking JSP Fragments

A JSP fragment is a portion of JSP code encapsulated in an object that can be


invoked zero or more times. Though rare, it is possible to write JSP fragments
directly in Java. However, they are normally defined using JSP syntax as the body of
a <jsp:attribute> or <jsp:body> standard action, during a tag invocation. If written
using JSP syntax, the JSP fragment must only contain template text and JSP action
elements. It must not contain, for example, scriptlets or scriptlet expressions.
Once a JSP Fragment is created, it is typically passed to a tag handler in the
context of a tag invocation. The tag handler can then invoke the fragment zero or
more times, or pass it along to other tags, before returning.
JSP fragments accept parameters from the invoker, which are exposed as
Expression Language variables to the JSP code that composes the fragment. This
allows the tag handler to parameterize the body each time it is invoked.

JSP.8.3.1 The javax.servlet.jsp.tagext.JspFragment interface


JSP Fragments are represented in Java by an instance of the javax.serv-
let.jsp.tagext.JspFragment interface. See the JspFragment API for details.
Before being passed to a simple tag handler, the JspFragment is associated
with the JspContext of the surrounding page in an implementation-dependent
manner. In addition, it is associated with the parent Tag or SimpleTag instance for
collaboration purposes, so that when a custom action is invoked from within the
fragment, setParent() can be called with the appropriate value. The fragment
implementation must keep these associations for the duration of the tag invocation
in which it is used. The container must not reuse the same JspFragment instance

PUBLIC DRAFT
Defining and Invoking JSP Fragments 1-152

for future invocations, so tag handler implementations can rely on getting a unique
instance for each invocation.
The invoke() method executes the body and directs all output to the JspWriter
returned by the getOut() method of the JspContext associated with the fragment.
The method accepts a parameter map, containing the body-input parameters
passed to the body by its invoker (e.g. a tag handler). The keys in this map are
parameter names, and the values are parameter values. This allows the invoker to
parameterize a fragment invocation.
The implementation of each method can optionally throw a javax.jsp.serv-
let.JspException, which must be handled by the invoker. Note that tag library
developers and page authors should not generate JspFragment implementations
manually.

JSP.8.3.2 Writing JSP Fragments using JSP Syntax


JSP fragments can be defined in JSP syntax in the context of a tag invocation.
This is done when providing the body of a <jsp:attribute> or <jsp:body> standard
action. See Section JSP.8.1, “Custom Action Invocation” for more details about tag
invocation.
When defining a JSP fragment using JSP syntax, the conatiner must generate
code to expose each parameter, passed in via the java.util.Map parameter in the
invoke() method, as a page scope variable in the JspContext of the fragment.
These variables are actually scoped locally to the fragment itself and must remain
in the page scope for the duration of the fragment invocation, but must be restored
to their original values after the fragment invocation is complete. This allows
different fragments to have different local page scoped variables in the same
invocation.

JSP.8.3.3 The <jsp:invoke> Standard Action


The <jsp:invoke> standard action takes a fragment name and optional
parameter elements, and invokes the fragment, sending the output of the result to
the JspWriter, or to a page-scope variable that can be examined and manipulated.
This standard action can only be used inside tag files. Using it anywhere else must
result in a translation error.
The most basic usage of this standard action will invoke a fragment with the
given name with no parameters. The fragment will be invoked using the JspFrag-
ment.invoke() method, passing in null for the Writer parameter so that the results
will be sent to the JspWriter of the JspContext associated with the JspFragment.
The following is an example of such a basic fragment invocation:

PUBLIC DRAFT
1-153 JSP FRAGMENTS

<jsp:invoke fragment=”frag1”/>

It is also possible to invoke the fragment and send the results to a scoped
attribute for further examination and manipulation. This can be accomplished by
specifying the varReader attribute in the action. In this usage, the fragment is be
invoked using the JspFragment.invoke() method, but a custom java.io.Writer is
passed in instead of null. The container must ensure that a java.io.Reader object is
constructed and is made available in a scoped attribute with the name specified by
varReader. The Reader object must produce the content sent by the fragment to
the provided Writer. The Reader must also be resettable. That is, if its reset()
method is called, the result of the invoked fragment must be able to be read again
without re-executing the fragment.
If xyz is a Reader exposed via varReader, then the evaluation of the EL
expression ‘${xyz}’ must produce the same output the fragment did when it was
invoked. Immediately following the evaluation, the Reader object must be reset
such that on the next evaluation of the expression the same value is produced.

Note – The above paragraph should be worked in to the EL chapter.

An optional scope attribute indicates the scope of the resulting scoped


variable. The following is an example of this usage:

<jsp:invoke fragment=”frag2” varReader=”fragresult”/>

If the <jsp:param> action is used in the body of the <jsp:invoke> tag,


parameters are passed to the fragment during invocation. One <jsp:param>
element must be present for each fragment input declared required using the frag-
ment-input directive, or a translation error will result (see Section JSP.8.4.8 for
details). It is legal for a <jsp:param> element to appear without a corresponding
fragment-input directive. This is useful for less formal definitions of simple tag
handlers, though it is discouraged for situations where the tag handler will be
packaged and distributed for use by page authors. If this mechanism is used, the
tag handler first assembles the fragment parameters. It then calls the JspFrag-
ment.invoke() method, and passes in the fragment parameters. The following is an
example of a fragment invocation with parameters:

<jsp:invoke fragment=”frag3”>
<jsp:param name=”param1” value=”value1”/>
<jsp:param name=”param2” value=”${val2}”/>
</jsp:invoke>

PUBLIC DRAFT
Defining and Invoking JSP Fragments 1-154

A translation error shall result if the <jsp:invoke> action contains body


content other than whitespace and <jsp:param> subelements.
See Section JSP.1.3.9, “Standard JSP Syntax Grammar” for the formal syntax
definition of the <jsp:invoke> standard action.
The attributes are:

Table JSP.8-1 Attributes for the <jsp:invoke> standard action

fragment (required) The name used to identify this fragment during


this tag invocation.
varReader (optional) The name of a scoped attribute to store the result
of the fragment invocation in, as a java.io.Reader object. If
not specified, the result of the fragment invocation goes
directly to the JspWriter, as described above.
scope (optional) The scope in which to store the resulting
variable. Possible values are “page”, “request”, “session”
or “application.” A translation error will result if this
attribute appears without specifying the varReader attribute
as well. Defaults to “page.”

JSP.8.3.4 The <jsp:doBody> Standard Action


The <jsp:doBody> invokes the body of the tag, sending the output of the
result to the JspWriter, or to a scoped attribute that can be examined and
manipulated. This standard action can only be used inside tag files. Using it
anywhere else must result in a translation error.
The <jsp:doBody> standard action behaves exactly like <jsp:invoke>, except
that it operates on the body of the tag instead of on a specific fragment passed as
an attribute. Because it always operates on the body of the tag, there is no name
attribute for this standard action.
The body of a tag is passed to the simple tag handler as a JspFragment object.
In addition to passing parameters for each <jsp:param> subelement, a parameter
is passed for each variable defined using the variable directive with a scope of
AT_BEGIN or NESTED.
A translation error shall result if the <jsp:doBody> action contains body
content other than whitespace and <jsp:param> subelements.
See Section JSP.1.3.9, “Standard JSP Syntax Grammar” for the formal syntax
definition of the <jsp:doBody> standard action.

PUBLIC DRAFT
1-155 JSP FRAGMENTS

The attributes are:

Table JSP.8-2 Attributes for the <jsp:doBody> standard action

varReader (optional) The name of a scoped attribute to store the result


of the body invocation in as a java.io.Reader object. If not
specified, the result of the body invocation goes directly to
the JspWriter, as described above.
scope (optional) The scope in which to store the resulting
variable. Possible values are “page”, “request”, “session”
or “application.” A translation error will result if this
attribute appears without specifying the varReader attribute
as well. Defaults to “page.”

JSP.8.3.5 Lifecycle of JSP Fragments


This section describes the lifecycle of a JSP fragment, from creation to
invocation, from the JSP container’s perspective. The first section describes the
creation of a JSP fragment. The second section describes the invocation of an
existing JSP Fragment.

JSP.8.3.5.1 Creation of a JSP Fragment


JSP fragments are defined in the context of a tag invocation, either as the body
of a <jsp:attribute> element, the body of a <jsp:body> element, or as the body of a
tag invocation without <jsp:attribute> or <jsp:body> elements. Once a fragment
has been created, it is invoked zero or more times, and then discarded after the tag
invocation is complete. When a JSP fragment is defined, the following steps occur
(in order):

1. A new instance of a class implementing the JspFragment interface is created


each time the tag is invoked. This instance must be configured to produce the
contents of the body of the fragment when invoked, depending on the body-
content declared for the tag:

If the body-content is “tagdependent”, then the fragment must echo the con-
tents of the body verbatim when invoked.

If the body-content is “scriptless”, then the fragment must evaluate the body
each time it is invoked.
2. The JspFragment instance is passed a reference to the current JspContext.
Whenever the fragment invokes a tag handler, it must use this value when call-

PUBLIC DRAFT
Defining and Invoking JSP Fragments 1-156

ing setJspContext().
3. The fragment calls JspContext.peekPageScope() and stores a reference to the
current page scope. This value is used during an invocation, to access the sur-
rounding context from the page in which the fragment was defined.
4. The JspFragment instance is associated with an instance of the tag handler of
the nearest enclosing tag invocation, or with null if there is no enclosing tag.
Whenever the fragment invokes a tag handler, the fragment must use this value
when calling setParent().

JSP.8.3.5.2 Invocation of a JSP Fragment


After a JSP fragment is created, it is passed to a tag handler for later invocation.
JSP fragments can be invoked either programmatically from a tag handler written
in Java, or from a tag file using the <jsp:invoke> or <jsp:doBody> standard action.
When writing simple tag handlers in Java, it becomes necessary to be able to
programmatically invoke the body or fragments passed to the tag. JSP fragments are
passed to tag handlers using a bean property of type javax.servlet.jsp.tagext.Jsp-
Fragment. These fragments can be invoked by calling one of the methods available
in the JspFragment interface. See Section JSP.8.3.1 for the details of this interface.
When writing simple tag handlers using tag files, fragments can be invoked
using the <jsp:invoke> standard action, and the tag body can be invoked using the
<jsp:doBody> standard action. See Section JSP.8.3.3 for details
Note that it is legal (and possible) for a fragment to recursively invoke itself.
The following steps are followed when invoking a JSP fragment:

1. A java.util.Map object is assembled, containing the parameters of the fragment


invocation. In the case of <jsp:invoke> or <jsp:doBody>, these are assembled
from the nested <jsp:param> standard action elements, where the name at-
tribute specifies the key and the value attribute evaluates to the value. In the
case of programmatic invocation, the assembly of the Map is the responsibility
of the tag library developer.
2. If <jsp:doBody> is being used to invoke the body of the tag as passed by set-
JspBody(), for each scripting variable declared with scope AT_BEGIN or
NESTED, an entry is added to the Map with a key equal to the variable name,
and a value equal to the value of the page scope variable with the same name.
3. If <jsp:invoke> or <jsp:doBody> is being used to invoke a fragment, if the
varReader attribute is specified, a custom java.io.Writer object is created that
can expose the resulting invocation as a java.io.Reader.
4. The invoke() method of the fragment is invoked, passing in the Map of param-

PUBLIC DRAFT
1-157 JSP FRAGMENTS

eters.
5. The fragment instance calls JspContext.pushPageScope(), passing in the
page scope stored during the creation of the fragment. This restores the page
scope of the page that defined this fragment.
6. For each key present in the Map, the fragment must make a page scope variable
available to the fragment body, so that the parameters can be accessed via the
Expression Language and via other mechanisms. Changes made to the value
of any page scope variable with the same name as a key in the Map must only
last for the duration of the fragment invocation, and must be scoped to this
fragment invocation only. That is, if the same fragment instance is invoked
more than once in the same thread of execution, changes to variables with the
same name as a key in the Map in one invocation must not affect the same vari-
ables in the other invocation.
7. The body of the fragment is evaluated by executing the generated code. The
body of the fragment may execute other standard or custom actions. The re-
sults of the body invocation must go to the JspWriter returned from the Jsp-
Context.getOut() method.
8. Once the body has completed its evaluation, even if an exception is thrown, the
page scope must be restored to its original state. The fragment instance calls
JspContext.popPageScope(), restoring the page scope of the caller of the
fragment.
9. The fragment returns from invoke()
10. If <jsp:invoke> or <jsp:doBody> is being used to invoke a fragment, if the
varReader attribute is specified, a variable with a name equal to the value of
the varReader attribute is created (or modified) in the page scope, and the val-
ue is set to a java.io.Reader that can produce the results of the fragment invo-
cation.
11. The fragment instance is not discarded until the tag invocation defining the
fragment is complete. The invoke() method can be called zero or more times
after this execution.

JSP.8.4 Tag Files

As of JSP version 2.0, the JSP Compiler is required to recognize tag files. A
tag file is a source file that provides a way for a page author to abstract a fragment
of JSP code and make it reusable via a custom action.
Tag files allow a JSP page author to create tag libraries using JSP syntax. This
means that page authors no longer need to know Java or ask someone who knows

PUBLIC DRAFT
Tag Files 1-158

Java to write a tag extension. Even for page authors or tag library developers who
know Java, writing tag files is more convenient when developing tags that
primarily output template text.
The recommended file extension for a tag file is .tag. As is the case with JSP
files, the actual tag may be composed of a top file that includes other files that
contain either a complete tag or a fragment of a tag file. Just as the recommended
extension for a fragment of a JSP file is .jspf, the recommended extension for a
fragment of a tag file is .tagf.

JSP.8.4.1 Syntax of Tag Files


The syntax of a tag file is similar to that of a JSP page, with the following
exceptions:

• Directives - Some directives are not available or have limited availability, and
some tag file specific directives are available. See Section JSP.8.4.4, “Tag File
Directives” for a discussion on tag file directives.
The EBNF grammar in Section JSP.1.3.9, “Standard JSP Syntax Grammar”
describes the syntax of tag files, building on top of the grammar defined in
Section JSP.1.3.9, “Standard JSP Syntax Grammar”. The root production for a tag
files is JSPTagDef.

JSP.8.4.2 Semantics of Tag Files


For each tag file in the web application, a tag handler is made available to JSP
pages and other tag files. The specifics of how this is done are left up to the con-
tainer implementation. For example, some containers may choose to compile tag
files into Java tag handlers, whereas others may decide to interpret the tag handlers.
However the container chooses to prepare the tag handler, the following
conditions must hold true for all tag handlers defined as tag files:

• The tag file implementation must share a JspContext instance with the invok-
ing page, and push its own page scope by calling JspContext.pushPage-
Scope().

• The tag file implementation must restore the original page scope before re-
turning (even if an exception is thrown), by calling JspContext.popPage-
Scope().

PUBLIC DRAFT
1-159 JSP FRAGMENTS

• For each attribute declared, a page-scoped variable must be created in the


page scope. The name of the variable must be the name of the bean property
for the attribute. The value of the variable must be the value of the attribute
passed in during invocation, or null if the attribute was optional and not speci-
fied. If the tag accepts dynamic attributes, then page-scoped variables must
also be made available for each dynamic attribute passed in.
• The tag handler must behave as though a tag library descriptor entry was de-
fined for it, in accordance with the tag, attribute, variable, and fragment-input
directives that appear in the tag file translation unit.
It is legal for a tag file to forward to a page via the <jsp:forward> standard
action. Just as for JSP pages, the forward is handled through the request
dispatcher. Upon return from RequestDispatcher.forward(), the generated tag
handler must stop processing of the tag file and return SKIP_PAGE. Similarly, if a
tag file invokes a custom action which returns SKIP_PAGE from doEndTag() or
doTag(), it must stop processing of the tag file and return SKIP_PAGE. In either of
these two cases, the doFinally() method must be called on enclosing tags that
implement the TryCatchFinally interface before returning. The doEndTag()
methods of enclosing tags must not be called.
Care should be taken when invoking a classic tag handler from a tag file. In
general, SimpleTag Extensions can be used in environments other than Servlet.
However, because the Tag interface relies on PageContext, which in turn assumes
a Servlet environment, using classic tag handlers indirectly binds the use of the
tag file to Servlet environments. Nonetheless, the JSP container must allow such
an invocation to occur. When a tag file attempts to invoke a classic tag handler (i.e.
one that implements the Tag interface), it must cast the JspContext passed to the
SimpleTag into a PageContext. In the event that the class cast fails, the invocation
of the classic tag fails, and a JspException must be thrown.

JSP.8.4.3 Packaging Tag Files


One of the goals of tag files as a technology is to make it as easy to write a tag
handler as it is to write a JSP. Traditionally, writing tag handlers has been a
tedious task, with a lot of time spent compiling and packaging the tag handlers
and writing a TLD to provide information to tools and page authors about the
custom actions. The rules for packaging tag files are designed to make it very
simple and fast to write simple tags, while still providing as much power and
flexibility as classic tag handlers have.
Tag extensions written in JSP using tag files can be placed in one of two
locations. The first possibility is in the “/META-INF/tags/” directory in a JAR file

PUBLIC DRAFT
Tag Files 1-160

installed in the “/WEB-INF/lib/” directory. Tags placed here are typically part of a
reusable library of tags that can be easily dropped into any web application. The
second possibility is in a subdirectory of, the “/WEB-INF/tags/” directory of the
web application. Tags placed here are within easy reach and require little
packaging. Tag files that appear in any other location are not considered tag
extensions and must be ignored by the JSP container. For example, a tag file that
appears in the root of a web application would be treated as content to be served.
To be accessible, tag files bundled in a JAR require a Tag Library Descriptor.
Tag files that are not defined in a TLD must be ignored by the JSP container. JSP
2.0 adds two additional TLD elements to describe tags within a tag library,
namely <tag-file> and <path>. The <tag-file> element can appear wherever the
<tag> element appears and describes the location of a tag file defining a tag in this
tag library. The <tag-file> element requires <name> and <path> subelements,
which define the tag name and the location of the tag file relative to the TLD
respectively. Note that it is possible to combine both classic tag handlers and tag
handlers implemented using tag files in the same tag library by combining the use
of <tag> and <tag-file> elements under the <taglib> element. This means that in
most instances the client is unaware of how the tag extension was implemented.
See Section for these and other new TLD elements introduced by JSP 2.0.
Tag files placed in the “/WEB-INF/tags/” directory, or a subdirectory, are
made easily accessible to JSPs without the need to explicitly write a Tag Library
Descriptor. This makes it convenient for page authors to quickly abstract reusable
JSP code by simply creating a new file and placing the code inside of it. See the
new tagdir attribute of the <%@ taglib %> directive in Section JSP.1.10.4 for
details on how JSP files access tags defined here.
The JSP container must interpret the “/WEB-INF/tags/” directory and each
subdirectory under it, as another implicitly defined tag library containing tag
handlers defined by the tag files that appear in that directory. There are no special
relationships between subdirectories - they are allowed simply for organizational
purposes. For example, the following web application contains three tag libraries:

/WEB-INF/tags/
/WEB-INF/tags/a.tag
/WEB-INF/tags/b.tag
/wEB-INF/tags/foo/
/WEB-INF/tags/foo/c.tag
/WEB-INF/tags/foo/footags.tld
/WEB-INF/tags/bar/baz/
/WEB-INF/tags/bar/baz/d.tag

PUBLIC DRAFT
1-161 JSP FRAGMENTS

A tld file may or may not exist in each directory. If more than one tld file
exists in a directory, the behavior is undefined. If a tld file exists, the file is parsed
and a tag library is created. If a tld file does not exist for a directory, the JSP
container generates an implicit tag library, and must act as though a tld file were
present in that directory with the following defaults:

• <tlib-version> defaults to 1.0


• <jsp-version> defaults to 2.0
• <short-name> is derived from the directory name. If the directory is “/WEB-
INF/tags/”, the short name is simply “tags”. Otherwise, the full directory path
(relative to the web application) is taken, minus the “/WEB-INF/tags/” prefix.
Then, all ‘/’ characters are replaced with ‘-’, which yields the short name.
Note that short names are not guaranteed to be unique.
• A <tag-file> element is considered to exist for each tag file in this directory.
The <name> for each is the filename of the tag file, without the .tag exten-
sion.
For the above example, the implicit Tag Library Descriptor for the “/WEB-
INF/tags/bar/baz/” directory would be:

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>bar-baz</short-name>
<tag-file>
<name>d</name>
<path>d.tag</path>
</tag-file>
</taglib>

Upon deployment, the JSP container must search for and process all tag files
appearing in these JAR files, directories, and subdirectories. In processing a tag
file, the container makes the custom actions defined in these tags available to JSP
files.
Alternatively, tag files can be compiled into Java classes and bundled as a tag
library as indicated in Section JSP.8.2.5. This is useful for the situation where a
tag library developer wishes to distribute a binary version of the tag library
without the original source. Tag library developers that choose this form of
packaging must use a tool that produces portable JSP code that uses only standard
APIs

PUBLIC DRAFT
Tag Files 1-162

JSP.8.4.4 Tag File Directives


This section describes the directives available within tag files, which define
Simple Tag Handlers. Table JSP.8-3 outlines which directives are available in tag
files:

Table JSP.8-3 Directives available to tag files

Directive Available? Interpretation/Restrictions

page no A tag file is not a page. The tag directive must


be used instead. If this directive is used in a
tag file, a translation error must result.
taglib yes Identical to JSP pages.
include yes Identical to JSP pages. Note that if the
included file contains syntax unsuitable for tag
files, a translation error must occur.
tag yes Only applicable to tag files. An attempt to use
this attribute in JSP pages will result in a
translation error.
attribute yes Only applicable to tag files. An attempt to use
this attribute in JSP pages will result in a
translation error.
variable yes Only applicable to tag files. An attempt to use
this attribute in JSP pages will result in a
translation error.
fragment-input yes Only applicable to tag files. An attempt to use
this attribute in JSP pages will result in a
translation error.

JSP.8.4.5 The tag Directive


The tag directive is similar to the page directive, but applies to tag files instead
of JSPs. Like the page directive, a translation unit can contain more than one
instance of the tag directive, all the attributes will apply to the complete translation
unit (i.e. tag directives are position independent). However, there shall be only one
occurrence of any attribute/value defined by this directive in a given translation unit.
Multiple attribute/value (re)definitions result in a fatal translation error.

PUBLIC DRAFT
1-163 JSP FRAGMENTS

The attribute/value namespace is reserved for use by this, and subsequent, JSP
specification(s).
Unrecognized attributes or values result in fatal translation errors.

Examples
<%@ tag name=”add”
display-name=”Addition”
body-content=”scriptless”
dynamic-attributes=”true”
small-icon=”/WEB-INF/sample-small.jpg”
large-icon=”/WEB-INF/sample-large.jpg”
description=”Sample usage of tag directive” %>

Syntax
<%@ tag tag_directive_attr_list %>

tag_directive_attr_list ::=
{ name=”tagname” }
{ display-name=”display-name” }
{ body-content=”scriptless|tagdependent|empty” }
{ dynamic-attributes=”true|false” }
{ small-icon=”small-icon” }
{ large-icon=”large-icon” }
{ description=”description” }
{ example=”example” }
{ pageEncoding=”peinfo” }

The details of the attributes are as follows:

Table JSP.8-4 Details of tag directive attributes

name (optional) The unique action name for this tag. Defaults to
the filename of the tag file, without the .tag extension.
display-name (optional) A short name that is intended to be displayed by
tools. Defaults to the value of name.
body-content (optional) Provides information on the content of the body of
this tag. Can be either “empty”, “tagdependent” or
“scriptless”. A translation error will result if “JSP” or any
other value is used. Defaults to “scriptless”.

PUBLIC DRAFT
Tag Files 1-164

Table JSP.8-4 Details of tag directive attributes

dynamic-attributes (optional) Indicates whether this tag supports additional


attributes with dynamic names. If true, the generated tag
handler must implement the javax.servlet.jsp.tagext.Dynam-
icAttributes interface. Possible values are “true” and “false”.
Defaults to “false”.
small-icon (optional) Relative path, from the tag source file, of an image
file containing a small icon that can be used by tools.
Defaults to no small icon.
large-icon (optional) Relative path, from the tag source file, of an image
file containing a large icon that can be used by tools.
Defaults to no large icon.
description (optional) Defines an arbitrary string that describes this tag.
Defaults to no description.
example (optional) Defines an arbitrary string that presents an
informal description of an example of a use of this action.
Defaults to no example.
pageEncoding (optional) Carries the same syntax and semantics of the
pageEncoding directive in the page attribute.

JSP.8.4.6 The attribute Directive


The attribute directive is analogous to the <attribute> element in the Tag
Library Descriptor, and allows for the declaration of custom action attributes.

Examples
<%@ attribute name=”x” required=”true” fragment=”false”
rtexprvalue=”false” type=”java.lang.Integer”
description=”The first operand” %>

<%@ attribute name=”y” type=”java.lang.Integer” %>

<%@ attribute name=”prompt” fragment=”true” %>

PUBLIC DRAFT
1-165 JSP FRAGMENTS

Syntax
<%@ attribute attribute_directive_attr_list %>

attribute_directive_attr_list ::=
name=”attribute-name”
{ required=”true|false” }
{ fragment=”true|false” }
{ rtexprvalue=”true|false” }
{ type=”type” }
{ description=”description” }

The details of the attributes are as follows:

Table JSP.8-5 Details of attribute directive attributes

name (required) The unique name of the attribute being declared.


A translation error must result if more than one attribute
directive appears in the same translation unit with the same
name.

required (optional) Whether this attribute is required (true) or optional


(false). Defaults to “false” if not specified.
fragment (optional) Whether this attribute is a fragment to be
evaluated by the tag handler (true) or a normal attribute to be
evaluated by the container prior to being passed to the
container. If this attribute is true, the type attribute is fixed at
“javax.servlet.jsp.tagext.JspFragment” and a translation
error will result if the type attribute is specified. Also, if this
attribute is true, the rtexprvalue attribute is fixed at “true”
and a translation error will result if the rtexprvalue attribute
is specified. Defaults to false.
rtexprvalue (optional) Whether the attribute’s value may be dynamically
calculated at runtime by a scriptlet expression. Defaults to
false.
type (optional) The runtime type of the attribute’s value. Defaults
to java.lang.String if not specified.
description (optional) Description of the attribute. Defaults to no
description.

PUBLIC DRAFT
Tag Files 1-166

JSP.8.4.7 The variable Directive


The variable directive is analogous to the <variable> element in the Tag Library
descriptor, and defines the details of a variable exposed by the tag handler to the
calling page. See Section JSP.7.1.3.7, “Actions Defining Scripting Variables” for
more details.

Examples
<%@ variable name-given=”AT_BEGIN”
variable-class=”java.lang.Integer”
scope=”NESTED”
declare=”true”
description=”The sum of the two operands” %>

Syntax
<%@ variable variable_directive_attr_list %>

variable_directive_attr_list ::=
( name-given=”output-name”
| name-from-attribute=”attr-name”
)
{ variable-class=”output-type” }
{ scope=”AT_BEGIN|AT_END|NESTED” }
{ declare=”true|false” }
{ description=”description” }

The details of the attributes are as follows:

Table JSP.8-6 Details of variable directive attributes

name-given Defines a scripting variable to be defined in the page


invoking this tag. Either the name-given attribute or the
name-from-attribute attribute must be specified. Specifying
neither or both will result in a fatal translation error. A fatal
translation error will result if two variable directives have the
same name-given.

PUBLIC DRAFT
1-167 JSP FRAGMENTS

Table JSP.8-6 Details of variable directive attributes

name-from- Defines a scripting variable to be defined in the page


attribute invoking this tag. The specified name is the name of an
attribute whose (translation-time) value will give the name of
the variable. Either the name-given attribute or the name-
from-attribute attribute must be specified. Specifying neither
or both will result in a fatal translation error. A fatal
translation error will result if two variable directives have the
same name-from-attribute.
variable-class (optional) The name of the class of the variable. The default
is “java.lang.String”.
scope (optional) The scope of the scripting variable defined. Can be
either AT_BEGIN, AT_END, or NESTED. Defaults to
NESTED.

declare (optional) Whether the variable is declared or not. True is the


default.
description (optional) An optional description of this variable. Defaults
to no description.

JSP.8.4.8 The fragment-input Directive


The fragment-input directive is analogous to the <fragment-input> element in
the Tag Library descriptor, and defines the details of a single fragment input, which
is an Expression Language variable stored in the page-scope of the specified frag-
ment during the invocation of the fragment.
Before invoking a fragment, the tag handler creates a java.util.Map to store
fragment parameter names and values in. The map is then populated with keys
and values. Before invoking the fragment, for each fragment-input directive
specified, the tag handler verifies the key and value in the map to make sure the
types are valid and that required keys are present.
This directive is primarily used as a means to notify page authors what
fragment inputs can be expected. This information can be especially useful for
tools.

PUBLIC DRAFT
Tag Files 1-168

Examples
<%@ fragment-input name=”op1” fragment=”prompt”
required=”true” type=”java.lang.Integer”
description=”The first operand” %>

<%@ fragment-input name=”op2” fragment=”prompt”


type=”java.lang.Integer” %>

Syntax
<%@ fragment-input fragmentinput_directive_attr_list %>

fragmentinput_directive_attr_list ::=
name=”inputname”
fragment=”attributename”
{ required=”true|false” }
{ type=”type” }
{ description=”description” }

The details of the attributes are as follows:

Table JSP.8-7 Details of fragment-input directive attributes

name (required) The unique name for this fragment input. A


translation error must result if more than one fragment-input
directive appears in the same translation unit with the same
name and the same fragment.

fragment (required) The name of the corresponding attribute directive


this fragment-input directive is associated with. A translation
error must occur if this field is present, but no attribute
directive exists in this translation unit prior to this directive
with a name attribute equal to this field, or if such an
attribute directive exists but does not have its fragment
attribute set to “true”. A translation error must occur if there
are two fragment-input directives present in the same
translation unit, one of which contains no fragment attribute
and another which does.

PUBLIC DRAFT
1-169 JSP FRAGMENTS

Table JSP.8-7 Details of fragment-input directive attributes

required (optional) Whether it is required that a value be supplied for


this fragment input when invoking the fragment. Defaults to
“false”. If a fragment input is declared as required, but the
tag library developer tries to invoke the corresponding
fragment without a key equal to name, a java.lang.IllegalAr-
gumentException must be produced by the tag handler
implementation.
type (optional) The required runtime type of the fragment input.
Defaults to no checking. If this attribute is specified, then
when the tag library developer tries to invoke the
corresponding fragment with a key equal to name and a
value that is not an instance of type, a java.lang.IllegalArgu-
mentException must be produced by the tag handler
implementation.
description (optional) Defines an arbitrary string that describes this
fragment input. Defaults to no description.

JSP.8.4.9 XML View of a Tag File


Similar to JSP files, a tag file has an equivalent XML document. The XML view
of a tag file is exposed to the JSP compiler and to Tag Library Validators. the JSP
compiler must accept a tag file in either standard or XML syntax.
The XML view of a tag file is identical to the XML view of a JSP, except that
there are additional XML elements defined to handle tag file specific features:

• The jsp:directive.tag element:


This element must be a child of the root element and it must appear at the be-
ginning of the tag file. Its syntax is:

<jsp:directive.tag tag_directive_attr_list/>

Where tag_directive_attr_list is an XML-style attribute list as defined in


Section JSP.8.4.5.
• The jsp.directive.attribute element:
Zero or more of these elements may be present, and they must appear in suc-
cession. Each must be a child of the root element, and must appear in the be-
ginning of the tag file, after the jsp:directive.tag element. Its syntax is:

PUBLIC DRAFT
Example Scenario 1-170

<jsp:directive.attribute attribute_directive_attr_list/>

Where attribute_directive_attr_list is an XML-style attribute list as defined in


Section JSP.8.4.6.
• The jsp:directive.variable element:
Zero or more of these elements may be present, and they must appear in suc-
cession. Each must be a child of the root element, and must appear in the be-
ginning of the tag file, after the last jsp:directive.attribute element. Its syntax
is:

<jsp:directive.variable variable_directive_attr_list/>

Where variable_directive_attr_list is an XML style attribute list as defined in


Section JSP.8.4.7.
• The jsp:directive.fragment-input element:
Zero or more of these elements may be present, and they must appear in suc-
cession. Each must be a child of the root element, and must appear in the be-
ginning of the tag file, after the last jsp:directive.variable element. Its syntax
is:

<jsp:directive.fragment-input fragmentinput_directive_attr_list/>

Where fragmentinput_directive_attr_list is an XML style attribute list as de-


fined in Section JSP.8.4.8.

JSP.8.5 Example Scenario

The following non-normative example is intended to help solidify some of the


concepts in this Chapter. In the first section, two sample input files are presented, a
JSP (my.jsp), and a simple tag handler implemented using a tag file (simpletag.tag).
One possible output of the translation process is presented in the second section.
Although short, the example shows all concepts, including fragment-input; in prac-
tice most uses of tags will be simpler, but probably longer.
The sample generated code is annotated with comments that point to lifecycle
steps presented in various sections. The notation is as follows:

PUBLIC DRAFT
1-171 JSP FRAGMENTS

• “Step T.x” = Annotated step x from Section JSP.8.2.6, “Lifecycle of Simple


Tag Handlers”
• “Step C.x” = Annotated step x from Section JSP.8.3.5.1, “Creation of a JSP
Fragment”
• “Step F.x” = Annotated step x from Section JSP.8.3.5.2, “Invocation of a JSP
Fragment”

JSP.8.5.1 Sample Source Files


This section presents the sample source files in this scenario, from which the
output files are generated.

JSP.8.5.1.1 Original JSP (my.jsp)

<%@ taglib prefix="my" uri="/WEB-INF/mytags.tld" %>

<my:simpleTag x="10">
<jsp:attribute name="y" value="20"/>
<jsp:attribute name="nonfragment">
Nonfragment Template Text
</jsp:attribute>
<jsp:attribute name="frag">
Fragment Template Text ${param1}
</jsp:attribute>
<jsp:body>
Body of tag that defines an AT_BEGIN
scripting variable ${var1}.
</jsp:body>
</my:simpleTag>

PUBLIC DRAFT
Example Scenario 1-172

JSP.8.5.1.2 Original Tag File (simpletag.tag)

<%@ tag name="simpleTag" %>


<%@ attribute name="x" %>
<%@ attribute name="y" %>
<%@ attribute name="nonfragment" %>
<%@ attribute name="frag" fragment="true" %>
<%@ fragment-input name="param1" fragment="frag" %>
<%@ variable name-given="var1" scope="AT_BEGIN" %>

Some template text.


<jsp:invoke fragment="frag" varReader="var1">
<jsp:param name="param1" value="${x+y}"/>
</jsp:invoke>

Invoke the body:


<jsp:doBody/>

JSP.8.5.2 Sample Generated Files


This section presents the output files generated by the JSP compiler, from the
source files presented in the previous section.

JSP.8.5.2.1 Helper class for JspFragment (JspFragmentBase.java)

public abstract class JspFragmentBase


implements javax.servlet.jsp.tagext.JspFragment
{

private javax.servlet.jsp.JspContext jspContext;


private Object parentTag;
private java.util.Map origPageScope;

public void JspFragmentBase(


javax.servlet.jsp.JspContext jspContext,
Object parentTag )
{
this.jspContext = jspContext;
// C.3 - Store a reference to current page scope.
origPageScope = this.jspContext.peekPageScope();
this.parentTag = parentTag;
}

PUBLIC DRAFT
1-173 JSP FRAGMENTS

public javax.servlet.jsp.JspContext getJspContext() {


return this.jspContext;
}

public Object getParentTag() {


return this.parentTag;
}

/**
* Takes a snapshot of the current JspContext and stores
* the results in a Map for later restoration. Also sets the
* new values in the page context, given the provided params.
*
* @param params The parameters to set in the page scope
* @return A map that contains a snapshot of the old page scope.
*/
protected java.util.Map preparePageScope( java.util.Map params ) {
java.util.Map originalValues = new java.util.HashMap();

java.util.Iterator keys = params.keySet().iterator();


while( keys.hasNext() ) {
String key = (String)keys.next();
// Remember original values to restore later
originalValues.put( key, origPageScope.get( key ) );
// Set new values, based on params
jspContext.setAttribute( key, params.get( key ) );
}

return result;
}

PUBLIC DRAFT
Example Scenario 1-174

/**
* Restores the state of the page scope in the current page context,
* from the given map.
*
* @param originalValues The values to restore in the page
* context.
*/
protected void restorePageScope( java.util.Map originalValues ) {
keys = params.keySet().iterator();
while( keys.hasNext() ) {
String key = (String)keys.next();
// Value to be restored:
jspContext.setAttribute( key, originalValues.get( key ) );
originalValues.put( key, origPageScope.get( key ) );
}
}
}

JSP.8.5.2.2 Relevant Portion of JSP Service Method

// Step T.1 - Initial creation


MySimpleTag _jsp_mySimpleTag = new MySimpleTag();

// Step T.2 - Set page context and parent


_jsp_mySimpleTag.setJspContext( jspContext );
_jsp_mySimpleTag.setParent( null );

// Step T.3 - XML element attributes evaluated and set


_jsp.mySimpleTag.setX( "10" );

// Step T.4 - <jsp:attribute> elements evaluated and set

// - parameter y
_jsp.mySimpleTag.setY( "20" );

// - parameter nonfragment
// (using PageContext.pushBody() is ons possible implementation -
// one limitation is that this code will only work for Servlet-based code).
out = ((PageContext)jspContext).pushBody();
out.write( "\n Nonfragment Template Text\n " );
_jsp_mySimpleTag.setNonfragment(
((javax.servlet.jsp.tagext.BodyContent)out).getString() );
out = jspContext.popBody();

PUBLIC DRAFT
1-175 JSP FRAGMENTS

// - parameter frag
_jsp_mySimpleTag.setFrag(
// Step C.1 - New instance of fragment created
// Step C.2 - Store jspContext
// Step C.4 - Association with nearest enclosing Tag instance
new JspFragmentBase( jspContext, null ) {
// Step C.3 done in constructor (see above)
public void invoke( Map params ) {
// Step F.1-F.4 done in tag file (see following example)
// Step F.5 - Restore page scope of defining page
this.jspContext.pushPageScope( this.origPageScope );
// Step F.6 - Expose parameters in page scope
java.util.Map originalValues = preparePageScope( params );
// Step F.7 - Evaluate body to JspContext.getOut()
try {
javax.servlet.jsp.JspWriter out = jspContext.getOut();
out.write( "\n Fragment Template Text " );
out.write( javax.servlet.jsp.el.
ExpressionEvaluatorManager.evaluate(
"template text",
"${param1}",
java.lang.String.class,
jspContext )
);
out.write( " \n " );
}
finally {
// Step F.8 - Restore page scope to invoker’s state
restorePageScope( originalValues );
jspContext.popPageScope();
}

// Step F.9-F.11 done in tag file (see following example)


}
} );

PUBLIC DRAFT
Example Scenario 1-176

// Step T.5 - Determine and set body of the tag


// - body of tag
_jsp_mySimpleTag.setJspBody(
// Step C.1 - New instance of fragment created
// Step C.2 - Store jspContext
// Step C.4 - Association with nearest enclosing Tag instance
new JspFragmentBase( jspContext, null ) {
// Step C.3 done in constructor (see above)
public void invoke( java.util.Map params ) {
// Step F.1-F.4 done in tag file (see following example)
// Step F.5 - Restore page scope of defining page
this.jspContext.pushPageScope( this.origPageScope );
// Step F.6 - Expose parameters in page scope
java.util.Map originalValues = preparePageScope( params );
// Step F.7 - Evaluate body to JspContext.getOut()
try {
javax.servlet.jsp.JspWriter out = jspContext.getOut();
out.write(
" Body of tag that defines an AT_BEGIN\n" +
" scripting variable " );
out.write( javax.servlet.jsp.el.
ExpressionEvaluatorManager.evaluate(
"template text",
"${var1}",
java.lang.String.class,
jspContext )
);
out.write( ".\n" );
}
finally {
// Step F.8 - Restore page scope to invoker’s state
restorePageScope( originalValues );
jspContext.popPageScope();
}

// Step F.9-F.11 done in tag file (see following example)


}
} );

// Step T.6 - Inovke doTag


// Step T.7 occurs in the tag file (see following example)
// Step T.8 - Return value checked.
if( _jsp_mySimpleTag.doTag() == SKIP_PAGE ) return;

PUBLIC DRAFT
1-177 JSP FRAGMENTS

// Step T.9 - Declare AT_BEGIN and AT_END scripting variables


String var1 = (String)jspContext.findAttribute( "var1" );

JSP.8.5.2.3 Generated Simple Tag Handler (MySimpleTag.java)

public class MySimpleTag


implements javax.servlet.jsp.tagext.SimpleTag
{

private javax.servlet.jsp.JspContext jspContext;


private Object parent;
private javax.servlet.jsp.tagext.JspFragment jspBody;

// Attributes:
private String x;
private String y;
private String nonfragment;
private javax.servlet.jsp.tagext.JspFragment frag;

// Setters and getters for attributes:

public void setX( Stirng x ) {


this.x = x;
}

public String getX() {


return this.x;
}

public void setY( String y ) {


this.y = y;
}

public String getY() {


return this.y;
}

public void setNonfragment( String nonfragment ) {


this.nonfragment = nonfragment;
}

public String getNonfragment() {


return this.nonfragment;
}

PUBLIC DRAFT
Example Scenario 1-178

public void setFrag( javax.servlet.jsp.tagext.JspFragment frag ) {


this.frag = frag;
}

public javax.servlet.jsp.tagext.JspFragment getFrag() {


return this.frag;
}

// Implementation of SimpleTag interface:

public void setParent( Object parent ) {


this.parent = parent;
}

public Object getParent() {


return this.parent;
}

public void setJspBody( javax.servlet.jsp.tagext.JspFragment jspBody ) {


this.jspBody = jspBody;
}

public javax.servlet.jsp.tagext.JspFragment getJspBody() {


return this.jspBody;
}

public void setJspContext( javax.servlet.jsp.JspContext context ) {


this.jspContext = context;
}

public int doTag() throws JspException {


javax.servlet.jsp.JspWriter out = this.jspContext.getOut();

// See Section JSP.8.4.2, “Semantics of Tag Files”


this.jspContext.pushPageScope();

// Create page-scope attributes for each tag attribute:


this.jspContext.setAttribute( "x", getX() );
this.jspContext.setAttribute( "y", getX() );
this.jspContext.setAttribute( "nonfragment", getNonfragment() );
this.jspContext.setAttribute( "frag", getFrag() );

PUBLIC DRAFT
1-179 JSP FRAGMENTS

try {
// Tag template text:
out.write( "\n\n\n\n\n\n\nSome template text.\n" );

// Invoke the "frag" fragment:


// Step F.1 - Assemble parameter map
java.util.Map fragParams = new java.util.HashMap();
fragParams.put( "param1",
javax.servlet.jsp.el.ExpressionEvaluatorManager.evaluate(
"template text",
"${x+y}",
java.lang.String.class,
this.jspContext )
);

// Step F.2 does not apply (not invoking the body)

// Step F.3 - varReader is specified.


java.io.Writer sout = new java.io.StringWriter();

// Step F.4 - Invoke fragment with parameter map


getFrag().invoke( sout, fragParams );

// Step F.5 - F.9 occur in the fragment (see above)


// Step F.10 - varReader specified, so save to var
this.jspContext.setAttribute(
"var1", new StringReader( sout.toString() ) );
// Step F.11 - Done!

PUBLIC DRAFT
Example Scenario 1-180

out.write( "\n\nInvoke the body:\n" );

// Invoke the body of the tag:


// Step F.1 - Assemble parameter map
java.util.Map bodyParams = new java.util.HashMap();

// Step F.2 - Add scripting variables to parameter map for body


bodyParams.put( "var1", this.jspContext.getAttribute( "var1" ) );

// Step F.3 does not apply

// Step F.4 - Invoke body, passing parameter map


getJspBody().invoke( bodyParams );

// Steps F.5 - F.9 occur in the fragment (see above)


// Step F.10 does not apply.
// Step F.11 - Done!
}
finally {
this.jspContext.popPageScope();
}

return EVAL_PAGE;
}
}

PUBLIC DRAFT
C H A P T E R JSP.9
Scripting

This chapter describes the details of the Scripting Elements when the lan-
guage directive value is “java”.
The scripting language is based on the Java programming language (as
specified by “The Java Language Specification”), but note that there is no valid
JSP page, or a subset of a page, that is a valid Java program.
The following sections describe the details of the relationship between the
scripting declarations, scriptlets, and scripting expressions, and the Java
programming language. The description is in terms of the structure of the JSP
page implementation class. A JSP container need not generate the JSP page
implementation class, but it must behave as if one exists.

JSP.9.1 Overall Structure

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.

JSP.9.1.1 Valid JSP Page


A JSP page is valid for a Java Platform if and only if the JSP page implementa-
tion class defined by Table JSP.9-1 (after applying all include directives), together
with any other classes defined by the JSP container, is a valid program for the given
Java Platform, and if it passes the validation methods for all the tag libraries associ-
ated with the JSP page.

PUBLIC DRAFT 1-181


Overall Structure 1-182

JSP.9.1.2 Reserved Names


Sun Microsystems reserves all names of the form {_}jsp_* and {_}jspx_*, in
any combination of upper and lower case, for the JSP specification. Names of this
form that are not defined in this specification are reserved by Sun for future
expansion.

JSP.9.1.3 Implementation Flexibility


The transformations described in this chapter need not be performed literally.
An implementation may implement things differently to provide better perfor-
mance, lower memory footprint, or other implementation attributes.

Table JSP.9-1 Structure of the JavaProgramming Language Class

Optional imports import name1


clause as indicated
via jsp directive
SuperClass is either class _jspXXX extends SuperClass
selected by the JSP
container or by the
JSP author via jsp
directive.

Name of class
(_jspXXX) is
implementation
dependent.
Start of body of JSP {
page implementation
class
(1) Declaration // declarations...
Section
signature for public void _jspService(<ServletRequestSubtype>
generated method request,
<ServletResponseSubtype> response)
throws ServletException, IOException {

PUBLIC DRAFT
1-183 SCRIPTING

Table JSP.9-1 Structure of the JavaProgramming Language Class

(2) Implicit Objects // code that defines and initializes request, response,
Section page, pageContext etc.

(3) Main Section // code that defines request/response mapping


close of _jspService }
method
close of _jspXXX }

JSP.9.2 Declarations Section

The declarations section corresponds to the declaration elements.


The contents of this section is determined by concatenating all the
declarations in the page in the order in which they appear.

JSP.9.3 Initialization Section

This section defines and initializes the implicit objects available to the JSP page.
See Section JSP.1.8.3, “Implicit Objects”.

JSP.9.4 Main Section

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.9.4.1 Template Data


Template data is transformed into code that will place the template data into the
stream named by the implicit variable out when the code is executed. White space
is preserved.

PUBLIC DRAFT
Main Section 1-184

Ignoring quotation issues and performance issues, this corresponds to a


statement of the form:

Original Equivalent Text


template out.print(template)

JSP.9.4.2 Scriptlets
A scriptlet is transformed into its code fragment.:

Original Equivalent Text


<% fragment %> fragment

JSP.9.4.3 Expressions
An expression is transformed into a Java statement to insert the value of the
expression, converted to java.lang.String if needed, into the stream curnamed by the
implicit variable out. No additional newlines or space is included.
Ignoring quotation and performance issues, this corresponds to a statement of
the form:

Original Equivalent Text


<%= expression %> out.print(expression)

JSP.9.4.4 Actions
An action defining one or more objects is transformed into one or more variable
declarations for those objects, together with code that initializes the variables. Their
visibility is affected by other constructs, for example scriptlets.
The semantics of the action type determines the names of the variables
(usually the name of an id attribute, if present) and their type. The only standard
action in the JSP specification that defines objects is the jsp:usebean action. The
name of the variable introduced is the name of the id attribute and its type is the
type of the class attribute.

Original Equivalent Text


<x:tag> declare AT_BEGIN variables
foo {
</x:tag> declare NESTED variables
transformation of foo
}
declare AT_END variables

PUBLIC DRAFT
1-185 SCRIPTING

Note that the value of the scope attribute does not affect the visibility of the
variables within the generated program. It affects where and thus for how long
there will be additional references to the object denoted by the variable.

PUBLIC DRAFT
Main Section 1-186

PUBLIC DRAFT
PART II
T he next chapters provide detail specification information on some portions
of the JSP specification that are intended for JSP Container Vendors, .... etc..
The chapters are normative.
The chapters are

• JSP Container
• Core API
• Tag Extension API

PUBLIC DRAFT 2-1


C H A P T E R JSP.10
JSP Container

This chapter describes the contracts between a JSP container and a JSP page,
including the precompilation protocol and debugging support requirements.
The information in this chapter is independent of the Scripting Language used
in the JSP page. Chapter JSP.9 describes information specific to when the lan-
guage attribute of the page directive has “java” as its value.).
JSP page implementation classes should use the JspFactory and PageContext
classes to take advantage of platform-specific implementations.

JSP.10.1 JSP Page Model

A JSP page is represented at execution time by a JSP page implementation


object and is executed by a JSP container. The JSP page implementation object is a
servlet. The JSP container delivers requests from a client to a JSP page implementa-
tion object and responses from the JSP page implementation object to the client.
The JSP page describes how to create a response object from a request object
for a given protocol, possibly creating and/or using some other objects in the
process . A JSP page may also indicate how some events are to be handled. In JSP
2.0 only init and destroy events are allowed events.

JSP.10.1.1 Protocol Seen by the Web Server


The JSP container locates the appropriate instance of the JSP page implementa-
tion class and delivers requests to it using the Servlet protocol. A JSP container may
need to create such a class dynamically from the JSP page source before delivering
request and response objects to it.
The Servlet class defines the contract between the JSP container and the JSP
page implementation class. When the HTTP protocol is used, the contract is

PUBLIC DRAFT 2-2


2-3 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.1.8.3.

JSP.10.1.1.1 Protocol Seen by the JSP Page Author


The JSP specification defines the contract between the JSP container and the
JSP page author. This contract defines the assumptions an author can make for the
actions described in the JSP page.
The main portion of this contract is the _jspService() method that is generated
automatically by the JSP container from the JSP page. The details of this contract
are provided in Chapter JSP.9.
The contract also describes how a JSP author can indicate what actions will be
taken when the init() and destroy() methods of the page implementation occur. In
JSP 2.0 this is done by defining methods with names jspInit() and jspDestroy() in
a declaration scripting element in the JSP page. The jspInit() method, if present,
will be called to prepare the page before the first request is delivered. Similarly a
JSP container can reclaim resources used by a JSP page when a request is not
being serviced by the JSP page by invoking its jspDestroy() method, if present.
A JSP page author may not (re)define Servlet methods through a declaration
scripting element.
The JSP specification reserves names for methods and variables starting with
jsp, _jsp, jspx and _jspx, in any combination of upper and lower case.

JSP.10.1.1.2 The HttpJspPage Interface


The enforcement of the contract between the JSP container and the JSP page
author is aided by the requirement that the Servlet class corresponding to the JSP
page must implement the HttpJspPage interface (or the JspPage interface if the
protocol is not HTTP).

PUBLIC DRAFT
JSP Page Implementation Class 2-4

JSP Container JSP Page

init event jspInit <%!


public void jspInit()...

request public void jspDestroy()...


_jspService %>
response
<html>
This is the response..
</html>
destroy event jspDestroy

REQUEST PROCESSING TRANSLATION PHASE


PHASE

Figure JSP.10-1 Contracts between a JSP Page and a JSP Container.

The involved contracts are shown in Figure JSP.10-1. We now revisit this
whole process in more detail.

JSP.10.2 JSP Page Implementation Class

The JSP container creates a JSP page implementation class for each JSP page.
The name of the JSP page implementation class is implementation dependent.
The JSP Page implementation object belongs to an implementation-dependent
named package. The package used may vary between one JSP and another, so
minimal assumptions should be made. The unnamed package should not be used
without an explicit “import” of the class.
The JSP container may create the implementation class for a JSP page, or a
superclass may be provided by the JSP page author through the use of the extends
attribute in the page directive.
The extends mechanism is available for sophisticated users. It should be used
with extreme care as it restricts decisions that a JSP container can make. It may
restrict efforts to improve performance, for example.
The JSP page implementation class will implement Servlet and the Servlet
protocol will be used to deliver requests to the class.

PUBLIC DRAFT
2-5 JSP CONTAINER

A JSP page implementation class may depend on support classes. If the JSP
page implementation class is packaged into a WAR, any dependant classes will
have to be included so it will be portable across all JSP containers.
A JSP page author writes a JSP page expecting that the client and the server
will communicate using a certain protocol. The JSP container must guarantee that
requests from and responses to the page use that protocol. Most JSP pages use
HTTP, and their implementation classes must implement the HttpJspPage
interface, which extends JspPage. If the protocol is not HTTP, then the class will
implement an interface that extends JspPage.

JSP.10.2.1 API Contracts


The contract between the JSP container and a Java class implementing a JSP
page corresponds to the Servlet interface. Refer to the Servlet 2.4 specification for
details.
The responsibility for adhering to this contract rests on the JSP container
implementation if the JSP page does not use the extends attribute of the jsp
directive. If the extends attribute of the jsp directive is used, the JSP page author
must guarantee that the superclass given in the extends attribute supports this
contract.

Table JSP.10-1 How the JSP Container Processes JSP Pages

Comments Methods the JSP Container Invokes

Method is optionally defined in JSP void jspInit()


page.
Method is invoked when the JSP page
is initialized.
When method is called all the methods
in servlet, including
getServletConfig() are available

Method is optionally defined in JSP void jspDestroy()


page.
Method is invoked before destroying
the page.

PUBLIC DRAFT
JSP Page Implementation Class 2-6

Table JSP.10-1 How the JSP Container Processes JSP Pages

Method may not be defined in JSP void


page. _jspService(<ServletRequestSubtype>
The JSP container automatically , <ServletResponseSubtype>) throws
generates this method, based on the IOException, ServletException
contents of the JSP page.
Method invoked at each client request.

JSP.10.2.2 Request and Response Parameters


As shown in Table JSP.10-1, the methods in the contract between the JSP con-
tainer and the JSP page require request and response parameters.
The formal type of the request parameter (which this specification calls
<ServletRequestSubtype>) is an interface that extends
javax.servlet.ServletRequest. The interface must define a protocol-dependent
request contract between the JSP container and the class that implements the JSP
page.
Likewise, the formal type of the response parameter (which this specification
calls <ServletResponseSubtype>) is an interface that extends javax.servlet.Servlet-
Response. The interface must define a protocol-dependent response contract
between the JSP container and the class that implements the JSP page.
The request and response interfaces together describe a protocol-dependent
contract between the JSP container and the class that implements the JSP page.
The HTTP contract is defined by the javax.servlet.http.HttpServletRequest and
javax.servlet.http.HttpServletResponse interfaces.
The JspPage interface refers to these methods, but cannot describe
syntactically the methods involving the Servlet(Request,Response) subtypes.
However, interfaces for specific protocols that extend JspPage can, just as
HttpJspPage describes them for the HTTP protocol.
JSP containers that conform to this specification (in both JSP page
implementation classes and JSP container runtime) must implement the request
and response interfaces for the HTTP protocol as described in this section.

JSP.10.2.3 Omitting the extends Attribute


If the extends attribute of the page directive (see Section 1.10.1) in a JSP page
is not used, the JSP container can generate any class that satisfies the contract
described in Table JSP.10-1, when it transforms the JSP page.

PUBLIC DRAFT
2-7 JSP CONTAINER

In the following code examples, Code Example JSP.10-1 illustrates a generic


HTTP superclass named ExampleHttpSuper. Code Example JSP.10-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 JSP.10-1A Generic HTTP Superclass

imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;

/**
* An example of a superclass for an HTTP JSP class
*/

abstract class ExampleHttpSuper implements HttpJspPage {


private ServletConfig config;

final public void init(ServletConfig config) throws ServletException {


this.config = config;
jspInit();
}

public void jspInit() {


}

public void jspDestroy() {


}

final public ServletConfig getServletConfig() {


return config;
}

// This one is not final so it can be overridden by a more precise method


public String getServletInfo() {
return “A Superclass for an HTTP JSP”; // maybe better?
}

PUBLIC DRAFT
JSP Page Implementation Class 2-8

final public void destroy() {


jspDestroy();
}

/**
* The entry point into service.
*/

final public void service(ServletRequest req, ServletResponse res)


throws ServletException, IOException {

// casting exceptions will be raised if an internal error.


HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

_jspService(request, response);
}

/**
* abstract method to be provided by the JSP processor in the subclass
* Must be defined in subclass.
*/

abstract public void _jspService(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException;

Code Example JSP.10-2The Java Class Generated From a JSP Page

PUBLIC DRAFT
2-9 JSP CONTAINER

imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;

/**
* An example of a class generated for a JSP.
*
* The name of the class is unpredictable.
* We are assuming that this is an HTTP JSP page (like almost all are)
*/

class _jsp1344 extends ExampleHttpSuper {

// Next code inserted directly via declarations.


// Any of the following pieces may or not be present
// if they are not defined here the superclass methods
// will be used.

public void jspInit() {....}


public void jspDestroy() {....}

// The next method is generated automatically by the


// JSP processor.
// body of JSP page

public void _jspService(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// initialization of the implicit variables


// ...

// next is code from scriptlets, expressions, and static text.

PUBLIC DRAFT
Buffering 2-10

JSP.10.2.4 Using the extends Attribute


If the JSP page author uses extends, the generated class is identical to the one
shown in Code Example JSP.10-2, except that the class name is the one specified in
the extends attribute.
The contract on the JSP page implementation class does not change. The JSP
container should check (usually through reflection) that the provided superclass:

• Implements HttpJspPage if the protocol is HTTP, or JspPage otherwise.


• All of the methods in the Servlet interface are declared final.

Additionally, it is the responsibility of the JSP page author that the provided
superclass satisfies:

• The service() method of the Servlet API invokes the _jspService() method.
• The init(ServletConfig) method stores the configuration, makes it available as
getServletConfig, then invokes jspInit.

• The destroy method invokes jspDestroy.

A JSP container may give a fatal translation error if it detects that the provided
superclass does not satisfy these requirements, but most JSP containers will not
check them.

JSP.10.3 Buffering

The JSP container buffers data (if the jsp directive specifies it using the buffer
attribute) as it is sent from the server to the client. Headers are not sent to the client
until the first flush method is invoked. Therefore, none of the operations that rely on
headers, such as the setContentType, redirect, or error methods are valid once the
flush method is executed and the headers are sent.
The javax.servlet.jsp.JspWriter class buffers and sends output. The JspWriter
class is used in the _jspService method as in the following example:

PUBLIC DRAFT
2-11 JSP CONTAINER

import javax.servlet.jsp.JspWriter;

static JspFactory _jspFactory = JspFactory.getDefaultFactory();

_jspService(<SRequest> request, <SResponse> response) {

// initialization of implicit variables...


PageContext pageContext = _jspFactory.createPageContext(
this,
request,
response,
false,
PageContext.DEFAULT_BUFFER,
false
);
JSPWriter out = pageContext.getOut();
// ....
// .... the body goes here using "out"
// ....
out.flush();
}

You can find the complete listing of javax.servlet.jsp.JspWriter in


Chapter JSP.11.
With buffering turned on, you can still use a redirect method in a scriptlet in a
.jsp file, by invoking response.redirect(someURL) directly.

JSP.10.4 Precompilation

A JSP page that is using the HTTP protocol will receive HTTP requests. JSP
2.0 compliant containers must support a simple precompilation protocol, as well as
some basic reserved parameter names. Note that the precompilation protocol is
related but not the same as the notion of compiling a JSP page into a Servlet class
(Appendix JSP.A).

JSP.10.4.1 Request Parameter Names


All request parameter names that start with the prefix "jsp" are reserved by the
JSP specification and should not be used by any user or implementation except as
indicated by the specification.

PUBLIC DRAFT
Debugging Requirements 2-12

All JSPs pages should ignore (not depend on) any parameter that starts with
"jsp_"

JSP.10.4.2 Precompilation Protocol


A request to a JSP page that has a request parameter with name
"jsp_precompile" is a precompilation request. The "jsp_precompile" parameter
may have no value, or may have values "debug", "true" or "false". In all cases, the
request should not be delivered to the JSP page.
The intention of the precompilation request is that of a suggestion to the JSP
container to precompile the JSP page into its JSP page implementation class. The
suggestion is conveyed by giving the parameter the value "true" or no value, but
note that the request can be ignored.
For example:

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).

JSP.10.5 Debugging Requirements

With the completion of JSR-045 ("Debugging Support for Other Languages"),


the JSP Compiler now has a standard format to convey source map debugging infor-
mation to tools such as debuggers. See http://jcp.org/jsr/detail/45.jsp for details.
All JSP 2.0 containers must be capable of generating source map debugging
information for JSP pages written in either standard or XML syntax. The JSP
compiler must be able to produce .class files with a SourceDebugExtension
attribute, mapping each line or lines of JSP code to the corresponding generated
line or lines of Java code.

PUBLIC DRAFT
2-13 JSP CONTAINER

The exact mechanism for causing the JSP compiler to produce source map
debugging information is currently implementation-dependent.

PUBLIC DRAFT
C H A P T E R JSP.11
Core API

This chapter describes the javax.servlet.jsp package. The 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, specifica-
tion document.
The javax.servlet.jsp package contains a number of classes and interfaces that
describe and define the contracts between a JSP page implementation class and
the runtime environment provided for an instance of such a class by a conforming
JSP container.

JSP.11.1 JSP Page Implementation Object Contract

This section describes the basic contract between a JSP Page implementation
object and its container. The main contract is defined by the classes JspPage and
HttpJspPage. The JspFactory class describes the mechanism to portably instantiate
all needed runtime objects, and JspEngineInfo provides basic information on the cur-
rent JSP container.
None of the classes described here are intended to be used by JSP page
authors; an example of how these classes may be used is included elsewhere in
this chapter.

JSP.11.1.1 JspPage

Syntax
public interface JspPage extends javax.servlet.Servlet

All Known Subinterfaces: HttpJspPage

2-14
2-15 CORE API

All Superinterfaces: javax.servlet.Servlet

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.

Two plus One Methods


The interface defines a protocol with 3 methods; only two of them: jspInit() and
jspDestroy() are part of this interface as the signature of the third method: _jsp-
Service() depends on the specific protocol used and cannot be expressed in a
generic way in Java.
A class implementing this interface is responsible for invoking the above methods
at the appropriate time based on the corresponding Servlet-based method invoca-
tions.
The jspInit() and jspDestroy() methods can be defined by a JSP author, but the
_jspService() method is defined automatically by the JSP processor based on the
contents of the JSP page.
_jspService()
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.
The specific signature depends on the protocol supported by the JSP page.
public void _jspService(ServletRequestSubtype request,
ServletResponseSubtype response)
throws ServletException, IOException;

JSP.11.1.1.1 Methods
public void jspDestroy()
The jspDestroy() method is invoked when the JSP page is about to be
destroyed. A JSP page can override this method by including a definition for
it in a declaration element. A JSP page should redefine the destroy() method
from Servlet.

PUBLIC DRAFT
JSP Page Implementation Object Contract 2-16

public void jspInit()


The jspInit() method is invoked when the JSP page is initialized. It is the
responsibility of the JSP implementation (and of the class mentioned by the
extends attribute, if present) that at this point invocations to the getServlet-
Config() method will return the desired value. A JSP page can override this
method by including a definition for it in a declaration element. A JSP page
should redefine the init() method from Servlet.

JSP.11.1.2 HttpJspPage

Syntax
public interface HttpJspPage extends JspPage

All Superinterfaces: JspPage, javax.servlet.Servlet

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.

See Also: JspPage

JSP.11.1.2.1 Methods
public void _jspService(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
The _jspService()method corresponds to the body of the JSP page. This
method is defined automatically by the JSP container and should never be
defined by the JSP page author.
If a superclass is specified using the extends attribute, that superclass may
choose to perform some actions in its service() method before or after calling
the _jspService() method. See using the extends attribute in the JSP_Engine
chapter of the JSP specification.
Throws:
IOException, ServletException

PUBLIC DRAFT
2-17 CORE API

JSP.11.1.3 JspFactory

Syntax
public abstract class JspFactory

Description
The JspFactory is an abstract class that defines a number of factory methods
available to a JSP page at runtime for the purposes of creating instances of vari-
ous interfaces and classes used to support the JSP implementation.

A conformant JSP Engine implementation will, during it’s initialization instanti-


ate an implementation dependent subclass of this class, and make it globally
available for use by JSP implementation classes by registering the instance cre-
ated with this class via the static setDefaultFactory() method.
The PageContext and the JspEngineInfo classes are the only implementation-
dependent classes that can be created from the factory.
JspFactory objects should not be used by JSP page authors.

JSP.11.1.3.1 Constructors
public JspFactory()

JSP.11.1.3.2 Methods
public static synchronized JspFactory getDefaultFactory()
Returns: the default factory for this implementation
public abstract JspEngineInfo getEngineInfo()
called to get implementation-specific information on the current JSP engine
Returns: a JspEngineInfo object describing the current JSP engine
public abstract PageContext getPageContext(javax.servlet.Servlet servlet,
javax.servlet.ServletRequest request,
javax.servlet.ServletResponse response, java.lang.String errorPageURL,
boolean needsSession, int buffer, boolean autoflush)
obtains an instance of an implementation dependent javax.servlet.jsp.Page-
Context abstract class for the calling Servlet and currently pending request
and response.
This method is typically called early in the processing of the _jspService()
method of a JSP implementation class in order to obtain a PageContext object
for the request being processed.

PUBLIC DRAFT
JSP Page Implementation Object Contract 2-18

Invoking this method shall result in the PageContext.initialize() method being


invoked. The PageContext returned is properly initialized.
All PageContext objects obtained via this method shall be released by invok-
ing releasePageContext().
Parameters:
servlet - the requesting servlet
config - the ServletConfig for the requesting Servlet
request - the current request pending on the servlet
response - the current response pending on the servlet
errorPageURL - the URL of the error page for the requesting JSP, or null
needsSession - true if the JSP participates in a session
buffer - size of buffer in bytes, PageContext.NO_BUFFER if no buffer,
PageContext.DEFAULT_BUFFER if implementation default.
autoflush - should the buffer autoflush to the output stream on buffer
overflow, or throw an IOException?
Returns: the page context
See Also: PageContext
public abstract void releasePageContext(PageContext pc)
called to release a previously allocated PageContext object. Results in Page-
Context.release() being invoked. This method should be invoked prior to
returning from the _jspService() method of a JSP implementation class.
Parameters:
pc - A PageContext previously obtained by getPageContext()
public static synchronized void setDefaultFactory(JspFactory deflt)
set the default factory for this implementation. It is illegal for any principal
other than the JSP Engine runtime to call this method.
Parameters:
default - The default factory implementation

JSP.11.1.4 JspEngineInfo

Syntax
public abstract class JspEngineInfo

PUBLIC DRAFT
2-19 CORE API

Description
The JspEngineInfo is an abstract class that provides information on the current
JSP engine.

JSP.11.1.4.1 Constructors
public JspEngineInfo()

JSP.11.1.4.2 Methods
public abstract java.lang.String getSpecificationVersion()
Return the version number of the JSP specification that is supported by this
JSP engine.
Specification version numbers that consists of positive decimal integers sepa-
rated by periods “.”, for example, “2.0” or “1.2.3.4.5.6.7”. This allows an
extensible number to be used to represent major, minor, micro, etc versions.
The version number must begin with a number.
Returns: the specification version, null is returned if it is not known

JSP.11.2 Implicit Objects

The PageContext object and the JspWriter are available by default as implicit
objects.

JSP.11.2.1 JspContext

Syntax
public abstract class JspContext

Direct Known Subclasses: PageContext

Description
JspContext serves as the base class for the PageContext class and abstracts all
information that is not specific to servlets. This allows for Simple Tag Extensions
to be used outside of the context of a request/response Servlet.

The JspContext provides a number of facilities to the page/component author and


page implementor, including:
•a single API to manage the various scoped namespaces

PUBLIC DRAFT
Implicit Objects 2-20

•a mechanism to obtain the JspWriter for output


•a mechanism to expose page directive attributes to the scripting environ-
ment

Methods Intended for Container Generated Code

To facilitate Simple Tag Extensions, the pushPageScope(), popPageScope() and


peekPageScope() methods are added.

Methods Intended for JSP authors


The following methods provide convenient access to implicit objects: getOut()

JSP.11.2.1.1 Fields
public static final int APPLICATION_SCOPE
Application scope: named reference remains available in the ServletContext
until it is reclaimed.
public static final int PAGE_SCOPE
Page scope: (this is the default) the named reference remains available in this
JspContext until the return from the current Servlet.service() invocation.
public static final int REQUEST_SCOPE
Request scope: the named reference remains available from the Servlet-
Request associated with the Servlet until the current request is completed.
public static final int SESSION_SCOPE
Session scope (only valid if this page participates in a session): the named
reference remains available from the HttpSession (if any) associated with the
Servlet until the HttpSession is invalidated.

JSP.11.2.1.2 Constructors
public JspContext()

JSP.11.2.1.3 Methods
public abstract java.lang.Object findAttribute(java.lang.String name)
Searches for the named attribute in page, request, session (if valid), and appli-
cation scope(s) in order and returns the value associated or null.
Returns: the value associated or null
public abstract java.lang.Object getAttribute(java.lang.String name)

PUBLIC DRAFT
2-21 CORE API

Return the object associated with the name in the page scope or null if not
found.
Parameters:
name - the name of the attribute to get
Throws:
NullPointerException - if the name is null
IllegalArgumentException - if the scope is invalid
public abstract java.lang.Object getAttribute(java.lang.String name, int scope)
Return the object associated with the name in the specified scope or null if
not found.
Parameters:
name - the name of the attribute to set
scope - the scope with which to associate the name/object
Throws:
NullPointerException - if the name is null
IllegalArgumentException - if the scope is invalid
public abstract java.util.Enumeration getAttributeNamesInScope(int scope)
Enumerate all the attributes in a given scope
Returns: an enumeration of names (java.lang.String) of all the attributes the
specified scope
public abstract int getAttributesScope(java.lang.String name)
Get the scope where a given attribute is defined.
Returns: the scope of the object associated with the name specified or 0
public abstract ExpressionEvaluator getExpressionEvaluator()
Provides programmatic access to the ExpressionEvaluator. The JSP Con-
tainer must return a valid instance of an ExpressionEvaluator that can parse
EL expressions.
public abstract JspWriter getOut()
The current value of the out object (a JspWriter).
Returns: the current JspWriter stream being used for client response
public abstract java.util.Map peekPageScope()
Peeks at the top element of the page scope stack. This value is the current
state of the page scope. Does not modify the state of the stack or copy any
objects.

PUBLIC DRAFT
Implicit Objects 2-22

Returns: A Map representing the state of the page scope currently at the top
of the stack. This object can be passed to pushPageScope to restore this state.
The keys of the returned Map are Strings representing attribute names. The
values are the values of those attributes.
public abstract java.util.Map popPageScope()
Pops the page scope from the stack. After calling this method, the PageScope
will appear the same as it was before the last call to pushPageScope.
Returns: A Map representing the state of the page scope just before it was
popped. This object can be passed to pushPageScope to restore this state. The
keys of the returned Map are Strings representing attribute names. The values
are the values of those attributes.
Throws:
java.util.EmptyStackException - if this is the last page scope on the stack.
public abstract void pushPageScope(java.util.Map scopeState)
Pushes a page scope on the stack. The scopeState cannot be arbitrary. Only a
page scope returned from popPageScope() or peekPageScope() may be
passed in.
Parameters:
scopeState - If null, a new, empty, page scope is pushed. Otherwise, the state
of the page scope is restored to the contents of the provided Map.
public abstract void removeAttribute(java.lang.String name)
Remove the object reference associated with the given name, look in all
scopes in the scope order.
Parameters:
name - The name of the object to remove.
public abstract void removeAttribute(java.lang.String name, int scope)
Remove the object reference associated with the specified name in the given
scope.
Parameters:
name - The name of the object to remove.
scope - The scope where to look.
public abstract void setAttribute(java.lang.String name,
java.lang.Object attribute)
Register the name and object specified with page scope semantics.
Parameters:
name - the name of the attribute to set

PUBLIC DRAFT
2-23 CORE API

attribute - the object to associate with the name


Throws:
NullPointerException - if the name or object is null
public abstract void setAttribute(java.lang.String name, java.lang.Object o,
int scope)
register the name and object specified with appropriate scope semantics
Parameters:
name - the name of the attribute to set
o - the object to associate with the name
scope - the scope with which to associate the name/object
Throws:
NullPointerException - if the name or object is null
IllegalArgumentException - if the scope is invalid

JSP.11.2.2 PageContext

Syntax
public abstract class PageContext extends JspContext

Description
PageContext extends JspContext to provide useful context information for when
JSP technology is used in a Servlet environment.

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.
The PageContext class is an abstract class, designed to be extended to provide
implementation dependent implementations thereof, by conformant JSP engine
runtime environments. A PageContext instance is obtained by a JSP implementa-
tion class by calling the JspFactory.getPageContext() method, and is released by
calling JspFactory.releasePageContext().
An example of how PageContext, JspFactory, and other classes can be used
within a JSP Page Implementation object is given elsewhere.
The PageContext provides a number of facilities to the page/component author
and page implementor, including:
•a single API to manage the various scoped namespaces
•a number of convenience API’s to access various public objects

PUBLIC DRAFT
Implicit Objects 2-24

•a mechanism to obtain the JspWriter for output


•a mechanism to manage session usage by the page
•a mechanism to expose page directive attributes to the scripting environment
•mechanisms to forward or include the current request to other active compo-
nents in the application
•a mechanism to handle errorpage exception processing

Methods Intended for Container Generated Code

Some methods are intended to be used by the code generated by the container, not
by code written by JSP page authors, or JSP tag library authors.
The methods supporting lifecycle are initialize() and release()
The following methods enable the management of nested JspWriter streams to
implement Tag Extensions: pushBody() and popBody() To facilitate Simple Tag
Extensions, the pushPageScope(), popPageScope() and peekPageScope() meth-
ods are added.
Methods Intended for JSP authors
Some methods provide uniform access to the diverse objects representing
scopes. The implementation must use the underlying Servlet machinery corre-
sponding to that scope, so information can be passed back and forth between
Servlets and JSP pages. The methods are: setAttribute(), getAttribute(), find-
Attribute(), removeAttribute(), getAttributesScope() and getAttributeNamesIn-
Scope() .

The following methods provide convenient access to implicit objects: getOut(),


getException(), getPage() getRequest(), getResponse(), getSession(), getServlet-
Config() and getServletContext().

The following methods provide support for forwarding, inclusion and error
handling: forward(), include(), and handlePageException().

JSP.11.2.2.1 Fields
public static final java.lang.String APPLICATION
Name used to store ServletContext in PageContext name table.
public static final int APPLICATION_SCOPE
Application scope: named reference remains available in the ServletContext
until it is reclaimed.
public static final java.lang.String CONFIG
Name used to store ServletConfig in PageContext name table.
public static final java.lang.String EXCEPTION

PUBLIC DRAFT
2-25 CORE API

Name used to store uncaught exception in ServletRequest attribute list and


PageContext name table.
public static final java.lang.String OUT
Name used to store current JspWriter in PageContext name table.
public static final java.lang.String PAGE
Name used to store the Servlet in this PageContext’s nametables.
public static final int PAGE_SCOPE
Page scope: (this is the default) the named reference remains available in this
PageContext until the return from the current Servlet.service() invocation.
public static final java.lang.String PAGECONTEXT
Name used to store this PageContext in it’s own name table.
public static final java.lang.String REQUEST
Name used to store ServletRequest in PageContext name table.
public static final int REQUEST_SCOPE
Request scope: the named reference remains available from the Servlet-
Request associated with the Servlet until the current request is completed.
public static final java.lang.String RESPONSE
Name used to store ServletResponse in PageContext name table.
public static final java.lang.String SESSION
Name used to store HttpSession in PageContext name table.
public static final int SESSION_SCOPE
Session scope (only valid if this page participates in a session): the named
reference remains available from the HttpSession (if any) associated with the
Servlet until the HttpSession is invalidated.

JSP.11.2.2.2 Constructors
public PageContext()

JSP.11.2.2.3 Methods
public abstract void forward(java.lang.String relativeUrlPath)
This method is used to re-direct, or “forward” the current ServletRequest and
ServletResponse to another active component in the application.
If the relativeUrlPath begins with a “/” then the URL specified is calculated
relative to the DOCROOT of the ServletContext for this JSP. If the path does

PUBLIC DRAFT
Implicit Objects 2-26

not begin with a “/” then the URL specified is calculated relative to the URL
of the request that was mapped to the calling JSP.
It is only valid to call this method from a Thread executing within a _jsp-
Service(...) method of a JSP.
Once this method has been called successfully, it is illegal for the calling
Thread to attempt to modify the ServletResponse object. Any such attempt
to do so, shall result in undefined behavior. Typically, callers immediately
return from _jspService(...) after calling this method.
Parameters:
relativeUrlPath - specifies the relative URL path to the target resource as
described above
Throws:
ServletException, IOException
IllegalArgumentException - if target resource URL is unresolvable
IllegalStateException - if ServletResponse is not in a state where a forward
can be performed
SecurityException - if target resource cannot be accessed by caller
public abstract java.lang.Exception getException()
The current value of the exception object (an Exception).
Returns: any exception passed to this as an errorpage
public abstract java.lang.Object getPage()
The current value of the page object (a Servlet).
Returns: the Page implementation class instance (Servlet) associated with
this PageContext
public abstract javax.servlet.ServletRequest getRequest()
The current value of the request object (a ServletRequest).
Returns: The ServletRequest for this PageContext
public abstract javax.servlet.ServletResponse getResponse()
The current value of the response object (a ServletResponse).
Returns: the ServletResponse for this PageContext
public abstract javax.servlet.ServletConfig getServletConfig()
The ServletConfig instance.
Returns: the ServletConfig for this PageContext
public abstract javax.servlet.ServletContext getServletContext()

PUBLIC DRAFT
2-27 CORE API

The ServletContext instance.


Returns: the ServletContext for this PageContext
public abstract javax.servlet.http.HttpSession getSession()
The current value of the session object (an HttpSession).
Returns: the HttpSession for this PageContext or null
public abstract void handlePageException(java.lang.Exception e)
This method is intended to process an unhandled “page” level exception by
redirecting the exception to either the specified error page for this JSP, or if
none was specified, to perform some implementation dependent action.
A JSP implementation class shall typically clean up any local state prior to
invoking this and will return immediately thereafter. It is illegal to generate
any output to the client, or to modify any ServletResponse state after invok-
ing this call.
This method is kept for backwards compatiblity reasons. Newly generated
code should use PageContext.handlePageException(Throwable).
Parameters:
e - the exception 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.Throwable t)
public abstract void handlePageException(java.lang.Throwable t)
This method is identical to the handlePageException(Exception), except that
it accepts a Throwable. This is the preferred method to use as it allows proper
implementation of the errorpage semantics.
This method is intended to process an unhandled “page” level exception by
redirecting the exception to either the specified error page for this JSP, or if
none was specified, to perform some implementation dependent action.
A JSP implementation class shall typically clean up any local state prior to
invoking this and will return immediately thereafter. It is illegal to generate
any output to the client, or to modify any ServletResponse state after invok-
ing this call.
Parameters:
t - the throwable to be handled

PUBLIC DRAFT
Implicit Objects 2-28

Throws:
ServletException, IOException
NullPointerException - if the exception is null
SecurityException - if target resource cannot be accessed by caller
See Also: public abstract void handlePageException(java.lang.Exception
e)
public abstract void include(java.lang.String relativeUrlPath)
Causes the resource specified to be processed as part of the current Servlet-
Request and ServletResponse being processed by the calling Thread. The
output of the target resources processing of the request is written directly to
the ServletResponse output stream.
The current JspWriter “out” for this JSP is flushed as a side-effect of this call,
prior to processing the include.
If the relativeUrlPath begins with a “/” then the URL specified is calculated
relative to the DOCROOT of the ServletContext for this JSP. If the path does
not begin with a “/” then the URL specified is calculated relative to the URL
of the request that was mapped to the calling JSP.
It is only valid to call this method from a Thread executing within a _jsp-
Service(...) method of a JSP.
Parameters:
relativeUrlPath - specifies the relative URL path to the target resource to be
included
Throws:
ServletException, IOException
IllegalArgumentException - if the target resource URL is unresolvable
SecurityException - if target resource cannot be accessed by caller
public abstract void initialize(javax.servlet.Servlet servlet,
javax.servlet.ServletRequest request,
javax.servlet.ServletResponse response, java.lang.String errorPageURL,
boolean needsSession, int bufferSize, boolean autoFlush)
The initialize method is called to initialize an uninitialized PageContext so
that it may be used by a JSP Implementation class to service an incoming
request and response within it’s _jspService() method.
This method is typically called from JspFactory.getPageContext() in order to
initialize state.
This method is required to create an initial JspWriter, and associate the “out”
name in page scope with this newly created object.

PUBLIC DRAFT
2-29 CORE API

This method should not be used by page or tag library authors.


Parameters:
servlet - The Servlet that is associated with this PageContext
request - The currently pending request for this Servlet
response - The currently pending response for this Servlet
errorPageURL - The value of the errorpage attribute from the page directive
or null
needsSession - The value of the session attribute from the page directive
bufferSize - The value of the buffer attribute from the page directive
autoFlush - The value of the autoflush attribute from the page directive
Throws:
IOException - during creation of JspWriter
IllegalStateException - if out not correctly initialized
IllegalArgumentException
public JspWriter popBody()
Return the previous JspWriter “out” saved by the matching pushBody(), and
update the value of the “out” attribute in the page scope attribute namespace
of the PageConxtext
Returns: the saved JspWriter.
public BodyContent pushBody()
Return a new BodyContent object, save the current “out” JspWriter, and
update the value of the “out” attribute in the page scope attribute namespace
of the PageContext
Returns: the new BodyContent
public abstract void release()
This method shall “reset” the internal state of a PageContext, releasing all
internal references, and preparing the PageContext for potential reuse by a
later invocation of initialize(). This method is typically called from Jsp-
Factory.releasePageContext().
Subclasses shall envelope this method.
This method should not be used by page or tag library authors.

PUBLIC DRAFT
Implicit Objects 2-30

JSP.11.2.3 JspWriter

Syntax
public abstract class JspWriter extends java.io.Writer

Direct Known Subclasses: BodyContent

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.

This abstract class emulates some of the functionality found in the


java.io.BufferedWriter and java.io.PrintWriter classes, however it differs in that it
throws java.io.IOException from the print methods while PrintWriter does not.
Buffering
The initial JspWriter object is associated with the PrintWriter object of the
ServletResponse in a way that depends on whether the page is or is not buffered.
If the page is not buffered, output written to this JspWriter object will be written
through to the PrintWriter directly, which will be created if necessary by invoking
the getWriter() method on the response object. But if the page is buffered, the
PrintWriter object will not be created until the buffer is flushed and operations
like setContentType() are legal. Since this flexibility simplifies programming sub-
stantially, buffering is the default for JSP pages.
Buffering raises the issue of what to do when the buffer is exceeded. Two
approaches can be taken:
•Exceeding the buffer is not a fatal error; when the buffer is exceeded, just
flush the output.
•Exceeding the buffer is a fatal error; when the buffer is exceeded, raise an
exception.

Both approaches are valid, and thus both are supported in the JSP technology. The
behavior of a page is controlled by the autoFlush attribute, which defaults to true.
In general, JSP pages that need to be sure that correct and complete data has been
sent to their client may want to set autoFlush to false, with a typical case being
that where the client is an application itself. On the other hand, JSP pages that
send data that is meaningful even when partially constructed may want to set
autoFlush to true; such as when the data is sent for immediate display through a
browser. Each application will need to consider their specific needs.

PUBLIC DRAFT
2-31 CORE API

An alternative considered was to make the buffer size unbounded; but, this had
the disadvantage that runaway computations would consume an unbounded
amount of resources.
The “out” implicit variable of a JSP implementation class is of this type. If the
page directive selects autoflush=“true” then all the I/O operations on this class
shall automatically flush the contents of the buffer if an overflow condition would
result if the current operation were performed without a flush. If autof-
lush=“false” then all the I/O operations on this class shall throw an IOException
if performing the current operation would result in a buffer overflow condition.

See Also: java.io.Writer, java.io.BufferedWriter, java.io.PrintWriter

JSP.11.2.3.1 Fields
protected boolean autoFlush
protected int bufferSize
public static final int DEFAULT_BUFFER
constant indicating that the Writer is buffered and is using the implementa-
tion default buffer size
public static final int NO_BUFFER
constant indicating that the Writer is not buffering output
public static final int UNBOUNDED_BUFFER
constant indicating that the Writer is buffered and is unbounded; this is used
in BodyContent

JSP.11.2.3.2 Constructors
protected JspWriter(int bufferSize, boolean autoFlush)
protected constructor.

JSP.11.2.3.3 Methods
public abstract void clear()
Clear the contents of the buffer. If the buffer has been already been flushed
then the clear operation shall throw an IOException to signal the fact that
some data has already been irrevocably written to the client response stream.
Throws:
IOException - If an I/O error occurs
public abstract void clearBuffer()

PUBLIC DRAFT
Implicit Objects 2-32

Clears the current contents of the buffer. Unlike clear(), this method will not
throw an IOException if the buffer has already been flushed. It merely clears
the current content of the buffer and returns.
Throws:
IOException - If an I/O error occurs
public abstract void close()
Close the stream, flushing it first
This method needs not be invoked explicitly for the initial JspWriter as the
code generated by the JSP container will automatically include a call to
close().
Closing a previously-closed stream, unlike flush(), has no effect.
Overrides: java.io.Writer.close() in class java.io.Writer
Throws:
IOException - If an I/O error occurs
public abstract void flush()
Flush the stream. If the stream has saved any characters from the various
write() methods in a buffer, write them immediately to their intended destina-
tion. Then, if that destination is another character or byte stream, flush it.
Thus one flush() invocation will flush all the buffers in a chain of Writers and
OutputStreams.
The method may be invoked indirectly if the buffer size is exceeded.
Once a stream has been closed, further write() or flush() invocations will
cause an IOException to be thrown.
Overrides: java.io.Writer.flush() in class java.io.Writer
Throws:
IOException - If an I/O error occurs
public int getBufferSize()
This method returns the size of the buffer used by the JspWriter.
Returns: the size of the buffer in bytes, or 0 is unbuffered.
public abstract int getRemaining()
This method returns the number of unused bytes in the buffer.
Returns: the number of bytes unused in the buffer
public boolean isAutoFlush()
This method indicates whether the JspWriter is autoFlushing.

PUBLIC DRAFT
2-33 CORE API

Returns: if this JspWriter is auto flushing or throwing IOExceptions on


buffer overflow conditions
public abstract void newLine()
Write a line separator. The line separator string is defined by the system prop-
erty line.separator, and is not necessarily a single newline (’\n’) character.
Throws:
IOException - If an I/O error occurs
public abstract void print(boolean b)
Print a boolean value. The string produced by
java.lang.String.valueOf(boolean) is translated into bytes according to the
platform’s default character encoding, and these bytes are written in exactly
the manner of the java.io.Writer.write(int) method.
Parameters:
b - The boolean to be printed
Throws:
java.io.IOException
public abstract void print(char c)
Print a character. The character is translated into one or more bytes according
to the platform’s default character encoding, and these bytes are written in
exactly the manner of the java.io.Writer.write(int) method.
Parameters:
c - The char to be printed
Throws:
java.io.IOException
public abstract void print(char[] s)
Print an array of characters. The characters are converted into bytes accord-
ing to the platform’s default character encoding, and these bytes are written
in exactly the manner of the java.io.Writer.write(int) method.
Parameters:
s - The array of chars to be printed
Throws:
NullPointerException - If s is null
java.io.IOException
public abstract void print(double d)
Print a double-precision floating-point number. The string produced by
java.lang.String.valueOf(double) is translated into bytes according to the plat-

PUBLIC DRAFT
Implicit Objects 2-34

form’s default character encoding, and these bytes are written in exactly the
manner of the java.io.Writer.write(int) method.
Parameters:
d - The double to be printed
Throws:
java.io.IOException
See Also: java.lang.Double
public abstract void print(float f)
Print a floating-point number. The string produced by
java.lang.String.valueOf(float) is translated into bytes according to the plat-
form’s default character encoding, and these bytes are written in exactly the
manner of the java.io.Writer.write(int) method.
Parameters:
f - The float to be printed
Throws:
java.io.IOException
See Also: java.lang.Float
public abstract void print(int i)
Print an integer. The string produced by java.lang.String.valueOf(int) is trans-
lated into bytes according to the platform’s default character encoding, and
these bytes are written in exactly the manner of the java.io.Writer.write(int)
method.
Parameters:
i - The int to be printed
Throws:
java.io.IOException
See Also: java.lang.Integer
public abstract void print(long l)
Print a long integer. The string produced by java.lang.String.valueOf(long) is
translated into bytes according to the platform’s default character encoding,
and these bytes are written in exactly the manner of the
java.io.Writer.write(int) method.
Parameters:
l - The long to be printed
Throws:
java.io.IOException
See Also: java.lang.Long

PUBLIC DRAFT
2-35 CORE API

public abstract void print(java.lang.Object obj)


Print an object. The string produced by the java.lang.String.valueOf(Object)
method is translated into bytes according to the platform’s default character
encoding, and these bytes are written in exactly the manner of the
java.io.Writer.write(int) method.
Parameters:
obj - The Object to be printed
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 DRAFT
Implicit Objects 2-36

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)
Print a double-precision floating-point number and then terminate the line.
This method behaves as though it invokes public abstract void print(double d)
and then public abstract void println() .
Throws:
java.io.IOException
public abstract void println(float x)
Print a floating-point number and then terminate the line. This method
behaves as though it invokes public abstract void print(float f) and then public
abstract void println() .
Throws:
java.io.IOException
public abstract void println(int x)
Print an integer and then terminate the line. This method behaves as though it
invokes public abstract void print(int i) and then public abstract void println() .
Throws:
java.io.IOException
public abstract void println(long x)
Print a long integer and then terminate the line. This method behaves as
though it invokes public abstract void print(long l) and then public abstract void
println() .
Throws:
java.io.IOException
public abstract void println(java.lang.Object x)
Print an Object and then terminate the line. This method behaves as though it
invokes public abstract void print(java.lang.Object obj) and then public abstract
void println() .
Throws:
java.io.IOException
public abstract void println(java.lang.String x)

PUBLIC DRAFT
2-37 CORE API

Print a String and then terminate the line. This method behaves as though it
invokes public abstract void print(java.lang.String s) and then public abstract
void println() .
Throws:
java.io.IOException

JSP.11.3 An Implementation Example

An instance of an implementation dependent subclass of this abstract base class


can be created by a JSP implementation class at the beginning of it’s _jspService()
method via an implementation default JspFactory .
Here is one example of how to use these classes

PUBLIC DRAFT
Exceptions 2-38

public class foo implements Servlet {


// ...
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
JspFactory factory = JspFactory.getDefaultFactory();
PageContext pageContext = factory.getPageContext(
this,
request,
response,
null, // errorPageURL
false, // needsSession
JspWriter.DEFAULT_BUFFER,
true // autoFlush
);
// initialize implicit variables for scripting env ...
HttpSession session = pageContext.getSession();
JspWriter out = pageContext.getOut();
Object page = this;
try {
// body of translated JSP here ...
} catch (Exception e) {
out.clear();
pageContext.handlePageException(e);
} finally {
out.close();
factory.releasePageContext(pageContext);
}
}

JSP.11.4 Exceptions

The JspException class is the base class for all JSP exceptions. The JspTag-
Exception is used by the tag extension mechanism.

JSP.11.4.1 JspException

Syntax
public class JspException extends java.lang.Exception

Direct Known Subclasses: JspTagException

All Implemented Interfaces: java.io.Serializable

PUBLIC DRAFT
2-39 CORE API

Description
A generic exception known to the JSP engine; uncaught JspExceptions will result
in an invocation of the errorpage machinery.

JSP.11.4.1.1 Constructors
public JspException()
Construct a JspException
public JspException(java.lang.String msg)
Constructs a new JSP exception with the specified message. The message can
be written to the server log and/or displayed for the user.
Parameters:
msg - a String specifying the text of the exception message
public JspException(java.lang.String message, java.lang.Throwable rootCause)
Constructs a new JSP exception when the JSP needs to throw an exception
and include a message about the “root cause” exception that interfered with
its normal operation, including a description message.
Parameters:
message - a String containing the text of the exception message
rootCause - the Throwable exception that interfered with the servlet’s normal
operation, making this servlet exception necessary
public JspException(java.lang.Throwable rootCause)
Constructs a new JSP exception when the JSP needs to throw an exception
and include a message about the “root cause” exception that interfered with
its normal operation. The exception’s message is based on the localized mes-
sage of the underlying exception.
This method calls the getLocalizedMessage method on the Throwable excep-
tion to get a localized exception message. When subclassing JspException,
this method can be overridden to create an exception message designed for a
specific locale.
Parameters:
rootCause - the Throwable exception that interfered with the JSP’s normal
operation, making the JSP exception necessary

JSP.11.4.1.2 Methods
public java.lang.Throwable getRootCause()
Returns the exception that caused this JSP exception.

PUBLIC DRAFT
Exceptions 2-40

Returns: the Throwable that caused this JSP exception

JSP.11.4.2 JspTagException

Syntax
public class JspTagException extends JspException

All Implemented Interfaces: java.io.Serializable

Description
Exception to be used by a Tag Handler to indicate some unrecoverable error. This
error is to be caught by the top level of the JSP page and will result in an error
page.

JSP.11.4.2.1 Constructors
public JspTagException()
No message
public JspTagException(java.lang.String msg)
Constructor with a message.

PUBLIC DRAFT
C H A P T E R JSP.12
Tag Extension API

This chapter describes the details of tag handlers and other tag extension
classes as well as methods that are available to access the Tag Library Descriptor
files. This complements a previous chapter that described the Tag Library Descrip-
tor files formats and their use in taglib directives.
This chapter includes content that is generated automatically from javadoc
embedded into the actual Java classes and interfaces. This allows the creation of a
single, authoritative, specification document.
Custom actions can be used by JSP authors and authoring tools to simplify
writing JSP pages. A custom action can be either an empty or a non-empty action.
An empty tag has no body. There are two equivalent syntaxes, one with
separate start and an end tag, and one where the start and end tags are combined.
The two following examples are identical:
<x:foo att=“myObject” />
<x:foo att=“myObject” ></foo>
A non-empty tag has a start tag, a body, and an end tag. A prototypical example
is of the form:
<x:foo att=“myObject” >
BODY
</x:foo/>
The JavaServer Pages(tm) (JSP) 1.2 specification provides a portable mecha-
nism for the description of tag libraries containing:
•A Tag Library Descriptor (TLD)
•A number of Tag handler classes defining request-time behavior
•A number of classes defining translation-time behavior
•Additional resources used by the classes
This chapter is organized in three sections. The first section presents the basic
tag handler classes. The second section describes the more complex tag handlers
that need to access their body evaluation. The last section looks at translation-time
issues.

2-41
Classic Tag Handlers 2-42

JSP.12.1 Classic Tag Handlers

This section introduces the notion of a tag handler and describes the classic
types of tag handler.
JSP 2.0 introduces a new type of Tag Handler called a Simple Tag Handler,
which is described in a later section in this chapter. The protocol for Simple Tag
handlers is much more straightforward.

Tag Handler
A tag handler is a run-time, container-managed, object that evaluates custom
actions during the execution of a JSP page. A tag handler supports a protocol that
allows the JSP container to provide good integration of the server-side actions
within a JSP page.
A tag handler is created initially using a zero argument constructor on its
corresponding class; the method java.beans.Beans.instantiate() is not used.
A tag handler has some properties that are exposed to the page as attributes on
an action; these properties are managed by the JSP container (via generated code).
The setter methods used to set the properties are discovered using the JavaBeans
introspector machinery.
The protocol supported by a tag handler provides for passing of parameters,
the evaluation and reevaluation of the body of the action, and for getting access to
objects and other tag handlers in the JSP page.
A tag handler instance is responsible for processing one request at a time. It is
the responsability of the JSP container to enforce this.
Additional translation time information associated with the action indicates
the name of any scripting variables it may introduce, their types and their scope.
At specific moments, the JSP container will automatically synchronize the Page-
Context information with variables in the scripting language so they can be made
available directly through the scripting elements.

Properties
A tag handler has some properties. All tag handlers have a pageContext prop-
erty for the JSP page where the tag is located, and a parent property for the tag han-
dler to the closest enclosing action. Specific tag handler classes may have additional
properties.
All attributes of a custom action must be JavaBeans component properties,
although some properties may not be exposed as attributes. The attributes that are
visible to the JSP translator are exactly those listed in the Tag Library Descriptor
(TLD).

PUBLIC DRAFT
2-43 TAG EXTENSION API

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
invoke the appropriate setter methods to initialize these properties. It is the
responsability of user code, be it scriptlets, JavaBeans code, or code inside custom
tags, to not invoke these setter methods, as doing otherwise would interfere with
the container knowledge.
The setter methods that should be used when assigning a value to an attribute
of a custom action are determined by using the JavaBeans introspector on the tag
handler class, then use the setter method associated with the property that has the
same name as the attribute in question. An implication (unclear in the JavaBeans
specification) is that there is only one setter per property.
Unspecified attributes/properties should not be set (using a setter method).
Once properly set, all properties are expected to be persistent, so that if the
JSP container ascertains that a property has already been set on a given tag
handler instance, it needs not set it again. User code can access property
information and access and modify tag handler internal state starting with the first
action method (doStartTag) up until the last action method (doEndTag or
doFinally for tag handlers implementing TryCatchFinally).

Tag Handler as a Container-Managed Object


Since a tag handler is a container managed object, the container needs to main-
tain its references; specifically, user code should not keep references to a tag handler
except between the start of the first action method (doStartTag()) and the end of the
last action method (doEndTag() or doFinally() for those tags that implement Try-
CatchFinally).
The restrictions on references to tag handler objects and on modifying
attribute properties gives the JSP container substantial freedom in effectively
managing tag handler objects to achieve different goals. For example, a container
may implementing different pooling strategies to minimize creation cost, or may
hoist setting of properties to reduce cost when a tag handler is inside another
iterative tag.

Conversions
A tag handler implements an action; the JSP container must follow the type
conversions described in Section 2.13.2 when assigning values to the attributes of an
action.

PUBLIC DRAFT
Classic Tag Handlers 2-44

Empty and Non-Empty Actions


An empty action has no body; it may use one of two syntaxes: either <foo/> or
<foo></foo>. Since empty actions have no body the methods related to body manip-
ulation are not invoked. There is a mechanism in the Tag Library Descriptor to indi-
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.

The Tag Interface


A Tag handler that does not want to process its body can implement just the Tag
interface. A tag handler may not want to process its body because it is an empty tag
or because the body is just to be “passed through”.
The Tag interface includes methods to provide page context information to the
Tag Handler instance, methods to handle the life-cycle of tag handlers, and two
main methods for performing actions on a tag: doStartTag() and doEndTag(). The
method doStartTag() is invoked when encountering the start tag and its return value
indicates whether the body (if there is any) should be skipped, or evaluated and
passed through to the current response stream. The method doEndTag() is invoked
when encountering the end tag; its return value indicates whether the rest of the
page should continue to be evaluated or not.
If an exception is encountered during the evaluation of the body of a tag, its
doEndTag method will not be evaluated. See the TryCatchFinally tag for methods
that are guaranteed to be evaluated.

The IterationTag Interface


The IterationTag interface is used to repeatedly reevaluate the body of a custom
action. The interface has one method: doAfterBody() which is invoked after each
evaluation of the body to determine whether to reevaluate or not.
Reevaluation is requested with the value 2, which in JSP 1.1 is defined to be
BodyTag.EVAL_BODY_TAG. That constant value is still kept in JSP 1.2 (for full
backwards compatibility) but, to improve clarity, a new name is also available:
IterationTag.EVAL_BODY_AGAIN. To stop iterating, the returned value should
be 0, which is Tag.SKIP_BODY.

The TagSupport Base Class


The TagSupport class is a base class that can be used when implementing the
Tag or IterationTag interfaces.

PUBLIC DRAFT
2-45 TAG EXTENSION API

JSP.12.1.1 Tag

Syntax
public interface Tag

All Known Subinterfaces: BodyTag, IterationTag

All Known Implementing Classes: TagAdapter

Description
The interface of a simple tag handler that does not want to manipulate its body.
The Tag interface defines the basic protocol between a Tag handler and JSP page
implementation class. It defines the life cycle and the methods to be invoked at
start and end tag.

Properties
The Tag interface specifies the setter and getter methods for the core pageContext
and parent properties.
The JSP page implementation object invokes setPageContext and setParent, in
that order, before invoking doStartTag() or doEndTag().
Methods
There are two main actions: doStartTag and doEndTag. Once all appropriate
properties have been initialized, the doStartTag and doEndTag methods can be
invoked on the tag handler. Between these invocations, the tag handler is assumed
to hold a state that must be preserved. After the doEndTag invocation, the tag han-
dler is available for further invocations (and it is expected to have retained its
properties).
Lifecycle
Lifecycle details are described by the transition diagram below, with the follow-
ing comments:
•[1] This transition is intended to be for releasing long-term data. no guaran-
tees are assumed on whether any properties have been retained or not.
•[2] This transition happens if and only if the tag ends normally without rais-
ing an exception
•[3] Note that since there are no guarantees on the state of the properties, a
tag handler that had some optional properties set can only be reused if those
properties are set to a new (known) value. This means that tag handlers can
only be reused within the same “AttSet” (set of attributes that have been set).

PUBLIC DRAFT
Classic Tag Handlers 2-46

•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()

PUBLIC DRAFT
2-47 TAG EXTENSION API

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.
If EVAL_BODY_INCLUDE is returned, the body is evaluated and “passed
through” to the current out.

JSP.12.1.1.1 Fields
public static final int EVAL_BODY_INCLUDE
Evaluate body into existing out stream. Valid return value for doStartTag.
public static final int EVAL_PAGE
Continue evaluating the page. Valid return value for doEndTag().
public static final int SKIP_BODY
Skip body evaluation. Valid return value for doStartTag and doAfterBody.
public static final int SKIP_PAGE
Skip the rest of the page. Valid return value for doEndTag.

JSP.12.1.1.2 Methods
public int doEndTag()
Process the end tag for this instance. This method is invoked by the JSP page
implementation object on all Tag handlers.
This method will be called after returning from doStartTag. The body of the
action may or not have been evaluated, depending on the return value of
doStartTag.
If this method returns EVAL_PAGE, the rest of the page continues to be eval-
uated. If this method returns SKIP_PAGE, the rest of the page is not evalu-
ated, the request is completed, and the doEndTag() methods of enclosing tags
are not invoked. If this request was forwarded or included from another page
(or Servlet), only the current page evaluation is stopped.
The JSP container will resynchronize any variable values that are indicated as
so in TagExtraInfo after the invocation of doEndTag().
Throws:
JspException., JspException
public int doStartTag()
Process the start tag for this instance. This method is invoked by the JSP page
implementation object.

PUBLIC DRAFT
Classic Tag Handlers 2-48

The doStartTag method assumes that the properties pageContext and parent
have been set. It also assumes that any properties exposed as attributes have
been set too. When this method is invoked, the body has not yet been evalu-
ated.
This method returns Tag.EVAL_BODY_INCLUDE or Body-
Tag.EVAL_BODY_BUFFERED to indicate that the body of the action
should be evaluated or SKIP_BODY to indicate otherwise.
When a Tag returns EVAL_BODY_INCLUDE the result of evaluating the
body (if any) is included into the current “out” JspWriter as it happens and
then doEndTag() is invoked.
BodyTag.EVAL_BODY_BUFFERED is only valid if the tag handler imple-
ments BodyTag.
The JSP container will resynchronize any variable values that are indicated as
so in TagExtraInfo after the invocation of doStartTag().
Throws:
JspException., JspException
See Also: BodyTag
public Tag getParent()
Get the parent (closest enclosing tag handler) for this tag handler.
The getParent() method can be used to navigate the nested tag handler struc-
ture at runtime for cooperation among custom actions; for example, the find-
AncestorWithClass() method in TagSupport provides a convenient way of
doing this.
The current version of the specification only provides one formal way of indi-
cating the observable type of a tag handler: its tag handler implementation
class, described in the tag-class subelement of the tag element. This is
extended in an informal manner by allowing the tag library author to indicate
in the description subelement an observable type. The type should be a sub-
type of the tag handler implementation class or void. This addititional con-
straint can be exploited by a specialized container that knows about that
specific tag library, as in the case of the JSP standard tag library.
public void release()
Called on a Tag handler to release state. The page compiler guarantees that
JSP page implementation objects will invoke this method on all tag handlers,
but there may be multiple invocations on doStartTag and doEndTag in
between.
public void setPageContext(PageContext pc)

PUBLIC DRAFT
2-49 TAG EXTENSION API

Set the current page context. This method is invoked by the JSP page imple-
mentation object prior to doStartTag().
This value is *not* reset by doEndTag() and must be explicitly reset by a
page implementation if it changes between calls to doStartTag().
Parameters:
pc - The page context for this tag handler.
public void setParent(Tag t)
Set the parent (closest enclosing tag handler) of this tag handler. Invoked by
the JSP page implementation object prior to doStartTag().
This value is *not* reset by doEndTag() and must be explicitly reset by a
page implementation.
Parameters:
t - The parent tag, or null.

JSP.12.1.2 IterationTag

Syntax
public interface IterationTag extends Tag

All Known Subinterfaces: BodyTag

All Superinterfaces: Tag

All Known Implementing Classes: TagSupport

Description
The IterationTag interface extends Tag by defining one additional method that
controls the reevaluation of its body.

A tag handler that implements IterationTag is treated as one that implements Tag
regarding the doStartTag() and doEndTag() methods. IterationTag provides a new
method: doAfterBody().
The doAfterBody() method is invoked after every body evaluation to control
whether the body will be reevaluated or not. If doAfterBody() returns Iteration-
Tag.EVAL_BODY_AGAIN, then the body will be reevaluated. If doAfterBody()
returns Tag.SKIP_BODY, then the body will be skipped and doEndTag() will be
evaluated instead.

PUBLIC DRAFT
Classic Tag Handlers 2-50

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.

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 is not evaluated, and then doEndTag() is
invoked.

PUBLIC DRAFT
2-51 TAG EXTENSION API

If EVAL_BODY_INCLUDE is returned, the body is evaluated and “passed


through” to the current out, then doAfterBody() is invoked and, after zero or more
iterations, doEndTag() is invoked.

JSP.12.1.2.1 Fields
public static final int EVAL_BODY_AGAIN
Request the reevaluation of some body. Returned from doAfterBody. For
compatibility with JSP 1.1, the value is carefully selected to be the same as
the, now deprecated, BodyTag.EVAL_BODY_TAG,

JSP.12.1.2.2 Methods
public int doAfterBody()
Process body (re)evaluation. This method is invoked by the JSP Page imple-
mentation object after every evaluation of the body into the BodyEvaluation
object. The method is not invoked if there is no body evaluation.
If doAfterBody returns EVAL_BODY_AGAIN, a new evaluation of the body
will happen (followed by another invocation of doAfterBody). If doAfter-
Body returns SKIP_BODY no more body evaluations will occur, the value of
out will be restored using the popBody method in pageContext, and then
doEndTag will be invoked.
The method re-invocations may be lead to different actions because there
might have been some changes to shared state, or because of external compu-
tation.
The JSP container will resynchronize any variable values that are indicated as
so in TagExtraInfo after the invocation of doAfterBody().
Returns: whether additional evaluations of the body are desired
Throws:
JspException

JSP.12.1.3 TryCatchFinally

Syntax
public interface TryCatchFinally

Description
The auxiliary interface of a Tag, IterationTag or BodyTag tag handler that wants
additional hooks for managing resources.

PUBLIC DRAFT
Classic Tag Handlers 2-52

This interface provides two new methods: doCatch(Throwable) and doFinally().


The prototypical invocation is as follows:
h = get a Tag(); // get a tag handler, perhaps from pool
h.setPageContext(pc); // initialize as desired
h.setParent(null);
h.setFoo(“foo”);

// tag invocation protocol; see Tag.java


try {
doStartTag()...
....
doEndTag()...
} catch (Throwable t) {
// react to exceptional condition
h.doCatch(t);
} finally {
// restore data invariants and release per-invocation resources
h.doFinally();
}

... other invocations perhaps with some new setters


...
h.release(); // release long-term resources

JSP.12.1.3.1 Methods
public void doCatch(java.lang.Throwable t)
Invoked if a Throwable occurs while evaluating the BODY inside a tag or in
any of the following methods: Tag.doStartTag(), Tag.doEndTag(), Iteration-
Tag.doAfterBody() and BodyTag.doInitBody().
This method is not invoked if the Throwable occurs during one of the setter
methods.
This method may throw an exception (the same or a new one) that will be
propagated further the nest chain. If an exception is thrown, doFinally() will
be invoked.
This method is intended to be used to respond to an exceptional condition.
Parameters:
t - The throwable exception navigating through this tag.
Throws:
Throwable
public void doFinally()
Invoked in all cases after doEndTag() for any class implementing Tag,
IterationTag or BodyTag. This method is invoked even if an exception has

PUBLIC DRAFT
2-53 TAG EXTENSION API

occurred in the BODY of the tag, or in any of the following methods:


Tag.doStartTag(), Tag.doEndTag(), IterationTag.doAfterBody() and Body-
Tag.doInitBody().
This method is not invoked if the Throwable occurs during one of the setter
methods.
This method should not throw an Exception.
This method is intended to maintain per-invocation data integrity and
resource management actions.

JSP.12.1.4 TagSupport

Syntax
public class TagSupport implements IterationTag, java.io.Serializable

Direct Known Subclasses: BodyTagSupport

All Implemented Interfaces: IterationTag, java.io.Serializable, Tag

Description
A base class for defining new tag handlers implementing Tag.

The TagSupport class is a utility class intended to be used as the base class for
new tag handlers. The TagSupport class implements the Tag and IterationTag
interfaces and adds additional convenience methods including getter methods for
the properties in Tag. TagSupport has one static method that is included to facili-
tate coordination among cooperating tags.
Many tag handlers will extend TagSupport and only redefine a few methods.

JSP.12.1.4.1 Fields
protected java.lang.String id
protected PageContext pageContext

JSP.12.1.4.2 Constructors
public TagSupport()
Default constructor, all subclasses are required to define only a public con-
structor with the same signature, and to call the superclass constructor. This
constructor is called by the code generated by the JSP translator.

PUBLIC DRAFT
Classic Tag Handlers 2-54

JSP.12.1.4.3 Methods
public int doAfterBody()
Default processing for a body
Returns: SKIP_BODY
Throws:
JspException
See Also: public int doAfterBody()
public int doEndTag()
Default processing of the end tag returning EVAL_PAGE.
Throws:
JspException
See Also: public int doEndTag()
public int doStartTag()
Default processing of the start tag, returning SKIP_BODY.
Throws:
JspException
See Also: public int doStartTag()
public static final Tag findAncestorWithClass(Tag from, java.lang.Class klass)
Find the instance of a given class type that is closest to a given instance. This
method uses the getParent method from the Tag interface. This method is
used for coordination among cooperating tags.
The current version of the specification only provides one formal way of indi-
cating the observable type of a tag handler: its tag handler implementation
class, described in the tag-class subelement of the tag element. This is
extended in an informal manner by allowing the tag library author to indicate
in the description subelement an observable type. The type should be a sub-
type of the tag handler implementation class or void. This addititional con-
straint can be exploited by a specialized container that knows about that
specific tag library, as in the case of the JSP standard tag library.
When a tag library author provides information on the observable type of a
tag handler, client programmatic code should adhere to that constraint. Spe-
cifically, the Class passed to findAncestorWithClass should be a subtype of
the observable type.
Parameters:
from - The instance from where to start looking.

PUBLIC DRAFT
2-55 TAG EXTENSION API

klass - The subclass of Tag or interface to be matched


public java.lang.String getId()
The value of the id attribute of this tag; or null.
public Tag getParent()
The Tag instance most closely enclosing this tag instance.
See Also: public Tag getParent()
public java.lang.Object getValue(java.lang.String k)
Get a the value associated with a key.
Parameters:
k - The string key.
public java.util.Enumeration getValues()
Enumerate the values kept by this tag handler.
public void release()
Release state.
See Also: public void release()
public void removeValue(java.lang.String k)
Remove a value associated with a key.
Parameters:
k - The string key.
public void setId(java.lang.String id)
Set the id attribute for this tag.
Parameters:
id - The String for the id.
public void setPageContext(PageContext pageContext)
Set the page context.
Parameters:
pageContenxt - The PageContext.
See Also: public void setPageContext(PageContext pc)
public void setParent(Tag t)
Set the nesting tag of this tag.
Parameters:
t - The parent Tag.
See Also: public void setParent(Tag t)

PUBLIC DRAFT
Tag Handlers that want Access to their Body Content 2-56

public void setValue(java.lang.String k, java.lang.Object o)


Associate a value with a String key.
Parameters:
k - The key String.
o - The value to associate.

JSP.12.2 Tag Handlers that want Access to their Body


Content

The evaluation of a body is delivered into a BodyContent object. This is then


made available to tag handlers that implement the BodyTag interface. The BodyTag-
Support class provides a useful base class to simplify writing these handlers.
If a Tag handler wants to have access to the content of its body then it must
implement the BodyTag interface. This interface extends IterationTag, provides
two additional methods setBodyContent(BodyContent) and doInitBody() and refers to
an object of type BodyContent.
A BodyContent is a subclass of JspWriter that has a few additional methods to
convert its contents into a String, insert the contents into another JspWriter, to get
a Reader into its contents, and to clear the contents. Its semantics also assure that
buffer size will never be exceeded.
The JSP page implementation will create a BodyContent if the doStartTag()
method returns a EVAL_BODY_BUFFERED. This object will be passed to
doInitBody(); then the body of the tag will be evaluated, and during that
evaluation out will be bound to the BodyContent just passed to the BodyTag
handler. Then doAfterBody() will be evaluated. If that method returns
SKIP_BODY, no more evaluations of the body will be done; if the method returns
EVAL_BODY_AGAIN, then the body will be evaluated, and doAfterBody() will
be invoked again.
The content of a BodyContent instance remains available until after the
invocation of its associated doEndBody() method.
A common use of the BodyContent is to extract its contents into a String and
then use the String as a value for some operation. Another common use is to take
its contents and push it into the out Stream that was valid when the start tag was
encountered (that is available from the PageContext object passed to the handler
in setPageContext).

PUBLIC DRAFT
2-57 TAG EXTENSION API

JSP.12.2.1 BodyContent

Syntax
public abstract class BodyContent extends JspWriter

Description
An encapsulation of the evaluation of the body of an action so it is available to a
tag handler. BodyContent is a subclass of JspWriter.

Note that the content of BodyContent is the result of evaluation, so it will not con-
tain actions and the like, but the result of their invocation.
BodyContent has methods to convert its contents into a String, to read its con-
tents, and to clear the contents.
The buffer size of a BodyContent object is unbounded. A BodyContent object
cannot be in autoFlush mode. It is not possible to invoke flush on a BodyContent
object, as there is no backing stream.
Instances of BodyContent are created by invoking the pushBody and popBody
methods of the PageContext class. A BodyContent is enclosed within another
JspWriter (maybe another BodyContent object) following the structure of their
associated actions.
A BodyContent is made available to a BodyTag through a setBodyContent() call.
The tag handler can use the object until after the call to doEndTag().

JSP.12.2.1.1 Constructors
protected BodyContent(JspWriter e)
Protected constructor. Unbounded buffer, no autoflushing.

JSP.12.2.1.2 Methods
public void clearBody()
Clear the body without throwing any exceptions.
public void flush()
Redefined flush() so it is not legal.
It is not valid to flush a BodyContent because there is no backing stream
behind it.
Overrides: public abstract void flush() in class JspWriter
Throws:

PUBLIC DRAFT
Tag Handlers that want Access to their Body Content 2-58

IOException
public JspWriter getEnclosingWriter()
Get the enclosing JspWriter.
Returns: the enclosing JspWriter passed at construction time
public abstract java.io.Reader getReader()
Return the value of this BodyContent as a Reader.
Returns: the value of this BodyContent as a Reader
public abstract java.lang.String getString()
Return the value of the BodyContent as a String.
Returns: the value of the BodyContent as a String
public abstract void writeOut(java.io.Writer out)
Write the contents of this BodyContent into a Writer. Subclasses may opti-
mize common invocation patterns.
Parameters:
out - The writer into which to place the contents of this body evaluation
Throws:
IOException

JSP.12.2.2 BodyTag

Syntax
public interface BodyTag extends IterationTag

All Superinterfaces: IterationTag, Tag

All Known Implementing Classes: BodyTagSupport

Description
The BodyTag interface extends IterationTag by defining additional methods that
let a tag handler manipulate the content of evaluating its body.

It is the responsibility of the tag handler to manipulate the body content. For
example the tag handler may take the body content, convert it into a String using
the bodyContent.getString method and then use it. Or the tag handler may take
the body content and write it out into its enclosing JspWriter using the body-
Content.writeOut method.

PUBLIC DRAFT
2-59 TAG EXTENSION API

A tag handler that implements BodyTag is treated as one that implements


IterationTag, except that the doStartTag method can return SKIP_BODY,
EVAL_BODY_INCLUDE or EVAL_BODY_BUFFERED.
If EVAL_BODY_INCLUDE is returned, then evaluation happens as in Iteration-
Tag.
If EVAL_BODY_BUFFERED is returned, then a BodyContent object will be
created (by code generated by the JSP compiler) to capture the body evaluation.
The code generated by the JSP compiler obtains the BodyContent object by call-
ing the pushBody method of the current pageContext, which additionally has the
effect of saving the previous out value. The page compiler returns this object by
calling the popBody method of the PageContext class; the call also restores the
value of out.
The interface provides one new property with a setter method and one new action
method.
Properties
There is a new property: bodyContent, to contain the BodyContent object, where
the JSP Page implementation object will place the evaluation (and reevaluation, if
appropriate) of the body. The setter method (setBodyContent) will only be
invoked if doStartTag() returns EVAL_BODY_BUFFERED.
Methods
In addition to the setter method for the bodyContent property, there is a new
action methods: doInitBody(), which is invoked right after setBodyContent() and
before the body evaluation. This method is only invoked if doStartTag() returns
EVAL_BODY_BUFFERED.
Lifecycle
Lifecycle details are described by the transition diagram below. Exceptions that
are thrown during the computation of doStartTag(), setBodyContent(), doInit-
Body(), BODY, doAfterBody() interrupt the execution sequence and are propa-
gated up the stack, unless the tag handler implements the TryCatchFinally
interface; see that interface for details.

PUBLIC DRAFT
Tag Handlers that want Access to their Body Content 2-60

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, EVAL_BODY_INCLUDE, or EVAL_BODY_BUFFERED.
If SKIP_BODY is returned the body is not evaluated, and doEndTag() is invoked.
If EVAL_BODY_INCLUDE is returned, setBodyContent() is not invoked,
doInitBody() is not invoked, the body is evaluated and “passed through” to the
current out, doAfterBody() is invoked and then, after zero or more iterations,
doEndTag() is invoked.

PUBLIC DRAFT
2-61 TAG EXTENSION API

If EVAL_BODY_BUFFERED is returned, setBodyContent() is invoked, doInit-


Body() is invoked, the body is evaluated, doAfterBody() is invoked, and then,
after zero or more iterations, doEndTag() is invoked.

JSP.12.2.2.1 Fields
public static final int EVAL_BODY_BUFFERED
Request the creation of new buffer, a BodyContent on which to evaluate the
body of this tag. Returned from doStartTag when it implements BodyTag.
This is an illegal return value for doStartTag when the class does not imple-
ment BodyTag.
public static final int EVAL_BODY_TAG
Deprecated. As of Java JSP API 1.2, use
BodyTag.EVAL_BODY_BUFFERED or
IterationTag.EVAL_BODY_AGAIN.
Deprecated constant that has the same value as EVAL_BODY_BUFFERED
and EVAL_BODY_AGAIN. This name has been marked as deprecated to
encourage the use of the two different terms, which are much more descrip-
tive.

JSP.12.2.2.2 Methods
public void doInitBody()
Prepare for evaluation of the body. This method is invoked by the JSP page
implementation object after setBodyContent and before the first time the
body is to be evaluated. This method will not be invoked for empty tags or for
non-empty tags whose doStartTag() method returns SKIP_BODY or
EVAL_BODY_INCLUDE.
The JSP container will resynchronize any variable values that are indicated as
so in TagExtraInfo after the invocation of doInitBody().
Throws:
JspException
public void setBodyContent(BodyContent b)
Set the bodyContent property. This method is invoked by the JSP page imple-
mentation object at most once per action invocation. This method will be
invoked before doInitBody. This method will not be invoked for empty tags
or for non-empty tags whose doStartTag() method returns SKIP_BODY or
EVAL_BODY_INCLUDE.
When setBodyContent is invoked, the value of the implicit object out has
already been changed in the pageContext object. The BodyContent object

PUBLIC DRAFT
Tag Handlers that want Access to their Body Content 2-62

passed will have not data on it but may have been reused (and cleared) from
some previous invocation.
The BodyContent object is available and with the appropriate content until
after the invocation of the doEndTag method, at which case it may be reused.
Parameters:
b - the BodyContent

JSP.12.2.3 BodyTagSupport

Syntax
public class BodyTagSupport extends TagSupport implements BodyTag

All Implemented Interfaces: BodyTag, IterationTag, java.io.Serializable,


Tag

Description
A base class for defining tag handlers implementing BodyTag.

The BodyTagSupport class implements the BodyTag interface and adds addi-
tional convenience methods including getter methods for the bodyContent prop-
erty and methods to get at the previous out JspWriter.
Many tag handlers will extend BodyTagSupport and only redefine a few methods.

JSP.12.2.3.1 Fields
protected BodyContent bodyContent

JSP.12.2.3.2 Constructors
public BodyTagSupport()
Default constructor, all subclasses are required to only define a public con-
structor with the same signature, and to call the superclass constructor. This
constructor is called by the code generated by the JSP translator.

JSP.12.2.3.3 Methods
public int doAfterBody()
After the body evaluation: do not reevaluate and continue with the page. By
default nothing is done with the bodyContent data (if any).
Overrides: public int doAfterBody() in class TagSupport

PUBLIC DRAFT
2-63 TAG EXTENSION API

Returns: SKIP_BODY
Throws:
JspException
public int doEndTag()
Default processing of the end tag returning EVAL_PAGE.
Overrides: public int doEndTag() in class TagSupport
Returns: EVAL_PAGE
Throws:
JspException
public void doInitBody()
Prepare for evaluation of the body just before the first body evaluation: no
action.
Throws:
JspException
public int doStartTag()
Default processing of the start tag returning EVAL_BODY_BUFFERED
Overrides: public int doStartTag() in class TagSupport
Returns: EVAL_BODY_BUFFERED;
Throws:
JspException
public BodyContent getBodyContent()
Get current bodyContent.
Returns: the body content.
public JspWriter getPreviousOut()
Get surrounding out JspWriter.
Returns: the enclosing JspWriter, from the bodyContent.
public void release()
Release state.
Overrides: public void release() in class TagSupport
public void setBodyContent(BodyContent b)
Prepare for evaluation of the body: stash the bodyContent away.
Parameters:
b - the BodyContent

PUBLIC DRAFT
Dynamic Attributes 2-64

JSP.12.3 Dynamic Attributes

Any tag handler can optionally extend the DynamicAttribute interface to indicate
that it supports dynamic attributes. See the JSP Fragments chapter for more details
on how Dynamic Attributes work.

JSP.12.3.1 DynamicAttributes

Syntax
public interface DynamicAttributes

Description
For a tag to declare that it accepts dynamic attributes, it must implement this
interface. The entry for the tag in the Tag Library Descriptor must also be config-
ured to indicate dynamic attributes are accepted.

For any attribute that is not declared in the Tag Library Descriptor for this tag,
instead of getting an error at translation time, the setDynamicAttribute() method is
called, with the name and value of the attribute. It is the responsibility of the tag
to remember the names and values of the dynamic attributes.

JSP.12.3.1.1 Methods
public void setDynamicAttribute(java.lang.String uri, java.lang.String localName,
java.lang.Object value)
Called when a tag declared to accept dynamic attributes is passed an attribute
that is not declared in the Tag Library Descriptor.
Parameters:
uri - the namespace of the attribute, nor null if in the default namespace.
localName - the name of the attribute being set.
value - the value of the attribute
Throws:
AttributeNotSupportedException - if the tag handler wishes to signal that it
does not accept the given attribute.

JSP.12.3.2 AttributeNotSupportedException

Syntax
public class AttributeNotSupportedException extends java.lang.Exception

PUBLIC DRAFT
2-65 TAG EXTENSION API

All Implemented Interfaces: java.io.Serializable

Description
Thrown by a tag handler that wants to indicate that the provided dynamic attribute
is not supported by this tag.

JSP.12.3.2.1 Constructors
public AttributeNotSupportedException()
Creates an AttributeNotSupportedException with no message.
public AttributeNotSupportedException(java.lang.String message)
Creates an AttributeNotSupportedException with the provided message.

JSP.12.4 Annotated Tag Handler Management Example

Below is a somewhat complete example of the way one JSP container could
choose to do some tag handler management. There are many other strategies that
could be followed, with different pay offs.
The example is as below. In this example, we are assuming that x:iterate is an
iterative tag, while x:doit and x:foobar are simple tag. We will also assume that
x:iterate and x:foobar implement the TryCatchFinally interface, while x:doit does
not.
<x:iterate src=“foo”>
<x:doit att1=“one” att2=“<%= 1 + 1 %>” />
<x:foobar />
<x:doit att1=“one” att2=“<%= 2 + 2 %>” />
</x:iterate>
<x:doit att1=“one” att2=“<%= 3 + 3 %>” />
The particular code shown below assumes there is some pool of tag handlers
that are managed (details not described, although pool managing is simpler when
there are no optional attributes), and attemps to reuse tag handlers if possible. The
code also “hoists” setting of properties to reduce the cost when appropriate, e.g.
inside an iteration.

PUBLIC DRAFT
Annotated Tag Handler Management Example 2-66

boolean b1, b2;


IterationTag i; // for x:iterate
Tag d; // for x:doit
Tag d; // for x:foobar
page: // label to end of page...
// initialize iteration tag
i = get tag from pool or new();
i.setPageContext(pc);
i.setParent(null);
i.setSrc(“foo”);
// x:iterate implements TryCatchFinally
try {
if ((b1 = i.doStartTag()) == EVAL_BODY_INCLUDE) {
// initialize doit tag
// code has been moved out of the loop for show
d = get tag from pool or new();
d.setPageContext(pc);
d.setParent(i);
d.setAtt1(“one”);
loop:
while (1) do {
// I'm ignoring newlines...
// two invocations, fused together
// first invocation of x:doit
d.setAtt2(1+1);
if ((b2 = d.doStartTag()) == EVAL_BODY_INCLUDE) {
// nothing
} else if (b2 != SKIP_BODY) {
// Q? protocol error ...
}
if ((b2 = d.doEndTag()) == SKIP_PAGE) {
break page; // be done with it.
} else if (b2 != EVAL_PAGE) {
// Q? protocol error
}
// x:foobar invocation
f = get tag from pool or new();
f.setPageContext(pc);
f.setParent(i);
// x:foobar implements TryCatchFinally
try {

if ((b2 = f.doStartTag()) == EVAL_BODY_INCLUDE) {


// nothing
} else if (b2 != SKIP_BODY) {
// Q? protocol error
}
if ((b2 = f.doEndTag()) == SKIP_PAGE) {
break page; // be done with it.
} else if (b2 != EVAL_PAGE) {
// Q? protocol error
}
} catch (Throwable t) {

PUBLIC DRAFT
2-67 TAG EXTENSION API

f.doCatch(t); // caught, may been rethrown!


} finally {
f.doFinally();
}
// put f back to pool

// second invocation of x:doit


d.setAtt2(2+2);
if ((b2 = d.doStartTag()) == EVAL_BODY_INCLUDE) {
// nothing
} else if (b2 != SKIP_BODY) {
// Q? protocol error
}
if ((b2 = d.doEndTag()) == SKIP_PAGE) {
break page; // be done with it.
} else if (b2 != EVAL_PAGE) {
// Q? protocol error
}
if ((b2 = i.doAfterBody()) == EVAL_BODY_AGAIN) {
break loop;
} else if (b2 != SKIP_BODY) {
// Q? protocol error
}
// loop
}
} else if (b1 != SKIP_BODY) {
// Q? protocol error
}
// tail end of the IteratorTag ...
if ((b1 = i.doEndTag()) == SKIP_PAGE) {
break page; // be done with it.
} else if (b1 != EVAL_PAGE) {
// Q? protocol error
}

// third invocation
// this tag handler could be reused from the previous ones.
d = get tag from pool or new();
d.setPageContext(pc);
d.setParent(null);
d.setAtt1(“one”);
d.setAtt2(3+3);
if ((b1 = d.doStartTag()) == EVAL_BODY_INCLUDE) {
// nothing
} else if (b1 != SKIP_BODY) {
// Q? protocol error
}
if ((b1 = d.doEndTag()) == SKIP_PAGE) {
break page; // be done with it.
} else if (b1 != EVAL_PAGE) {
// Q? protocol error
}
} catch (Throwable t) {

PUBLIC DRAFT
Cooperating Actions 2-68

i.doCatch(t); // caught, may been rethrown!


} finally {
i.doFinally();
}

JSP.12.5 Cooperating Actions

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.

The Runtime Stack


An alternative to explicit communication of information through a named object
is implicit coordination based on syntactic scoping.
For example, in the following JSP fragment the foo action might create a
server-side object; later the nested bar action might access that server-side object.
The object is not named within the pageContext: it is found because the specific
foo element is the closest enclosing instance of a known element type.
<foo>
<bar/>
</foo>
This functionality is supported through the BodyTagSupport.findAncestorWith-
Class(Tag, Class), which uses a reference to parent tag kept by each Tag instance,
which effectively provides a run-time execution stack.

PUBLIC DRAFT
2-69 TAG EXTENSION API

JSP.12.6 Simple Tag Handlers

This section presents the API to implement Simple Tag Handlers and JSP Frag-
ments. Simple Tag Handlers present a much simpler invocation protocol than do
Classic Tag Handlers.
Instead of invoking doStartTag() and doEndTag() and interpreting return values
to have the controller decide when and how many times to invoke the body of a
tag, Simple Tag Handlers encapsulate the tag body as a JSP Fragment, and pass it
in to a single doTag() method. This presents a much simpler invocation protocol
making it easier to design powerful tags.
See the JSP Fragments section for more details.

JSP.12.6.1 SimpleTag

Syntax
public interface SimpleTag

Description
Interface for defining “simple tag handlers.”

Instead of supporting doStartTag() and doEndTag(), the SimpleTag interface pro-


vides a simple doTag() method, which is called once and only once for any given
tag invocation. All tag logic, iteration, body evaluations, etc. are to be performed
in this single method. Thus, simple tag handlers have the equivalent power of
IterationTag, but with a much simpler lifecycle and interface.

To support body content, the setJspBody() and getJspBody() methods are pro-
vided. The container invokes the setJspBody() method with a JspFragment object
encapsulating the body of the tag. The tag handler implementation can call get-
JspBody().invoke() to evaluate the body as many times as it needs.

JSP.12.6.1.1 Methods
public int doTag()
Used for an action declared to have an empty body. The single doTag()
method replaces the doStartTag() and doEndTag() methods inherited from the
Tag interface.
Returns: SKIP_PAGE to abort the processing, or EVAL_PAGE * to
continue.
Throws:

PUBLIC DRAFT
Simple Tag Handlers 2-70

JspException
public java.lang.Object getParent()
Returns the parent of this tag, for collaboration purposes.
public void setJspBody(JspFragment jspBody)
Provides the body of this tag as a JspFragment object, able to be invoked zero
or more times by the tag handler.
This method is invoked by the JSP page implementation object prior to
doTag().
Parameters:
body - The fragment encapsulating the body of this tag.
public void setJspContext(JspContext pc)
Stores the provided page context in the protected jspContext field.
See Also: Tag#setJspContext
public void setParent(java.lang.Object parent)
Sets the parent of this tag, for collaboration purposes.

JSP.12.6.2 JspFragment

Syntax
public interface JspFragment

Description
Encapsulates a portion of JSP code in an object that can be invoked as many times
as needed. JSP Fragments are defined using JSP syntax as the body of a tag or the
body of a <jsp:attribute> standard action, during a tag invocation.

The definition of the JSP fragment must only contain template text and JSP action
elements. It must not contain, for example, scriptlets or scriptlet expressions. At
translation time, the container generates an implementation of the JspFragment
interface capable of executing the defined fragment.
A tag handler can invoke the fragment zero or more times, or pass it along to
other tags, before returning. JSP fragments accept parameters from the invoker,
which are exposed as Expression Language variables to the JSP code that com-
poses the fragment. This allows the tag handler to parameterize the body each
time it is invoked.
Note that tag library developers and page authors should not generate Jsp-
Fragment implementations manually.
PUBLIC DRAFT
2-71 TAG EXTENSION API

Implementation Note: It is not necessary to generate a separate class for each


fragment. One possible implementation is to generate a single helper class for
each page that implements JspFragment. Upon construction, a discriminator can
be passed to select which fragment that instance will execute.

JSP.12.6.2.1 Methods
public void invoke(java.io.Writer out, java.util.Map params)
Executes the fragment and directs all output to the given Writer, or the Jsp-
Writer returned by the getOut() method of the JspContext associated with the
fragment if out is null. The method accepts a parameter map, containing the
body-input parameters passed to the body by its invoker (e.g. a tag handler).
Parameters:
out - The Writer to output the fragment to, or null if output should be sent to
JspContext.getOut().
params - specifies the set of parameters to pass to the fragment. Keys in this
map are parameter names, and the values are parameter values. This allows
the invoker to parameterize a fragment invocation.
Throws:
JspException

JSP.12.6.3 TagAdapter

Syntax
public class TagAdapter implements Tag

All Implemented Interfaces: Tag

Description
Wraps any Object and exposes it using a Tag interface. This is used to allow col-
laboration between classic Tag handlers and SimpleTag handlers.

Because SimpleTag does not extend Tag, and because Tag.setParent() only
accepts a Tag instance, a classic tag handler (one that implements Tag) cannot
have a SimpleTag as its parent. To remedy this, a TagAdapter is created to wrap
the SimpleTag parent, and the adapter is passed to setParent() instead. A classic
Tag Handler can call getAdaptee() to retrieve the encapsulated SimpleTag
instance.

PUBLIC DRAFT
Simple Tag Handlers 2-72

JSP.12.6.3.1 Constructors
public TagAdapter(java.lang.Object adaptee, Tag parentTag)
Creates a new TagAdapter that wraps the given tag and returns the given par-
ent tag when getParent() is called.

JSP.12.6.3.2 Methods
public int doEndTag()
Must not be called.
Throws:
UnsupportedOperationException, JspException
public int doStartTag()
Must not be called.
Throws:
UnsupportedOperationException, JspException
public java.lang.Object getAdaptee()
Gets the tag that is being adapted to the Tag interface. This should be an
instance of SimpleTag in JSP 2.0, but room is left for other kinds of tags in
future spec versions.
public Tag getParent()
Returns the value passed to setParent(). This will either be the enclosing Tag
(if parent implements Tag), or an adapter to the enclosing Tag (if parent does
not implement Tag).
public void release()
Must not be called.
Throws:
UnsupportedOperationException
public void setAdaptee(java.lang.Object adaptee)
Sets the tag that is being adapted to the Tag interface. This should be an
instance of SimpleTag in JSP 2.0, but room is left for other kinds of tags in
future spec versions.
public void setPageContext(PageContext pc)
Must not be called.
Throws:
UnsupportedOperationException
public void setParent(Tag parentTag)

PUBLIC DRAFT
2-73 TAG EXTENSION API

Sets the value to be returned by getParent()


Parameters:
t - The parent tag, or null.

JSP.12.7 Translation-time Classes

The next classes are used at translation time.

Tag mapping, Tag name


A taglib directive introduces a tag library and associates a prefix to it. The TLD
associated with the library associates Tag handler classes (plus other information)
with tag names. This information is used to associate a Tag class, a prefix, and a
name with each custom action element appearing in a JSP page.
At execution time the implementation of a JSP page will use an available Tag
instance with the appropriate property settings and then follow the protocol
described by the interfaces Tag, IterationTag, BodyTag, and TryCatchFinally. The
implementation guarantees that all tag handler instances are initialized and all are
released, but the implementation can assume that previous settings are preserved
by a tag handler, to reduce run-time costs.

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
&quotid“ attribute. In other cases the logic that decides whether an action instance
will define a scripting variable may be quite complex and the name of a TagExtra-
Info class is instead given in the TLD. The getVariableInfo method of this class is
used at translation time to obtain information on each variable that will be created
at request time when this action is executed. The method is passed a TagData
instance that contains the translation-time attribute values.

Validation
The TLD file contains several pieces of information that is used to do syntactic
validation at translation-time. It also contains two extensible validation mecha-

PUBLIC DRAFT
Translation-time Classes 2-74

nisms: a TagLibraryValidator class can be used to validate a complete JSP page, and a
TagExtraInfo class can be used to validate a specific action. In some cases, additional
request-time validation will be done dynamically within the methods in the Tag
instance. If an error is discovered, an instance of JspTagException can be thrown. If
uncaught, this object will invoke the errorpage mechanism of JSP.
The TagLibraryValidator is an addition to the JSP 1.2 specification and is very
open ended, being strictly more powerful than the TagExtraInfo mechanism. A
JSP page is presented via the PageData object, which abstracts the XML view of
the JSP page.
A PageData instance will provides an InputStream (read-only) on the page.
Later specifications may add other views on the page (DOM, SAX, JDOM are all
candidates), for now these views can be generated from the InputStream and
perhaps can be cached for improved performance (recall the view of the page is
just read-only).
A JSP container may optionally support a jsp:id attribute to provide higher
quality validation errors. When supported, the container will track the JSP pages
as passed to the container, and will assign to each element a unique “id”, which is
passed as the value of the jsp:id attribute. Each XML element in the XML view
available will be extended with this attribute. The TagLibraryValidator can then
use the attribute in one or more ValidationMessage objects. The container then, in
turn, can use these values to provide more precise information on the location of
an error.

Validation Details
In detail, validation is done as follows:
First, the JSP page is parsed using the information in the TLD. At this stage
valid mandatory and optional attributes are checked.
Second, for all taglib directives in the page, and in the lexical order in which
they appear, their associated validator class (if any) is invoked. This involves
several substeps.
The first substep is to obtain an initialized validator instance by either:
•construct a new instance and invoke setInitParameters() on it, or
•obtain an existing instance that is not being used, invoke release() on it, and
then invoke setInitParameters() on it, or
•locate an existing instance that is not being used on which the desired set-
InitParameters() has already been invoked
The class name is as indicated in the <validator-class> element, and the Map
passed through setInitParameters() is as described in the <init-params> element. All
TagLibraryValidator classes are supposed to keep their initParameters until new
ones are set, or until release() is invoked on them.

PUBLIC DRAFT
2-75 TAG EXTENSION API

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.12.7.1 TagLibraryInfo

Syntax
public abstract class TagLibraryInfo

Description
Translation-time information associated with a taglib directive, and its underlying
TLD file. Most of the information is directly from the TLD, except for the prefix
and the uri values used in the taglib directive

JSP.12.7.1.1 Fields
protected java.lang.String info
protected java.lang.String jspversion
protected java.lang.String prefix
protected java.lang.String shortname
protected TagInfo[] tags
protected java.lang.String tlibversion
protected java.lang.String uri
protected java.lang.String urn

JSP.12.7.1.2 Constructors
protected TagLibraryInfo(java.lang.String prefix, java.lang.String uri)
Constructor. This will invoke the constructors for TagInfo, and TagAttribute-
Info after parsing the TLD file.
Parameters:
prefix - the prefix actually used by the taglib directive

PUBLIC DRAFT
Translation-time Classes 2-76

uri - the URI actually used by the taglib directive

JSP.12.7.1.3 Methods
public java.lang.String getInfoString()
Information (documentation) for this TLD.
public java.lang.String getPrefixString()
The prefix assigned to this taglib from the <%taglib directive
public java.lang.String getReliableURN()
The “reliable” URN indicated in the TLD. This may be used by authoring
tools as a global identifier (the uri attribute) to use when creating a taglib
directive for this library.
public java.lang.String getRequiredVersion()
A string describing the required version of the JSP container.
public java.lang.String getShortName()
The preferred short name (prefix) as indicated in the TLD. This may be used
by authoring tools as the preferred prefix to use when creating an include
directive for this library.
public TagInfo getTag(java.lang.String shortname)
Get the TagInfo for a given tag name, looking through all the tags in this tag
library.
Parameters:
shortname - The short name (no prefix) of the tag
public TagInfo[] getTags()
An array describing the tags that are defined in this tag library.
public java.lang.String getURI()
The value of the uri attribute from the <%@ taglib directive for this library.

JSP.12.7.2 TagInfo

Syntax
public class TagInfo

Description
Tag information for a tag in a Tag Library; This class is instantiated from the Tag
Library Descriptor file (TLD) and is available only at translation time.
PUBLIC DRAFT
2-77 TAG EXTENSION API

JSP.12.7.2.1 Fields
public static final java.lang.String BODY_CONTENT_EMPTY
static constant for getBodyContent() when it is empty
public static final java.lang.String BODY_CONTENT_JSP
static constant for getBodyContent() when it is JSP
public static final java.lang.String BODY_CONTENT_TAG_DEPENDENT
static constant for getBodyContent() when it is Tag dependent

JSP.12.7.2.2 Constructors
public TagInfo(java.lang.String tagName, java.lang.String tagClassName,
java.lang.String bodycontent, java.lang.String infoString,
TagLibraryInfo taglib, TagExtraInfo tagExtraInfo,
TagAttributeInfo[] attributeInfo)
Constructor for TagInfo from data in the JSP 1.1 format for TLD. This class
is to be instantiated only from the TagLibrary code under request from some
JSP code that is parsing a TLD (Tag Library Descriptor). Note that, since
TagLibibraryInfo reflects both TLD information and taglib directive informa-
tion, a TagInfo instance is dependent on a taglib directive. This is probably a
design error, which may be fixed in the future.
Parameters:
tagName - The name of this tag
tagClassName - The name of the tag handler class
bodycontent - Information on the body content of these tags
infoString - The (optional) string information for this tag
taglib - The instance of the tag library that contains us.
tagExtraInfo - The instance providing extra Tag info. May be null
attributeInfo - An array of AttributeInfo data from descriptor. May be null;
public TagInfo(java.lang.String tagName, java.lang.String tagClassName,
java.lang.String bodycontent, java.lang.String infoString,
TagLibraryInfo taglib, TagExtraInfo tagExtraInfo,
TagAttributeInfo[] attributeInfo, java.lang.String displayName,
java.lang.String smallIcon, java.lang.String largeIcon, TagVariableInfo[] tvi)
Constructor for TagInfo from data in the JSP 1.2 format for TLD. This class
is to be instantiated only from the TagLibrary code under request from some
JSP code that is parsing a TLD (Tag Library Descriptor). Note that, since
TagLibibraryInfo reflects both TLD information and taglib directive informa-

PUBLIC DRAFT
Translation-time Classes 2-78

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;
displayName - A short name to be displayed by tools
smallIcon - Path to a small icon to be displayed by tools
largeIcon - Path to a large icon to be displayed by tools
tagVariableInfo - An array of a TagVariableInfo (or null)

JSP.12.7.2.3 Methods
public TagAttributeInfo[] getAttributes()
Attribute information (in the TLD) on this tag. The return is an array describ-
ing the attributes of this tag, as indicated in the TLD. A null return means no
attributes.
Returns: The array of TagAttributeInfo for this tag.
public java.lang.String getBodyContent()
The bodycontent information for this tag.
Returns: the body content string.
public java.lang.String getDisplayName()
Get the displayName
Returns: A short name to be displayed by tools
public java.lang.String getInfoString()
The information string for the tag.
Returns: the info string
public java.lang.String getLargeIcon()
Get the path to the large icon
Returns: Path to a large icon to be displayed by tools
PUBLIC DRAFT
2-79 TAG EXTENSION API

public java.lang.String getSmallIcon()


Get the path to the small icon
Returns: Path to a small icon to be displayed by tools
public java.lang.String getTagClassName()
Name of the class that provides the handler for this tag.
Returns: The name of the tag handler class.
public TagExtraInfo getTagExtraInfo()
The instance (if any) for extra tag information
Returns: The TagExtraInfo instance, if any.
public TagLibraryInfo getTagLibrary()
The instance of TabLibraryInfo we belong to.
Returns: the tab library instance we belong to.
public java.lang.String getTagName()
The name of the Tag.
Returns: The (short) name of the tag.
public TagVariableInfo[] getTagVariableInfos()
Get TagVariableInfo objects associated with this TagInfo
Returns: A TagVariableInfo object associated with this
public VariableInfo[] getVariableInfo(TagData data)
Information on the scripting objects created by this tag at runtime. This is a
convenience method on the associated TagExtraInfo class.
Default is null if the tag has no “id” attribute, otherwise, {“id”, Object}
Parameters:
data - TagData describing this action.
Returns: Array of VariableInfo elements.
public boolean isValid(TagData data)
Translation-time validation of the attributes. This is a convenience method on
the associated TagExtraInfo class.
Parameters:
data - The translation-time TagData instance.
Returns: Whether the data is valid.
public void setTagExtraInfo(TagExtraInfo tei)

PUBLIC DRAFT
Translation-time Classes 2-80

Set the instance for extra tag information


Parameters:
tei - the TagExtraInfo instance
public void setTagLibrary(TagLibraryInfo tl)
Set the TagLibraryInfo property. Note that a TagLibraryInfo element is
dependent not just on the TLD information but also on the specific taglib
instance used. This means that a fair amount of work needs to be done to con-
struct and initialize TagLib objects. If used carefully, this setter can be used to
avoid having to create new TagInfo elements for each taglib directive.
Parameters:
tl - the TagLibraryInfo to assign
public java.lang.String toString()
Stringify for debug purposes...
Overrides: java.lang.Object.toString() in class java.lang.Object

JSP.12.7.3 TagAttributeInfo

Syntax
public class TagAttributeInfo

Description
Information on the attributes of a Tag, available at translation time. This class is
instantiated from the Tag Library Descriptor file (TLD).

Only the information needed to generate code is included here. Other information
like SCHEMA for validation belongs elsewhere.

JSP.12.7.3.1 Fields
public static final java.lang.String ID
“id” is wired in to be ID. There is no real benefit in having it be something
else IDREFs are not handled any differently.

JSP.12.7.3.2 Constructors
public TagAttributeInfo(java.lang.String name, boolean required,
java.lang.String type, boolean reqTime)

PUBLIC DRAFT
2-81 TAG EXTENSION API

Constructor for TagAttributeInfo. 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).
Parameters:
name - The name of the attribute.
required - If this attribute is required in tag instances.
type - The name of the type of the attribute.
reqTime - Whether this attribute holds a request-time Attribute.

JSP.12.7.3.3 Methods
public boolean canBeRequestTime()
Whether this attribute can hold a request-time value.
Returns: if the attribute can hold a request-time value.
public static TagAttributeInfo getIdAttribute(TagAttributeInfo[] a)
Convenience static method that goes through an array of TagAttributeInfo
objects and looks for “id”.
Parameters:
a - An array of TagAttributeInfo
Returns: The TagAttributeInfo reference with name “id”
public java.lang.String getName()
The name of this attribute.
Returns: the name of the attribute
public java.lang.String getTypeName()
The type (as a String) of this attribute.
Returns: the type of the attribute
public boolean isRequired()
Whether this attribute is required.
Returns: if the attribute is required.
public java.lang.String toString()
Overrides: java.lang.Object.toString() in class java.lang.Object

PUBLIC DRAFT
Translation-time Classes 2-82

JSP.12.7.4 PageData

Syntax
public abstract class PageData

Description
Translation-time information on a JSP page. The information corresponds to the
XML view of the JSP page.

Objects of this type are generated by the JSP translator, e.g. when being pased to
a TagLibraryValidator instance.

JSP.12.7.4.1 Constructors
public PageData()

JSP.12.7.4.2 Methods
public abstract java.io.InputStream getInputStream()
Returns an input stream on the XML view of a JSP page. Recall tht the XML
view of a JSP page has the include directives expanded.
Returns: An input stream on the document.

JSP.12.7.5 TagLibraryValidator

Syntax
public abstract class TagLibraryValidator

Description
Translation-time validator class for a JSP page. A validator operates on the XML
document associated with the JSP page.

The TLD file associates a TagLibraryValidator class and some init arguments
with a tag library.
The JSP container is reponsible for locating an appropriate instance of the appro-
priate subclass by
•new a fresh instance, or reuse an available one
•invoke the setInitParams(Map) method on the instance

PUBLIC DRAFT
2-83 TAG EXTENSION API

once initialized, the validate(String, String, PageData) method will be invoked,


where the first two arguments are the prefix and uri arguments used in the taglib
directive.

A TagLibraryValidator instance may create auxiliary objects internally to perform


the validation (e.g. an XSchema validator) and may reuse it for all the pages in a
given translation run.
The JSP container is not guaranteed to serialize invocations of validate() method,
and TagLibraryValidators should perform any synchronization they may require.
A JSP container may optionally support a jsp:id attribute to provide higher quality
validation errors. When supported, the container will track the JSP pages as
passed to the container, and will assign to each element a unique “id”, which is
passed as the value of the jsp:id attribute. Each XML element in the XML view
available will be extended with this attribute. The TagLibraryValidator can then
use the attribute in one or more ValidationMessage objects. The container then, in
turn, can use these values to provide more precise information on the location of
an error.

JSP.12.7.5.1 Constructors
public TagLibraryValidator()

JSP.12.7.5.2 Methods
public java.util.Map getInitParameters()
Get the init parameters data as an immutable Map. Parameter names are keys,
and parameter values are the values.
Returns: The init parameters as an immutable map.
public void release()
Release any data kept by this instance for validation purposes
public void setInitParameters(java.util.Map map)
Set the init data in the TLD for this validator. Parameter names are keys, and
parameter values are the values.
Parameters:
initMap - A Map describing the init parameters
public ValidationMessage[] validate(java.lang.String prefix, java.lang.String uri,
PageData page)
Validate a JSP page. This will get invoked once per directive in the JSP page.
This method will return null if the page is valid; otherwise the method should

PUBLIC DRAFT
Translation-time Classes 2-84

return an array of ValidationMessage objects. An array of length zero is also


interpreted as no errors.
Parameters:
prefix - the value of the prefix argument in the directive
uri - the value of the uri argument in the directive
thePage - the JspData page object
Returns: A null object, or zero length array if no errors, an array of
ValidationMessages otherwise.

JSP.12.7.6 ValidationMessage

Syntax
public class ValidationMessage

Description
A validation message from a TagLibraryValidator.

A JSP container may (optionally) support a jsp:id attribute to provide higher qual-
ity validation errors. When supported, the container will track the JSP pages as
passed to the container, and will assign to each element a unique “id”, which is
passed as the value of the jsp:id attribute. Each XML element in the XML view
available will be extended with this attribute. The TagLibraryValidator can then
use the attribute in one or more ValidationMessage objects. The container then, in
turn, can use these values to provide more precise information on the location of
an error.

JSP.12.7.6.1 Constructors
public ValidationMessage(java.lang.String id, java.lang.String message)
Create a ValidationMessage. The message String should be non-null. The
value of id may be null, if the message is not specific to any XML element, or
if no jsp:id attributes were passed on. If non-null, the value of id must be the
value of a jsp:id attribute for the PageData passed into the validate() method.
Parameters:
id - Either null, or the value of a jsp:id attribute.
message - A localized validation message.

JSP.12.7.6.2 Methods
public java.lang.String getId()

PUBLIC DRAFT
2-85 TAG EXTENSION API

Get the jsp:id. Null means that there is no information available.


Returns: The jsp:id information.
public java.lang.String getMessage()
Get the localized validation message.
Returns: A validation message

JSP.12.7.7 TagExtraInfo

Syntax
public abstract class TagExtraInfo

Description
Optional class provided by the tag library author to describe additional transla-
tion-time information not described in the TLD. The TagExtraInfo class is men-
tioned in the Tag Library Descriptor file (TLD).

This class can be used:


•to indicate that the tag defines scripting variables
•to perform translation-time validation of the tag attributes.

It is the responsibility of the JSP translator that the initial value to be returned by
calls to getTagInfo() corresponds to a TagInfo object for the tag being translated.
If an explicit call to setTagInfo() is done, then the object passed will be returned
in subsequent calls to getTagInfo().

The only way to affect the value returned by getTagInfo() is through a setTag-
Info() call, and thus, TagExtraInfo.setTagInfo() is to be called by the JSP transla-
tor, with a TagInfo object that corresponds to the tag being translated. The call
should happen before any invocation on isValid() and before any invocation on
getVariableInfo().

JSP.12.7.7.1 Constructors
public TagExtraInfo()

JSP.12.7.7.2 Methods
public final TagInfo getTagInfo()
Get the TagInfo for this class.
Returns: the taginfo instance this instance is extending
public VariableInfo[] getVariableInfo(TagData data)

PUBLIC DRAFT
Translation-time Classes 2-86

information on scripting variables defined by the tag associated with this Tag-
ExtraInfo instance. Request-time attributes are indicated as such in the Tag-
Data parameter.
Parameters:
data - The TagData instance.
Returns: An array of VariableInfo data.
public boolean isValid(TagData data)
Translation-time validation of the attributes. Request-time attributes are indi-
cated as such in the TagData parameter.
Parameters:
data - The TagData instance.
Returns: Whether this tag instance is valid.
public final void setTagInfo(TagInfo tagInfo)
Set the TagInfo for this class.
Parameters:
tagInfo - The TagInfo this instance is extending

JSP.12.7.8 TagData

Syntax
public class TagData implements java.lang.Cloneable

All Implemented Interfaces: java.lang.Cloneable

Description
The (translation-time only) attribute/value information for a tag instance.

TagData is only used as an argument to the isValid and getVariableInfo methods


of TagExtraInfo, which are invoked at translation time.

JSP.12.7.8.1 Fields
public static final java.lang.Object REQUEST_TIME_VALUE
Distinguished value for an attribute to indicate its value is a request-time
expression (which is not yet available because TagData instances are used at
translation-time).

PUBLIC DRAFT
2-87 TAG EXTENSION API

JSP.12.7.8.2 Constructors
public TagData(java.util.Hashtable attrs)
Constructor for a TagData. If you already have the attributes in a hashtable,
use this constructor.
Parameters:
attrs - A hashtable to get the values from.
public TagData(java.lang.Object[][] atts)
Constructor for TagData.
A typical constructor may be
static final Object[][] att = {{“connection”, “conn0”},
{“id”, “query0”}};
static final TagData td = new TagData(att);

All values must be Strings except for those holding the distinguished object
REQUEST_TIME_VALUE.
Parameters:
atts - the static attribute and values. May be null.

JSP.12.7.8.3 Methods
public java.lang.Object getAttribute(java.lang.String attName)
The value of the attribute. Returns the distinguished object
REQUEST_TIME_VALUE if the value is request time. Returns null if the
attribute is not set.
Returns: the attribute’s value object
public java.util.Enumeration getAttributes()
Enumerates the attributes.
Returns: An enumeration of the attributes in a TagData
public java.lang.String getAttributeString(java.lang.String attName)
Get the value for a given attribute.
Returns: the attribute value string
public java.lang.String getId()
The value of the id attribute, if available.
Returns: the value of the id attribute or null
public void setAttribute(java.lang.String attName, java.lang.Object value)
Set the value of an attribute.

PUBLIC DRAFT
Translation-time Classes 2-88

Parameters:
attName - the name of the attribute
value - the value.

JSP.12.7.9 VariableInfo

Syntax
public class VariableInfo

Description
Information on the scripting variables that are created/modified by a tag (at run-
time). This information is provided by TagExtraInfo classes and it is used by the
translation phase of JSP.

Scripting variables generated by a custom action may have scope values of page,
request, session, and application.
The class name (VariableInfo.getClassName) in the returned objects are used to
determine the types of the scripting variables. Because of this, a custom action
cannot create a scripting variable of a primitive type. The workaround is to use
“boxed” types.
The class name may be a Fully Qualified Class Name, or a short class name.
If a Fully Qualified Class Name is provided, it should refer to a class that should
be in the CLASSPATH for the Web Application (see Servlet 2.3 specification -
essentially it is WEB-INF/lib and WEB-INF/classes). Failure to be so will lead to
a translation-time error.
If a short class name is given in the VariableInfo objects, then the class name must
be that of a public class in the context of the import directives of the page where
the custom action appears (will check if there is a JLS verbiage to refer to). The
class must also be in the CLASSPATH for the Web Application (see Servlet 2.3
specification - essentially it is WEB-INF/lib and WEB-INF/classes). Failure to be
so will lead to a translation-time error.
Usage Comments
Frequently a fully qualified class name will refer to a class that is known to the tag
library and thus, delivered in the same JAR file as the tag handlers. In most other
remaining cases it will refer to a class that is in the platform on which the JSP
processor is built (like J2EE). Using fully qualified class names in this manner
makes the usage relatively resistant to configuration errors.

PUBLIC DRAFT
2-89 TAG EXTENSION API

A short name is usually generated by the tag library based on some attributes
passed through from the custom action user (the author), and it is thus less robust:
for instance a missing import directive in the referring JSP page will lead to an
invalid short name class and a translation error.
Synchronization Protocol
The result of the invocation on getVariableInfo is an array of VariableInfo objects.
Each such object describes a scripting variable by providing its name, its type,
whether the variable is new or not, and what its scope is. Scope is best described
through a picture:

The JSP 1.2 specification defines the interpretation of 3 values:


•NESTED, if the scripting variable is available between the start tag and the
end tag of the action that defines it.
•AT_BEGIN, if the scripting variable is available from the start tag of the
action that defines it until the end of the scope.
•AT_END, if the scripting variable is available after the end tag of the action
that defines it until the end of the scope.

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.

Variable Information in the TLD

Scripting variable information can also be encoded directly for most cases into
the Tag Library Descriptor using the <variable> subelement of the <tag> element.
See the JSP specification.
PUBLIC DRAFT
Translation-time Classes 2-90

JSP.12.7.9.1 Fields
public static final int AT_BEGIN
Scope information that scripting variable is visible after start tag
public static final int AT_END
Scope information that scripting variable is visible after end tag
public static final int NESTED
Scope information that scripting variable is visible only within the start/end
tags

JSP.12.7.9.2 Constructors
public VariableInfo(java.lang.String varName, java.lang.String className,
boolean declare, int scope)
Constructor These objects can be created (at translation time) by the Tag-
ExtraInfo instances.
Parameters:
id - The name of the scripting variable
className - The name of the scripting variable
declare - If true, it is a new variable (in some languages this will require a
declaration)
scope - Indication on the lexical scope of the variable

JSP.12.7.9.3 Methods
public java.lang.String getClassName()
public boolean getDeclare()
public int getScope()
public java.lang.String getVarName()

JSP.12.7.10 TagVariableInfo

Syntax
public class TagVariableInfo

PUBLIC DRAFT
2-91 TAG EXTENSION API

Description
Variable information for a tag in a Tag Library; This class is instantiated from the
Tag Library Descriptor file (TLD) and is available only at translation time. This
object should be immutable. This information is only available in JSP 1.2 format

JSP.12.7.10.1 Constructors
public TagVariableInfo(java.lang.String nameGiven,
java.lang.String nameFromAttribute, java.lang.String className,
boolean declare, int scope)
Constructor for TagVariableInfo
Parameters:
nameGiven - value of <name-given>
nameFromAttribute - value of <name-from-attribute>
className - value of <variable-class>
declare - value of <declare>
scope - value of <scope>

JSP.12.7.10.2 Methods
public java.lang.String getClassName()
The body of the <variable-class> element.
Returns: The name of the class of the variable
public boolean getDeclare()
The body of the <declare> element
Returns: Whether the variable is to be declared or not
public java.lang.String getNameFromAttribute()
The body of the <name-from-attribute> element. This is the name of an
attribute whose (translation-time) value will give the name of the variable.
One of <name-given> or <name-from-attribute> is required.
Returns: The attribute whose value defines the variable name
public java.lang.String getNameGiven()
The body of the <name-given> element
Returns: The variable name as a constant
public int getScope()
The body of the <scope> element

PUBLIC DRAFT
Translation-time Classes 2-92

Returns: The scope to give the variable.

PUBLIC DRAFT
2-93 TAG EXTENSION API

PUBLIC DRAFT
C H A P T E R JSP.13
Expression Language API

This chapter describes the javax.servlet.jsp.el package. The 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, specifica-
tion document.
The javax.servlet.jsp.el package contains a number of classes and interfaces
that describe and define programmatic access to the Expression Language
evaluator. This API can also be used by an implementation of JSP to evaluate the
expressions, but other implementations, like open-coding into Java bytecodes, are
allowed.

JSP.13.1 Expression Evaluator

Programmatic access to the EL Expression Evaluator is provided through the


following two classes:
•ExpressionEvaluator, which does the actual evaluation
•VariableResolver, which customizes the way the evaluator resolves variable
references.

JSP.13.1.1 ExpressionEvaluator

Syntax
public interface ExpressionEvaluator

Description
The interface for an expression-language validator and evaluator. Classes that
implement an expression language expose their functionality via this interface.

2-94
2-95 EXPRESSION LANGUAGE API

The validate() and evaluate() methods must be thread-safe. That is, multiple
threads may call these methods on the same ExpressionEvaluator object simulta-
neously. Implementations should synchronize access if they depend on transient
state. Implementations should not, however, assume that only one object of each
ExpressionEvaluator type will be instantiated; global caching should therefore be
static.

JSP.13.1.1.1 Methods
public java.lang.Object evaluate(java.lang.String attributeName,
java.lang.String expression, java.lang.Class expectedType, Tag tag,
PageContext pageContext)
Evaluates the expression at request time.
Throws:
JspException
public java.lang.String validate(java.lang.String attributeName,
java.lang.String expression)
Translation time validation of an expression. This method will return a null
String if the expression is valid; otherwise an error message.

JSP.13.1.2 VariableResolver

Syntax
public interface VariableResolver

Description
This class is used to customize the way the evaluator resolves variable references.
For example, instances of this class can implement their own variable lookup
mechanisms, or introduce the notion of “implicit variables” which override any
other variables. An instance of this class should be passed to the evaluator’s con-
structor.

Whenever the evaluator is invoked, it is passed a “context” Object from the appli-
cation. For example, in a JSP environment, the “context” is a PageContext. That
context object is eventually passed to this class, so that this class has a context in
which to resolve variables.

JSP.13.1.2.1 Methods
public java.lang.Object resolveVariable(java.lang.String pName,
java.lang.Object pContext)

PUBLIC DRAFT
Exceptions 2-96

Resolves the specified variable within the given context. Returns null if the
variable is not found.
Throws:
ELException

JSP.13.2 Exceptions

The ELException exception is used by the expression language.

JSP.13.2.1 ELException

Syntax
public class ELException extends java.lang.Exception

All Implemented Interfaces: java.io.Serializable

Description
Represents any of the exception conditions that arise during the operation evalua-
tion of the evaluator.

JSP.13.2.1.1 Constructors
public ELException()
Constructor
public ELException(java.lang.String pMessage)
Constructor
public ELException(java.lang.String pMessage,
java.lang.Throwable pRootCause)
Constructor
public ELException(java.lang.Throwable pRootCause)
Constructor

JSP.13.2.1.2 Methods
public java.lang.Throwable getRootCause()
Returns the root cause
public java.lang.String toString()

PUBLIC DRAFT
2-97 EXPRESSION LANGUAGE API

String representation
Overrides: java.lang.Throwable.toString() in class java.lang.Throwable

PUBLIC DRAFT
Exceptions 2-98

PUBLIC DRAFT
PART III
T he next Appendices provide details.
Only Appendices X, Y, and C are normative. Appendices U, Z, and W are
non-normative.
The Appendices are

• Packaging JSP pages


• The Rest
• Changes

PUBLIC DRAFT 3-1


A P P E N D I X JSP.A
Packaging JSP Pages

This appendix shows two simple examples of packaging a JSP page into a
WAR for delivery into a Web container. In the first example, the JSP page is deliv-
ered in source form. This is likely to be the most common example. In the second
example the JSP page is compiled into a Servlet that uses only Servlet 2.4 and JSP
2.0 API calls; the Servlet is then packaged into a WAR with a deployment descriptor
such that it looks as the original JSP page to any client.
This appendix is non normative. Actually, strictly speaking, the appendix
relates more to the Servlet 2.4 capabilities than to the JSP 2.0 capabilities. The
appendix is included here as this is a feature that JSP page authors and JSP page
authoring tools are interested in.

JSP.A.1A very simple JSP page

We start with a very simple JSP page HelloWorld.jsp.

<%@ page info="Example JSP pre-compiled" %>


<p>
Hello World
</p>

JSP.A.2The JSP page packaged as source in a WAR file

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:

PUBLIC DRAFT 3-2


3-3 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>

JSP.A.3The Servlet for the compiled JSP page

As an alternative, we will show how one can compile the JSP page into a Servlet
class to run in a JSP container.
The JSP page is compiled into a Servlet with some implementation dependent
name _jsp_HelloWorld_XXX_Impl. The Servlet code only depends on the JSP 2.0
and Servlet 2.4 APIs, as follows:

imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;

class _jsp_HelloWorld_XXX_Impl
extends_PlatformDependent_Jsp_Super_Impl {
public void _jspInit() {
// ...
}

public void jspDestroy() {


// ...
}
static JspFactory_factory= JspFactory.getDefaultFactory();

public void _jspService(HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException

PUBLIC DRAFT
3-4

{
Object page= this;
HttpSessionsession= request.getSession();
ServletConfigconfig= getServletConfig();
ServletContextapplication = config.getServletContext();

PageContextpageContext
= _factory.getPageContext(this,
request,
response,
(String)NULL,
true,
JspWriter.DEFAULT_BUFFER,
true
);

JspWriterout= pageContext.getOut();
// page context creates initial JspWriter "out"

try {
out.println("<p>");
out.println("Hello World");
out.println("</p>");
} catch (Exception e) {
pageContext.handlePageException(e);
} finally {
_factory.releasePageContext(pageContext);
}
}
}

JSP.A.4The Web Application Descriptor

The Servlet is made to look as a JSP page with the following web.xml:

PUBLIC DRAFT
3-5 PACKAGING JSP PAGES

<!DOCTYPE webapp
SYSTEM "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<webapp>
<servlet>
<servlet-name> HelloWorld </servlet-name>
<servlet-class> _jsp_HelloWorld_XXX_Impl.class </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> HelloWorld </servlet-name>
<url-pattern> /HelloWorld.jsp </url-pattern>
</servlet-mapping>

<session-config>
<session-timeout> 1 </session-timeout>
</session-config>
</webapp>

JSP.A.5The WAR for the compiled JSP page

Finally everything is packaged together into a WAR:

/WEB-INF/web.xml

/WEB-INF/classes/_jsp_HelloWorld_XXX_Impl.class

Note that if the Servlet class generated for the JSP page had depended on
some support classes, they would have to be included in the WAR.

PUBLIC DRAFT
A P P E N D I X JSP.B
DTD and Schemas for XML
Syntax

T his appendix includes the DTD and XSchema for JSP pages in XML syntax.
This appendix is non-normative.
As indicated in Section JSP.6.4, a DTD is not a good description to be used
for validating a document that is using namespaces like a JSP page in XML
syntax, but its familiarity with many readers makes it nevertheless useful.

JSP.B.1DTD for JSP documents

The following is a DTD for JSP documents. Since a JSP document is a


namespace-aware document, this DTD is included here just for documentation pur-
poses.

<!-- DTD for JSP 1.2 -->

<!--
This DTD is not conditional on any parameter entities in the
internal subset and does not export any general entities.
-->

<!-- Constrained Names -->

PUBLIC DRAFT 3-6


3-7

<!ENTITY % URI “CDATA”>


<!-- a Uniform Resource Identifier, see [RFC2396] -->

<!ENTITY % UriList “CDATA”>


<!-- a space separated list of Uniform Resource Identifiers -->

<!ENTITY % URL “CDATA”>


<!-- a relative urlSpec is as in Section 2.10.2. -->

<!ENTITY % BeanID “IDREF”>


<!-- a previously declared bean ID in the current scope. -->

<!ENTITY % Prefix “CDATA”>


<!-- a Name that contains no : characters. -->

<!ENTITY % ClassName “CDATA”>


<!-- a fully qualified class name. -->

<!ENTITY % TypeName “CDATA”>


<!-- a fully qualified class or interface name. -->

<!ENTITY % BeanName “CDATA”>


<!-- a bean name as expected by java.beans.Beans instantiate(). -->

<!ENTITY % Content “CDATA”>


<!-- a MIME type followed by an IANA charset, as “ type [; S? [‘charset=’] char-
set] “ -->

<!ENTITY % Length “CDATA”>


<!-- nn for pixels or nn% for percentage length -->

<!ENTITY % Pixels “CDATA”>


<!-- integer representing length in pixels -->

<!ENTITY % Bool “(true|false|yes|no)”>


<!-- boolean -->

<!-- used for object, applet, img, input and iframe -->
<!ENTITY % ImgAlign “(top|middle|bottom|left|right)”>

<!-- Element Groups -->

PUBLIC DRAFT
3-8

<!ENTITY % Directives “jsp:directive.page|jsp:directive.include”>

<!ENTITY % Scripts “jsp:scriptlet|jsp:declaration|jsp:expression”>

<!ENTITY % Actions
“jsp:useBean
|jsp:setProperty
|jsp:getProperty
|jsp:include
|jsp:forward
|jsp:plugin”
>

<!ENTITY % Body “(jsp:text|%Directives;|%Scripts;|%Actions;)*”>

<!-- Elements -->

<!-- Root element of a JSP page.


-->
<!ELEMENT jsp:root %Body;>
<!ATTLIST jsp:root
xmlns:jsp CDATA “http://java.sun.com/JSP/Page”
version CDATA #REQUIRED
>

<!ELEMENT jsp:directive.page EMPTY>


<!--
The contentType default is not relevant for XML views of
JSP pages since it differs depending on the originating
syntax (text/html;ISO-8859-1 for JSP Pages in standard syntax, or
text/xml;UTF-8 for JSP Documents in XML syntax.
-->

<!ATTLIST jsp:directive.page

language CDATA “java”


extends %ClassName; #IMPLIED
contentType %Content; “text/xml; UTF-8”
import CDATA #IMPLIED

PUBLIC DRAFT
3-9

session %Bool; “true”


buffer CDATA “8kb”
autoFlush %Bool; “true”
isThreadSafe %Bool; “true”
info CDATA #IMPLIED
errorPage %URL; #IMPLIED
isErrorPage %Bool; “false”
>

<!-- the jsp:directive.include element only appears in JSP documents and does
not appear in XML views of JSP pages -->

<!ELEMENT jsp:directive.include EMPTY>


<!ATTLIST jsp:directive.include
file %URI; #REQUIRED
>

<!ELEMENT jsp:scriptlet (#PCDATA)>

<!ELEMENT jsp:declaration (#PCDATA)>

<!ELEMENT jsp:expression (#PCDATA)>

<!ELEMENT jsp:useBean %Body;>


<!ATTLIST jsp:useBean
id ID #REQUIRED
class %ClassName; #IMPLIED
type %TypeName; #IMPLIED
beanName %BeanName; #IMPLIED
scope (page
|session
|request
|application) “page”
>

<!ELEMENT jsp:setProperty EMPTY>


<!ATTLIST jsp:setProperty
name %BeanID; #REQUIRED
property CDATA #REQUIRED
value CDATA #IMPLIED
param CDATA #IMPLIED

PUBLIC DRAFT
3-10

>

<!ELEMENT jsp:getProperty EMPTY>


<!ATTLIST jsp:getProperty
name %BeanID; #REQUIRED
property CDATA #REQUIRED
>

<!ELEMENT jsp:include (jsp:param*)>


<!ATTLIST jsp:include
flush %Bool; “false”
page %URL; #REQUIRED
>

<!ELEMENT jsp:forward (jsp:param*)>


<!ATTLIST jsp:forward
page %URL; #REQUIRED
>

<!ELEMENT jsp:plugin (jsp:params?, jsp:fallback?)>


<!ATTLIST jsp:plugin
type (bean|applet) #REQUIRED
code %URI; #IMPLIED
codebase %URI; #IMPLIED
align %ImgAlign; #IMPLIED
archive %UriList; #IMPLIED
height %Length; #IMPLIED
hspace %Pixels; #IMPLIED
jreversion CDATA “1.2”
name NMTOKEN #IMPLIED
vspace %Pixels; #IMPLIED
width %Length; #IMPLIED
nspluginurl %URI; #IMPLIED
iepluginurl %URI; #IMPLIED
>

<!ELEMENT jsp:params (jsp:param+)>

<!ELEMENT jsp:param EMPTY>


<!ATTLIST jsp:param
name CDATA #REQUIRED

PUBLIC DRAFT
3-11

value CDATA #REQUIRED


>

<!ELEMENT jsp:text #PCDATA>

JSP.B.2XSchema Description of JSP documents

The following is a description using XML Schema:


<?xml version ="1.0"?>
<!DOCTYPE schema [
<!-- Patterns -->
<!ENTITY Identifier "(\p{L}|_|$)(\p{N}|\p{L}|_|$)*">
<!ENTITY TypeName "&Identifier;(\.&Identifier;)*">
<!ENTITY WS "\s*">
<!ENTITY Import "&TypeName;(\.\*)?">
<!ENTITY ImportList "&Import;(&WS;,&WS;&Import;)*">
<!ENTITY SetProp "(&Identifier;|\*)">
<!ENTITY RelativeURL "[^:#/\?]*(:{0,0}|[#/\?].*)">
<!ENTITY Length "[0-9]*&#x25;?">
<!ENTITY AsciiName "[A-Za-z0-9_-]*">
<!ENTITY ValidContentType
"&AsciiName;/&AsciiName;(;&WS;(charset=)?&AsciiName;)?">
<!ENTITY ValidPageEncoding "&AsciiName;/&AsciiName;">
<!ENTITY Buffer "[0-9]+kb">
<!ENTITY RTexpr "&#x25;=.*&#x25;">
]>

<!--Conforms to w3c http://www.w3.org/2001/XMLSchema -->

<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.

This schema is based upon the recent (May 5th, 2001)


W3C recommendation for XML Schema.

A JSP translator should reject an XML-format file that is

PUBLIC DRAFT
3-12

not strictly valid according to this schema or does not observe


the constraints documented here. A translator is not required
to use this schema for validation or to use a validating parser.
</xsd:documentation>
</xsd:annotation>

<!-- Complex Types -->

<xsd:complexType name = "Body">


<xsd:annotation>
<xsd:documentation>
Body defines the "top-level" elements in root and beanInfo.
There are probably other elements that should use it.
</xsd:documentation>
</xsd:annotation>
<xsd:group ref = "Bodygroup" minOccurs = "0" maxOccurs = "unbounded"/>
</xsd:complexType>

<xsd:complexType name = "BasicType">


<xsd:simpleContent>
<xsd:extension base = "xsd:string">
<xsd:attribute ref = "jsp:id"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>

<!-- groups -->

<xsd:group name = "Bodygroup">


<xsd:choice>
<xsd:element ref = "directive.page"/>
<xsd:element ref = "directive.include"/>
<xsd:element ref = "scriptlet"/>
<xsd:element ref = "declaration"/>
<xsd:element ref = "expression"/>
<xsd:element ref = "useBean"/>
<xsd:element ref = "setProperty"/>
<xsd:element ref = "getProperty"/>
<xsd:element ref = "include"/>
<xsd:element ref = "forward"/>
<xsd:element ref = "plugin"/>
<xsd:element ref = "text"/>
<xsd:any namespace="##other" processContents = "lax"/>
</xsd:choice>
</xsd:group>

PUBLIC DRAFT
3-13

<!-- jsp:id attribute -->

<xsd:attribute name = "id" type = "xsd:string"/>

<!--
There should be a constraint for jsp:id to be unique within all elements
in the document.
-->

<!-- Simple types are next -->

<xsd:simpleType name = "RTE">


<xsd:annotation>
<xsd:documentation>
A request-time expression value
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&RTexpr;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "Bool">


<xsd:annotation>
<xsd:documentation>
Bool would be boolean except it does not accept 1 and 0.
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:NMTOKEN" >
<xsd:enumeration value = "true"/>
<xsd:enumeration value = "false"/>
<xsd:enumeration value = "yes"/>
<xsd:enumeration value = "no"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "Identifier">


<xsd:annotation>
<xsd:documentation>
Identifier is an unqualified Java identifier.
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&Identifier;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "TypeName">

PUBLIC DRAFT
3-14

<xsd:annotation>
<xsd:documentation>
TypeName is one or more Java identifiers separated by dots
with no whitespace.
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&TypeName;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "ImportList">


<xsd:annotation>
<xsd:documentation>
ImportList is one or more typeNames separated by commas.
Whitespace is allowed before and after the comma.
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&ImportList;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "SetProp">


<xsd:annotation>
<xsd:documentation>
SetProp is an Identifier or *.
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&SetProp;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "RelativeURL">


<xsd:annotation>
<xsd:documentation>
RelativeURL is a uriReference with no colon character
before the first /, ? or #, if any (RFC2396).
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:anyURI">
<xsd:pattern value = "&RelativeURL;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "RTERelativeURL">


<xsd:union memberTypes = "RelativeURL RTE"/>

PUBLIC DRAFT
3-15

</xsd:simpleType>

<xsd:simpleType name = "Length">


<xsd:annotation>
<xsd:documentation>
Length is nn or nn%.
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&Length;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "ExplicitBufferSize">


<xsd:annotation>
<xsd:documentation>
Buffer Size with an explicit value
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&Buffer;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "NoneBufferSize">


<xsd:annotation>
<xsd:documentation>
Buffer Size with a "none" value
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:enumeration value = "none"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "BufferSize">


<xsd:annotation>
<xsd:documentation>
Buffer size is xkb or none.
</xsd:documentation>
</xsd:annotation>
<xsd:union memberTypes = "ExplicitBufferSize NoneBufferSize"/>
</xsd:simpleType>

<xsd:simpleType name = "ContentType">


<xsd:annotation>
<xsd:documentation>

PUBLIC DRAFT
3-16

Contetn Type for this page


</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&ValidContentType;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "PageEncoding">


<xsd:annotation>
<xsd:documentation>
Page Encoding for this page. Default is that of ContentType.
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:string">
<xsd:pattern value = "&ValidPageEncoding;"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "Scope">


<xsd:annotation>
<xsd:documentation>
valid scope values
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:NMTOKEN">
<xsd:enumeration value = "page"/>
<xsd:enumeration value = "session"/>
<xsd:enumeration value = "request"/>
<xsd:enumeration value = "application"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "PlugInType">


<xsd:annotation>
<xsd:documentation>
valid values for a plugin type
</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:NMTOKEN">
<xsd:enumeration value = "bean"/>
<xsd:enumeration value = "applet"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name = "AlignType">


<xsd:annotation>
<xsd:documentation>

PUBLIC DRAFT
3-17

Buffer size is xkb.


</xsd:documentation>
</xsd:annotation>
<xsd:restriction base = "xsd:NMTOKEN">
<xsd:enumeration value = "top"/>
<xsd:enumeration value = "middle"/>
<xsd:enumeration value = "bottom"/>
<xsd:enumeration value = "left"/>
<xsd:enumeration value = "right"/>
</xsd:restriction>
</xsd:simpleType>

<!-- Elements follow -->

<xsd:element name = "root">


<xsd:annotation>
<xsd:documentation>
The root element of all JSP documents is named root.

Authors may, if they wish, include schema location information.


If specified, the information may appear as attributes of
the root element as follows:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/JSP/Page xsd-file-location"

Documents should not specify the system identifier of a DTD


in a DOCTYPE declaration.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base = "Body">
<xsd:attribute name = "version" fixed = "1.2" type = "xsd:string"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>

<xsd:element name = "directive.page">


<xsd:annotation>
<xsd:documentation>
directive.page is the "page directive".
directive.page is the "page directive".
The contentType default is not relevant for XML views of
JSP pages since it differs depending on the originating
syntax (text/html;ISO-8859-1 for JSP Pages in standard syntax, or
text/xml;UTF-8 for JSP Documents in XML syntax.

PUBLIC DRAFT
3-18

</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "language" default = "java" type = "xsd:string"/>
<xsd:attribute name = "extends" type = "TypeName"/>
<xsd:attribute name = "contentType"
default = "text/xml; UTF-8" type = "ContentType"/>
<xsd:attribute name = "pageEncoding"
use = "optional" type = "PageEncoding"/>
<xsd:attribute name = "import" type = "ImportList"/>
<xsd:attribute name = "session" default = "true" type = "Bool"/>
<xsd:attribute name = "buffer" default = "8kb" type = "BufferSize"/>
<xsd:attribute name = "autoFlush" default = "true" type = "Bool"/>
<xsd:attribute name = "isThreadSafe" default = "true" type = "Bool"/>
<xsd:attribute name = "info" type = "xsd:string"/>
<xsd:attribute name = "errorPage" type = "RelativeURL"/>
<xsd:attribute name = "isErrorPage" default = "false" type = "Bool"/>
</xsd:complexType>
</xsd:element>

<xsd:element name = "directive.include">


<xsd:annotation>
<xsd:documentation>
directive.include is the "include directive".
This element does not appear on XML views of JSP pages.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "file" use = "required" type = "RelativeURL"/>
</xsd:complexType>
</xsd:element>

<xsd:element name = "scriptlet" type = "BasicType">


<xsd:annotation>
<xsd:documentation>
The representation of a scriplet.
</xsd:documentation>
</xsd:annotation>
</xsd:element>

<xsd:element name = "declaration" type = "BasicType">


<xsd:annotation>
<xsd:documentation>
The reprsentation of a declaration.
</xsd:documentation>
</xsd:annotation>

PUBLIC DRAFT
3-19

</xsd:element>

<xsd:element name = "expression" type = "BasicType">


<xsd:annotation>
<xsd:documentation>
The representation of an expression.
</xsd:documentation>
</xsd:annotation>
</xsd:element>

<xsd:element name = "text" type = "BasicType">


<xsd:annotation>
<xsd:documentation>
Verbatim template text.
</xsd:documentation>
</xsd:annotation>
</xsd:element>

<xsd:element name = "useBean">


<xsd:annotation>
<xsd:documentation>
useBean instantiates or accesses a bean in the specified scope.

Constraint: The allowed combinations of attributes are:

class [type] | type [( class | beanName)]

</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>

<xsd:element name = "setProperty">


<xsd:annotation>
<xsd:documentation>
setProperty changes the value of an object property.

PUBLIC DRAFT
3-20

Constraint: The object named by the name must have been


"introduced" to the JSP processor using either the
jsp:useBean action or a custom action with an associated
VariableInfo entry for this name.

Exact valid combinations are not expressable in XML Schema.


They are:

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:element name = "getProperty">


<xsd:annotation>
<xsd:documentation>
getProperty obtains the value of an object property.

Constraint: The object named by the name must have been


"introduced" to the JSP processor using either the
jsp:useBean action or a custom action with an associated
VariableInfo entry for this name.

</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:element name = "include">


<xsd:complexType>
<xsd:sequence>
<xsd:element ref = "param" minOccurs = "0" maxOccurs = "unbounded"/>
</xsd:sequence>
<xsd:attribute ref = "jsp:id"/>

PUBLIC DRAFT
3-21

<xsd:attribute name = "flush" default = "false" type = "Bool"/>


<xsd:attribute name = "page" use = "required" type = "RTERelativeURL"/>
</xsd:complexType>
</xsd:element>

<xsd:element name = "forward">


<xsd:complexType>
<xsd:sequence>
<xsd:element ref = "param" minOccurs = "0" maxOccurs = "unbounded"/>
</xsd:sequence>
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "page" use = "required" type = "RTERelativeURL"/>
</xsd:complexType>
</xsd:element>

<xsd:element name = "plugin">


<xsd:complexType> <!-- content only! -->
<xsd:sequence>
<xsd:element ref = "params" minOccurs = "0" maxOccurs = "1"/>
<xsd:element name = "fallback"
minOccurs = "0" maxOccurs = "1" type = "Body"/>
</xsd:sequence>
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "type" use = "required" type = "PlugInType"/>
<xsd:attribute name = "code" type = "xsd:anyURI"/>
<xsd:attribute name = "codebase" type = "xsd:anyURI"/>
<xsd:attribute name = "align" type = "AlignType"/>
<xsd:attribute name = "archive">
<xsd:simpleType>
<xsd:list itemType="xsd:anyURI"/>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name = "height" type = "Length"/>
<xsd:attribute name = "hspace" type = "xsd:int"/>
<xsd:attribute name = "jreversion" default = "1.2" type = "xsd:string"/>
<xsd:attribute name = "name" type = "xsd:NMTOKEN"/>
<xsd:attribute name = "vspace" type = "xsd:int"/>
<xsd:attribute name = "width" type = "Length"/>
<xsd:attribute name = "nspluginurl" type = "xsd:anyURI"/>
<xsd:attribute name = "iepluginurl" type = "xsd:anyURI"/>
</xsd:complexType>
</xsd:element>

<xsd:element name = "params">


<xsd:complexType>
<xsd:sequence>
<xsd:element ref = "param" minOccurs = "1" maxOccurs = "unbounded"/>
</xsd:sequence>

PUBLIC DRAFT
3-22

<xsd:attribute ref = "jsp:id"/>


</xsd:complexType>
</xsd:element>

<xsd:element name = "param">


<xsd:complexType>
<xsd:attribute ref = "jsp:id"/>
<xsd:attribute name = "name" use = "required" type = "xsd:NMTOKEN"/>
<xsd:attribute name = "value" use = "required" type = "xsd:string"/>
</xsd:complexType>
</xsd:element>

</xsd:schema>

PUBLIC DRAFT
A P P E N D I X JSP.C
DTD for TagLibrary
Descriptor, JSP 1.2

This appendix includes the DTD for a tag library descriptor using JSP 1.2.
All JSP 1.2 containers are required to accept such a TLD.
This is the same DTD as "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd",
except for some formatting changes to extract comments and make them more
readable.

JSP.C.1DTD for TagLibrary Descriptor Files


The following is a DTD describing a Tag Library Descriptor file in JSP 1.2 format.

<!--
This is the DTD defining the JavaServer Pages 1.2 Tag Library descriptor (.tld)
(XML) file format/syntax.
A Tag Library is a JAR file containing a valid instance of a Tag Library Descriptor
file, along with the appropriate implementation classes and other resources re-
quired to implement the actions defined therein. When deployed inside a JAR file,
the tag library descriptor files must be in the META-INF directory, or a subdirec-
tory of it. When deployed directly into a web application, the tag library descriptor
files must always be in the WEB-INF directory, or some subdirectory of it.
Packaged tag libraries must have at least one tag library descriptor file. The JSP
1.1 specification allowed for only a single TLD, in META-INF/taglib.tld, but in JSP
1.2 multiple tag libraries are allowed.

PUBLIC DRAFT 3-23


3-24

Use is subject to license terms.


-->

<!NOTATION WEB-JSPTAGLIB.1_2 PUBLIC “-//Sun Microsystems, Inc.//DTD


JSP Tag Library 1.2//EN”>

<!--
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:

tlib-version the version of the tag library implementation

jsp-version the version of JSP the tag library depends upon

short-name a simple default name that could be used by a JSP authoring


tool to create names with a mnemonicvalue; for example, the it
may be used as the preferedprefix value in taglib directives

uri a uri uniquely identifying this taglib

display-name the display-name element contains a short name that is intend-


ed to be displayed by tools

small-icon optional small-icon that can be used by tools

large-icon optional large-icon that can be used by tools

description a simple string describing the “use” of this taglib, should be user
discernable

validator optional TagLibraryValidator information

listener optional event listener specification

-->

<!ELEMENT taglib (tlib-version, jsp-version, short-name, uri?, display-name?,


small-icon?, large-icon?, description?, validator?, listener*, tag+) >

PUBLIC DRAFT
3-25 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2

<!ATTLIST taglib
id ID #IMPLIED
xmlns CDATA #FIXED “http://java.sun.com/JSP/TagLibraryDescriptor”>

<!--
The value of the tlib-version element describes this version (number) of the tagl-
ibrary. This element is mandatory.

#PCDATA ::= [0-9]*{ “.”[0-9] }0..3


-->

<!ELEMENT tlib-version (#PCDATA)

<!--
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).

#PCDATA ::= [0-9]*{ “.”[0-9] }0..3


-->

<!ELEMENT jsp-version (#PCDATA) >

<!--
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.

#PCDATA ::= NMTOKEN


-->

<!ELEMENT short-name (#PCDATA) >

<!--
The value of the uri element is a public URI that uniquely identifies the exact se-
mantics of this taglibrary.
-->

<!ELEMENT uri (#PCDATA) >

PUBLIC DRAFT
3-26

<!--
The value of the description element is an arbitrary text string describing the tag
library.
-->

<!ELEMENT description(#PCDATA) >

<!--
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.
-->

<!ELEMENT validator (validator-class, init-param*, description?) >

<!--
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.
-->

<!ELEMENT validator-class (#PCDATA) >

<!--
The init-param element contains a name/value pair as an
initialization param.
-->

<!ELEMENT init-param (param-name, param-value, description?)>

<!--
The param-name element contains the name of a parameter.
-->

<!ELEMENT param-name (#PCDATA)>

<!--
The param-value element contains the value of a parameter.
-->

<!ELEMENT param-value (#PCDATA)>

PUBLIC DRAFT
3-27 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2

<!--
The listener element defines an optional event listener object to be instantiated
and
registered automatically.
-->

<!ELEMENT listener (listener-class) >

<!--
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.
-->

<!ELEMENT listener-class (#PCDATA) >

<!--
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:

name The unique action name

tag-class The tag handler class implementing javax.servlet.jsp.tagext.Tag

tei-class An optional subclass of javax.servlet.jsp.tagext.TagExtraInfo

body-content The body content type

display-name A short name that is intended to be displayed by tools

small-icon Optional small-icon that can be used by tools

large-icon Optional large-icon that can be used by tools

description Optional tag-specific information

variable Optional scripting variable information

attribute All attributes of this action

example Optional informal description of an example of a use of this ac-


tion.

-->

PUBLIC DRAFT
3-28

<!ELEMENT tag (name, tag-class, tei-class?, body-content?, display-name?,


small-icon?, large-icon?, description?, variable*, attribute*, example?) >

<!--
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.

#PCDATA ::= fully qualified Java class name


-->

<!ELEMENT tag-class (#PCDATA) >

<!--
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.

#PCDATA ::= fully qualified Java class name


-->

<!ELEMENT tei-class (#PCDATA) >

<!--
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.

JSP The body of the tag contains nested JSP syntax

empty The body must be empty

This element is optional; the default value is JSP

#PCDATA ::= tagdependent | JSP | empty


-->

<!ELEMENT body-content (#PCDATA) >

PUBLIC DRAFT
3-29 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2

<!--
The display-name element contains a short name that is intended to be displayed
by tools.
-->

<!ELEMENT display-name (#PCDATA) >

<!--
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.
-->

<!ELEMENT large-icon (#PCDATA) >

<!--
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.
-->

<!ELEMENT small-icon (#PCDATA) >

<!--
The example element provides an informal description of an example of the use
of a tag.
-->

<!ELEMENT example (#PCDATA) >

<!--
The variable element provides information on the scripting variables defined by
this tag.
It is a (translation time) error for an action that has one or more variable subele-
ments to have a TagExtraInfo class that returns a non-null object.
The subelements of variable are of the form:

PUBLIC DRAFT
3-30

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.

variable-class Name of the class of the variable. java.lang.String is default.

declare Whether the variable is declared or not. True is the default.

scope The scope of the scripting variable defined. NESTED is de-


fault.

-->

<!ELEMENT variable ( (name-given | name-from-attribute), variable-class?, de-


clare?, scope?, description?) >

<!--
The name-given element provides the name for the scripting variable.
One of name-given or name-from-attribute is required.
-->

<!ELEMENT name-given (#PCDATA) >

<!--
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.
-->

<!ELEMENT name-from-attribute (#PCDATA) >

<!--
The variable-class element is the name of the class for the scripting variable.
This element is optional; the default is java.lang.String.
-->

<!ELEMENT variable-class (#PCDATA) >

<!--
The value of the declare element indicates whether the scripting variable is to be
defined or not. See TagExtraInfo for details.

PUBLIC DRAFT
3-31 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2

This element is optional and is the default is true.


-->

<!ELEMENT declare (#PCDATA) >

<!--
The value of the scope element describes the scope of the scripting variable.
See TagExtraInfo for details.
This element is optional and the default value is the string “NESTED”. The other
legal values are “AT_BEGIN” and “AT_END”.
-->

<!ELEMENT scope (#PCDATA) >

<!--
The attribute element defines an attribute for the nesting tag.
The attributre element may have several subelements defining:

name the name of the attribute

attribute whether the attribute is required or optional

rtexpravalue whether the attribute is a runtime attribute

type the type of the attributes

description a description of the attribute

-->

<!ELEMENT attribute (name, required? , rtexprvalue?, type?, description?) >

<!--
The name element defines the canonical name of a tag or attribute being defined

#PCDATA ::= NMTOKEN


-->

<!ELEMENT name(#PCDATA) >

<!--
The value of the required element indicates if the nesting attribute is required or
optional. This attribute is optional and its default value is false.

PUBLIC DRAFT
3-32

#PCDATA ::= true | false | yes | no


-->

<!ELEMENT required (#PCDATA) >

<!--
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

#PCDATA ::= true | false | yes | no


-->

<!ELEMENT rtexprvalue (#PCDATA) >

<!--
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.
-->

<!ELEMENT type (#PCDATA) >

<!-- ID attributes -->

<!ATTLIST tlib-version id ID #IMPLIED>


<!ATTLIST jsp-version id ID #IMPLIED>
<!ATTLIST short-name id ID #IMPLIED>
<!ATTLIST uri id ID #IMPLIED>
<!ATTLIST description id ID #IMPLIED>
<!ATTLIST example id ID #IMPLIED>
<!ATTLIST tag id ID #IMPLIED>
<!ATTLIST tag-class id ID #IMPLIED>
<!ATTLIST tei-class id ID #IMPLIED>
<!ATTLIST body-content id ID #IMPLIED>
<!ATTLIST attribute id ID #IMPLIED>
<!ATTLIST name id ID #IMPLIED>
<!ATTLIST required id ID #IMPLIED>
<!ATTLIST rtexprvalue id ID #IMPLIED>
<!ATTLIST param-name id ID #IMPLIED>
<!ATTLIST param-value id ID #IMPLIED>

PUBLIC DRAFT
3-33 DTD FOR TAGLIBRARY DESCRIPTOR, JSP 1.2

<!ATTLIST listener id ID #IMPLIED>


<!ATTLIST listener-class id ID #IMPLIED>

PUBLIC DRAFT
A P P E N D I X JSP.D
DTD for TagLibrary
Descriptor, JSP 1.1

T his appendix includes the DTD for a tag library descriptor using JSP 1.1.
All JSP 1.2 containers are required to accept such a TLD.
This is the same DTD as "http://java.sun.com/dtd/web-jsptaglibrary_1_1.dtd",
except for some formatting changes to extract comments and make them more
readable.

JSP.D.1DTD for TagLibrary Descriptor Files


The following is a DTD describing a Tag Library Descriptor file in JSP 1.1 format.

<!--
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.

Use is subject to license terms.


-->

<!--
The taglib tag is the document root, it defines:

PUBLIC DRAFT 3-34


3-35

tlibversion the version of the tag library implementation


jspversion the version of JSP the tag library depends upon
shortname a simple default short name that could be used by a JSP authoring
tool to create names with a mnemonic value; for example, the it may be used
as the prefered prefix value in taglib directives
uri a uri uniquely identifying this taglib
info a simple string describing the “use” of this taglib, should be user
discernable
-->

<!ELEMENT taglib (tlibversion, jspversion?, shortname, uri?, info?, tag+) >


<!ATTLIST taglib id ID #IMPLIED
xmlns CDATA #FIXED
“http://java.sun.com/dtd/web-jsptaglibrary_1_1.dtd”
>

<!--
Describes this version (number) of the taglibrary (dewey decimal)
#PCDATA ::= [0-9]*{ “.”[0-9] }0..3
-->

<!ELEMENT tlibversion (#PCDATA) >

<!--
Describes the JSP version (number) this taglibrary requires in order to function
(dewey decimal)
The default is 1.1

#PCDATA ::= [0-9]*{ “.”[0-9] }0..3


-->

<!ELEMENT jspversion (#PCDATA) >

<!--
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.

#PCDATA ::= NMTOKEN


-->

PUBLIC DRAFT
3-36

<!ELEMENT shortname (#PCDATA) >

<!--
Defines a public URI that uniquely identifies this version of the taglibrary Leave it
empty if it does not apply.
-->

<!ELEMENT uri (#PCDATA) >

<!--
Defines an arbitrary text string descirbing the tag library
-->

<!ELEMENT info(#PCDATA) >

<!--
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
-->

<!ELEMENT tag (name, tagclass, teiclass?, bodycontent?, info?, attribute*) >

<!--
Defines the subclass of javax.serlvet.jsp.tagext.Tag that implements the request
time semantics for this tag. (required)

#PCDATA ::= fully qualified Java class name


-->

<!ELEMENT tagclass (#PCDATA) >

<!--
Defines the subclass of javax.servlet.jsp.tagext.TagExtraInfo for this tag. (option-
al)
If this is not given, the class is not consulted at translation time.

PUBLIC DRAFT
3-37

#PCDATA ::= fully qualified Java class name


-->

<!ELEMENT teiclass (#PCDATA) >

<!--
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

#PCDATA ::= tagdependent | JSP | empty


-->

<!ELEMENT bodycontent (#PCDATA) >

<!--
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)
-->

<!ELEMENT attribute (name, required? , rtexprvalue?) >

<!--
Defines the canonical name of a tag or attribute being defined

#PCDATA ::= NMTOKEN


-->

<!ELEMENT name(#PCDATA) >

<!--
Defines if the nesting attribute is required or optional.

PUBLIC DRAFT
3-38

#PCDATA ::= true | false | yes | no

If not present then the default is “false”, i.e the attribute is optional.
-->

<!ELEMENT required (#PCDATA) >

<!--
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.

#PCDATA ::= true | false | yes | no

If not present then the default is “false”, i.e the attribute has a static value
-->

<!ELEMENT rtexprvalue (#PCDATA) >

<!ATTLIST tlibversion id ID #IMPLIED>


<!ATTLIST jspversion id ID #IMPLIED>
<!ATTLIST shortname id ID #IMPLIED>
<!ATTLIST uri id ID #IMPLIED>
<!ATTLIST info id ID #IMPLIED>
<!ATTLIST tag id ID #IMPLIED>
<!ATTLIST tagclass id ID #IMPLIED>
<!ATTLIST teiclass id ID #IMPLIED>
<!ATTLIST bodycontent id ID #IMPLIED>
<!ATTLIST attribute id ID #IMPLIED>
<!ATTLIST name id ID #IMPLIED>
<!ATTLIST required id ID #IMPLIED>
<!ATTLIST rtexprvalue id ID #IMPLIED>

PUBLIC DRAFT
A P P E N D I X JSP.E
Changes

This appendix lists the changes in the JavaServer Pages specification. This
appendix is non-normative.

JSP.E.1Changes between JSP 2.0 CD2 and JSP 2.0 PD1

• Moved all the JSP configuration description into its own chapter.
• Reordered the EBNF description to be at the end of JSP 1.3.
• Restored some pieces in the Syntax chapter that were lost in an editing opera-
tion. The only substantive piece was the description of the <include-prelude>
and <include-coda> elements, which are now in the JSP configuration chapter.
• Added details on how to implement functions in EL.

JSP.E.2Changes between JSP 2.0 CD1 and JSP 2.0 CD2

E.2.1 Between CD2c and CD2

• Upgraded major version from JSP 1.3 to JSP 2.0, added section to the Preface
explaining change.
• Added directive examples to JSP Fragments chapter.
• Moved section describing passing attribute values via <jsp:attribute> and
<jsp:body> to syntax chapter and moved definitions of these two standard ac-
tions to Standard Actions chapter, from JSP Fragments chapter.

PUBLIC DRAFT 3-39


3-40

• Added optional scope attribute to <jsp:invoke> and <jsp:doBody>.


• Improved and simplified the way tag files are packaged. One can now package
tag files in JARs or place them in a subdirectory of /WEB-INF/tags/ and ac-
cess them without specifying a uri.
• Changed SimpleTag to not extend Tag. Added TagAdapter to handle tag col-
laboration, and removed dependency on PageContext in SimpleTag. These
changes help make SimpleTag usable in environments other than Servlet re-
quest/response.
• Changed fragment invocation via <jsp:invoke> and <jsp:doBody> to be able
to expose their result as a java.io.Reader object instead of a String. This is ex-
pected to be more efficient.
• Added <include-prelude> and <include-coda> elements to <jsp-properties-
group>. Added a description in the Syntax Chapter.

• Added a getExpressionEvaluator() method to JspContext (and, thus, to Page-


Context).

• Added better description of JSP configuration information to different chap-


ters.
• Added to-do notes on EL to Syntax chapter, sketching where the information
will go.
• Renamed elEvaluation property of page directive. The new name is isELEna-
bled, to be consistent with other properties.

E.2.2 Between CD2b and CD2c

• Fixed syntax table so that flush is optional in <jsp:include> standard action.


• Integrated EL grammar with JSP EBNF.
• Clarified doEndTag() description when SKIP_PAGE is returned.
• Added dynamic-attributes element in tag directive to describe a tag file that
accepts dynamic attributes.
• Added SimpleTag, JSPFragment, DynamicAttributes, AttributeNotSupporte-
dException, ExpressionEvaluator, and VariableResolver classes to API. Add-
ed new API chapter for javax.servlet.jsp.el package.
• Added isScriptingEnabled directive and scripting-enabled JSP configuration el-
ement.
PUBLIC DRAFT
3-41

• Renamed jsp-group JSP configuration element to jsp-properties-group. Clari-


fied conflict resolution rules.
• Clarified direction with EL function - details still to come.
• Added a chapter for EL API.
• Added description of page-encoding JSP configuration element to Localiza-
tion chapter.

E.2.3 Between CD2a and CD2b

• Reordered "Users of JSP Technology" and "Basic Concepts" in the Overview


section.
• Added <jsp-config> element to web.xml as a parent element for <taglib>.
Added <jsp-group> as a new subelement to describe properties for a group of
JSP pages that are described using <url-pattern> and other elements. Current-
ly the only other element is <el-evaluation>, which can be used to describe
whether EL evaluation is active or not by default.
• Modified the default rules for EL evaluation. Now, EL evaluation is always
off, but it is very easy to add evaluation on through a <jsp-group> element.
• Various EBNF fixes
• Fixed some typos in Example Scenario in JSP_Fragments chapter
• Clarified issues on <jsp:forward> from within a tag file?
• Clarified issues on <jsp:attribute> and whitespace

E.2.4 Changes between CD1 and CD2a

• Added a part structure to the specification description. This helps provide


guideance to the readers.
• Added a mechanism to pass attributes whose names are not known until runt-
ime to tag handlers (Dynamic Attributes).
• Added getPageContext() to SimpleTag.
• Adjustment to i18n table to make defaultInputEncoding the default output en-
coding if unspecified.
• Moved EBNF description from Fragments chapter to Core Syntax.

PUBLIC DRAFT
3-42

• Improved EBNF description of <jsp:attribute> and <jsp:body>. Also, easier


to read valid standard action attribute sets.

JSP.E.3Changes between JSP 2.0 ED1 and JSP 2.0 CD1

This is the first Community Draft of the JSP 2.0 specification.

E.3.5 JSP Fragments, .tag Files, and Simple Tag Handlers

• A new chapter on JSP fragments and supporting technologies such as the .tag
mechanism and simple tag handlers:

JSP fragments allow a portion of JSP code to be encapsulated into a Java ob-
ject which can be passed around and evaluated zero or more times.

The .tag mechanism allows page authors to use JSP syntax to write Custom
Actions.

Simple tag handlers integrates tightly with JSP fragments and allows for a
much easier and more natural invocation protocol for tag extensions.

E.3.6 Expression Language Added


• Added the Expression Language chapter, equivalent to that released in the JSP
Standard Tag Library (JSTL) Public Draft, Appendix A.
• Updated the Expression Language chapter, including preliminary information
on the API to invoke the EL evaluator.

E.3.7 EBNF Fixes


Various fixes to the EBNF, to handle CustomAction translation errors correctly.
Improved readability by adding ATTR[] construct, to allow easier expression of
XML-style attributes that can appear in any order.

E.3.8 I18N Clarifications


Incorporated JSP 1.2 errata_a. Clarified when container can call setContent-
Type() and how it is possible to dynamically affect content type and character encod-
ing from within a page or custom action.

PUBLIC DRAFT
3-43

E.3.9 Other Changes


• Updated Status, Preface, Changes chapters.
• Made support for jsp:id mandatory.
• Various typographical fixes.

JSP.E.4Changes Between JSP 1.2 Final Draft and JSP 2.0 ED1

This is the first expert draft of the JSP 2.0 specification.

E.4.10 Typographical Fixes and Version Numbers


Various typographical fixes that do not change any specification requirements,
and version number updates for JSP 2.0. Various things were fixed from JSP 1.2
such as missing page numbers, repeated table numbers, etc.

E.4.11 Added EBNF Grammar for JSP Standard Syntax


A new section was added to the Syntax Chapter that presents a simple EBNF
grammar for the standard (i.e. non-XML) JSP syntax. The grammar is intended to
provide a concise syntax overview and to resolve any syntax ambiguities present in
the specification.

E.4.12 Added Users of JavaServer Pages Section


A new section was added to the Overview Chapter that describes the various
classes of users that make use of JSP technology, describing their role, the technol-
ogy they’re familiar with, and the sections of this specifications that are relevant to
them.

E.4.13 Added Placeholders for Expression Language and Custom Actions


Using JSP
Two new chapters were added in anticipation of the new Expression Language
and Custom Actions Using JSP features.

PUBLIC DRAFT
3-44

E.4.14 Added Requirement for Debugging Support


A new section was added to the JSP Container Chapter requiring support for
JSR-045 ("Debugging Support for Other Languages"). The precompilation protocol
was also updated.

JSP.E.5Changes Between PFD 2 and Final Draft

This is the final version approved by JCP Executive Comittee; the document
was updated to reflect that status. All change bars were reset.

E.5.15 Added jsp:id mechanism


A new mechanism was added to allow willing JSP containers to provide
improved translation-time error information from TagLibraryValidator classes. The
signature of TagLibraryValidator.validate() was modified slightly, and a new Valida-
tionMessage class was added. These objects act through a new attribute, jsp:id,
which is optionally supported by a JSP container and exposed only through the
XML view of a JSP page. Chapter JSP.6 (mostly Section JSP.6.3.13), Chapter JSP.7
(Section JSP.7.5.1.2) and Chapter JSP.12 (Section JSP.12.7.5) were affected.

E.5.16 Other Small Changes


• Made height & width be rtexprs. Section JSP.5.7 was affected.
• Added attribute value conversion from String literal to short and Short, and
corrected conversion for char and Character in Table JSP.1-11.
• Corrected a statement on the allowed return values for doStartTag() for Tag,
IterationTag and BodyTag.. PFD2 incorrectly indicated that "emtpy" tags
could only return SKIP_BODY; the correct statement is that tags whose body-
content is "empty" can only return SKIP_BODY.

E.5.17 Clarification of role of id


The mandated interpretations of the "id" attribute in Section JSP 2.13.3 (that id
represents page-wide unique ids) and the "scope" attribute in Section JSP 2.13.4
(regarding the scope for the introduced variable) were not enforced by most (per-
haps all?) containers, and were inconsistent with prevalent practices in custom tag
library development. Essentially these sections were being interpreted as localized

PUBLIC DRAFT
3-45

statements about the jsp:useBean standard action. This has been made explicit and
the sections were moved to Chapter 5 to reflect that.
Sections JSP.2.13.3 and JSP.2.13.4, and Chapter 4 were affected.

E.5.18 Clarifications on Multiple Requests and Threading


• Clarify that TLV instances need be thread safe. This affected
Section JSP.12.7.5.
• Clarify that a tag handler instance is actively processing only one request at a
time; this happens naturally if the tag handler is instantiated afresh through
new() invocations, but it requires spelling once tag handler pooling is intro-
duced. This clarification affected Section JSP.12.1.

E.5.19 Clarifications on JSP Documents


Several clarifications in Chapter 6.

• 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.

E.5.20 Clarifications on Well Known Tag Libraries


Clarified that a tag library author may indicate, through the description
comment, that a tag handler may expose at runtime only some subset of the
information described through the tag handler implementation class. This is useful
for specialized implementations of well-known tag libraries like the JSP standard
tag library. This clarification affected the description of the tag element in
Section JSP.7.4 and the description of Tag.setParent() and TagSupport.findAnces-
torWithClass().
Removed the last paragraph on Section JSP.7.3.9; we don’t have any plans to
remove the well-know URI mechanism.
In general cleaned up the presentation of the computation of the taglib map
between a URI and a TLD resource path; the previous version was clunky.

PUBLIC DRAFT
3-46

E.5.21 Clarified Impact of Blocks


Clarified further the legal uses and the role of block constructs within scriptlets
and nested actions. This affected small portions of Sections JSP.1.3.3, JSP.9.4,
JSP.9.4.4 and JSP.12.7.9.

E.5.22 Other Small Clarifications


• Reafirmed more explicitly that the location of icons is relative to TLD file.
Section JSP.7.4 was affected.
• Removed non-normative comment about JSR-045 in Section JSP.1.1.8.
• Removed the comment on errorPages needing to be JSP pages, they can also
be static objects. This affects Table JSP.1-8.
• Reaffirmed that event listeners in a tag library are registered before the appli-
cation is started. This affects Section JSP.7.1.2.2.
• Clarify when the use of quoting conventions is required for attribute values.
Clarified that request-time attribute values follow the same rules. This affects
Section JSP.1.3.5, Section JSP.1.6 and Section JSP.1.14.1.
• Clarified the interpretation of relative specifications for include directives and
jsp:include and jsp:forward actions. This affected Section JSP.1.2.1,
Section JSP.1.10.7, Section JSP.5.4 and Section JSP.5.5
• Corrected the inconsistency on the precompilation protocol in
Section JSP.10.4.2 regarding whether the requests are delivered to the page or
not; they are not.
• Clarified that the <type> subelement of <attribute> in the TLD file should
match that of the underlying JavaBean component property.
• Spelled out the use of ClassLoader.getResource() to get at data from a TagLi-
braryValidator class.

JSP.E.6Changes Between 1.2 PFD 1b and PFD 2

Change bars are used in almost all chapters to indicate changes between PFD 1b
and PFD 2. The exception are Chapters 11 and 12 which are generated automati-
cally from the Java sources and have no change bars. Most changes are semantical,
but some of them are editorial.

PUBLIC DRAFT
3-47

E.6.23 Added elements to Tag Library Descriptor


The Tag Library Descriptor (TLD) was extended with descriptive information
that is useful to users of the tag library. In particular, a TLD can now be massaged
directly (e.g. using an XSLT stylesheet) into an end-user document.
A new <example> element was added, as an optional subelement of <tag>.
The existing <description> element was made a valid optional subelement of
<variable>, <attribute> and <validator>.
Section JSP.7.4 and Appendix JSP.C were affected. The TLD 1.2 DTD and
Schemas were also affected.

E.6.24 Changed the way version information is encoded into TLD


The mechanism used to provide version information on the TLD was changed.
In the PFD the version was encoded into the namespace. In PFD2 the namespace is
not intended to change unless there are non-compatible changes, and the version is
encoded into the <jsp-version> element, which is now mandatory. The new URI for
the namespace is "http://java.sun.com/JSP/TagLibraryDescriptor".
Chapter JSP.7 and Appendix JSP.C were affected.

E.6.25 Assigning String literals to Object attributes


It is now possible to assign string literals to an attribute that is defined as having
type Object, as well as to a property of type Object. The valid type conversions are
now all described in Section JSP.1.14.2, and used by reference in the semantics of
<jsp:setProperty>.

E.6.26 Clarification on valid names for prefix, action and attributes


We clarified the valid names for prefixes used in taglib directives, element
names used in actions, and attribute names.

E.6.27 Clarification of details of empty actions


The JSP 1.1 specification distinguishes empty from non-empty actions,
although the description could be better. Unfortunately, the JSP 1.2 PFD1 draft did
not improve the description. This draft improves the description by making it clear
what methods are invoked when.
Chapters 1, 7 and 12 were affected.

PUBLIC DRAFT
3-48

E.6.28 Corrections related to XML syntax


We clarified several issues related to the XML syntax for JSP pages and to the
XML view of a JSP page. Most changes are in Chapter 6.

• Removed an inexistant flush attribute in the include directive at


Section JSP.6.2.4().
• Changed the name of jsp:cdata to jsp:text, since its semantics are very similar
to the text element in XSLT.
• Changed the way the version information is encoded into the XML syntax;
the URI used now is not version-specific and instead there is a required ver-
sion attribute of jsp:root.
• Clarified that JSP comments in a JSP page in JSP syntax are not preserved on
the XML view of the page.
• Clarified that JSP pages in XML syntax should have no DOCTYPE.
• Clarified the treatment of include directives in the XML view of a JSP page.
• Clarified the format of the URIs to use in xmlns attributes for taglib directives,
and corrected Appendix JSP.B.

E.6.29 Other changes


We clarified several other inconsistencies or mistakes

• Explicitly indicated which attributes are reserved (Section JSP.1.3.5) and


which prefixes are reserved (Section JSP.1.10.4).

• Add a comment to the DTD for the TLD indicating that a DOCTYPE is needed
and what its value is. No changes to the value.
• Removed the paragraph at the end of Section JSP.7.3.9 that used to contain
non-normative comments on the future of "well kwown URIs".
• Corrected the description of the valid values that can be passed to the flush at-
tribute of the include action in Section JSP.5.4.
• Clarified that <jsp:param> can only appear within <jsp:forward>, <jsp:in-
clude>, and <jsp:params>.
• Clarified that <jsp:params> and <jsp:fallback> can only appear within
<jsp:plugin>.

PUBLIC DRAFT
3-49

• Resolved a conflict in Section JSP.5.4 between the Servlet and the JSP specifi-
cation regarding how to treat modifications to headers in included actions.
• Section 10.1.1 in PFD1 incorrectly described the valid return values for
doStartTag() in tag handlers that implement the BodyTag interface. The cor-
rect valid values are SKIP_BODY, EVAL_BODY_INCLUDE and
EVAL_BODY_BUFFER. Section now indicates this.

JSP.E.7Changes Between 1.2 PFD and 1.2 PFD 1b

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.

JSP.E.8Changes Between 1.2 PD1 and 1.2 PFD

The following changes ocurred between the Public Draft 1 and the Proposed
Final Draft versions of the JSP 1.2 specification.

E.8.30 Deletions

• Removed the resetCustomAttributes() method.

E.8.31 Additions

• Added constructors and methods to JspException to support a rootCause (par-


alleling the ServletException).
• Added a PageContext.handleException(Throwable) method.
• Added references to JSR-045 regarding debugging support.
• Added new TryCatchFinally interface to provide better control over excep-
tions in tag handlers.
• Added an implicit URI to TLD map for packaged tag libraries. This also pro-
vides support for multiple TLDs inside a single JAR file.
• Added pageEncoding attribute to page directive.

PUBLIC DRAFT
3-50

• Added material to Chapter JSP.4.


• Added TagValidatorInfo class.
• Added Section JSP.1.1.7 with a suggestion on extension convention for top
and included JSP files.

E.8.32 Clarifications

• A tag handler object can be created with a simple “new()”; it needs not be a
fully fledged Beans, supporting the complete behavior of the ja-
va.beans.Beans.instantiate() method.
• Removed the “recommendation” that the <uri> element in a TLD be a URL to
anything.
• Clarified that extension dependency information in packaged tag libraries
should be honored.
• Clarified invocation and lifecycle of TagLibraryValidator.
• Clarified where TLDs may appear in a packaged JAR file.
• Clarified when are response.getWriter().

E.8.33 Changes

• Moved a couple of chapters around


• Improved and clarified Chapter JSP.6.
• Moved the include directive back into Chapter JSP.1.
• Renamed javax.servlet.jsp.tagext.PageInfo to javax.servlet.jsp.tagext.PageDa-
ta (for consistency with existing TagData).
• Added initialization parameters to TagLibraryInformation validation in TLD,
adding a new <validator> element, renaming <validatorclass> to <validator-
class> for consistency, and adding <init-param> as in the Servlet web.xml de-
scriptor.
• Added method to pass the initialization parameters to the validator class and
removed the use of TagLibraryInfo. Added prefix and uri String arguments to
validate() method.
• Changed element names in TLD to consistently follow convention. New

PUBLIC DRAFT
3-51

names are <tag-class>. <tei-class>, <tlib-version, <jsp-version>, <short-


name> and <body-content>. <info> was renamed <description>.

JSP.E.9Changes Between 1.1 and 1.2 PD1

The following changes ocurred between the JSP 1.1 and JSP 1.2 Public Draft 1.

E.9.34 Organizational Changes

• 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.9.35 New Document


We created a new, non-normative document, “Using JSP Technology”. The
document is still being updated to JSP 1.2 and Servlet 2.3. We moved to this docu-
ment the following:

• Some of the non-normative Overview material.


• All of the appendix on tag library examples.
• Some of the material on the Tag Extensions chapter.

E.9.36 Additions to API

• jsp:include can now indicate “flush=’false’”.


• Made the XML view of a JSP page available for input, and for validation.
• PropertyEditor.setAsText() can now be used to convert from a literal string at-
tribute value.
• New ValidatorClass and JspPage classes for validation against tag libraries.

PUBLIC DRAFT
3-52

• New IteratorTag interface to support iteration without BodyContent. Added


two new constants (EVAL_BODY_BUFFERED and EVAL_BODY_AGAIN)
to help document better how the tag protocol works; they are carefully de-
signed so that old tag handlers will still work unchanged, but the old name for
the constant EVAL_BODY_TAG is now deprecated.
• Added listener classes to the TLD.
• Added elements to the TLD to avoid having to write TagExtraInfo classes in
the most common cases.
• Added a resetCustomAttributes() method to Tag interface.
• Added elements to the TLD for delivering icons and descriptions to use in au-
thoring tools.

E.9.37 Clarifications

• Incorporated errata 1.1_a and (in progress) 1.1_b.

E.9.38 Changes

• JSP 1.2 is based on Servlet 2.3, in particular:


• JSP 1.2 is based on the Java 2 platform.

JSP.E.10Changes Between 1.0 and 1.1

The JSP 1.1 specification builds on the JSP 1.0 specification. The following
changes ocurred between the JSP 1.0 final specification and the JSP 1.1 final specifi-
cation.

E.10.39 Additions

• Added a portable tag extension mechanism with an XML-based Tag Library


Descriptor, and a run-time stack of tag handlers. Tag handers are based on the
JavaBeans component model. Adjusted the semantics of the uri attribute in
taglib directives.
• Flush is now a mandatory attribute of jsp:include, and the only valid value is
“true”.

PUBLIC DRAFT
3-53

• Added parameters to jsp:include and jsp:forward.


• Enabled the compilation of JSP pages into Servlet classes that can be trans-
ported from one JSP container to another. Added appendix with an example
of this.
• Added a precompilation protocol.
• Added pushBody() and popBody() to PageContext.
• Added JspException and JspTagException classes.
• Consistent use of the JSP page, JSP container, and similar terms.
• Added a Glossary as Appendix JSP.F.
• Expanded Chapter 1 so as to cover 0.92’s "model 1" and "model 2".
• Clarified a number of JSP 1.0 details.

E.10.40 Changes

• Use Servlet 2.2 instead of Servlet 2.1 (as clarified in Appendix B), including
distributable JSP pages.
• jsp:plugin no longer can be implemented by just sending the contents of
jsp:fallback to the client.
• Reserved all request parameters starting with "jsp".

PUBLIC DRAFT
A P P E N D I X JSP.F
Glossary

This appendix is a glossary of the main concepts mentioned in this specifica-


tion. This appendix is non-normative.

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.

PUBLIC DRAFT 3-54


3-55

declaration A scripting element that declares methods, variables, or both in a


JSP page. Syntactically it is delimited by the <%! and %> characters.
directive An element in a JSP page that gives an instruction to the JSP container
and is interpreted at translation time. Syntactically it is delimited by the <%@
and %> characters.
element A portion of a JSP page that is recognized by the JSP translator. An ele-
ment can be a directive, an action, or a scripting element.
expression A scripting element that contains a valid scripting language expres-
sion that is evaluated, converted to a String, and placed into the implicit out
object. Syntactically it is delimited by the <%= and %> characters.
fixed template data Any portions of a JSP file that are not described in the JSP
specification, such as HTML tags, XML tags, and text. The template data is
returned to the client in the response or is processed by a component.
implicit object A server-side object that is defined by the JSP container and is
always available in a JSP file without being declared. The implicit objects are
request, response, pageContext, session, application, out, config, page, and
exception.

JavaServer Pages technology An extensible Web technology that uses template


data, custom elements, scripting languages, and server-side Java objects to
return dynamic content to a client. Typically the template data is HTML or
XML elements, and in many cases the client is a Web browser.
JSP container A system-level entity that provides life cycle management and
runtime support for JSP and Servlet components.
JSP file A text file that contains a JSP page. In the current version of the specifi-
cation, the JSP file must have a .jsp extension.
JSP page A text-based document that uses fixed template data and JSP elements
and describes how to process a request to create a response. The semantics of
a JSP page are realized at runtime by a JSP page implementation class.

JSP page, frontA JSP page that receives an HTTP request directly from the cli-
ent. It creates, updates, and/or accesses some server-side data and then for-
wards the request to a presentation JSP page.
JSP page, presentation A JSP page that is intended for presentation purposes
only. It accesses and/or updates some server-side data and incorporates fixed
template data to create content that is sent to the client.

PUBLIC DRAFT
3-56

JSP page implementation class The Java programming language class, a Servlet,
that is the runtime representation of a JSP page and which receives the request
object and updates the response object. The page implementation class can
use the services provided by the JSP container, including both the Servlet and
the JSP APIs.
JSP page implementation object The instance of the JSP page implementation
class that receives the request object and updates the response object.
scripting element A declaration, scriptlet, or expression, whose tag syntax is
defined by the JSP specification, and whose content is written according to the
scripting language used in the JSP page. The JSP specification describes the
syntax and semantics for the case where the language page attribute is "java".
scriptlet An scripting element containing any code fragment that is valid in the
scripting language used in the JSP page. The JSP specification describes what
is a valid scriptlet for the case where the language page attribute is "java".
Syntactically a scriptlet is delimited by the <% and %> characters.
tag A piece of text between a left angle bracket and a right angle bracket that has
a name, can have attributes, and is part of an element in a JSP page. Tag
names are known to the JSP translator, either because the name is part of the
JSP specification (in the case of a standard action), or because it has been
introduced using a Tag Library (in the case of custom action).
tag handler A Java class that implements the Tag or the BodyTag interfaces and
that is the run-time representation of a custom action.
tag handler A JavaBean component that implements the Tag or BodyTag inter-
faces and is the run-time representation of a custom action.
tag library A collection of custom actions described by a tag library descriptor
and Java classes.
tag library descriptor An XML document describing a tag library.
Tag Library Provider A vendor that provides a tag library. Typical examples
may be a JSP container vendor, a development group within a corporation, a
component vendor, or a service vendor that wants to provide easier use of
their services.
web application An application built for the Internet, an intranet, or an extranet.
web application, distributable A Web application that is written so that it can be
deployed in a Web container distributed across multiple Java virtual machines

PUBLIC DRAFT
3-57

running on the same host or different hosts. The deployment descriptor for
such an application uses the distributable element.
Web Application Deployer A person who deploys a Web application in a Web
container, specifying at least the root prefix for the Web application, and in a
J2EE environment, the security and resource mappings.
web component A servlet class or JSP page that runs in a JSP container and pro-
vides services in response to requests.
Web Container Provider A vendor that provides a servlet and JSP container that
support the corresponding component contracts.

PUBLIC DRAFT

Potrebbero piacerti anche