Next Section

• | Table of Contents
Java™ 2 Platform, Enterprise Edition: Platform and Component Specifications
By Bill Shannon, Mark Hapner, Vlada Matena, James Davidson, Eduardo Pelegri-Llopart, Larry Cable, Enterprise Team
Publisher | : Addison Wesley
Pub Date | : May 26, 2000
ISBN | : 0-201-70456-0
Pages | : 800

The Java 2(TM) Platform, Enterprise Edition (J2EE) defines a new standard in enterprise solutions through a simplified, component-based development model. By extending the "write-once, run-anywhere(TM)" benefits of the Java programming language to enterprise servers, J2EE adds the scalability, robustness, and security required for today's vital e-commerce and enterprise solutions. The Java(TM) 2 Platform, Enterprise Edition: Platform and Components Specifications defines the architecture for developing applications with J2EE. This volume includes:

  • Java(TM) 2 Platform, Enterprise Edition Specification, version 1.2
    This specification defines the initial release of the J2EE platform. It discusses application architecture using Java(TM) Servlets, JavaServer Pages(TM), Enterprise JavaBeans(TM), and other technologies. It specifies application access to services such as JDBC(TM), Java Transaction API, JavaMail(TM), CORBA connectivity, and others. It also discusses J2EE policies regarding application deployment and security.

  • Enterprise JavaBeans(TM) Specification, version 1.1
    Enterprise JavaBeans technology provides the standard middle-tier components in the J2EE model. This technology provides simplified support for transaction management and remote object access, and it frees enterprise developers to focus on the business logic of their applications. Version 1.1 of the specification includes a number of enhancements, including mandatory entity beans and XML deployment descriptors.

  • Java(TM) Servlet Specification, version 2.2
    Java Servlets technology defines a standard for developing server-side behaviors in web applications based on the Java programming language. As part of the J2EE specifications, servlets technology supports development of dynamic web content for e-commerce and other enterprise applications.

  • JavaServer Pages(TM) Specification, version 1.2
    The JavaServer Pages (JSP) technology simplifies the development and deployment of interactive web applications. Using an extensible markup language based on HTML and the Java programming language, JSP defines a server-side mechanism to allow content experts greater freedom in creating and displaying dynamic web content.

Developed with the input of a wide range of industry experts, these specifications define a new standard for resolving many complex issues related to developing, deploying, and managing multi-tier enterprise applications.

Next Section


• | Table of Contents
Java™ 2 Platform, Enterprise Edition: Platform and Component Specifications
By Bill Shannon, Mark Hapner, Vlada Matena, James Davidson, Eduardo Pelegri-Llopart, Larry Cable, Enterprise Team
Publisher | : Addison Wesley
Pub Date | : May 26, 2000
ISBN | : 0-201-70456-0
Pages | : 800

Copyright
Foreword
 | History and Acknowledgements
About the Authors
Java™ 2 Platform Enterprise Edition Specification, v1.2 (J2EE)
 | Chapter J2EE.1. Introduction
 |  | Acknowledgments
 | Chapter J2EE.2. Platform Overview
 |  | Section J2EE.2.1. Architecture
 |  | Section J2EE.2.2. Product Requirements
 |  | Section J2EE.2.3. Product Extensions
 |  | Section J2EE.2.4. Platform Roles
 |  | Section J2EE.2.5. Platform Contracts
 | Chapter J2EE.3. Security
 |  | Section J2EE.3.1. Introduction
 |  | Section J2EE.3.2. A Simple Example
 |  | Section J2EE.3.3. Security Architecture
 |  | Section J2EE.3.4. User Authentication Requirements
 |  | Section J2EE.3.5. Authorization Requirements
 |  | Section J2EE.3.6. Deployment Requirements
 |  | Section J2EE.3.7. Future Directions
 | Chapter J2EE.4. Transaction Management
 |  | Section J2EE.4.1. Overview
 |  | Section J2EE.4.2. Requirements
 |  | Section J2EE.4.3. Transaction Interoperability
 |  | Section J2EE.4.4. System Administration Tools
 | Chapter J2EE.5. Naming
 |  | Section J2EE.5.1. Overview
 |  | Section J2EE.5.2. Java Naming and Directory Interface™ (JNDI) Naming Context
 |  | Section J2EE.5.3. Enterprise JavaBeans™ (EJB) References
 |  | Section J2EE.5.4. Resource Factory References
 |  | Section J2EE.5.5. UserTransaction References
 | Chapter J2EE.6. Application Programming Interface
 |  | Section J2EE.6.1. Required APIs
 |  | Section J2EE.6.2. Java 2 Platform, Standard Edition (J2SE) Requirements
 |  | Section J2EE.6.3. JDBC™ 2.0 Standard Extension Requirements
 |  | Section J2EE.6.4. RMI-IIOP 1.0 Requirements
 |  | Section J2EE.6.5. Enterprise JavaBeans™ (EJB) 1.1 Requirements
 |  | Section J2EE.6.6. Servlet 2.2 Requirements
 |  | Section J2EE.6.7. JavaServer Pages™ (JSP) 1.1 Requirements
 |  | Section J2EE.6.8. Java™ Message Service (JMS) 1.0 Requirements
 |  | Section J2EE.6.9. Java Naming and Directory Interface™ (JNDI) 1.2 Requirements
 |  | Section J2EE.6.10. Java™ Transaction API (JTA) 1.0 Requirements
 |  | Section J2EE.6.11. JavaMail™ 1.1 Requirements
 |  | Section J2EE.6.12. JavaBeans™ Activation Framework 1.0 Requirements
 | Chapter J2EE.7. Interoperability
 |  | Section J2EE.7.1. Introduction to Interoperability
 |  | Section J2EE.7.2. Interoperability Protocols
 | Chapter J2EE.8. Application Assembly and Deployment
 |  | Section J2EE.8.1. Application Development Life Cycle
 |  | Section J2EE.8.2. Application Assembly
 |  | Section J2EE.8.3. Deployment
 |  | Section J2EE.8.4. J2EE:application XML DTD
 | Chapter J2EE.9. Application Clients
 |  | Section J2EE.9.1. Overview
 |  | Section J2EE.9.2. Security
 |  | Section J2EE.9.3. Transactions
 |  | Section J2EE.9.4. Naming
 |  | Section J2EE.9.5. Application Programming Interfaces
 |  | Section J2EE.9.6. Packaging and Deployment
 |  | Section J2EE.9.7. J2EE:application-client XML DTD
 | Chapter J2EE.10. Service Provider Interface
 | Chapter J2EE.11. Future Directions
 |  | Section J2EE.11.1. Java™ Message Service API
 |  | Section J2EE.11.2. Enterprise JavaBeans™ (EJB)/IIOP Protocol
 |  | Section J2EE.11.3. J2EE SPI
 |  | Section J2EE.11.4. Connectors
 |  | Section J2EE.11.5. XML APIs
 |  | Section J2EE.11.6. JDBC RowSets
 |  | Section J2EE.11.7. Security APIs
 |  | Section J2EE.11.8. Deployment APIs
 |  | Section J2EE.11.9. Management APIs
 |  | Section J2EE.11.10. SQLJ Part 0
 | Appendix J2EE.A. Revision History
 |  | Section J2EE.A.1. Changes Since Public Draft
 |  | Section J2EE.A.2. Changes Since Public Release 1
 |  | Section J2EE.A.3. Changes Since Public Release 2
 | Appendix J2EE.B. Related Documents
Java™ Servlet Specification, v2.2 (SRV)
 | Preface
 |  | Section SRV.P.1. Who Should Read This Specification
 |  | Section SRV.P.2. API Reference
 |  | Section SRV.P.3. Other Java™ Platform Specifications
 |  | Section SRV.P.4. Other Important References
 |  | Section SRV.P.5. Providing Feedback
 |  | Section SRV.P.6. Acknowledgments
 | Chapter SRV.1. Overview
 |  | Section SRV.1.1. What Is a Servlet?
 |  | Section SRV.1.2. What Is a Servlet Container?
 |  | Section SRV.1.3. An Example
 |  | Section SRV.1.4. Comparing Servlets with Other Technologies
 |  | Section SRV.1.5. Relationship to Java 2 Enterprise Edition
 |  | Section SRV.1.6. Distributable Servlet Containers
 |  | Section SRV.1.7. Changes Since Version 2.1
 | Chapter SRV.2. Terms Used
 |  | Section SRV.2.1. Basic Terms
 |  | Section SRV.2.2. Roles
 |  | Section SRV.2.3. Security Terms
 | Chapter SRV.3. The Servlet Interface
 |  | Section SRV.3.1. Request Handling Methods
 |  | Section SRV.3.2. Number of Instances
 |  | Section SRV.3.3. Servlet Life Cycle
 | Chapter SRV.4. Servlet Context
 |  | Section SRV.4.1. Scope of a ServletContext
 |  | Section SRV.4.2. Initialization Parameters
 |  | Section SRV.4.3. Context Attributes
 |  | Section SRV.4.4. Resources
 |  | Section SRV.4.5. Multiple Hosts and Servlet Contexts
 |  | Section SRV.4.6. Reloading Considerations
 |  | Section SRV.4.7. Temporary Working Directories
 | Chapter SRV.5. The Request
 |  | Section SRV.5.1. Parameters
 |  | Section SRV.5.2. Attributes
 |  | Section SRV.5.3. Headers
 |  | Section SRV.5.4. Request Path Elements
 |  | Section SRV.5.5. Path Translation Methods
 |  | Section SRV.5.6. Cookies
 |  | Section SRV.5.7. SSL Attributes
 |  | Section SRV.5.8. Internationalization
 | Chapter SRV.6. The Response
 |  | Section SRV.6.1. Buffering
 |  | Section SRV.6.2. Headers
 |  | Section SRV.6.3. Convenience Methods
 |  | Section SRV.6.4. Internationalization
 |  | Section SRV.6.5. Closure of Response Object
 | Chapter SRV.7. Sessions
 |  | Section SRV.7.1. Session Tracking Mechanisms
 |  | Section SRV.7.2. Creating a Session
 |  | Section SRV.7.3. Session Scope
 |  | Section SRV.7.4. Binding Attributes into a Session
 |  | Section SRV.7.5. Session Timeouts
 |  | Section SRV.7.6. Last Accessed Times
 |  | Section SRV.7.7. Important Session Semantics
 | Chapter SRV.8. Dispatching Requests
 |  | Section SRV.8.1. Obtaining a RequestDispatcher
 |  | Section SRV.8.2. Using a Request Dispatcher
 |  | Section SRV.8.3. include
 |  | Section SRV.8.4. forward
 |  | Section SRV.8.5. Error Handling
 | Chapter SRV.9. Web Applications
 |  | Section SRV.9.1. Relationship to ServletContext
 |  | Section SRV.9.2. Elements of a Web Application
 |  | Section SRV.9.3. Distinction Between Representations
 |  | Section SRV.9.4. Directory Structure
 |  | Section SRV.9.5. Web Application Archive File
 |  | Section SRV.9.6. Web Application Configuration Descriptor
 |  | Section SRV.9.7. Replacing a Web Application
 |  | Section SRV.9.8. Error Handling
 |  | Section SRV.9.9. Web Application Environment
 | Chapter SRV.10. Mapping Requests to Servlets
 |  | Section SRV.10.1. Use of URL Paths
 |  | Section SRV.10.2. Specification of Mappings
 | Chapter SRV.11. Security
 |  | Section SRV.11.1. Introduction
 |  | Section SRV.11.2. Declarative Security
 |  | Section SRV.11.3. Programmatic Security
 |  | Section SRV.11.4. Roles
 |  | Section SRV.11.5. Authentication
 |  | Section SRV.11.6. Server Tracking of Authentication Information
 |  | Section SRV.11.7. Specifying Security Constraints
 | Chapter SRV.12. Application Programming Interface
 |  | Section SRV.12.1. Package javax.servlet
 | Chapter SRV.13. Deployment Descriptor
 |  | Section SRV.13.1. Deployment Descriptor Elements
 |  | Section SRV.13.2. DTD
 |  | Section SRV.13.3. Examples
 | Chapter SRV.14. Futures
JavaServer Pages™ Specification, v1.1 (JSP)
 | Preface
 |  | Section JSP.P.1. Who Should Read This Document
 |  | Section JSP.P.2. Related Documents
 |  | Section JSP.P.3. Acknowledgments
 | Chapter JSP.1. Overview
 |  | Section JSP.1.1. The JavaServer Pages™ Technology
 |  | Section JSP.1.2. What Is a JSP Page?
 |  | Section JSP.1.3. Features in JSP 1.1
 |  | Section JSP.1.4. Overview of JSP Page Semantics
 |  | Section JSP.1.5. Web Applications
 |  | Section JSP.1.6. Application Model
 | Chapter JSP.2. Standard Syntax and Semantics
 |  | Section JSP.2.1. General Syntax Rules
 |  | Section JSP.2.2. Error Handling
 |  | Section JSP.2.3. Comments
 |  | Section JSP.2.4. Quoting and Escape Conventions
 |  | Section JSP.2.5. Overview of Semantics
 |  | Section JSP.2.6. Template Text Semantics
 |  | Section JSP.2.7. Directives
 |  | Section JSP.2.8. Implicit Objects
 |  | Section JSP.2.9. The PageContext Object
 |  | Section JSP.2.10. Scripting Elements
 |  | Section JSP.2.11. Actions
 |  | Section JSP.2.12. Tag Attribute Interpretation Semantics
 |  | Section JSP.2.13. Standard Actions
 | Chapter JSP.3. The JSP Container
 |  | Section JSP.3.1. The JSP Page Model
 |  | Section JSP.3.2. JSP Page Implementation Class
 |  | Section JSP.3.3. Buffering
 |  | Section JSP.3.4. Precompilation
 | Chapter JSP.4. Scripting
 |  | Section JSP.4.1. Overall Structure
 |  | Section JSP.4.2. Declarations Section
 |  | Section JSP.4.3. Initialization Section
 |  | Section JSP.4.4. Main Section
 | Chapter JSP.5. Tag Extensions
 |  | Section JSP.5.1. Introduction
 |  | Section JSP.5.2. Tag Library
 |  | Section JSP.5.3. Tag Library Descriptor
 |  | Section JSP.5.4. Tag Handlers
 |  | Section JSP.5.5. Scripting Variables
 |  | Section JSP.5.6. Cooperating Actions
 |  | Section JSP.5.7. Validation
 |  | Section JSP.5.8. Conventions and Other Issues
 | Chapter JSP.6. JSP Technology Classes
 |  | Section JSP.6.1. Package javax.servlet.jsp
 |  | Section JSP.6.2. Package javax.servlet.jsp.tagext
 | Chapter JSP.7. JSP Pages as XML Documents
 |  | Section JSP.7.1. Why an XML Representation
 |  | Section JSP.7.2. Document Type
 |  | Section JSP.7.3. Directives
 |  | Section JSP.7.4. Scripting Elements
 |  | Section JSP.7.5. Actions
 |  | Section JSP.7.6. Transforming a JSP Page into an XML Document
 |  | Section JSP.7.7. DTD for the XML Document
 | Appendix JSP.A. Examples
 |  | Section JSP.A.1. Simple Examples
 |  | Section JSP.A.2. A Set of SQL Tags
 | Appendix JSP.B. Implementation Notes
 |  | Section JSP.B.1. Delivering Localized Content
 |  | Section JSP.B.2. Processing taglib Directives
 |  | Section JSP.B.3. Processing Tag Libraries
 |  | Section JSP.B.4. Implementing Buffering
 | Appendix JSP.C. Packaging JSP Pages
 |  | Section JSP.C.1. A Very Simple JSP Page
 |  | Section JSP.C.2. The JSP Page Packaged as Source in a WAR File
 |  | Section JSP.C.3. The Servlet for the Compiled JSP Page
 |  | Section JSP.C.4. The Web Application Descriptor
 |  | Section JSP.C.5. The WAR for the Compiled JSP Page
 | Appendix JSP.D. Future
 |  | Section JSP.D.1. Meta-Tag Information
 |  | Section JSP.D.2. Standard Tags
 |  | Section JSP.D.3. Additional Application Support
 |  | Section JSP.D.4. JSP, XML, and XSL Technologies
 | Appendix JSP.E. Changes
 |  | Section JSP.E.1. Changes Between 1.1 PR2 and 1.1 Final
 |  | Section JSP.E.2. Changes Between 1.1 PR1 and PR2
 |  | Section JSP.E.3. Changes Between 1.1 PD1 and PR1
 |  | Section JSP.E.4. Changes Between 1.0 and 1.1 PD1
Enterprise JavaBeans™ Specification, v1.1 (EJB)
 | Chapter EJB.1. Introduction
 |  | Section EJB.1.1. Target Audience
 |  | Section EJB.1.2. What Is New in EJB 1.1
 |  | Section EJB.1.3. Application Compatibility and Interoperability
 |  | Section EJB.1.4. Acknowledgments
 |  | Section EJB.1.5. Organization
 |  | Section EJB.1.6. Document Conventions
 | Chapter EJB.2. Goals
 |  | Section EJB.2.1. Overall Goals
 |  | Section EJB.2.2. Goals for Release 1.0
 |  | Section EJB.2.3. Goals for Release 1.1
 | Chapter EJB.3. EJB Architecture Roles and Scenarios
 |  | Section EJB.3.1. EJB Architecture Roles
 |  | Section EJB.3.2. Scenario: Development, Assembly, and Deployment
 | Chapter EJB.4. Overview
 |  | Section EJB.4.1. Enterprise Beans as Components
 |  | Section EJB.4.2. Enterprise JavaBeans Architecture Contracts
 |  | Section EJB.4.3. Session and Entity Objects
 |  | Section EJB.4.4. Standard Mapping to CORBA Protocols
 | Chapter EJB.5. Client View of a Session Bean
 |  | Section EJB.5.1. Overview
 |  | Section EJB.5.2. EJB Container
 |  | Section EJB.5.3. Home Interface
 |  | Section EJB.5.4. EJBObject
 |  | Section EJB.5.5. Session Object Identity
 |  | Section EJB.5.6. Client View of Session Object's Life Cycle
 |  | Section EJB.5.7. Creating and Using a Session Object
 |  | Section EJB.5.8. Object Identity
 |  | Section EJB.5.9. Type Narrowing
 | Chapter EJB.6. Session Bean Component Contract
 |  | Section EJB.6.1. Overview
 |  | Section EJB.6.2. Goals
 |  | Section EJB.6.3. A Container's Management of Its Working Set
 |  | Section EJB.6.4. Conversational State
 |  | Section EJB.6.5. Protocol Between a Session Bean Instance and Its Container
 |  | Section EJB.6.6. Stateful Session Bean State Diagram
 |  | Section EJB.6.7. Object Interaction Diagrams for a Stateful Session Bean
 |  | Section EJB.6.8. Stateless Session Beans
 |  | Section EJB.6.9. Object Interaction Diagrams for a Stateless Session Bean
 |  | Section EJB.6.10. The Responsibilities of the Bean Provider
 | Chapter EJB.7. Example Session Scenario
 |  | Section EJB.7.1. Overview
 |  | Section EJB.7.2. Inheritance Relationship
 | Chapter EJB.8. Client View of an Entity
 |  | Section EJB.8.1. Overview
 |  | Section EJB.8.2. EJB Container
 |  | Section EJB.8.3. Entity Bean's Home Interface
 |  | Section EJB.8.4. Entity Object's Life Cycle
 |  | Section EJB.8.5. Primary Key and Object Identity
 |  | Section EJB.8.6. Entity Bean's Remote Interface
 |  | Section EJB.8.7. Entity Bean's Handle
 |  | Section EJB.8.8. Entity Home Handles
 |  | Section EJB.8.9. Type Narrowing of Object References
 | Chapter EJB.9. Entity Bean Component Contract
 |  | Section EJB.9.1. Concepts
 |  | Section EJB.9.2. Responsibilities of the Enterprise Bean Provider
 |  | Section EJB.9.3. The Responsibilities of the Container Provider
 |  | Section EJB.9.4. Entity Beans with Container-Managed Persistence
 |  | Section EJB.9.5. Object Interaction Diagrams
 | Chapter EJB.10. Example Entity Scenario
 |  | Section EJB.10.1. Overview
 |  | Section EJB.10.2. Inheritance Relationship
 | Chapter EJB.11. Support for Transactions
 |  | Section EJB.11.1. Overview
 |  | Section EJB.11.2. Sample Scenarios
 |  | Section EJB.11.3. Bean Provider's Responsibilities
 |  | Section EJB.11.4. Application Assembler's Responsibilities
 |  | Section EJB.11.5. Deployer's Responsibilities
 |  | Section EJB.11.6. Container Provider Responsibilities
 |  | Section EJB.11.7. Access from Multiple Clients in the Same Transaction Context
 | Chapter EJB.12. Exception Handling
 |  | Section EJB.12.1. Overview and Concepts
 |  | Section EJB.12.2. Bean Provider's Responsibilities
 |  | Section EJB.12.3. Container Provider Responsibilities
 |  | Section EJB.12.4. Client's View of Exceptions
 |  | Section EJB.12.5. System Administrator's Responsibilities
 |  | Section EJB.12.6. Differences from EJB 1.0
 | Chapter EJB.13. Support for Distribution
 |  | Section EJB.13.1. Overview
 |  | Section EJB.13.2. Client-Side Objects in Distributed Environment
 |  | Section EJB.13.3. Standard Distribution Protocol
 | Chapter EJB.14. Enterprise Bean Environment
 |  | Section EJB.14.1. Overview
 |  | Section EJB.14.2. Bean Environment as JNDI Naming Context
 |  | Section EJB.14.3. EJB References
 |  | Section EJB.14.4. Resource Manager Connection Factory References
 |  | Section EJB.14.5. Deprecated EJBContext.getEnvironment() Method
 |  | Section EJB.14.6. UserTransaction Interface
 | Chapter EJB.15. Security Management
 |  | Section EJB.15.1. Overview
 |  | Section EJB.15.2. Bean Provider's Responsibilities
 |  | Section EJB.15.3. Application Assembler's Responsibilities
 |  | Section EJB.15.4. Deployer's Responsibilities
 |  | Section EJB.15.5. EJB Architecture Client Responsibilities
 |  | Section EJB.15.6. EJB Container Provider's Responsibilities
 |  | Section EJB.15.7. System Administrator's Responsibilities
 | Chapter EJB.16. Deployment Descriptor
 |  | Section EJB.16.1. Overview
 |  | Section EJB.16.2. Bean Provider's Responsibilities
 |  | Section EJB.16.3. Application Assembler's Responsibility
 |  | Section EJB.16.4. Container Provider's Responsibilities
 |  | Section EJB.16.5. Deployment Descriptor DTD
 |  | Section EJB.16.6. Deployment Descriptor Example
 | Chapter EJB.17. EJB JAR File
 |  | Section EJB.17.1. Overview
 |  | Section EJB.17.2. Deployment Descriptor
 |  | Section EJB.17.3. Class Files
 |  | Section EJB.17.4. ejb-client JAR File
 |  | Section EJB.17.5. Deprecated in EJB 1.1
 | Chapter EJB.18. Runtime Environment
 |  | Section EJB.18.1. Bean Provider's Responsibilities
 |  | Section EJB.18.2. Container Provider's Responsibility
 | Chapter EJB.19. Responsibilities of EJB Architecture Roles
 |  | Section EJB.19.1. Bean Provider's Responsibilities
 |  | Section EJB.19.2. Application Assembler's Responsibilities
 |  | Section EJB.19.3. EJB Container Provider's Responsibilities
 |  | Section EJB.19.4. Deployer's Responsibilities
 |  | Section EJB.19.5. System Administrator's Responsibilities
 |  | Section EJB.19.6. Client Programmer's Responsibilities
 | Chapter EJB.20. Enterprise JavaBeans™ API Reference
 |  | Section EJB.20.1. Package javax.ejb
 |  | Section EJB.20.2. Package javax.ejb.deployment
 | Chapter EJB.21. Related Documents
 | Appendix EJB.A. Features Deferred to Future Releases
 | Appendix EJB.B. Frequently Asked Questions
 |  | Section EJB.B.1. Client-Demarcated Transactions
 |  | Section EJB.B.2. Inheritance
 |  | Section EJB.B.3. Entities and Relationships
 |  | Section EJB.B.4. Finder Methods for Entities with Container-Managed Persistence
 |  | Section EJB.B.5. JDK 1.1 or Java 2
 |  | Section EJB.B.6. javax.transaction.UserTransaction Versus javax.jts.UserTransaction
 |  | Section EJB.B.7. How to Obtain Database Connections
 |  | Section EJB.B.8. Session Beans and Primary Key
 |  | Section EJB.B.9. Copying of Parameters Required for EJB Calls Within the Same JVM
 | Appendix EJB.C. Revision History
 |  | Section EJB.C.1. Changes Since Release 0.8
 |  | Section EJB.C.2. Changes Since Release 0.9
 |  | Section EJB.C.3. Changes Since Release 0.95
 |  | Section EJB.C.4. Changes Since 1.0
 |  | Section EJB.C.5. Changes Since EBJ.1.1 Draft 1
 |  | Section EJB.C.6. Changes Since EJB.1.1 Draft 2
 |  | Section EJB.C.7. Changes Since EJB 1.1 Draft 3
 |  | Section EJB.C.8. Changes Since EJB 1.1 Public Draft
 |  | Section EJB.C.9. Changes Since EJB 1.1 Public Draft 2
 |  | Section EJB.C.10. Changes Since EJB 1.1 Public Draft 3
 |  | Section EJB.C.11. Changes Since EJB 1.1 Public Release
 |  | Section EJB.C.12. Changes Since EJB 1.1 Public Release
Glossary


Copyright

Copyright © 1999–2000 Sun Microsystems, Inc.

901 San Antonio Road, Palo Alto, California 94303, U.S.A.

All rights reserved.

Duke™ logo designed by Joe Palrang

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 or otherwise copying the Specification, you agree that you have read, understood, and will comply with all of the terms and conditions set forth herein.

Sun hereby grants you a fully-paid, non-exclusive, non-transferable, worldwide, limited license (without the right to sublicense), under Sun's intellectual property rights that are essential to practice the Specification, to internally practice the Specification solely for the purpose of creating a clean room implementation of the Specification that: (i) includes a complete implementation of the current version of the Specification, without subsetting or supersetting; (ii) implements all of the interfaces and functionality of the Specification, as defined by Sun, without subsetting or supersetting; (iii) includes a complete implementation of any optional components (as defined by Sun in the Specification) which you choose to implement, without subsetting or supersetting; (iv) implements all of the interfaces and functionality of such optional components, without subsetting or supersetting; (v) does not add any additional packages, classes or interfaces to the "java.*" or "javax.*" packages or subpackages (or other packages defined by Sun); (vi) satisfies all testing requirements available from Sun relating to the most recently published version of the Specification six (6) months prior to any release of the clean room implementation or upgrade thereto; (vii) does not derive from any Sun source code or binary code materials; and (viii) does not include any Sun source code or binary code materials without an appropriate and separate license from Sun. The Specification contains the proprietary information of Sun and may only be used in accordance with the license terms set forth herein. This license will terminate immediately without notice from Sun if you fail to comply with any provision of this license. Upon termination or expiration of this license, you must cease use of or destroy the Specification.

TRADEMARKS

No right, title, or interest in or to any trademarks, service marks, or trade names of Sun or Sun's licensors is granted hereunder. Sun, Sun Microsystems, the Sun logo, Java, JavaScript, Java Compatible, JavaBeans, Enterprise JavaBeans, EJB, JavaServer Pages, JDBC, JavaMail, Java Naming and Directory Interface, and "Write Once, Run Anywhere", are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. CORBA is a trademark of the Object Management Group (http://www.omg.org).

DISCLAIMER OF WARRANTIES

THE SPECIFICATION IS PROVIDED "AS IS". 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 arising or resulting from: (i) your use of the Specification; (ii) the use or distribution of your Java application, applet and/or clean room implementation; and/or (iii) 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

U.S. Government: If this Specification 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 use of the Specification ("Feedback"). To the extent that you provide Sun with any Feedback, you hereby: (i) agree that such Feedback is provided on a non-proprietary and non-confidential basis, and (ii) grant Sun a perpetual, non-exclusive, worldwide, fully paid-up, irrevocable license, with the right to sublicense through multiple levels of sublicensees, to incorporate, disclose, and use without limitation the Feedback for any purpose related to the Specification and future versions, implementations, and test suites thereof.

Library of Congress Cataloging-in-Publication Data

Java 2 platform, enterprise edition : platform and component specifications / Bill Shannon ... [et al.].

p. cm.

Includes bibliographical references and index.

0-201-70456-0

1. Java (Computer program language) I. Shannon, Bill, 1955-

QA76.73.J38 J35945 2000

005.2'762—dc21

00-035528

The publisher offers discounts on this book when ordered in quantity for special sales. For more information, please contact

Pearson Education Corporate Sales Division

One Lake Street

Upper Saddle River, New Jersey 07458

Text printed on recycled paper.

1 2 3 4 5 6 7 8 9 10—DOC—0403020100

First printing, May 2000


Foreword

In the old days (like, 1995) computing servers were only used by a company's employees, i.e., on an intranet. Today every company seems to be on the Internet. They have an order of magnitude: customers, suppliers, distributors, and potentially anyone (or anything) with access to their web site. Companies have been forced to move from local client-server or mainframe computing to a new multitier computing model. They have a completely new set of problems in reliability, scalability, security, application deployment, transaction processing, web interface design, and timely software development.

This book describes a solution to those problems: Java™ 2 Platform, Enterprise Edition, or J2EE. J2EE extends the Java™ 2 Platform, Standard Edition to enable "Write Once Run Anywhere" for multi-tier computing. It is an industry standard from dozens of companies who are developing J2EE-compliant products for their customers.

This book is targeted at software developers who are building those products, or who are writing applications on top of them. It is the definitive reference for J2EE and its component models: Enterprise JavaBeans, servlets, and JavaServer Pages. These component models enable the use of Java technology in web servers and application servers as well as with clients in a distributed computing environment.

Part I of the book, the J2EE specification, defines the standard. This standard enables portability of software across products from a wide variety of vendors selling J2EE-compliant server products.

Parts II and III of the book describe servlets and JavaServer Pages, the web server components for the J2EE platform. Servlets and JavaServer Pages provide standards for extending server functionality and the generation of dynamic web content. Servlets define a simple way to process web server requests, while JavaServer Pages provide a simple way of invoking and embedding Java code in HTML and XML templates.

Part IV describes Enterprise JavaBeans, the application server component model for the J2EE platform. In addition to providing a binary standard for portability across products, Enterprise JavaBeans greatly simplify the development of server code by automating the details of transactions, security, scalability, and other complex aspects of server-side computing. They also add value by simplifying the deployment and customization of components to specific installations. This book is a specification and a reference manual. It defines the J2EE platform. For a beginning introduction to J2EE, refer to white papers, documentation, and example code at: http://java.sun.com/j2ee/download.html

You may also want to download or purchase Nick Kassem's Designing Enterprise Applications with the Java™ 2 Platform, Enterprise Edition, which provides a programmer's guide to J2EE. If you do not have access to a J2EE-compliant product, a reference implementation of J2EE is available for download at the same location. This implementation is suitable for trying out J2EE prior to investing in a third-party product.


History and Acknowledgements

Of course, a foreword to a book like this requires a history of the people behind the project. My own involvement began in 1995, when I transferred to the JavaSoft division to work on JDBC database connectivity with Graham Hamilton. We liked the Java platform because it combined the best features of many programming languages we had used in our careers. At the time, it was gaining popularity for use in Internet browsers, but our intuition was that it had wider appeal. Indeed, in the years to come, the Java platform proved more popular in distributed computing than anyone could have envisioned in 1995.

In 1996, Mark Hapner joined us to help with JDBC, and then with a group of application programming interfaces (APIs) I was calling "enterprise Java." Over the years that followed Mark participated in the design of more of the evolving J2EE platform than any other individual, becoming the central architect. Vlada Matena joined us later in 1996, leading the design of a transaction API and then Enterprise JavaBeans, which became a cornerstone of J2EE. Vlada wrote the original summary for a J2EE specification, which later evolved into Part I of this book, written by Bill Shannon.

The Java Web Server project also began in 1996. Through the work of a lot of dedicated people, this project eventually culminated in the servlet and JavaServer Pages APIs. James Davidson and Eduardo Pelegri-Llopart most recently led these efforts. Along with Brian Behlendorf, Jon Stevens, and others, they pioneered the use of the Apache open source model to provide a widely-adopted implementation of these APIs. Servlets and JavaServer Pages also became cornerstones for the J2EE platform. These component models have been widely-adopted as the basis for web applications, by themselves or as a front-end to Enterprise JavaBeans.

Jon Kannegaard joined JavaSoft as vice president and general manager in late 1995. He was the single most important person involved in the delivery of Java technology in the years that followed. J2EE in particular would never have happened without his fight for the cause. He got it. He had faith. Jon and I recruited Mala Chandra to direct the enterprise work in mid-1996. I was very glad to have her on board; I was doing all management and no engineering by that time. Mala built an impressive organization very quickly. She utilized her wide respect in the industry to build support. She provided a clear vision for a J2EE platform. She led us to success.

Mala hired her former colleague Shel Finkelstein soon after her arrival. Shel managed most of the J2EE architecture team and served as a core J2EE architect himself. More importantly, he handled technical diplomacy with the partners. Partnership turned out to be the quintessential element of the project: Without the long list of people and companies that committed to the J2EE effort and industry consensus, the platform would not have developed the tremendous momentum it has today.

By the beginning of 1998, Mala's engineering team numbered 60 people. Two key additions were Jeff Jackson and Bill Shannon. Bill became an essential member of the core architectural team, resolving the many technical issues in our weekly meetings. We really needed his insight. Jeff Jackson wandered the halls chanting the mantra "4, 6, 9, 1"—the months we had targeted in 1999 for the prealpha, alpha, beta, and final releases of J2EE. We made those dates, and after the successful 12/99 release Jeff was promoted to direct J2EE engineering.

It is not practical to acknowledge here the dozens of people in J2EE engineering who worked beyond the call of duty for the cause. However, I must mention Sanjeev Krishnan, Carla Mott, Vivek Nagar, Vella Raman, and Anil Vijendran, whose contributions were truly outstanding. You will find many others acknowledged in the J2EE specifications and elsewhere.

The excellent engineering management team is also due credit for the timeliness and quality of J2EE: Janet Breuer, Carla Carlson, Jim Driscoll, David Heisser, Jim Inscore, Tom Kincaid, Stans Kleijnen, Kathy Knutsen, Margot Miller, Steve Nahm, Karen Tegan, and Connie Weiss. Bill Roth, Sharada Achanta, and Gina Centoni managed J2EE marketing.

However it should be said that the most important contributors were not Sun Microsystems employees. J2EE was an industry-wide effort. Experts from dozens of partner companies successfully developed and reached consensus on J2EE APIs. These APIs encompass a broad range of capabilities including naming and directory services, distributed transactions, OMG CORBA connectivity, asynchronous messaging, security, web server development, enterprise application integration, EJB, and JDBC.

Dave Rosenberg from Oracle and Ian Brackenbury from IBM had the tough job of bringing together the diverse viewpoints of their large companies to facilitate consensus on these APIs. Rod Butters, Mathieu Devin, Hal Hilderbrand, Larry Jacobs, Julie Basi, and Gary Hallmark from Oracle, Jack Boyce, Elias Bayeh, Mike Connor, George Copeland, Paul Cotton, Don Ferguson, Tom Freund, Simon Nash, Peter Niblett, and Tony Storey from IBM, Scott Dietzen, Ed Cobb, Mark Carges, and Pete Homan from BEA, Johannes Klein from Compaq, Mary Leland from HP, Steve Holbrook and Art Navajjrez from Novell, Paul Butterworth and Sean Fitts from Forté, Vijay Anand, Yarden Malka, and Peter Yared from NetDynamics, Marc San Soucie from GemStone, Richard Pledereder from Sybase, John Goodson from Merant, Yeh-Heng Sheng from Informix, Larry Ciscon and Bernard Barcio from Modulus, Terry Olkin from Open Horizon, and Pete Ohler from Tibco were particularly helpful in bringing their expertise and their company viewpoints to the J2EE effort. Many others are acknowledged in the J2EE specifications for their contributions to various APIs.

The consensus-building process which began with JDBC was refined through these and other efforts, and eventually became the Java Community Process. This process has proven very successful in achieving industry adoption of real standards while minimizing the "design by committee" that often plagues formal standards processes. The Java Community Process avoids a "paper design" through the participation of engineers whose success depends on delivery of products that implement an API, and by demanding a reference implementation and compatibility test suite that give the standard substance.

The Java platform has come a long way from the first JavaOne conference in 1996. At that conference, we introduced JDBC to an audience of developers who were using the Java platform primarily in client-side Internet browsers. At the third JavaOne in 1998, nearly 8,000 developers attended the presentation about the enterprise Java platform. Over half of them raised their hands when I asked who was writing server-side Java code. In early 2000, a dozen vendors have already announced server products expected to comply with the J2EE specification and compatibility test suite by year-end. 100,000 enterprise developers have downloaded the J2EE reference implementation in just the few months since its December release. We're delighted. We hope that you too will find our work useful.

Rick Cattell, Distinguished Engineer, Sun Microsystems
Cupertino, California, March 15, 2000


About the Authors

Bill Shannon is a Distinguished Engineer at Sun Microsystems, where he is one of the architects of the J2EE. He previously worked on the JavaMail API, the Hot-Java Views product, the Common Desktop Environment, the Solaris operating system, and all versions of SunOS.

Mark Hapner is Lead Architect for the Java 2 Platform, Enterprise Edition. He participated in the development of the JDBC API, wrote the Java Message Service specification, and co-authored the Enterprise JavaBeans specification.

Vlada Matena is a Distinguished Engineer with the Java Software division of Sun Microsystems Inc., where he works on the J2EE architecture team. He is the Chief Architect of the Enterprise JavaBeans specification, and an architect of the JTS and JTA specifications.

James Davidson is a Staff Engineer at Sun Microsystems, working on web server–related technologies. Before joining Sun, James was involved in building some of the very first e-commerce sites on the World Wide Web.

Eduardo Pelegri-Llopart is the Web Layer Architect for the Java platform, coordinating technical efforts on the Servlet, JSP, and XML layers. He is also the co-spec lead for the JSP 1.0 and JSP 1.1.

Larry Cable is a Senior Staff Engineer with Sun Microsystems where he is the lead architect for the iPlanet Application Server developed jointly by Sun and Netscape.


Java™ 2 Platform Enterprise Edition Specification, v1.2 (J2EE)

    Chapter J2EE.1. Introduction

    Chapter J2EE.2. Platform Overview

    Chapter J2EE.3. Security

    Chapter J2EE.4. Transaction Management

    Chapter J2EE.5. Naming

    Chapter J2EE.6. Application Programming Interface

    Chapter J2EE.7. Interoperability

    Chapter J2EE.8. Application Assembly and Deployment

    Chapter J2EE.9. Application Clients

    Chapter J2EE.10. Service Provider Interface

    Chapter J2EE.11. Future Directions

    Appendix J2EE.A. Revision History

    Appendix J2EE.B. Related Documents


Chapter J2EE.1. Introduction

Enterprises today need to extend their reach, reduce their costs, and lower their response times by providing easy-to-access services to their customers, employees, and suppliers.

Typically, applications that provide these services must combine existing Enterprise Information Systems (EISs) with new business functions that deliver services to a broad range of users. These services need to be:

  • Highly available, to meet the needs of today's global business environment.

  • Secure, to protect the privacy of users and the integrity of the enterprise.

  • Reliable and scalable, to insure that business transactions are accurately and promptly processed.

In most cases, these services are architected as multi-tier applications. A middle tier that implements the new services needs to integrate existing EISs with the business functions and data of the new service. The service middle tier shields first-tier clients from the complexity of the enterprise and takes advantage of rapidly maturing web technologies to eliminate or drastically reduce user administration and training while leveraging existing enterprise assets.

The Java™ 2 Platform, Enterprise Edition (J2EE) reduces the cost and complexity of developing these multi-tier services, resulting in services that can be rapidly deployed and easily enhanced as the enterprise responds to competitive pressures.

J2EE achieves these benefits by defining a standard architecture that is delivered as the following elements:

  • J2EE Application Model— A standard application model for developing multi-tier, thin-client services.

  • J2EE Platform— A standard platform for hosting J2EE applications.

  • J2EE Compatibility Test Suite— A suite of compatibility tests for verifying that a J2EE platform product complies with the J2EE platform standard.

  • J2EE Reference Implementation— A reference implementation for demonstrating the capabilities of J2EE and for providing an operational definition of the J2EE platform.

This document provides the specification of the J2EE platform and describes the requirements that a J2EE platform product must meet.


Acknowledgments

This specification is the work of many people. Vlada Matena wrote the first draft as well as the Transaction Management and Naming chapters. Sekhar Vajjhala, Kevin Osborn, and Ron Monzillo wrote the Security chapter. Hans Hrasna wrote the Application Assembly and Deployment chapter. Seth White wrote the JDBC API requirements. Jim Inscore, Eric Jendrock, and Beth Stearns provided editorial assistance. Shel Finkelstein, Mark Hapner, Danny Coward, Tom Kincaid, and Tony Ng provided feedback on many drafts. And of course this specification was formed and molded based on conversations with and review feedback from our many industry partners.


Chapter J2EE.2. Platform Overview

This chapter provides an overview of the Java™ 2 Platform, Enterprise Edition (J2EE).


J2EE.2.1 Architecture

The J2EE runtime environment consists of the following parts:

  • Application components. The J2EE programming model defines four application component types that a J2EE product must support:

    - Application clients are Java programming language programs that are typically GUI programs that execute on a desktop computer. Application clients offer a user experience similar to that of native applications, and have access to all of the facilities of the J2EE middle tier.

    - Applets are GUI components that typically execute in a web browser, but can execute in a variety of other applications or devices that support the applet programming model. Applets can be used to provide a powerful user interface for J2EE applications. (Simple HTML pages can also be used to provide a more limited user interface for J2EE applications.)

    - Servlets and JSP pages typically execute in a web server and respond to HTTP requests from web clients. Servlets and JSP pages may be used to generate HTML pages that are an application's user interface. They may also be used to generate XML or other format data that is consumed by other application components. Servlets, and pages created with the JavaServer Pages™ technology, are often referred to collectively in this specification as "web components." Web applications are composed of web components and other data such as HTML pages.

    - Enterprise JavaBeans™ (EJB) components execute in a managed environment that supports transactions. Enterprise beans typically contain the business logic for a J2EE application.

    These application components can be divided into three categories:

    - Components that are deployed, managed, and executed on a J2EE server. These components include JavaServer Pages, servlets, and Enterprise JavaBeans.

    - Components that are deployed and managed on a J2EE server, but are loaded to and executed on a client machine. These components include HTML pages and applets embedded in the HTML pages.

    - Components whose deployment and management are not completely defined by this specification. Application clients fall into this category. Future versions of this specification may more fully define deployment and management of application clients.

  • Containers. Containers provide the runtime support for the application components. A container provides a federated view of the underlying J2EE APIs to the application components. Interposing a container between the application components and the J2EE services allows the container to transparently inject services defined by the components' deployment descriptors, such as declarative transaction management, security checks, resource pooling, and state management. A typical J2EE product will provide a container for each application component type: application client container, applet container, web component container, and enterprise bean container.

    This specification requires that these containers provide a Java Compatible™ runtime environment, as defined by the Java 2 Platform, Standard Edition, v1.2 specification (J2SE). The applet container may use the Java Plugin product to provide this environment, or it may provide it natively. The use of applet containers providing only the JDK™ 1.1 APIs is outside the scope of this specification.

    The container tools also understand the file formats for packaging of the application components for deployment. The containers are implemented by a J2EE product provider.

    This specification defines a set of standard services that each J2EE product must support. These standard services are described below. The J2EE containers provide the APIs to access these services to application components. A future release of this specification will describe standard ways to extend J2EE services with connectors to other non-J2EE application systems, such as mainframe systems and ERP systems.

    Underlying the J2EE containers is the J2EE core. A J2EE product provider typically implements the J2EE server core using an existing transaction processing infrastructure in combination with Java 2 technology. The J2EE client core is typically built on Java 2 Platform, Standard Edition technology.

    Figure J2EE.2-1 illustrates the relationship of these components of the J2EE platform. Note that this figure shows the logical relationships of the components; it is not meant to imply a physical partitioning of the components into separate machines, processes, address spaces, or virtual machines.

    Figure J2EE.2-1. J2EE Architecture Diagram

  • Resource manager drivers. A resource manager driver (driver for short) is a system-level software component that implements network connectivity to an external resource manager. A driver can extend the functionality of the J2EE platform either by implementing one of the J2EE standard service APIs (such as a JDBC™ driver), or by defining and implementing a resource manager driver for a connector to an external application system (supported in a future release). Drivers interface with the J2EE platform through the J2EE service provider interfaces (J2EE SPI). A driver that uses the J2EE SPIs to attach to the J2EE platform will be able to work with all J2EE products.

  • Database. The J2EE platform includes a database, accessible through the JDBC API, for the storage of business data. The database is accessible from web components, enterprise beans, and application client components. The database need not be accessible from applets.

The J2EE standard services include the following (specified in more detail later in this document):

  • HTTP. The HTTP client-side API is defined by the java.net package. The HTTP server-side API is defined by the servlet and JSP interfaces.

  • HTTPS. Use of the HTTP protocol over the SSL protocol is supported by the same client and server APIs as HTTP.

  • Java™ Transaction API (JTA). The Java Transaction API consists of two parts:

    - An application-level demarcation interface that is used by the container and application components to demarcate transaction boundaries.

    - An interface between the transaction manager and a resource manager used at the J2EE SPI level (in a future release).

  • RMI-IIOP. The RMI-IIOP subsystem is composed of APIs that allow for the use of RMI-style programming that is independent of the underlying protocol, as well as an implementation of these APIs that supports both the J2SE native RMI protocol (JRMP) and the CORBA IIOP protocol. J2EE applications can use RMI-IIOP, with the IIOP protocol support, to access CORBA services that are compatible with the RMI programming restrictions (see the RMI-IIOP spec for details). Such CORBA services would typically be defined by components that live outside a J2EE product, usually in a legacy system. Only J2EE application clients are required to be able to define their own CORBA services directly, using the RMI-IIOP APIs. Typically such CORBA objects would be used for callbacks when accessing other CORBA objects.

    J2EE applications are required to use the RMI-IIOP APIs (specifically the narrow method of javax.rmi.PortableRemoteObject) when accessing Enterprise JavaBeans components, as described in the EJB 1.1 specification. This allows enterprise beans to be protocol independent. However, there is currently no requirement that enterprise beans be accessible using the IIOP protocol. Such a requirement will be added in a future version of this speci-fication. With this requirement, enterprise bean components will appear as CORBA objects.

  • JavaIDL. JavaIDL allows J2EE application components to invoke external CORBA objects using the IIOP protocol. These CORBA objects may be written in any language and typically live outside a J2EE product. J2EE applications may use JavaIDL to act as clients of CORBA services, but only J2EE application clients are required to be allowed to use JavaIDL directly to present CORBA services themselves. (As described above, a future version of this specification will require that enterprise beans appear as CORBA objects.)

  • JDBC™. The JDBC API is the API for connectivity with database systems. The JDBC API has two parts: an application-level interface used by the application components to access a database, and a service provider interface to attach a JDBC driver to the J2EE platform.

  • Java™ Message Service (JMS). The Java Messaging Service is a standard API for messaging that supports reliable point-to-point messaging as well as the publish-subscribe model. This specification requires the JMS API definition to be available, but does not require any messaging service implementation to be available. A future version of this specification will require an implementation of both point-to-point messaging as well as publish-subscribe messaging.

  • Java Naming and Directory Interface™ (JNDI). The JNDI API is the standard API for naming and directory access. The JNDI API has two parts: an application-level interface used by the application components to access naming and directory services and a service provider interface to attach a provider of a naming and directory service.

  • JavaMail™. Many Internet applications require the ability to send email notifications, so the J2EE platform includes the JavaMail API along with a JavaMail service provider that allows an application component to send Internet mail. The JavaMail API has two parts: an application-level interface used by the application components to send mail, and a service provider interface used at the J2EE SPI level.

  • JavaBeans™ Activation Framework (JAF). The JavaMail API makes use of the JAF API, so it must be included as well.

Many of the APIs described above provide interoperability with components that are not a part of the J2EE platform, such as external web or CORBA services. Figure J2EE.2-2 illustrates the interoperability facilities of the J2EE platform. (The directions of the arrows indicate the client/server relationships of the components.)

Figure J2EE.2-2. J2EE Interoperability


J2EE.2.2 Product Requirements

This specification doesn't require that a J2EE product be implemented by a single program, a single server, or even a single machine. In general, this specification doesn't describe the partitioning of services or functions between machines, servers, processes, etc. As long as the requirements in this specification are met, J2EE product providers can partition the functionality however they see fit. A J2EE product must be able to deploy application components that execute with the semantics described by this specification.

A very simple J2EE product might be provided as a single Java virtual machine that supports applets, web components, and enterprise beans simultaneously in one container (although this would be an extreme, and probably rare, case), and application clients each in their own container. A typical low end J2EE product will support applets in one of the popular browsers, application clients each in their own Java virtual machine, and will provide a single server that supports both web components and enterprise beans. A high end J2EE product might split the server components into multiple servers, each of which can be distributed and load-balanced across a collection of machines. This specification does not prescribe or preclude any of these configurations.

In addition, this specification does not describe which of the components that make up a J2EE product must be packaged together in a single product. A vendor of a fully integrated J2EE product might provide a complete package that includes all the software required to provide the J2EE services as well as the underlying operating system and even hardware. A more typical J2EE product provider might provide a middleware application server along with components that allow the server to integrate with products from other vendors (e.g., a database, a web server) to provide the complete J2EE product. Some vendors may require that the end customer purchase and integrate significant additional components to create a J2EE product. This specification does not prescribe or preclude any of these approaches. In all cases, it is the responsibility of the J2EE product provider to describe to the customer exactly what to do to create an environment that is J2EE-compatible.

A wide variety of J2EE product configurations and implementations, all of which meet the requirements of this specification, are possible. A portable J2EE application will function correctly when successfully deployed in any of these products.


J2EE.2.3 Product Extensions

This specification describes a minimum set of facilities that all J2EE products must provide. Most J2EE products will provide facilities beyond the minimum required by this specification. This specification includes only a few limits to the ability of a product to provide extensions. In particular, it includes the same restrictions as J2SE on extensions to Java APIs. A J2EE product may not add classes to the Java programming language packages included in this specification, and may not add methods or otherwise alter the signatures of the specified classes.

However, many other extensions are possible. A J2EE product may provide additional Java APIs, either other Java standard extensions or other (appropriately named) packages. A J2EE product may include support for additional protocols or services not specified here. A J2EE product may support applications written in other languages, or may support connectivity to other platforms or applications.

Of course, portable applications will not make use of any platform extensions. Applications that do make use of facilities not required by this specification will be less portable. Depending on the facility used, the loss of portability may be minor or it may be significant. The Java 2 Platform, Enterprise Edition Application Programming Model [1] will help application developers construct portable applications, and will contain advice on how best to manage the use of non-portable code when the use of such facilities is necessary.

[1] Available at http://java.sun.com/j2ee/apm

In addition, we expect J2EE products to vary widely, and in fact compete, on various quality of service aspects. Different products will provide different levels of performance, scalability, robustness, availability, security, etc. In some cases this specification describes minimum required levels of service. Future versions of this specification may allow applications to describe their requirements in these areas.


J2EE.2.4 Platform Roles

This section describes typical Java 2 Platform, Enterprise Edition roles. Although these roles are considered to be typical, an organization could use slightly different roles to match that organization's actual application development and deployment workflow.

The following sections describe the roles in greater detail. Subsets of some of these roles are defined in the EJB, JSP, and servlet specifications.

J2EE.2.4.1 J2EE Product Provider

A J2EE product provider, typically an operating system vendor, database system vendor, application server vendor, or a web server vendor, implements a J2EE product providing the component containers, J2EE platform APIs, and other features defined in this specification. A J2EE product provider must provide the J2EE APIs to the application components through the containers. A product provider frequently bases an implementation on an existing infrastructure.

A J2EE product provider must provide the mapping of the application components to the network protocols as specified by this specification. A J2EE product is free to implement the interfaces that are not specified by this specification in an implementation-specific way.

A J2EE product provider must provide application deployment and management tools. Deployment tools enable a deployer (see Section J2EE.2.4.4, "Deployer") to deploy application components on the J2EE product. Management tools allow a system administrator (see Section J2EE.2.4.5, "System Administrator" ) to manage the J2EE product and the applications deployed on the J2EE product. The form of these tools is not prescribed by this specification.

J2EE.2.4.2 Application Component Provider

There are multiple roles for application component providers, including HTML document designers, document programmers, enterprise bean developers, etc. These roles use tools to produce J2EE applications and components.

J2EE.2.4.3 Application Assembler

The application assembler takes a set of components developed by application component providers and assembles them into a complete J2EE application delivered in the form of an enterprise archive (.ear) file. The application assembler will generally use GUI tools provided by either a platform provider or tool provider. The application assembler is responsible for providing assembly instructions describing external dependencies of the application that the deployer must resolve in the deployment process.

J2EE.2.4.4 Deployer

The deployer, an expert in a specific operational environment, is responsible for deploying web applications and Enterprise JavaBeans components into that environment. The deployer uses tools supplied by the J2EE product provider to perform the deployment tasks. The deployment process is typically a three-stage process:

  1. Installation: Moves the media to the server, generates the additional container-specific classes and interfaces that enable the container to manage the application components at runtime, and installs the application components and additional classes and interfaces into the J2EE containers.

  2. Configuration: Resolves all the external dependencies declared by the application component provider and follows the application assembly instructions defined by the application assembler. For example, the deployer is responsible for mapping the security roles defined by the application assembler to the user groups and accounts that exist in the operational environment into which the application components are deployed.

  3. Execution: Starts up the newly installed and configured application.

In some cases, a qualified deployer may customize the business logic of the application's components at deployment time by using tools provided with a J2EE product to write relatively simple application code that wraps an enterprise bean's business methods, or to customize the appearance of a JSP page, for example.

The deployer's output is web applications, enterprise beans, applets, and application clients that have been customized for the target operational environment and are deployed in a specific J2EE container.

J2EE.2.4.5 System Administrator

The system administrator is responsible for the configuration and administration of the enterprise's computing and networking infrastructure. The system administrator is also responsible for overseeing the runtime well-being of the deployed J2EE applications. The system administrator typically uses runtime monitoring and management tools provided by the J2EE product provider to accomplish these tasks.

J2EE.2.4.6 Tool Provider

A tool provider provides tools used for the development and packaging of application components. A variety of tools are anticipated, corresponding to the many application component types supported by the J2EE platform. Platform-independent tools can be used for all phases of development up to the deployment of an application. Platform-dependent tools are used for deployment, management, and monitoring of applications. Future versions of this specification may define more interfaces that allow such tools to be platform independent.


J2EE.2.5 Platform Contracts

This section describes the Java 2 Platform, Enterprise Edition contracts that must be fulfilled by the J2EE product provider.

J2EE.2.5.1 J2EE API

The J2EE API defines the contract between the J2EE application components and the J2EE platform. The contract specifies both the runtime and deployment interfaces.

The J2EE product provider has the obligation to implement the J2EE APIs in a way that supports the semantics and policies described in this specification. The application component provider has the obligation to provide components that will conform to these APIs and policies.

J2EE.2.5.2 Network Protocols

This specification defines the mapping of the application components to industry-standard network protocols. The mapping allows client access to the application components from systems that have not installed J2EE product specific technology. See Chapter J2EE.7, "Interoperability," for details on the network protocol support required for interoperability.

The J2EE product provider is required to publish the installed application components on the industry-standard protocols. This specification defines the mapping of servlets and JSP pages to the HTTP and HTTPS protocols, and the (optional) mapping of EJB to IIOP. A future version of this specification will require that enterprise beans be accessible through the IIOP protocol.

J2EE.2.5.3 Deployment Descriptors

Deployment descriptors are used to communicate the needs of application components to the deployer. The deployment descriptor is a contract between the application component provider or assembler and the deployer. The application component provider or assembler is required to specify the application component's external resource requirements, security requirements, environment parameters, etc. in the component's deployment descriptor. The J2EE product provider is required to provide a deployment tool that interprets the J2EE deployment descriptors and allows the deployer to map the application component's requirements to the capabilities of a specific J2EE product and environment.


Chapter J2EE.3. Security

This chapter describes the security requirements for the Java™ 2 Platform, Enterprise Edition (J2EE).

The J2EE product provider is responsible for determining the level of security and security assurances afforded by their implementation. However, a J2EE product provider is required to satisfy the requirements specified in this chapter.


J2EE.3.1 Introduction

An enterprise contains many resources that can be accessed by many users. Sensitive information often traverses unprotected open networks (such as the Internet). In such an environment, almost every enterprise has security requirements and specific mechanisms and infrastructure to meet them. Although the quality assurances and implementation details may vary, they all share some of the following characteristics:

  • Authentication: The means by which communicating entities prove to one another that they are acting on behalf of specific identities (e.g., client to server and/or server to client).

  • Access control for resources: The means by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.

  • Data integrity: The means used to prove that information could not have been modified by a third party (some entity other than the source of the information). For example, a recipient of data sent over an open network must be able to detect and discard messages that were modified after they were sent.

  • Confidentiality or data privacy: The means used to ensure that information is made available only to users who are authorized to access it.

  • Non-repudiation: The means used to prove that a user performed some action such that the user cannot reasonably deny having done so.

  • Auditing: The means used to capture a tamper-resistant record of security related events for the purpose of being able to evaluate the effectiveness of security policies and mechanisms.

This chapter specifies how the J2EE platform addresses some of these security requirements, and identifies those requirements left to be addressed by J2EE product providers. Issues being considered for future versions of this specification are briefly mentioned in Section J2EE.3.7, "Future Directions."


J2EE.3.2 A Simple Example

The security behavior of a J2EE environment may be better understood by examining what happens in a simple application with a web client, JSP page user interface, and enterprise bean business logic. We include here a descriptive example; this example is not meant to specify requirements. In this example, the web client relies on the web server to act as its authentication proxy by collecting user authentication data from the client and using it to establish an authenticated session.

Step 1. Initial Request

The web client requests the main application URL, shown in Figure J2EE.3-1.

Figure J2EE.3-1. Initial Request

Since this client has not yet authenticated itself to the application environment, the server responsible for delivering the web portion of the application (hereafter referred to as "web server") detects this and invokes the appropriate authentication mechanism for this resource.

Step 2. Initial Authentication

The web server returns a form that the web client uses to collect authentication data (e.g., username and password) from the user. The web client forwards the authentication data to the web server, where it is validated by the web server, as shown in Figure J2EE.3-2.

Figure J2EE.3-2. Initial Authentication

This validation mechanism could be local to the server, or it could leverage the underlying security services. The web server then sets a credential for the user.

Step 3. URL Authorization

The web server determines if the user whose identity is captured in the credential is authorized to access the resource represented by the URL. The web server performs the authorization decision by consulting the security policy (derived from the deployment descriptor) associated with the web resource to determine the security roles that are permitted access to the resource. The web container then tests the user's credentials against each role to determine if it can map the user to the role. Figure J2EE.3-3 shows this process.

Figure J2EE.3-3. URL Authorization

The evaluation stops with an "is authorized" outcome on the first role that the web container is able to map the user to. A "not authorized" outcome is reached if the web container is unable to map the user to any of the permitted roles.

Step 4. Fulfilling the Original Request

If the user is authorized, the web server returns the result of the original URL request, as shown in Figure J2EE.3-4.

Figure J2EE.3-4. Fulfilling the Original Request

In this case, the response of a JSP page is returned. Next, the user performs some action (perhaps posting form data) that needs to be handled by the business logic component of the application.

Step 5. Invoking Enterprise Bean Business Methods

When the JSP page performs the remote method call to the enterprise bean, the user's credential is used to establish (as shown in Figure J2EE.3-5) a secure association between the JSP page and the enterprise bean. The association is implemented as two related security contexts, one in the web server and one in the EJB container.

Figure J2EE.3-5. Invoking an Enterprise Bean Business Method

The EJB container is responsible for enforcing access control on the enterprise bean method; it does so by consulting the security policy (derived from the deployment descriptor) associated with the enterprise bean to determine the security roles that are permitted access to the method. Then for each role, the EJB container will use the security context associated with the call to determine if it can map the caller to the role. The evaluation stops with an "is authorized" outcome on the first role that the EJB container is able to map to the caller. A "not authorized" outcome is reached if the container is unable to map the caller to any of the permitted roles and results in an exception being thrown by the container, and propagated back to the caller (in this case the JSP page). If the call "is authorized," the container dispatches control to the enterprise bean method, which then returns a result to the caller.

The platform provides two sets of methods for use by security aware applications: the EJBContext methods isCallerInRole and getCallerPrincipal available to enterprise beans through the EJB container, and the HttpServletRequest methods isUserInRole and getUserPrincipal available to servlets and JSP pages through the web container. When an enterprise bean calls the isCallerInRole method, the enterprise bean container determines if the caller (as represented by the security context) is in the specified role. When an enterprise bean calls the getCallerPrincipal method, the enterprise bean container returns the principal associated with the security context. The web container APIs behave similarly.


J2EE.3.3 Security Architecture

This section describes the J2EE security architecture on which the security requirements defined by this specification are based.

J2EE.3.3.1 Goals

  1. Portability: The J2EE security architecture must support the Write Once, Run Anywhere™ application property.

  2. Transparency: Application component providers should not have to know anything about security to write an application.

  3. Isolation: The J2EE platform will perform authentication and access control, and its ability to do so will be established by the deployer and managed by the system administrator.

    By divorcing responsibility for security from the application, this specification ensures greater portability of J2EE applications.

  4. Extensibility: The use of platform services by security aware applications must not compromise application portability. For applications that need access to information available in the security environment, this specification provides APIs in the component programming model for the purpose of interacting with container/server security information. Applications that restrict their interactions to the provided APIs should retain portability.

  5. Flexibility: Mechanisms and declarations of security properties of applications should not impose a particular security policy, but facilitate the implementation of security policies specific to the particular J2EE installation.

  6. Abstraction: A component's security requirements are logically specified using deployment descriptors. Security roles and access requirements are mapped into environment specific security roles, users, and policies. A deployer may choose to modify the security properties to be consistent with the deployment environment. The deployment descriptor should document which parameters can be modified and which should not.

  7. Independence: Required security behaviors and deployment contracts should be implementable using a variety of popular security technologies.

  8. Compatibility testing: The J2EE security requirements architecture must be expressed in a manner that allows for an unambiguous determination of whether or not an implementation is compatible.

J2EE.3.3.2 Non Goals

  1. This specification does not dictate a specific security policy. Security policy for applications and for enterprise information systems varies for many reasons. This specification allows product providers to provide people the technology to implement and administer the policies they require.

  2. This specification does not mandate a specific security technology, such as Kerberos, PK, NIS+, NTLM, etc.

  3. This specification does not require that the J2EE security behaviors be universally implementable (i.e., using any or all security technologies).

  4. This specification does not afford any warranty or assurance of the effective security of a J2EE product.

  5. This specification does not require support for secure interactions between enterprise beans running on different but compatible J2EE products. (We expect this to be a goal of the next version of this specification.)

J2EE.3.3.3 Terminology

This section introduces the terminology that is used to describe the security requirements of the J2EE platform.

Principal

A principal is an entity that can be authenticated by an authentication protocol in a security service that is deployed in an enterprise. A principal is identified using a principal name and authenticated using authentication data. The content and format of the principal name and the authentication data depend upon the authentication protocol.

Security Policy Domain

A security policy domain (referred to as security domain) is a scope over which security policies are defined and enforced by a security administrator of the security service. A security policy domain is also sometimes referred to as a realm. This specification uses the term security policy domain or security domain.

Security Technology Domain

A security technology domain is the scope over which the same security mechanism (e.g., Kerberos) is used to enforce a security policy. A single security technology domain may include multiple security policy domains, for example.

Security Attributes

A set of security attributes is associated with every principal. The security attributes have many uses (e.g., access to protected resources, auditing of users, etc.). Security attributes can be associated with a principal by an authentication protocol and/or by the J2EE product provider.

The J2EE platform does not specify the security attributes that can be associated with a principal.

Credential

A credential might contain or reference information (security attributes) that can authenticate a principal to additional services. A principal acquires a credential upon authentication or from another principal that allows its credential to be used (delegation).

This specification does not specify the contents or the format of a credential, because both can vary widely.

J2EE.3.3.4 Container Based Security

To achieve the goals for security in a J2EE environment, security for components is provided by their containers. A container provides security in two forms:

  • Declarative security

  • Programmatic security

J2EE.3.3.5 Declarative Security

Declarative security refers to the means of expressing an application's security structure, including security roles, access control, and authentication requirements in a form external to the application. The deployment descriptor is the primary vehicle for declarative security in the J2EE platform.

A deployment descriptor is a contract between an application component provider and a deployer or application assembler. In the context of J2EE security, it can be used by an application programmer to represent an application's security related environmental requirements. Groups of components are associated with a deployment descriptor.

The application's logical security requirements are mapped by a deployer to a representation of the security policy that is specific to the environment at deployment time. A deployer uses a deployment tool to process the deployment descriptor.

At runtime, the container uses the security policy that was derived from the deployment descriptor and configured by the deployer to enforce authorization (see Section J2EE.3.3.8, "Authorization Model").

J2EE.3.3.6 Programmatic Security

Programmatic security is used by security aware applications. Programmatic security is useful when declarative security alone is not sufficient to express the security model of the application. Programmatic security consists of two methods of the EJB EJBContext interface and two methods of the servlet HttpServletRequest interface:

  • isCallerInRole (EJBContext)

  • getCallerPrincipal (EJBContext)

  • isUserInRole (HttpServletRequest)

  • getUserPrincipal (HttpServletRequest)

These methods allow components to make business logic decisions based on the security role of the caller or remote user. They also allow the component to determine the principal name of the caller or remote user to use as a database key, for example. (Note that the form and content of principal names will vary widely between products and enterprises, and portable components will not depend on the actual contents of a principal name.)

J2EE.3.3.7 Distributed Security

Some product providers may produce J2EE products in which the containers for various component types are distributed. In a distributed environment, communication between J2EE components can be subject to security attacks (for example, data modification and replay attacks).

Such threats can be countered by using a secure association to secure communications. A secure association is shared security state information which permits secure communication between two components. Establishing a secure association could involve several steps such as:

  1. Authenticating the target principal to the client and/or authenticating the client to the target principal

  2. Negotiating a quality of protection, such as confidentiality or integrity

  3. Establishing a security context between the components

Since a container provides security in J2EE, secure associations for a component are typically established by a container. Secure associations for web access are specified here. This specification does not specify how or when such secure associations are formed for access to enterprise beans.

A J2EE product provider may allow control over the quality of protection or other aspects of secure association at deployment time. These aspects depend upon the application and are essentially application requirements. Applications can specify their quality of protection requirements for access to web resources using elements in their deployment descriptor. This specification does not define any mechanisms that an application component provider can use to communicate an enterprise bean's requirements for secure associations.

J2EE.3.3.8 Authorization Model

The J2EE authorization model is based on the concept of security roles. A security role is a logical grouping of users that is defined by an application component pro-vider or assembler. It is then mapped by a deployer to security identities (e.g., principals, groups, etc.) in the operational environment. A security role can be used either with declarative security or with programmatic security.

Declarative authorization can be used to control access to an enterprise bean method and is specified in the deployment descriptor. An enterprise bean method can be associated with a method-permission element in the deployment descriptor. The method-permission element contains a list of methods that can be accessed by a given security role. If the calling principal is in one of the security roles allowed access to a method, the principal is allowed to execute the method. Conversely, if the calling principal is in none of the roles, the caller is not allowed to execute the method. Access to web resources can be protected in a similar manner.

A security role can be used in the EJBContext method isCallerInRole and the HttpServletRequest method isUserInRole. Each method returns true if the calling principal is in the specified security role.

J2EE.3.3.9 Role Mapping

Enforcement of either programmatic or declarative security depends upon determining if the principal associated with an incoming request of an enterprise bean or web resource is in a given security role or not. A container makes this determination based on the security attributes of the calling principal. For example,

  1. A deployer could have mapped a security role to a user group in the operational environment. In this case, the user group to which the calling principal belongs is retrieved from its security attributes. If the principal's user group matches the user group in the operational environment that the security role has been mapped to, the principal is in the security role.

  2. A deployer could have mapped a security role to a principal name in a security policy domain. In this case, the principal name of the calling principal is retrieved from its security attributes. If this principal is the same as the principal name to which the security role was mapped, the calling principal is in the security role.

The source of security attributes may vary across implementations of the J2EE platform. Security attributes could have been transmitted in the calling principal's credential or in the security context. If security attributes are not transmitted, they may be retrieved from a trusted third party such as a directory service or security service.

J2EE.3.3.10 HTTP Login Gateways

Secure interoperability between enterprise beans in different security policy domains is not addressed in this specification. A future version will specify an interoperability protocol (based on industry standards) that will allow EJB containers in different domains to interoperate securely.

To gain access to another J2EE product that may be incompatible (i.e., in terms of communications protocols, security technology, or policy domain), a component may choose to log in to a foreign server via HTTP. HTTP over SSL can be used to provide secure, interoperable communication between J2EE products from different providers. An application component can be configured to use SSL mutual authentication when accessing a remote resource using HTTP. Applications using HTTP in this way may want to exchange data using XML or some other structured format, rather than HTML.

We call this use of HTTP with SSL mutual authentication to access a remote service an HTTP Login Gateway. Requirements in this area are specified in Section J2EE.3.4.1, "Web Clients."

J2EE.3.3.11 User Authentication

User authentication is the process by which a user proves his or her identity to the system. This authenticated identity is then used to perform authorization decisions for accessing J2EE application components. An end user can authenticate using either of the two supported client types:

  • Web client

  • Application client

J2EE.3.3.11.1 Web Client

A web client can authenticate a user to a web server using one of the following mechanisms:

  • HTTP basic authentication

  • HTTPS client authentication

  • Form based authentication

HTTP digest authentication is not widely supported by web browsers and hence is not required.

The deployer or system administrator determines which method to apply to an application or groups of applications. A web client can employ a web server as its authentication proxy. In this case, the client's credentials are established for the client in the server, where they may be used by the server to perform authorization decisions, to act as the client in calls to enterprise beans, or to negotiate secure associations with resources.

Current web browsers commonly rely on proxy authentication.

HTTP Basic Authentication HTTP basic authentication is the authentication mechanism supported by the HTTP protocol. This mechanism is based on a username and password. A web server requests a web client to authenticate the user. As part of the request, the web server passes the realm in which the user is to be authenticated. The web client obtains the username and the password from the user and transmits them to the web server. The web server then authenticates the user in the specified realm (referred to as HTTP Realm in this document).

HTTP basic authentication is not secure. Passwords are sent with a simple base64 encoding. The target server is not authenticated. Additional protection can be applied to overcome these weaknesses. For example, the password may be protected by applying security at the transport layer (e.g., HTTPS) or at the network layer (e.g., IPSEC or VPN).

Despite its limitations, the HTTP basic authentication mechanism is included in this specification because it is widely used in many form based applications.

HTTPS Authentication End user authentication using HTTPS (HTTP over SSL) is a strong authentication mechanism. This mechanism requires the user to possess a public key certificate (PKC). Currently, PKC is rarely used by end users on the Internet. However, it is useful in e-commerce applications and also for single signon from within the browser. For these reasons, it is a required feature of the J2EE platform.

Form Based Authentication The look and feel of the "login screen" cannot be controlled with the web browser's built-in authentication mechanisms. This specification introduces the ability to package a standard HTML or servlet/JSP based form for logging in. The login form allows customization of the user interface. The form based authentication mechanism is described in the servlet specification.

Web Single Signon HTTP is a stateless protocol. However, many web applications need support for sessions that can maintain state across multiple requests from a client. Therefore, it is desirable to:

  1. Make login mechanisms and policies a property of the environment the web application is deployed in.

  2. Be able to use the same login session to represent a user to all the applications that they access.

  3. Require the user to re-authenticate only when crossing a security policy domain.

Credentials that are acquired through a web login process are associated with the session. The container uses these credentials to establish a security context for the session. The container uses the security context to determine authorization for access to web resources and for the establishment of secure associations with other components or with enterprise beans.

Login Session In the J2EE platform, session support is provided by a servlet container. When a user successfully authenticates with a web server, the container establishes a login session context for the user. The login session contains the credentials associated with the user. [1]

[1] This is true where the client is stateless with respect to authentication, and as such, requires that the server act as its proxy and maintain its login context. In this case login session state is made available for use by the client by giving the client a reference (to use with its requests) to its authentication state stored on the server. Cookies or URL rewriting are used to carry such references. If SSL mutual authentication is used as the authentication protocol, the client can manage its own authentication context, and need not depend on references.

J2EE.3.3.11.2 Application Client

Application clients (described in detail in Chapter J2EE.9) are client programs that may directly (i.e., without the help of a web browser and without traversing a web server) interact with enterprise beans. Of course, application clients may also access web resources.

Application clients, like the other J2EE application component types, execute in a managed environment that is provided by an appropriate container. Application clients are expected to have access to a graphical display and input device and can expect to communicate with a human user.

Application clients are used to authenticate the end user to the J2EE platform, for instance when accessing protected web resources or enterprise beans.

J2EE.3.3.11.3 Lazy Authentication

There is a cost associated with authentication. For example, an authentication process may require exchanging multiple messages across the network. Therefore, it is desirable to perform authentication only when necessary (i.e., lazy authentication). With lazy authentication, an end user is not required to authenticate until the user tries to access a protected resource.

Lazy authentication can be used by first tier clients (applets, application clients) when they access protected resources that require authentication. When a user tries to access such a resource, the user can be asked to provide the needed authentication data. If a user is successfully authenticated, they are allowed to access the resource.


J2EE.3.4 User Authentication Requirements

J2EE.3.4.1 Web Clients

The J2EE product provider must support several methods of web based user authentication.

J2EE.3.4.1.1 Web Single Signon

All J2EE compatible web servers must support single signon by maintaining a login session for each web user. This allows applications to remain independent of the details of implementing and securing login information. This also provides the J2EE product provider with the flexibility to choose authentication mechanisms independent of the applications secured by these mechanisms. It must be possible for one login session to span more than one application, allowing a user to log in once and access multiple applications.

J2EE.3.4.1.2 Login Sessions

All J2EE products must support login sessions as described in the servlet specification.

Lazy authentication must be supported by web servers for protected web resources. If authentication is required, then one of the three required login mechanisms listed in the next section may be used.

J2EE.3.4.1.3 Required Login Mechanisms

All J2EE products are required to support three login mechanisms: HTTP basic authentication, SSL mutual authentication, and form-based login. An application is not required to use any of these mechanisms, but they are required to be available for any application's use.

HTTP Basic Authentication All J2EE products are required to support HTTP basic authentication (RFC2068). Platform Providers are also required to support basic authentication over SSL.

SSL Mutual Authentication SSL 3.0 [2] and the means to perform mutual (client and server) certificate based authentication are required by this specification.

[2] The SSL 3.0 specification is available at: http://home.netscape.com/eng/ssl3

All J2EE products must support the following cipher suites to ensure interoperable authentication with clients:

  • SSL_RSA_EXPORT_WITH_RC4_40_MD5

  • SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA

These cipher suites are supported by the major web browsers and meet the U.S. government export restrictions.

Form Based Login The web application deployment descriptor contains an element that causes a J2EE product to associate an HTML form resource (perhaps dynamically generated) with the web application. If the deployer chooses this form of authentication (over HTTP basic, or SSL certificate based authentication), this form must be used as the user interface for login to the application.

The form based login mechanism and web application deployment descriptors are described in the Servlet 2.2 specification.

J2EE.3.4.1.4 Unauthenticated Users

Web containers are required to support access to web resources by clients that have not authenticated themselves to the container. This is the common mode of access to web resources on the Internet. A web container reports that no user has been authenticated by returning null from the HttpServletRequest method getUserPrincipal.

The EJB specification requires that the EJBContext method getCallerPrincipal always returns a valid Principal object. It can never return null. However, it's important that components running in a web container be able to call enterprise beans, even when no user has been authenticated in the web container. When a call is made in such a case from a component in a web container to an enterprise bean, a J2EE product must provide a principal for use in the call.

A J2EE product may provide a principal for use by unauthenticated callers using many approaches, including, but not limited to:

  • Always use a single distinguished principal.

  • Use a different distinguished principal per server, or per session, or per application.

  • Allow the deployer or system administrator to choose which principal to use.

This specification does not specify how a J2EE product should choose a principal to represent unauthenticated users, although future versions of this specification may add requirements in this area.

J2EE.3.4.2 Application Clients

To satisfy the authentication and authorization constraints enforced by the enterprise bean containers and web containers, the application client container must authenticate the application user. The techniques used may vary based on the implementation of the application client container and are beyond the control of the application. The application client container may integrate with a J2EE product's authentication system, to provide a single signon capability, or the container may authenticate the user when the application is started. The container may delay authentication until it is necessary to access a protected resource or enterprise bean. If the container needs to interact with the user to gather authentication data, the container must provide an appropriate user interface. In this specification, no mechanism is provided to customize the user authentication interface of individual application clients. In a future version of this specification, application clients will be able to use the Java™ Authentication and Authorization Service APIs to access information about the currently authenticated user, to write portable authentication user interfaces, and to participate in and control the authentication process.

Application clients execute in an environment controlled by a J2SE security manager and are subject to the security permissions defined in Table J2EE.6-2, "J2EE Security Permissions Set." Although this specification does not define the relationship between the operating system identity associated with a running application client and the authenticated user identity, a J2EE product's ability to relate these identities is a fundamental aspect of single signon.

Additional application client requirements are described in Chapter J2EE.9 of this specification.

J2EE.3.4.3 Resource Authentication Requirements

Resources within an enterprise are often deployed in security policy domains that are different from the security policy domain to which the component belongs. Because the authentication mechanisms used to authenticate the caller to resources can vary widely, a J2EE product must provide the ability to authenticate in the security policy domain of the resource.

A product provider must support both of the following:

  1. Specification of the principal and authentication data for a resource by the deployer at deployment time. A J2EE container must authenticate to the resource using the specified principal and authentication data; the application component must not need to provide this data. If the authentication data is stored by a J2EE container, then its confidentiality is the responsibility of the product provider.

  2. Specification of the principal and authentication data for a resource by the application component at runtime using APIs appropriate to the resource. The application may obtain the principal and authentication data through a variety of mechanisms, including receiving them as parameters, obtaining them from the component's environment, etc.


J2EE.3.5 Authorization Requirements

To support the authorization models described in this chapter, the following requirements are imposed on J2EE products.

J2EE.3.5.1 Code Authorization

A J2EE product may restrict the use of certain J2SE classes and methods to secure and insure proper operation of the system. The minimum set of permissions that are required for a J2EE product are defined in Section J2EE.6.2, "Java 2 PlatformStandard Edition (J2SE) Requirements, ." All J2EE products must be capable of deploying application components with exactly these permissions.

A J2EE product provider may choose to enable selective access to resources using the J2SE 1.2 protection model. The mechanism used is J2EE product dependent.

A future version of the J2EE deployment descriptor definition (see Chapter J2EE.8) may make it possible to express any additional permissions that a component needs.

J2EE.3.5.2 Caller Authorization

A J2EE product must enforce the access control rules specified at deployment time (see Section J2EE.3.6, "Deployment Requirements") and more fully described in the EJB and Servlet specifications.

It must be possible to configure a J2EE product so that the propagated caller identity is used in authorization decisions. This is, for all calls to all enterprise beans from a single application within a single J2EE product, the principal name returned by the EJBContext method getCallerPrincipal must be the same as that returned by the first enterprise bean in the call chain. If the first enterprise bean in the call chain is called by a servlet or JSP page, the principal name must be the same as that returned by the HttpServletRequest method getUserPrincipal in the calling servlet or JSP page. (However, if the HttpServletRequest method getUserPrincipal returns null, the principal used in calls to enterprise beans is not specified by this specification, although it must still be possible to configure enterprise beans to be callable by such components.) Note that this does not require delegation of credentials, only identification of the caller. This principal must be the principal used in authorization decisions for access to all enterprise beans in the call chain. The requirements in this paragraph apply only when a J2EE product has been configured to propagate caller identity.

J2EE products may also provide other deployment modes or configuration options in which the original caller identity is not propagated to all components in the call chain. For instance, some enterprise beans may execute with their own identity and corresponding privileges, and that identity may be made available to other enterprise beans that they call.


J2EE.3.6 Deployment Requirements

The deployment descriptor describes the contract between the application component provider or assembler and the deployer. All J2EE products must implement the access control semantics described in the EJB, JSP, and servlet specifications, and provide a means of mapping the deployment descriptor security roles to the actual roles exposed by a J2EE product.

While most J2EE products will allow the deployer to customize the role mappings and change the assignment of roles to methods, all J2EE products must support the ability to deploy applications and components using exactly the mappings and assignments specified in their deployment descriptors.

As described in the EJB specification and the servlet specification, a J2EE product must provide a deployment tool or tools capable of assigning the security roles in deployment descriptors to the entities that are used to determine role membership at authorization time.

Application developers will need to specify (in the application's deployment descriptors) the security requirements of an application in which some components may be accessed by unauthenticated users as well as authenticated users (as described above in Section J2EE.3.4.1.4, "Unauthenticated Users"). Applications express their security requirements in terms of security roles, which the deployer maps to users (principals) in the operational environment at deployment time. An application might define a role representing all authenticated and unauthenticated users and configure some enterprise bean methods to be accessible by this role.

To support such usage, this specification requires that it be possible to map an application defined security role to the universal set of application principals independent of authentication.


J2EE.3.7 Future Directions

J2EE.3.7.1 Interoperability

Secure interoperability for enterprise beans will be an important goal of the next version of the J2EE specification. We expect a future version of this specification to require support for an industry standard interoperability protocol for enterprise beans. We expect this protocol to be based on the CORBA IIOP protocol.

J2EE.3.7.2 Auditing

This specification does not specify requirements for the auditing of security relevant events, nor APIs for application components to generate audit records. A future version of this specification may include such a specification for products that choose to provide auditing.


Chapter J2EE.4. Transaction Management

This chapter describes the transaction management and runtime environment that must be supported by product providers on the Java™ 2 Platform, Enterprise Edition (J2EE).

Product providers must transparently support transactions that span multiple components and transactional resources within a single J2EE product, as described in this chapter. These requirements must be met regardless of whether the J2EE product is implemented as a single process, multiple processes on the same node, or multiple processes on multiple network nodes.


J2EE.4.1 Overview

A J2EE product provider must support a transactional application that is comprised of a combination of servlet or JSP page accessing multiple enterprise beans within a single transaction. Each component may acquire one or more connections to access one or more shared resource managers.

For example, in Figure J2EE.4-1, the call tree starts from a servlet or JSP page accessing multiple enterprise beans, which in turn may access other enterprise beans. The components access resource managers via connections.

Figure J2EE.4-1. Servlets/JSP Pages Accessing Enterprise Beans

The application component provider specifies, using a combination of programmatic and declarative transaction demarcation APIs, how the platform must manage transactions on behalf of the application.

For example, the application may require that all the components in Figure J2EE.4-1 access resources as part of a single transaction. The platform provider must provide the transaction capabilities to support such a scenario.

This specification does not define how the components and the resources are partitioned or distributed within a single J2EE product. In order to achieve the transactional semantics required by the application, the J2EE product provider is free to execute the application components sharing a transaction in the same Java virtual machine, or distribute them across multiple virtual machines.

The rest of this chapter describes the transactional requirements for a J2EE product in more detail.


J2EE.4.2 Requirements

This section defines the transaction support requirements for the J2EE product provider.

J2EE.4.2.1 Web Components

Servlets and JSP pages are allowed to demarcate transactions using the javax.transaction.UserTransaction interface, defined in the JTA specification. These web components are allowed to access multiple resource managers and invoke multiple enterprise beans within a single transaction. The web component assumes that the transaction is automatically propagated to the enterprise beans (subject to the enterprise bean transaction attributes, e.g., such beans must use container managed transactions) and transactional resource managers.

The J2EE platform must meet the following requirements:

  • The J2EE platform must provide an object implementing the javax.transaction.UserTransaction interface to both servlets and JSP pages. The platform must publish the UserTransaction object in the Java™ Naming and Directory Interface (JNDI) name space available to web components under the name java:comp/UserTransaction.

  • If a web component invokes an enterprise bean from a thread associated with a JTA transaction, the J2EE platform must propagate the transaction context with the enterprise bean invocation. Whether the target enterprise bean will be invoked in this transaction context or not is determined by the rules defined in the EJB specification.

  • If a web component accesses a transactional resource manager from a thread associated with a JTA transaction, the J2EE platform must ensure that the resource access is included as part of the JTA transaction.

  • If a web component creates a thread, the J2EE platform must ensure that the newly created thread is not associated with any JTA transaction.

The product provider is not required to support import of a transaction context by a web component from its client.

The product provider is not required to support transaction context propagation across multiple web components accessed via an HTTP request. If a web component associated with a transaction makes an HTTP request to another web component, the transaction context is not propagated to the target servlet or page. (The HTTP protocol does not support such transaction context propagation.)

However, when another web component is invoked through the RequestDispatcher interface, any active transaction context must be propagated to the called web component.

A web component may start a transaction only in its service method. A transaction that is started by a servlet or JSP page must be completed before the service method returns. That is, transactions may not span web requests from a client. Returning from the service method with an active transaction context is an error. The web container is required to detect this error and abort the transaction.

There are many subtle and complex interactions between the use of transactional resources, threads, and JDBC connections. To ensure correct operation, web components should obey the following guidelines, and the web container must support at least these usages.

  • JTA transactions should be started and completed only from the thread in which the service method is called. If the web component creates additional threads for any purpose, these threads should not attempt to start JTA transactions.

  • JDBC connections may be acquired and released by a thread other than the service method thread, but should not be shared between threads.

  • JDBC Connection objects should not be stored in static fields.

  • For web components implementing SingleThreadModel, JDBC Connection objects may be stored in class instance fields.

  • For web components not implementing SingleThreadModel, JDBC Connection objects should not be stored in class instance fields, and should be acquired and released within the same invocation of the service method.

  • Enterprise beans may be invoked from any thread used by a web component. Transaction context propagation requirements are described above and in the EJB specification.

J2EE.4.2.2 Enterprise JavaBeans™ Components

The J2EE product provider must implement support for transactions as defined in the EJB specification.

J2EE.4.2.3 Application Clients

The J2EE product provider is not required to provide any transaction management support for application clients.

J2EE.4.2.4 Applet Clients

The J2EE product provider is not required to provide any transactional management support for applets.

J2EE.4.2.5 Transactional JDBC™ Technology Support

A J2EE product must support at least a JDBC technology database as a transaction resource manager. The platform must enable transactional JDBC API access from servlets, JSP pages, and enterprise beans.

It must be possible to access the JDBC technology database from multiple application components within a single transaction. For example, a servlet may wish to start a transaction, access a database, invoke an enterprise bean that accesses the same database as part of the same transaction, and finally commit the transaction.


J2EE.4.3 Transaction Interoperability

J2EE.4.3.1 Multiple J2EE Platform Interoperability

This specification does not require the product provider to implement any particular protocol for transaction interoperability across multiple J2EE products. J2EE compatibility requires interoperability neither among identical J2EE products from the same product provider, nor among heterogeneous J2EE products from multiple product providers.

Note

We recommend that J2EE product providers use RMI-IIOP as the EJB server interoperability protocol, and use the IIOP transaction propagation protocol defined by OMG and described in the OTS specification (and implemented by the Java transaction service), for transaction interoperability. We plan to require RMI-IIOP and the IIOP transaction propagation protocol as the EJB server interoperability protocols in a future release of this specification.

J2EE.4.3.2 Support for Transactional Resource Managers

This specification encourages, but does not require, the product provider to support the javax.transaction.xa.XAResource interface. Such support may be required in a future version of this specification.


J2EE.4.4 System Administration Tools

Although there are no compatibility requirements for system administration capabilities, the J2EE product provider will typically include tools that allow the system administrator to perform the following tasks:

  • Integrate transactional resource managers with the platform.

  • Configure the transaction management parts of the platform.

  • Monitor transactions at runtime.

  • Receive notifications of abnormal transaction processing conditions (such as abnormally high number of transaction rollbacks).


Chapter J2EE.5. Naming

This chapter describes the naming system requirements for the Java™ 2 Platform, Enterprise Edition (J2EE). These requirements are based on features defined in the JNDI specification.

Note

This chapter is largely derived from the EJB 1.1 specification, Chapter SRV.14, "Enterprise Bean Environment."


J2EE.5.1 Overview

The application assembler and deployer should be able to customize an application's business logic without accessing the application's source code.

In addition, ISVs typically develop applications that are, to a large degree, independent from the operational environment in which the application will be deployed. Most applications must access resources and external information. The key issue is how applications can locate the external information without knowledge of how the external information is named and organized in the target operational environment.

This specification defines naming requirements for the J2EE platform that address both of the above issues.

This chapter is organized as follows.

  • Section J2EE.5.2 defines the interfaces that specify and access the application component's naming environment. The section illustrates the use of the application component's naming environment for generic customization of the application component's business logic.

  • SectionJ2EE.5.3 defines the interfaces for obtaining the home interface of an enterprise bean using an EJB reference. An EJB reference is a special entry in the application component's environment.

  • Section J2EE.5.4 defines the interfaces for obtaining a resource factory using a resource factory reference. A resource factory reference is a special entry in the application component's environment.

Only J2EE application clients, enterprise beans, and web components are required to have access to a JNDI naming environment. Only the containers for these application component types must provide the naming environment support described here.

The deployment descriptor entries described here are present in identical form in the deployment descriptor DTDs for each of these application component types. See the corresponding specification of each application component type for the details.


J2EE.5.2 Java Naming and Directory Interface™ (JNDI) Naming Context

The application component's naming environment is a mechanism that allows customization of the application component's business logic during deployment or assembly. The application component's environment allows the application component to be customized without the need to access or change the application component's source code.

The container implements the application component's environment, and provides it to the application component instance as a JNDI naming context. The application component's environment is used as follows:

  1. The application component's business methods access the environment using the JNDI interfaces. The application component provider declares in the deployment descriptor all the environment entries that the application component expects to be provided in its environment at runtime.

  2. The container provides an implementation of the JNDI naming context that stores the application component environment. The container also provides the tools that allow the deployer to create and manage the environment of each application component.

  3. The deployer uses the tools provided by the container to initialize the environment entries that are declared in the application component's deploy-ment descriptor. The deployer can set and modify the values of the environment entries.

  4. The container makes the environment naming context available to the application component instances at runtime. The application component's instances use the JNDI interfaces to obtain the values of the environment entries.

Each application component defines its own set of environment entries. All instances of an application component within the same container share the same environment entries. Application component instances are not allowed to modify the environment at runtime.

Note

Terminology warning: The application component's "environment" should not be confused with the "environment properties" defined in the JNDI documentation. The JNDI environment properties are used to initialize and configure the JNDI naming context itself. The application component's environment is accessed through a JNDI naming context for direct use by the application component.

The following subsections describe the responsibilities of each J2EE role.

J2EE.5.2.1 Application Component Provider's Responsibilities

This section describes the application component provider's view of the application component's environment, and defines his or her responsibilities. It does so in two sections, the first describing API for accessing environment entries, and the second describing syntax for declaring the environment entries.

J2EE.5.2.1.1 Access to Application Component's Environment

An application component instance locates the environment naming context using the JNDI interfaces. An instance creates a javax.naming.InitialContext object by using the constructor with no arguments, and looks up the naming environment via the InitialContext under the name java:comp/env. The application component's environment entries are stored directly in the environment naming context, or in any of its direct or indirect subcontexts.

The value of an environment entry is of the Java programming language type declared by the application component provider in the deployment descriptor.

The following code example illustrates how an application component accesses its environment entries.

public void setTaxInfo(int numberOfExemptions, ...)
       throws InvalidNumberOfExemptionsException {
   ...

   // Obtain the application component's
   // environment naming context.
   Context initCtx = new InitialContext();
   Context myEnv = (Context)initCtx.lookup("java:comp/env");

   // Obtain the maximum number of tax exemptions
   // configured by the Deployer.
   Integer max = (Integer)myEnv.lookup("maxExemptions");

   // Obtain the minimum number of tax exemptions
   // configured by the Deployer.
   Integer min = (Integer)myEnv.lookup("minExemptions");

   // Use the environment entries to customize business logic.
   if (numberOfExeptions > max.intValue() ||
       numberOfExemptions < min.intValue())
          throw new InvalidNumberOfExemptionsException();

   // Get some more environment entries. These environment
   // entries are stored in subcontexts.
   String val1 = (String)myEnv.lookup("foo/name1");
   Boolean val2 = (Boolean)myEnv.lookup("foo/bar/name2");

   // The application component can also
   // lookup using full pathnames.
   Integer val3 = (Integer)
      initCtx.lookup("java:comp/env/name3");
   Integer val4 = (Integer)
      initCtx.lookup("java:comp/env/foo/name4");
   ...
}
J2EE.5.2.1.2 Declaration of Environment Entries

The application component provider must declare all the environment entries accessed from the application component's code. The environment entries are declared using the env-entry elements in the deployment descriptor. Each env-entry element describes a single environment entry. The env-entry element consists of an optional description of the environment entry, the environment entry name relative to the java:comp/env context, the expected Java programming language type of the environment entry value (i.e., the type of the object returned from the JNDI lookup method), and an optional environment entry value.

The environment entry values may be one of the following Java types: String, Byte, Short, Integer, Long, Boolean, Double, and Float.

If the application component provider provides a value for an environment entry, the value can be changed later by the application assembler or deployer. The value must be a string that is valid for the constructor of the specified type that takes a single String parameter.

The following example is the declaration of environment entries used by the application component whose code was illustrated in the previous subsection.

...
<env-entry>
   <description>
          The maximum number of tax exemptions
          allowed to be set.
   </description>
   <env-entry-name>maxExemptions</env-entry-name>
   <env-entry-type>java.lang.Integer</env-entry-type>
   <env-entry-value>15</env-entry-value>
</env-entry>
<env-entry>
   <description>
          The minimum number of tax exemptions
          allowed to be set.
   </description>
   <env-entry-name>minExemptions</env-entry-name>
   <env-entry-type>java.lang.Integer</env-entry-type>
   <env-entry-value>1</env-entry-value>
</env-entry>
<env-entry>
   <env-entry-name>foo/name1</env-entry-name>
   <env-entry-type>java.lang.String</env-entry-type>
   <env-entry-value>value1</env-entry-value>
</env-entry>
<env-entry>
   <env-entry-name>foo/bar/name2</env-entry-name>
   <env-entry-type>java.lang.Boolean</env-entry-type>
   <env-entry-value>true</env-entry-value>
</env-entry>
<env-entry>
   <description>Some description.</description>
   <env-entry-name>name3</env-entry-name>
   <env-entry-type>java.lang.Integer</env-entry-type>
</env-entry>
<env-entry>
   <env-entry-name>foo/name4</env-entry-name>
   <env-entry-type>java.lang.Integer</env-entry-type>
   <env-entry-value>10</env-entry-value>
</env-entry>
...

J2EE.5.2.2 Application Assembler's Responsibilities

The application assembler is allowed to modify the values of the environment entries set by the bean provider, and is allowed to set the values of those environment entries for which the bean provider has not specified any initial values.

J2EE.5.2.3 Deployer's Responsibilities

The deployer must ensure that the values of all the environment entries declared by an application component are set to meaningful values.

The deployer can modify the values of the environment entries that have been previously set by the application component provider and/or application assembler, and must set the values of those environment entries for which no value has been specified.

J2EE.5.2.4 J2EE Product Provider's Responsibilities

The J2EE product provider has the following responsibilities:

  • Provide a deployment tool that allows the deployer to set and modify the values of the application component's environment entries.

  • Implement the java:comp/env environment naming context, and provide it to the application component instances at runtime. The naming context must include all the environment entries declared by the application component provider, with their values supplied in the deployment descriptor or set by the deployer. The environment naming context must allow the deployer to create subcontexts if they are needed by an application component.

  • The container must ensure that the application component instances have only read access to their environment variables. The container must throw the javax.naming.OperationNotSupportedException from all the methods of the javax.naming.Context interface that modify the environment naming context and its subcontexts.


J2EE.5.3 Enterprise JavaBeans™ (EJB) References

This section describes the programming and deployment descriptor interfaces that allow the application component provider to refer to the homes of enterprise beans using "logical" names called EJB references. The EJB references are special entries in the application component's naming environment. The deployer binds the EJB references to the enterprise bean's homes in the target operational environment.

The deployment descriptor also allows the application assembler to link an EJB reference declared in one application component to an enterprise bean contained in an EJB JAR file in the same J2EE application. The link is an instruction to the tools used by the deployer describing the binding of the EJB reference to the home of the specified target enterprise bean.

J2EE.5.3.1 Application Component Provider's Responsibilities

This subsection describes the application component provider's view and responsibilities with respect to EJB references. It does so in two sections, the first describing the API for accessing EJB references, and the second describing the syntax for declaring the EJB references.

J2EE.5.3.1.1 Programming Interfaces for EJB References

The application component provider must use EJB references to locate the home interfaces of enterprise bean as follows.

  • Assign an entry in the application component's environment to the reference. (See Section J2EE.5.3.1.2 for information on how EJB references are declared in the deployment descriptor.)

  • This specification recommends, but does not require, that all references to enterprise beans be organized in the ejb subcontext of the application component's environment (i.e., in the java:comp/env/ejb JNDI context).

  • Look up the home interface of the referenced enterprise bean in the application component's environment using JNDI.

The following example illustrates how an application component uses an EJB reference to locate the home interface of an enterprise bean.

public void changePhoneNumber(...) {
   ...

   // Obtain the default initial JNDI context.
   Context initCtx = new InitialContext();

   // Look up the home interface of the EmployeeRecord
   // enterprise bean in the environment.
   Object result = initCtx.lookup(
      "java:comp/env/ejb/EmplRecord");

   // Convert the result to the proper type.
   EmployeeRecordHome emplRecordHome = (EmployeeRecordHome)
      javax.rmi.PortableRemoteObject.narrow(result,
                EmployeeRecordHome.class);
   ...
}

In the example, the application component provider assigned the environment entry ejb/EmplRecord as the EJB reference name to refer to the home of an enterprise bean.

J2EE.5.3.1.2 Declaration of EJB References

Although the EJB reference is an entry in the application component's environment, the application component provider must not use a env-entry element to declare it. Instead, the application component provider must declare all the EJB references using the ejb-ref elements of the deployment descriptor. This allows the consumer of the application component's JAR file (i.e., the application assembler or deployer) to discover all the EJB references used by the application component.

Each ejb-ref element describes the interface requirements that the referencing application component has for the referenced enterprise bean. The ejb-ref element contains an optional description element and the mandatory ejb-ref-name, ejb-ref-type, home, and remote elements.

The ejb-ref-name element specifies the EJB reference name; its value is the environment entry name used in the application component code. The ejb-ref-type element specifies the expected type of the enterprise bean; its value must be either Entity or Session. The home and remote elements specify the expected Java types of the referenced enterprise bean's home and remote interfaces.

The following example illustrates the declaration of EJB references in the deployment descriptor.

...
<ejb-ref>
   <description>
          This is a reference to the entity bean that
          encapsulates access to employee records.
   </description>
   <ejb-ref-name>ejb/EmplRecord</ejb-ref-name>
   <ejb-ref-type>Entity</ejb-ref-type>
   <home>com.wombat.empl.EmployeeRecordHome</home>
   <remote>com.wombat.empl.EmployeeRecord</remote>
</ejb-ref>

<ejb-ref>
   <ejb-ref-name>ejb/Payroll</ejb-ref-name>
   <ejb-ref-type>Entity</ejb-ref-type>
   <home>com.aardvark.payroll.PayrollHome</home>
   <remote>com.aardvark.payroll.Payroll</remote>
</ejb-ref>

<ejb-ref>
   <ejb-ref-name>ejb/PensionPlan</ejb-ref-name>
   <ejb-ref-type>Session</ejb-ref-type>
   <home>com.wombat.empl.PensionPlanHome</home>
   <remote>com.wombat.empl.PensionPlan</remote>
</ejb-ref>
...

J2EE.5.3.2 Application Assembler's Responsibilities

The application assembler can use the ejb-link element in the deployment descriptor to link an EJB reference to a target enterprise bean. The link will be observed by the deployment tools.

The application assembler specifies the link to an enterprise bean as follows:

  • The application assembler uses the optional ejb-link element of the ejb-ref element of the referencing application component. The value of the ejb-link element is the name of the target enterprise bean. (It is the name defined in the ejb-name element of the target enterprise bean.) The target enterprise bean can be in any EJB JAR file in the same J2EE application as the referencing application component.

  • The application assembler must ensure that the target enterprise bean is type-compatible with the declared EJB reference. This means that the target enterprise bean must be of the type indicated in the ejb-ref-type element, and that the home and remote interfaces of the target enterprise bean must be Java type-compatible with the interfaces declared in the EJB reference.

The following example illustrates the use of the ejb-link element in the deployment descriptor. The enterprise bean reference should be satisfied by the bean named EmployeeRecord. The EmployeeRecord enterprise bean may be packaged in the same module as the component making this reference, or it may be packaged in another module within the same J2EE application as the component making this reference.

...
<ejb-ref>
   <description>
          This is a reference to the entity bean that
          encapsulates access to employee records. It
          has been linked to the entity bean named
          EmployeeRecord in this application.
   </description>
   <ejb-ref-name>ejb/EmplRecord</ejb-ref-name>
   <ejb-ref-type>Entity</ejb-ref-type>
   <home>com.wombat.empl.EmployeeRecordHome</home>
   <remote>com.wombat.empl.EmployeeRecord</remote>
   <ejb-link>EmployeeRecord</ejb-link>
</ejb-ref>
...

J2EE.5.3.3 Deployer's Responsibilities

The deployer is responsible for the following:

  • The deployer must ensure that all the declared EJB references are bound to the homes of enterprise beans that exist in the operational environment. The deployer may use, for example, the JNDI LinkRef mechanism to create a symbolic link to the actual JNDI name of the target enterprise bean's home.

  • The deployer must ensure that the target enterprise bean is type-compatible with the types declared for the EJB reference. This means that the target enterprise bean must be of the type indicated in the ejb-ref-type element, and that the home and remote interfaces of the target enterprise bean must be Java type-compatible with the home and remote interfaces declared in the EJB reference.

  • If an EJB reference declaration includes the ejb-link element, the deployer must bind the enterprise bean reference to the home of the enterprise bean specified as the link's target.

J2EE.5.3.4 J2EE Product Provider's Responsibilities

The J2EE product provider must provide the deployment tools that allow the deployer to perform the tasks described in the previous subsection. The deployment tools provided by the J2EE product provider must be able to process the information supplied in the ejb-ref elements in the deployment descriptor.

At the minimum, the tools must be able to:

  • Preserve the application assembly information in the ejb-link elements by binding an EJB reference to the home interface of the specified target enterprise bean.

  • Inform the deployer of any unresolved EJB references, and allow him or her to resolve an EJB reference by binding it to a specified compatible target enterprise bean.


J2EE.5.4 Resource Factory References

A resource is an object that encapsulates access to a resource manager. A resource factory is an object that is used to create resources. For example, an object that implements the java.sql.Connection interface is a resource that provides access to a database management system, and an object that implements the javax.sql.Data-Source interface is a resource factory.

This section describes the application component programming and deployment descriptor interfaces that allow the application component code to refer to resource factories using logical names called resource factory references. The resource factory references are special entries in the application component's environment. The deployer binds the resource factory references to the actual resource factories that exist in the target operational environment.

Resource factory objects accessed through the naming environment are valid only within the component instance that performed the lookup. See the individual component specifications for additional restrictions that may apply.

J2EE.5.4.1 Application Component Provider's Responsibilities

This subsection describes the application component provider's view of locating resource factories and defines his or her responsibilities. It does so in two sections, the first describing the API for accessing resource factory references, and the second describing the syntax for declaring the factory references.

J2EE.5.4.1.1 Programming Interfaces for Resource Factory References

The application component provider must use resource factory references to obtain resources as follows.

  • Assign an entry in the application component's naming environment to the resource factory reference. (See Section J2EE.5.4.1.2 for information on how resource factory references are declared in the deployment descriptor.)

  • This specification recommends, but does not require, that all resource factory references be organized in the subcontexts of the application component's environment, using a different subcontext for each resource manager type. For example, all JDBC™ DataSource references should be declared in the java:comp/env/jdbc subcontext, all JMS connection factories in the java:comp/env/jms subcontext, all JavaMail connection factories in the java:comp/env/mail subcontext, and all URL connection factories in the java:comp/env/url subcontext.

  • Look up the resource factory object in the application component's environment using the JNDI interface.

  • Invoke the appropriate method on the resource factory method to obtain a resource. The factory method is specific to the resource type. It is possible to obtain multiple resource objects by calling the factory object multiple times.

The application component provider has two choices with respect to dealing with associating a principal with the resource access:

  • Allow the deployer to set up principal mapping or resource signon information. In this case, the application component code invokes a resource factory method that has no security-related parameters.

  • Sign on to the resource from the application component code. In this case, the application component invokes the appropriate resource factory method that takes the signon information as method parameters.

The application component provider uses the res-auth deployment descriptor element to indicate which of the two resource authentication approaches is used.

We expect that the first form (i.e., letting the deployer set up the resource signon information) will be the approach used by most application components.

The following code sample illustrates obtaining a resource.

public void changePhoneNumber(...) {
   ...

   // obtain the initial JNDI context
   Context initCtx = new InitialContext();

   // perform JNDI lookup to obtain resource factory
   javax.sql.DataSource ds = (javax.sql.DataSource)
      initCtx.lookup("java:comp/env/jdbc/EmployeeAppDB");

   // Invoke factory to obtain a resource. The security
   // principal for the resource is not given, and therefore
   // it will be configured by the Deployer.
   java.sql.Connection con = ds.getConnection();
   ...
}
J2EE.5.4.1.2 Declaration of Resource Factory References

Although a resource factory reference is an entry in the application component's environment, the application component provider must not use an env-entry element to declare it.

Instead, the application component provider must declare all the resource factory references in the deployment descriptor using the resource-ref elements. This allows the consumer of the application component's jar file (i.e., the application assembler or deployer) to discover all the resource factory references used by an application component.

Each resource-ref element describes a single resource factory reference. The resource-ref element consists of the description element and the mandatory res-ref-name, res-type, and res-auth elements. The res-ref-name element contains the name of the environment entry used in the application component's code. The res-type element contains the Java type of the resource factory that the application component code expects. The res-auth element indicates whether the application component code performs resource signon programmatically, or whether the container signs on to the resource based on the principal mapping information supplied by the deployer. The application component provider indicates the signon responsibility by setting the value of the res-auth element to Bean or Container.

The type declaration allows the deployer to identify the type of the resource factory.

Note that the indicated type is the Java programming language type of the resource factory, not the type of the resource.

The following example is the declaration of resource references used by the application component illustrated in the previous subsection.

...
<resource-ref>
   <description>
          A data source for the database in which
          the EmployeeService enterprise bean will
          record a log of all transactions.
   </description>
   <res-ref-name>jdbc/EmployeeAppDB</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>
J2EE.5.4.1.3 Standard Resource Factory Types

The application component provider must use the javax.sql.DataSource resource factory type for obtaining JDBC API connections.

The application component provider must use the javax.jms.QueueConnectionFactory or the javax.jms.TopicConnectionFactory for obtaining JMS connections.

The application component provider must use the javax.mail.Session resource factory type for obtaining JavaMail connections.

The application component provider must use the java.net.URL resource factory type for obtaining URL connections.

It is recommended that the application component provider name JDBC API data sources in the java:comp/env/jdbc subcontext, all JMS connection factories in the java:comp/env/jms subcontext, all JavaMail API connection factories in the java:comp/env/mail subcontext, and all URL connection factories in the java:comp/env/url subcontext.

Note

A future version of this specification will add the "connector" mechanism that will allow an application component to use the API described in this section to obtain resource objects that provide access to additional back-end systems.

J2EE.5.4.2 Deployer's Responsibilities

The deployer uses deployment tools to bind the resource factory references to the actual resource factories configured in the target operational environment.

The deployer must perform the following tasks for each resource factory reference declared in the deployment descriptor:

  • Bind the resource factory reference to a resource factory that exists in the operational environment. The deployer may use, for example, the JNDI LinkRef mechanism to create a symbolic link to the actual JNDI name of the resource factory. The resource factory type must be compatible with the type declared in the res-type element.

  • Provide any additional configuration information that the resource manager needs for opening and managing resources. The configuration mechanism is resource manager specific, and is beyond the scope of this specification.

  • If the value of the res-auth element is Container, the deployer is responsible for configuring the signon information for the resource. This is performed in a manner specific to the container and resource manager; it is beyond the scope of this specification.

For example, if principals must be mapped from the security domain and principal realm used at the application component level to the security domain and principal realm of the resource manager, the deployer or system administrator must define the mapping. The mapping is performed in manner specific to the container and resource manager; it is beyond the scope of this specification.

J2EE.5.4.3 J2EE Product Provider's Responsibilities

The J2EE product provider is responsible for the following:

  • Provide the deployment tools that allow the deployer to perform the tasks described in the previous subsection.

  • Provide the implementation of the resource factory classes.

  • If the application component provider set the res-auth of a resource reference to Bean, the container must allow the application component to perform explicit programmatic signon using the resource manager's API.

  • The container must provide tools that allow the deployer to set up resource signon information for the resource manager references whose res-auth element is set to Container. The minimum requirement is that the deployer must be able to specify the user/password information for each resource factory reference declared by the application component, and the container must be able to use the user/password combination for user authentication when obtaining a resource by invoking the resource factory.

Although not required by this specification, we expect that containers will support some form of a single signon mechanism that spans the application server and the resource managers. The container will allow the deployer to set up the resources such that the principal can be propagated (directly or through principal mapping) to a resource manager, if required by the application.

While not required by this specification, most J2EE products will provide the following features:

  • A tool to allow the system administrator to add, remove, and configure a resource manager for the J2EE server.

  • A mechanism to pool resources for the application components and otherwise manage the use of resources by the container. The pooling must be transparent to the application components.

J2EE.5.4.4 System Administrator's Responsibilities

The system administrator is typically responsible for the following:

  • Add, remove, and configure resource managers in the J2EE server environment.

In some scenarios, these tasks can be performed by the deployer.


J2EE.5.5 UserTransaction References

Many J2EE application component types are allowed to use the JTA UserTransaction interface to start, commit, and abort transactions. Such application components can find an appropriate object implementing the UserTransaction interface by looking up the JNDI name java:comp/UserTransaction. The container is required to provide java:comp/UserTransaction only for those components that can validly make use of it. Any such UserTransaction object is valid only within the component instance that performed the lookup. See the individual component definitions for further information.

The following example illustrates how an application component acquires and uses a UserTransaction object.

public void updateData(...) {
   ...

   // Obtain the default initial JNDI context.
   Context initCtx = new InitialContext();

   // Look up the UserTransaction object.
   UserTransaction tx = (UserTransaction)initCtx.lookup(
      "java:comp/UserTransaction");

   // Start a transaction.
   tx.begin();
   ...
   // Perform transactional operations on data.
   ...
   // Commit the transaction.
   tx.commit();
   ...
}

J2EE.5.5.1 Application Component Provider's Responsibilities

The application component provider is responsible for using the defined name to look up the UserTransaction object. Only some application component types are required to have access to a UserTransaction object; see Table J2EE.6-1 in this specification and the EJB 1.1 specification for details.

J2EE.5.5.2 Deployer's Responsibilities

The deployer has no specific responsibilities associated with the UserTransaction object.

J2EE.5.5.3 J2EE Product Provider's Responsibilities

The J2EE product provider is responsible for providing an appropriate UserTransaction object as required by this specification.

J2EE.5.5.4 System Administrator's Responsibilities

The system administrator has no specific responsibilities associated with the UserTransaction object.


Chapter J2EE.6. Application Programming Interface

The Java™ 2 Platform, Enterprise Edition (J2EE) provides a number of APIs for use by J2EE applications, starting with the core Java APIs and including several Java standard extensions. This chapter describes the requirements for those APIs.


J2EE.6.1 Required APIs

J2EE application components execute in runtime environments provided by the containers that are a part of the J2EE platform. The J2EE platform supports four separate types of containers, one for each J2EE application component type—application client containers, applet containers, web containers for servlets and JSP pages, and enterprise bean containers. The containers provide all application components with the Java 2 Platform, Standard Edition, v1.2 (J2SE) APIs, which include the following enterprise APIs:

  • JavaIDL API

  • JDBC Core API

The containers for all application component types must provide Java Compatible™ runtime environments. In particular, a J2EE product must provide an applet execution environment that is J2SE 1.2 compatible. Since typical browsers don't yet provide such support, the J2EE platform may make use of the Java Plugin to provide the required applet execution environment. Use of the Java Plugin is not required, but a J2EE product is required to provide a J2SE 1.2 compatible applet execution environment.

The specifications for the J2SE components are available at http://java.sun.com/products/jdk/1.2/docs/.

The J2EE platform also includes a number of Java standard extensions. Table J2EE.6-1 indicates which standard extensions are required to be available in each type of container. Table J2EE.6-1 also indicates the required version of the standard extension.

Table J2EE.6-1. J2EE-Required Java Standard Extensions

Standard Extension

App Client

Applet

Web

EJB

JDBC 2.0 Extension

Y

N

Y

Y

RMI-IIOP 1.0

Y

N

Y

Y

EJB 1.1

Y [a]

N

Y [b]

Y

Servlets 2.2

N

N

Y

N

JSP 1.1

N

N

Y

N

JMS 1.0

Y

N

Y

Y

JNDI 1.2

Y

N

Y

Y

JTA 1.0

N

N

Y

Y

JavaMail 1.1

N

N

Y

Y

JAF 1.0

N

N

Y

Y

[a] Application clients can only make use of the enterprise bean client APIs.

[b] Servlets and JSP pages can only make use of the enterprise bean client APIs.

The APIs included in the J2EE platform must be included in their entirety. Definitions for all classes and interfaces required by the specifications must be included. Some of the APIs include interfaces that are intended to be implemented by an application server. In some cases a J2EE product is not required to provide objects that implement such interfaces. Nonetheless, the definitions of such interfaces must be included in the J2EE platform.


J2EE.6.2 Java 2 Platform, Standard Edition (J2SE) Requirements

J2EE.6.2.1 Programming Restrictions

The J2EE programming model splits the responsibilities between the application component providers and the J2EE product provider. As a result of this split, the application component providers focus on writing business logic and the J2EE product providers focus on providing a managed system infrastructure in which the application components can be deployed. This division of responsibilities requires that the application components do not contain functionality that would clash with the functions provided by the J2EE platform. If an application component tried to provide a function that the J2EE platform implements, the J2EE platform could not properly manage the function.

Thread management is one example of functionality that would clash with the J2EE platform's function. If enterprise beans were allowed to manage threads, the J2EE platform could not manage the life cycle of the enterprise beans, and it could not properly manage transactions.

This means that the application components must not use certain Java 2 Platform, Standard Edition (J2SE) functions. Because we do not want to subset the J2SE platform, and we want a J2SE product to be usable without modification by the J2EE product providers in the J2EE platform, we use the J2SE security permissions mechanism to express the programming restrictions imposed on application component providers. We specify the J2SE security permissions that the J2EE product provider must provide for the execution of each application component type. We call these permissions the J2EE security permissions set. The J2EE security permissions set is part of the J2EE API contract.

Since the exact set of security permissions in use in any installation is a matter of policy, this specification does not define a fixed set of permissions. Instead, the J2EE security permissions set defines the minimum set of permissions that application components should expect. Application components that need permissions not in this minimal set should describe their requirements in their documentation. (A future version of this specification will allow these security requirements to be specified in the deployment descriptor for application components.) All J2EE products must be capable of deploying application components that require the set of permissions described here. Some J2EE products will allow the set of permissions available to a component to be configurable, providing some components with more or fewer permissions than those described here.

From the application component provider's perspective, the provider must ensure that the application components do not use functions that would conflict with the J2EE security permission set.

The J2SE security permissions are fully described in http://java.sun.com/products/jdk/1.2/docs/guide/security/permissions.html.

Table J2EE.6-2 lists the J2EE security permissions set. This is the typical set of permissions that components of each type should expect to have.

Table J2EE.6-2. J2EE Security Permissions Set

Security Permissions

Target

Action

Application Clients

java.awt.AWTPermission

accessClipboard

java.awt.AWTPermission

accessEventQueue

java.awt.AWTPermission

showWindowWithout WarningBanner

java.lang.RuntimePermission

exitVM

java.lang.RuntimePermission

loadLibrary

java.lang.RuntimePermission

queuePrintJob

java.net.SocketPermission

*

connect

java.net.SocketPermission

localhost:1024-

accept,listen

java.io.FilePermission

*

read, write

java.util.PropertyPermission

*

read

Applet Clients

java.net.SocketPermission

codebase

connect

java.util.PropertyPermission

limited

read

Servlets/JSPs

java.lang.RuntimePermission

loadLibrary

java.lang.RuntimePermission

queuePrintJob

java.net.SocketPermission

*

connect

java.io.FilePermission

*

read, write

java.util.PropertyPermission

*

read

EJB Components

java.lang.RuntimePermission

queuePrintJob

java.net.SocketPermission

*

connect

java.util.PropertyPermission

*

read

Note that an operating system that hosts a J2EE product may impose additional security restrictions of its own that must be taken into account. For instance, the user identity under which a servlet executes is not likely to have permission to read and write all files.

J2EE.6.2.2 Additional Requirements

J2EE.6.2.2.1 Networking

The J2SE platform includes a pluggable mechanism for supporting multiple URL protocols through the java.net.URLStreamHandler class and java.net.URLStreamHandlerFactory interface.

The following URL protocols must be supported:

  • file: Only reading from a file URL need be supported, that is, the corresponding URLConnection object's getOutputStream method may fail with an UnknownServiceException. Of course, file access is restricted according to the permissions described above.

  • http: Only version 1.0 of the HTTP protocol need be supported, although HTTP 1.1 is allowed. An http URL must support both input and output.

  • https: SSL version 3.0 must be supported by https URL objects. Both input and output must be supported.

The J2SE platform also includes a mechanism for converting a URL's byte stream to an appropriate object, using the java.net.ContentHandler class and java.net.ContentHandlerFactory interface. A ContentHandler object converts from a MIME byte stream to an object. ContentHandler objects are typically accessed indirectly using the getContent method of URL and URLConnection.

When accessing data of the following MIME types using the getContent method, objects of the corresponding Java type listed in Table J2EE.6-3 must be returned.

Table J2EE.6-3. Java Type of Objects Returned When Using the getContent Method

MIME Type

Java Type

image/gif

java.awt.ImageProducer

image/jpeg

java.awt.ImageProducer

Many environments will use HTTP proxies rather than connecting directly to HTTP servers. If HTTP proxies are being used in the local environment, the HTTP support in the J2SE platform should be configured to use the proxy appropriately; application components must not be required to configure proxy support in order to use an http URL.

Most enterprise environments will include a firewall that limits access from the internal network (intranet) to the public Internet, and vice versa. While it is typical for access using the HTTP protocol to pass through such firewalls, perhaps by using proxy servers, it is not typical that general TCP/IP traffic, including RMI-JRMP, RMI-IIOP, etc., can pass through firewalls. This of course has implications on the use of various protocols to communicate between application components. This specification requires only that, where local policy allows, HTTP access through firewalls be possible. Some J2EE products may provide support for tunneling other communication through firewalls, perhaps using HTTP, but this is neither specified nor required.

J2EE.6.2.2.2 AWT

AWT provides the ability to read binary image data and convert it into a java.awt.image object, using the createImage methods in java.awt.Toolkit. The AWT Toolkit must support binary data in the GIF and JPEG formats.

J2EE.6.2.2.3 JDBC ™ API

The JDBC API allows for access to a wide range of data storage systems. The J2SE platform does not require that a system meeting the Java Compatible™ quality standards provide a database that is accessible through the JDBC API. To allow for the development of portable applications, this specification does require that such a database be available and accessible from a J2EE product through the JDBC API. Such a database must be accessible from web components, enterprise beans, and application clients, but need not be accessible from applets. In addition, the driver for the database must meet the JDBC compatible requirements in the JDBC specification.

J2EE applications should not attempt to load JDBC drivers directly. Instead, they should use the technique recommended in the JDBC specification and perform a JNDI lookup to locate a DataSource object. The JNDI name of the DataSource object should be chosen as described in Section J2EE.5.4, "Resource Factory References." The J2EE platform must be able to supply a DataSource that does not require the application to supply any authentication information when obtaining a database connection. Of course, applications may also supply a user name and password explicitly when connecting to the database.

When a JDBC API connection is used in an enterprise bean, the transaction characteristics will typically be controlled by the container. The component should not attempt to change the transaction characteristics of the connection, commit the transaction, roll back the transaction, or set autocommit mode. Attempts to make changes that are incompatible with the current transaction context may result in a SQLException being thrown. The EJB specification contains the precise rules for enterprise beans.

Similar restrictions apply when a component creates a transaction using the JTA UserTransaction interface. The component should not attempt operations on the JDBC Connection object that would conflict with the transaction context.

Drivers supporting the JDBC API used in a J2EE environment must meet a number of additional requirements on their implementation of JDBC APIs, described below.

  • Drivers are required to provide accurate and complete metadata through the Connection.getMetaData method. J2EE applications should examine the DatabaseMetaData object and adapt their behavior to the capabilities of the current database. How this information is used to create portable applications that are independent of the underlying database vendor and driver is beyond the scope of this specification; see the Java 2 Platform, Enterprise Edition Application Programming Model [1] for additional information.

    [1] Available at http://java.sun.com/j2ee/apm.

  • Drivers must support stored procedures (DatabaseMetaData.supportsStoredProcedures must return true). The driver must also support the full JDBC API escape syntax for calling stored procedures with the following methods on the Statement, PreparedStatement, and CallableStatement classes:

    - executeUpdate

    - executeQuery

    Support for calling stored procedures using the method execute on the Statement, PreparedStatement, and CallableStatement interfaces is not required because some databases don't support returning more than a single ResultSet from a stored procedure.

  • Drivers must support all of the CallableStatement methods that apply to SQL92 types, including the following:

    - getBigDecimal(int parameterIndex)

    - getBoolean

    - getByte

    - getBytes

    - getDate(int parameterIndex)

    - getDate(int parameterIndex, Calendar cal)

    - getDouble(int parameterIndex)

    - getFloat(int parameterIndex)

    - getInt

    - getLong

    - getObject(int parameterIndex)

    - getShort

    - getString

    - getTime(int parameterIndex)

    - getTime(int parameterIndex, Calendar cal)

    - getTimestamp(int parameterIndex)

    - getTimestamp(int parameterIndex, Calendar cal)

    - registerOutParameter(int parameterIndex, int sqlType)

    - registerOutParameter(int parameterIndex, int sqlType, int scale)

    - wasNull()

    Support for the new BLOB, CLOB, ARRAY, REF, STRUCT, and JAVA_OBJECT types is not required. All parameter types (IN, OUT, and INOUT) must be supported.

  • Full support for PreparedStatements is required. This implies support for the following methods:

    - setAsciiStream

    - setBigDecimal

    - setBinaryStream(int parameterIndex, InputStream x, int length)

    - setBoolean

    - setByte

    - setBytes

    - setCharacterStream

    - setDate(int parameterIndex, Date x)

    - setDate(int parameterIndex, Date x, Calendar cal)

    - setDouble

    - setFloat

    - setInt

    - setLong

    - setNull

    - setObject(int parameterIndex, Object x)

    - setObject(int parameterIndex, Object x, int targetSqlType)

    - setObject(int parameterIndex, Object x, int targetSqlType, int scale)

    - setShort

    - setString

    - setTime(int parameterIndex, Time x)

    - setTime(int parameterIndex, Time x, Calendar cal)

    - setTimestamp(int parameterIndex, Timestamp x)

    - setTimestamp(int parameterIndex, Timestamp x, Calendar cal)

    Support for the new BLOB, CLOB, ARRAY, REF, STRUCT and JAVA_OBJECT types is not required. Support for the PreparedStatement method getMetaData is not required. This method must throw an SQLException if it is not supported.

  • Full support for batch updates is required. This implies support for the following methods on the Statement, PreparedStatement, and CallableStatement classes:

    - addBatch

    - clearBatch

    - executeBatch

    Drivers are free to implement these methods any way they choose (including a non-batching implementation) as long as the semantics are correct. The following amendment was added in the JDBC 2.1 core specification, beyond what was in the JDBC 2.0 specification, and defines additional compliant behavior.

The Statement method executeBatch returns an integer array containing one entry for each statement in the batch. The elements are ordered in the same order in which the statements were executed (which is the same as the order in which they were originally added to the batch). For successful execution, an element of the array may have the following values:

  • If the value of an array element is greater than or equal to zero, then the command executed successfully and the value is an update count indicating the number of rows in the database that were effected by the command.

  • A value of –2 indicating that a command executed successfully, but that the number of effected rows is unknown.

In the event that execution of an element of the batch fails, a driver may or may not continue processing the remaining elements of the batch. However, a driver must always provide the same behavior when used with a particular DBMS. For example, a driver cannot continue processing after a failure for one batch, and not continue processing for another batch.

If a driver stops processing after the first failure, the array returned by the BatchUpdateException method getUpdateCounts will always contain fewer elements than were in the batch. Since commands are executed in the same order that they are added to the batch, if the array contained N elements, this means that the first N commands in the batch were processed successfully when the executeBatch method was called.

When a driver continues processing in the presence of failures, the number of elements, N, in the array returned by the BatchUpdateException method getUpdateCounts is always equal to the number of elements in the batch. The following additional array value is returned when a BatchUpdateException is thrown and the driver continues processing after a failure:

  • A value of –3 indicates that the command or element failed to execute successfully. This value is also returned for elements that could not be processed for some reason; such elements fail implicitly.

Drivers that do not continue processing after a failure never return –3 in an update count array. Drivers of this type simply return a status array containing an entry for each command that was processed successfully.

An application can distinguish a driver that continues processing after a failure from one that does not by examining the size of the array returned by the BatchUpdateException method getUpdateCounts. A driver that continues processing always returns an array containing one entry for each element in the batch. A driver that does not continue processing after a failure will always return an array in which the number of entries is less than the number of elements in the batch.

The array returned by the PreparedStatement method executeBatch contains an element for each set of parameters in the batch, similar to the case for Statement. Each element either contains an update count or the generic success indicator (–2).

Error handling in the case of PreparedStatement objects is the same as error handling in the case of Statement objects.

Error handling for the CallableStatement method executeBatch is analogous to PreparedStatement.

Note

JDBC 3.0 will define symbolic constants for the negative array entry values described above. Metadata to allow the exact behavior of a driver to be determined is planned.

  • A driver must provide full support for DatabaseMetaData and ResultSetMetaData. This implies that all of the methods in the DatabaseMetaData interface must be implemented and must behave as specified in the JDBC 1.0 and 2.0 specifications. None of the methods in DatabaseMetaData and ResultSetMetaData may throw an exception because they are not implemented.

  • The JDBC API core specification requires that JDBC compliant drivers provide support for the SQL92, transitional level, DROP TABLE command, full support for the CASCADE and RESTRICT options is required. As many popular databases do not support DROP TABLE as specified in the SQL92 specification, the following clarification is required.

A JDBC 2.1 compliant driver is required to support the DROP TABLE command as specified by the SQL92, transitional level. However, support for the CASCADE and RESTRICT options of DROP TABLE is optional. In addition, the behavior of DROP TABLE is implementation defined when there are views or integrity constraints defined that reference the table that is being dropped.

J2EE.6.2.2.4 Java™IDL

JavaIDL allows applications to access any CORBA object, written in any language, using the standard IIOP protocol. The J2EE security restrictions typically prevent all application component types except application clients from creating and exporting a CORBA object, but all J2EE application component types can be clients of CORBA objects.

J2EE.6.2.2.5 RMI-JRMP

JRMP is the Java technology-specific remote method invocation (RMI) protocol. The J2EE security restrictions typically prevent all application component types except application clients from creating and exporting an RMI object, but all J2EE application component types can be clients of RMI objects.


J2EE.6.3 JDBC™ 2.0 Standard Extension Requirements

The JDBC 2.0 standard extension includes APIs for row sets, connection naming via JNDI, connection pooling, and distributed transaction support. The connection pooling and distributed transaction features are intended for use by JDBC drivers to coordinate with an application server. J2EE products are not required to support the application server facilities described by these APIs, although their use is encouraged. We expect that such a requirement will be added in a future version of this specification, after more vendors have had a chance to implement these features.

The JDBC 2.0 standard extension specification is available at http://java.sun.com/products/jdbc/jdbcse2.html.


J2EE.6.4 RMI-IIOP 1.0 Requirements

RMI-IIOP allows objects defined using RMI style interfaces to be accessed using the IIOP protocol. Enterprise beans may (and in a future release, must) be accessible using RMI-IIOP. All components accessing enterprise beans must use the narrow method of the javax.rmi.PortableRemoteObject class, as described in the EJB specification.

The J2EE security restrictions typically prevent all application component types, except application clients, from creating and exporting an RMI-IIOP object. All J2EE application component types, except applets, can be clients of RMI-IIOP objects. (Some products might also allow applets to use RMI-IIOP, but this capability is not required.)


J2EE.6.5 Enterprise JavaBeans™ (EJB) 1.1 Requirements

This specification requires that a J2EE product provides support for enterprise beans as specified in the EJB 1.1 specification. The EJB 1.1 specification is included in this volume.

This specification does not impose any additional requirements at this time. However, a future version of this specification will require that J2EE products support the use of RMI-IIOP and the EJB CORBA mapping to access enterprise beans, as specified in the Enterprise JavaBeans to CORBA Mapping document available at the above URL.


J2EE.6.6 Servlet 2.2 Requirements

Servlet 2.2 extends Servlet 2.1 with support for the packaging and deployment of web applications, standalone and as part of a J2EE application. Servlet 2.2 also addresses security, both standalone and within the J2EE platform, and provides support for the notion of a web application.

The Servlet 2.2 specification defines distributable web applications. To support J2EE applications that are distributable, this specification adds the following requirements.

A distributable application may only place objects of the following types into a javax.servlet.http.HttpSession object using the setAttribute or putValue methods:

  • java.io.Serializable

  • javax.ejb.EJBObject

  • javax.ejb.EJBHome

  • javax.transaction.UserTransaction

  • a javax.naming.Context object for the java:comp/env context

Web containers may throw an IllegalArgumentException if an object that is not one of the above types is passed to the setAttribute or putValue methods of an HttpSession object corresponding to a distributable session. This exception indicates to the programmer that the web container does not support moving the object between VMs. A web container that supports multi-VM operation must ensure that, when a session is moved from one VM to another, all objects of the above types are accurately recreated on the target VM.

The Servlet 2.2 specification is included in this volume.


J2EE.6.7 JavaServer Pages™ (JSP) 1.1 Requirements

JSP 1.1 depends on and builds on the Servlet 2.2 framework. In addition to supporting the new Servlet 2.2 concepts for JSP pages, JSP 1.1 includes a Tag Extension mechanism that is portable and supports JSP syntax authoring tools.

The JSP 1.1 specification is available at http://java.sun.com/products/jsp.


J2EE.6.8 Java™ Message Service (JMS) 1.0 Requirements

The Java Message Service API definitions must be included in a J2EE product, but the platform is not required to include an implementation of the JMS ConnectionFactory and Destination objects. These are the objects used by an application to access a JMS service provider. A future version of this specification will require that the J2EE platform provide support for both JMS point-to-point and publish/subscribe messaging, and thus must make those facilities available using the ConnectionFactory and Destination APIs.

If an application component's deployment descriptor includes a resource reference to a JMS ConnectionFactory or Destination object, and the product into which the application component is being deployed does not provide a JMS service provider, the deployment tool must warn the deployer that the application component's request cannot be satisfied. The deployer may choose not to deploy the component, or may choose to continue the deployment if it is known that the component can function correctly without the JMS resource being available.

The latest JMS 1.0 specification is version 1.0.2 and is available at http://java.sun.com/products/jms.


J2EE.6.9 Java Naming and Directory Interface™ (JNDI) 1.2 Requirements

A J2EE product must make the following types of objects available in the application visible JNDI namespace—EJBHome objects, JTA UserTransaction objects, JDBC API DataSource objects, and (if JMS is supported) JMS ConnectionFactory and Destination objects. The JNDI implementation in a J2EE product must be capable of supporting all of these uses in a single application component using a single JNDI InitialContext. Application components will generally create a JNDI InitialContext using the default constructor with no arguments. The application component may then perform lookups on that InitialContext to find EJBHome objects, JTA UserTransaction objects, JDBC API DataSource objects, and JMS ConnectionFactory and Destination objects.

The names used to perform lookups for J2EE objects are application-dependent; the application component's deployment descriptor lists all of the names and the type of resource expected to correspond to each name. The deployer configures the JNDI namespace to make appropriate components available. The JNDI names used to look up such resources must be in the JNDI java: namespace. See Chapter J2EE.5, "Naming," for details.

One particular name is defined by this specification. For all application components that have access to the JTA UserTransaction interface, the appropriate UserTransaction object can be found using the name java:comp/UserTransaction.

The name used to look up a particular J2EE object may be different in different application components. In general, JNDI names cannot be meaningfully passed as arguments in remote calls from one application component to another remote component (for example, in a call to an enterprise bean).

The JNDI java: namespace is commonly implemented as symbolic links to other naming systems. Different underlying naming services may be used to store different kinds of objects, or even different instances of objects. It is up to a J2EE product to provide the JNDI service providers necessary to access the various J2EE-defined objects.

Different JNDI service providers may provide different capabilities; for instance, some service providers may provide only read-only access to the data in the name service. This specification requires only that the J2EE platform provide the ability to perform lookup operations as described above.

See Chapter J2EE.5, "Naming," for the complete naming requirements for the J2EE platform.

The JNDI 1.2 specification is available at http://java.sun.com/products/jndi/docs.html.


J2EE.6.10 Java™ Transaction API (JTA) 1.0 Requirements

JTA defines the UserTransaction interface that is used by applications to start and commit or abort transactions. Enterprise beans are expected to get UserTransaction objects through the EJBContext's getUserTransaction method. Other application components get a UserTransaction object through a JNDI lookup using the name java:comp/UserTransaction.

JTA also defines a number of interfaces that would be used by an application server to communicate with a transaction manager, and for a transaction manager to interact with a resource manager. JTA does not architect any method for acquiring an appropriate TransactionManager object, and this specification does not require any objects implementing that interface to be available from the J2EE platform. Similarly, a J2EE product need not support objects that implement the XAResource interface. A future version of this specification may require support for these application server APIs. Of course, support for other distributed transaction facilities may be provided by the platform, transparently to the application.

The latest JTA 1.0 specification is version 1.0.1 and is available at http://java.sun.com/products/jta.


J2EE.6.11 JavaMail™ 1.1 Requirements

The JavaMail API allows for access to e-mail messages contained in message stores, and for the creation and sending of e-mail messages using a message transport. Specific support is included for Internet standard MIME messages. Access to message stores and transports is through protocol providers supporting specific store and transport protocols. The JavaMail API specification does not require any specific protocol providers, but the JavaMail reference implementation includes an IMAP message store provider and an SMTP message transport provider.

Configuration of the JavaMail API is typically done by setting properties in a Properties object that is used to create a javax.mail.Session object using a static factory method. To allow the J2EE platform to configure and manage JavaMail API sessions, an application component that uses the JavaMail API should request a Session object using JNDI, and should list its need for a Session object in its deployment descriptor using a resource-ref element. A JavaMail API Session object should be considered a resource factory, as described in Section J2EE.5.4, "Resource Factory References." This specification requires that the J2EE platform support javax.mail.Session objects as resource factories, as described in that section.

The J2EE platform requires that a message transport be provided that is capable of handling addresses of type javax.mail.internet.InternetAddress and messages of type javax.mail.internet.MimeMessage. The default message transport must be properly configured to send such messages using the send method of the javax.mail.Transport class. Any authentication needed by the default transport must be handled without need for the application to provide a javax.mail.Authenticator or to explicitly connect to the transport and supply authentication information.

This specification does not require that a J2EE product support any message store protocols.

Note that the JavaMail API creates threads to deliver notifications of Store, Folder, and Transport events. The use of these notification facilities may be limited by the restrictions on the use of threads in various containers. In EJB containers, for instance, it is typically not possible to create threads.

The JavaMail API uses the JavaBeans Activation Framework API to support various MIME data types. The JavaMail API must include javax.activation.DataContentHandlers for the following MIME data types, corresponding to the Java programming language type indicated in Table J2EE.6-4.

Table J2EE.6-4. JavaMail API MIME Data Type to Java Type Mappings

MIME Type

Java Type

text/plain

java.lang.String

multipart/*

javax.mail.internet.MimeMultipart

message/rfc822

javax.mail.internet.MimeMessage

The JavaMail 1.1 API specification is available at http://java.sun.com/products/javamail.


J2EE.6.12 JavaBeans™ Activation Framework 1.0 Requirements

The JavaBeans Activation Framework integrates support for MIME data types into the Java platform. MIME byte streams can be converted to and from Java programming language objects, using javax.activation.DataContentHandler objects. JavaBeans components can be specified for operating on MIME data, such as viewing or editing the data. The JavaBeans Activation Framework also provides a mechanism to map filename extensions to MIME types.

The JavaBeans Activation Framework is used by the JavaMail API to handle the data included in e-mail messages; typical applications will not need to use the JavaBeans Activation Framework directly, although applications making sophisticated use of e-mail may need it.

This specification requires that the J2EE platform need only provide the DataContentHandlers specified above for the JavaMail API. This specification requires the J2EE platform to provide a javax.activation.Mimetypes-FileTypeMap that supports the mappings listed in Table J2EE.6-5.

Table J2EE.6-5. Filename Extension to MIME Type Mappings

MIME Type

Filename Extensions

text/html

html htm

text/plain

txt text

image/gif

gif GIF

image/jpeg

jpeg jpg jpe JPG

The JavaBeans Activation Framework 1.0 specification is available at http://java.sun.com/beans/glasgow/jaf.html.


Chapter J2EE.7. Interoperability

This chapter describes the interoperability requirements for the Java™ 2 Platform, Enterprise Edition (J2EE).


J2EE.7.1 Introduction to Interoperability

The J2EE platform will be used by enterprise environments that support clients of many different types. Often, these enterprise environments will add new services to their existing enterprise information systems. These enterprise environments very likely will be using different hardware platforms and various software applications written in different languages.

Enterprise environments may leverage the J2EE platform to bring together applications written in such languages as C++ and Visual Basic. One or more of these existing applications may be running on a personal computer platform, while others may be running on Unix® workstations. In addition, these enterprise environments may also be supporting standalone Java technology-based applications that are not directly supported by the J2EE platform.

The J2EE platform provides indirect support for various types of clients, different hardware platforms, and a multitude of software applications through its interoperability requirements. To an application component provider or system administrator in an enterprise environment, the interoperability features of the J2EE platform permit the underlying disparate systems to work together seamlessly. In addition, the platform hides much of the complexity required to join these pieces.

The interoperability requirements for the current J2EE platform release allow:

  • J2EE applications to connect to legacy systems using CORBA or low-level Socket interfaces.

  • J2EE applications to connect to other J2EE applications across multiple J2EE products. The J2EE products can be from multiple product providers or they can be from the same provider.

This specification allows J2EE applications to connect to EIS or legacy systems. At the current time, these connections may be accomplished using CORBA services or low-level socket interfaces.

In addition, this specification requires that J2EE applications be allowed to connect to other J2EE applications. These other J2EE applications may be running on other J2EE platforms. J2EE applications must also be able to connect and work with J2EE applications written by other application providers. In this version of the specification, interoperability between J2EE applications running in different platforms is accomplished through the HTTP protocol, possibly using SSL.

Future versions of this specification will require interoperability using IIOP to access enterprise beans. See the document Enterprise JavaBeans to CORBA Mapping, available at http://java.sun.com/products/ejb/docs.html for details.


J2EE.7.2 Interoperability Protocols

This specification requires that a J2EE product support a standard set of protocols and formats to ensure interoperability. The specification requires support for the following groups of protocols and formats:

  • Internet protocols

  • OMG protocols

  • RMI protocols

  • Data formats

Many of these protocols and formats are supported by J2SE and by the underlying operating system.

J2EE.7.2.1 Internet Protocols

Internet protocols define the standards by which the different pieces of the platform communicate with each other. The J2EE platform requires support for the following Internet protocols:

  • TCP/IP protocol family— This is the core component of Internet communication. TCP/IP and UDP/IP are the standard transport protocols for the Internet.

  • HTTP 1.0— This is the core protocol of web communication. As with TCP/IP, HTTP 1.0 is supported by J2SE and the underlying operating system. A J2EE web container must be capable of advertising its HTTP services on the standard HTTP port, port 80.

  • SSL 3.0— SSL 3.0 (Secure Socket Layer) represents the security layer for web communication. It is available indirectly when using the https URL as opposed to the http URL. A J2EE web container must be capable of advertising its HTTPS service on the standard HTTPS port, port 443.

J2EE.7.2.2 OMG Protocols

This specification requires the J2EE platform to support the following Object Management Group (OMG) protocol:

  • IIOP (Internet Inter-ORB Protocol)— Supported by Java IDL in J2SE and RMI-IIOP in J2EE. Java IDL provides standards-based interoperability and connectivity through the common object request broker architecture (CORBA). CORBA specifies the object request broker (ORB) which allows applications to communicate with each other regardless of location. This interoperability is delivered through IIOP, and is typically found in an intranet setting.

J2EE.7.2.3 RMI Protocols

This specification requires the J2EE platform to support the JRMP protocol, which is the Java technology-specific remote method invocation (RMI) protocol. JRMP is a distributed object model for the Java programming language. Distributed systems, which run in different address spaces and often on different hosts, must still be able to communicate with each other. RMI permits program-level objects in different address spaces to invoke remote objects using the semantics of the Java programming language object model.

Complete information on the JRMP specification can be found at http://java.sun.com/products/jdk/1.2/docs/guide/rmi.

J2EE.7.2.4 Data Formats

In addition to the protocols that allow communication between components, this specification also requires J2EE platform support for a number of data formats. These formats provide a definition for data that is exchanged between components.

The following data formats must be supported:

  • HTML 3.2— This represents the minimum web standard. It is not directly supported by J2EE APIs. However, it must be able to be displayed by J2EE web clients.

  • Image file formats— The J2EE platform must support both GIF and JPEG images. Support for these formats is provided by the java.awt.image APIs (see the URL: http://java.sun.com/products/jdk/1.2/docs/api/java/awt/image/package-summary.html) and by J2EE web clients.

  • JAR files— JAR (Java archive) files are the standard packaging format for Java technology-based application components, including the EJB JAR specialized format and the (to be specified) J2EE application jar package. JAR is a platform-independent file format that permits many files to be aggregated into one file. This allows multiple Java components to be bundled into one JAR file and downloaded to a browser in a single HTTP transaction. JAR file formats are supported by the java.util.jar and java.util.zip packages. For complete information on the JAR specification, see the URL: http://java.sun.com/products/jdk/1.2/docs/guide/jar.

  • Class file format— The class file format is specified in the Java virtual machine specification. Each class file contains one Java programming language type—either a class or an interface—and consists of a stream of 8-bit bytes. For complete information on the class file format, see the URL: http://java.sun.com/docs/books/vmspec.


Chapter J2EE.8. Application Assembly and Deployment

This chapter specifies Java™ 2 Platform, Enterprise Edition (J2EE) requirements for assembling, packaging, and deploying a J2EE application. The main goal of these requirements is to provide scalable modular application assembly and portable deployment of J2EE applications into any J2EE product.

J2EE applications are composed of one or more J2EE components and one J2EE application deployment descriptor. The deployment descriptor lists the application's components as modules. A J2EE module represents the basic unit of composition of a J2EE application. J2EE modules consist of one or more J2EE components and one component level deployment descriptor. The flexibility and extensibility of the J2EE component model facilitate the packaging and deployment of J2EE components as individual components, component libraries, or J2EE applications.

Figure J2EE.8-1 shows the composition model for J2EE deployment units and includes the optional usage of alternate deployment descriptors by the application package to preserve the signing of the original J2EE modules.

Figure J2EE.8-1. J2EE Deployment


J2EE.8.1 Application Development Life Cycle

The development life cycle of a J2EE application begins with the creation of discrete J2EE components. These components are then packaged with a component level deployment descriptor to create a J2EE module. J2EE modules can be deployed as stand-alone units or can be assembled with a J2EE application deployment descriptor and deployed as a J2EE application.

Figure J2EE.8-2 shows the life cycle of a J2EE application.

Figure J2EE.8-2. J2EE Application Life Cycle

J2EE.8.1.1 Component Creation

The EJB, Servlet, and application client specifications include the XML document type definition (DTD) of the associated component level deployment descriptors and component packaging architecture required to produce J2EE modules. (The application client specification is found in Chapter J2EE.9 of this document.)

J2EE.8.1.2 Component Packaging: Composing a J2EE Module

A J2EE module is a collection of one or more J2EE components of the same container type with one component deployment descriptor of that type. Deployment descriptors for J2EE modules are extensible. Any number of components of the same container type can be packaged together with a single container-specific J2EE deployment descriptor to produce a J2EE module.

  • A J2EE module represents the basic unit of composition of a J2EE application.

  • The deployment descriptor for a J2EE module contains all of the declarative data required to deploy the components in the module. The deployment descriptor for a J2EE module also contains assembly instructions that describe how the components are composed into an application.

  • An individual J2EE module can be deployed as a stand-alone J2EE module without an application level deployment descriptor.

  • The J2EE platform supports the use of bundled extensions as specified in Support for Extensions and Applications in Version 1.2 of the Java™ Platform (available at http://java.sun.com/products/jdk/1.2/docs/guide/extensions/spec.html).

J2EE.8.1.3 Application Assembly

A J2EE application consists of one or more J2EE modules and one J2EE application deployment descriptor. A J2EE application is packaged using the Java archive (JAR) file format into a file with a .ear (enterprise archive) filename extension. A minimal J2EE application package will contain only J2EE modules and the application deployment descriptor. A J2EE application package may also include libraries referenced by J2EE modules, help files, and documentation to aid the deployer, etc.

The deployment of a portable J2EE application should not depend on any entities that may be contained in the package other than those defined by this specification. Deployment of a portable J2EE application must be possible using only the application deployment descriptor and the J2EE modules (and their dependent libraries) and descriptors listed in it.

The J2EE application deployment descriptor represents the top level view of a J2EE application's contents. The J2EE application deployment descriptor is specified by the J2EE:application XML document type definition (DTD) (see Section J2EE.8.4, "J2EE:application XML DTD").

J2EE.8.1.3.1 Customization

In certain cases, a J2EE application will need customization before it can be deployed into the enterprise. New J2EE modules may be added to the application. Existing modules may be removed from the application. Some J2EE modules may need custom content created, changed, or replaced. For example, an application consumer may need to use an html editor to add company graphics to a template login page that was provided with a J2EE web application.

J2EE.8.1.4 Deployment

During the deployment phase of an application's life cycle, the application is installed on the J2EE platform and then is configured and integrated into the existing infrastructure. Each J2EE module listed in the application deployment descriptor must be deployed according to the requirements of the specification for the respective J2EE module type. Each module listed must be installed in the appropriate container type and the environment properties of each module must be set appropriately in the target container to reflect the values declared by the deployment descriptor element for each component.


J2EE.8.2 Application Assembly

This section specifies the sequence of steps that are typically followed when composing a J2EE application.

J2EE.8.2.1 Assembling a J2EE Application

  1. Select the J2EE modules that will used by the application.

  2. Create an application directory structure.

    The directory structure of an application is arbitrary. The structure should be designed around the requirements of the contained components.

  3. Reconcile J2EE module deployment parameters.

    The deployment descriptors for the J2EE modules must be edited to link internally satisfied dependencies and eliminate any redundant security role names. An optional element alt-dd (described in Section J2EE.8.4, "J2EE:application XML DTD") may be used when it is desirable to preserve the original deployment descriptor. The element alt-dd specifies an alternate deployment descriptor to use at deployment time. The edited copy of the deployment descriptor file may be saved in the application directory tree in a location determined by the application assembler. If the alt-dd element is not present, the deployer must read the deployment descriptor directly from the JAR.

    1. Link the internally satisfied dependencies of all components in every module contained in the application. For each component dependency, there must only be one corresponding component that fulfills that dependency in the scope of the application.

      1. For each ejb-link, there must be only one matching ejb-name in the scope of the entire application (see Section J2EE.5.3, "Enterprise JavaBeans™ (EJB) References").

      2. Dependencies that are not linked to internal components must be handled by the deployer as external dependencies that must be met by resources previously installed on the platform. External dependencies must be linked to the resources on the platform during deployment.

    2. Synchronize security role-names across the application. Rename unique role-names with redundant meaning to a common name.

  4. Create an XML deployment descriptor for the application. The deployment descriptor must be named "application.xml" and must reside in the top level of the META-INF directory of the application .ear file. The deployment descriptor must be a valid XML document according to the document type definition (DTD) for a J2EE: application XML document. The deployment descriptor must include an XML document type definition with a PUBLIC identifier of "-//Sun Microsystems//J2EE Application Deployment 1.0//EN."

  5. Package the application.

    1. Place the J2EE modules and the deployment descriptor in the appropriate directories. The deployment descriptor must be located at META-INF/application.xml.

    2. Package the application directory hierarchy in a file using the Java archive (JAR) file format. The file should be named with a .ear filename extension.

J2EE.8.2.2 Adding and Removing Modules

After the application is created, J2EE modules may be added or removed before deployment. When adding or removing a module the following steps must be performed:

  1. Decide on a location in the application package for the new module. Optionally create new directories in the application package hierarchy to contain any J2EE modules that are being added to the application.

  2. Copy the new J2EE modules to the desired location in the application package. The packaged modules are inserted directly in the desired location; the modules are not unpackaged.

  3. Edit the deployment descriptors for the J2EE modules to link the dependencies which are internally satisfied by the J2EE modules included in the application.

  4. Edit the J2EE application deployment descriptor to meet the content requirements of the J2EE platform and the validity requirements of the J2EE:application XML DTD.


J2EE.8.3 Deployment

The J2EE platform supports two types of deployment units:

  • Stand-alone J2EE modules.

  • J2EE applications, consisting of one or more J2EE modules. A J2EE application must include one J2EE application deployment descriptor.

Any J2EE platform must be able to accept a J2EE application delivered as a .ear file.

J2EE.8.3.1 Deploying a Stand-Alone J2EE Module

This section specifies the requirements for deployment of a stand-alone J2EE module.

  1. The deployment tool must first read the J2EE module deployment descriptor from the package. See the EJB and servlet specifications for the required location and name of the deployment descriptor for each component type.

  2. The deployment tool must deploy all of the components listed in the J2EE module deployment descriptor according to the deployment requirements of the respective J2EE component specification.

J2EE.8.3.2 Deploying a J2EE Application

This section specifies the requirements for deployment of a J2EE application.

  1. The deployment tool must first read the J2EE application deployment descriptor from the application .ear file (META-INF/application.xml).

  2. The deployment tool must open each of the J2EE modules listed in the J2EE application deployment descriptor and read the J2EE module deployment descriptor from the package. See the Enterprise JavaBeans, servlet, and application client specifications for the required location and name of the deployment descriptor for each component type. (The application client specification is Chapter J2EE.9, "Application Clients.")

  3. The deployment tool must install all of the components described by each module deployment descriptor into the appropriate container according to the deployment requirements of the respective J2EE component specification.

  4. The deployment tool must allow the deployer to configure the container to reflect the values of all the properties declared by the deployment descriptor element for each component.

  5. Repeat steps 2 through 4 until all the modules listed in the application deployment descriptor have been deployed.


J2EE.8.4 J2EE:application XML DTD

This section provides the XML DTD for the J2EE application deployment descriptor. The XML grammar for a J2EE application deployment descriptor is defined by the J2EE:application document type definition. The granularity of composition for J2EE application assembly is the J2EE module. A J2EE: application deployment descriptor contains a name and description for the application and the URI of a UI icon for the application, as well as a list of the J2EE modules that comprise the application. The content of the XML elements is in general case sensitive. This means, for example, that <role-name>Manager</role-name> is a different role than <role-name>manager</role-name>.

All valid J2EE application deployment descriptors must contain the following DOCTYPE declaration:

<!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD
J2EE Application 1.2//EN" "http://java.sun.com/j2ee/dtds/
application_1_2.dtd">

Figure J2EE.8-3 shows a graphic representation of the structure of the J2EE:application XML DTD.

Figure J2EE.8-3. J2EE:application XML DTD Structure

The DTD that follows defines the XML grammar for a J2EE application deployment descriptor.

<!--
The alt-dd element specifies an optional URI to the post-assembly
version of the deployment descriptor file for a particular J2EE
module. The URI must specify the full pathname of the deployment
descriptor file relative to the application's root directory. If
alt-dd is not specified, the deployer must read the deployment
descriptor from the default location and file name required by the
respective component specification.
-->
<!ELEMENT alt-dd (#PCDATA)>

<!--
The application element is the root element of a J2EE application
deployment descriptor.
-->
<!ELEMENT application (icon?, display-name, description?, module+,
security-role*)>

<!--
The context-root element specifies the context root of a web
application
-->
<!ELEMENT context-root (#PCDATA)>

<!--
The description element provides a human readable description of the
application. The description element should include any information
that the application assembler wants to provide the deployer.
-->
<!ELEMENT description (#PCDATA)>

<!--
The display-name element specifies an application name.
The application name is assigned to the application by the
application assembler and is used to identify the application to the
deployer at deployment time.
-->
<!ELEMENT display-name (#PCDATA)>

<!--
The ejb element specifies the URI of a ejb-jar, relative to the top
level of the application package.
-->
<!ELEMENT ejb (#PCDATA)>

<!--
The icon element contains a small-icon and large-icon element which
specify the URIs for a small and a large GIF or JPEG icon image to
represent the application in a GUI.
-->
<!ELEMENT icon (small-icon?, large-icon?)>

<!--
The java element specifies the URI of a java application client
module, relative to the top level of the application package.
-->
<!ELEMENT java (#PCDATA)>

<!--
The large-icon element specifies the URI for a large GIF or JPEG
icon image to represent the application in a GUI.
-->
<!ELEMENT large-icon (#PCDATA)>

<!--
The module element represents a single J2EE module and contains an
ejb, java, or web element, which indicates the module type and
contains a path to the module file, and an optional alt-dd element,
which specifies an optional URI to the post-assembly version of the
deployment descriptor.
The application deployment descriptor must have one module element
for each J2EE module in the application package.
-->
<!ELEMENT module ((ejb | java | web), alt-dd?)>

<!--
The role-name element contains the name of a security role.
-->
<!ELEMENT role-name (#PCDATA)>

<!--
The security-role element contains the definition of a security role
which is global to the application. The definition consists of a
description of the security role, and the security role name. The
descriptions at this level override those in the component level
security-role definitions and must be the descriptions tool display
to the deployer.
-->
<!ELEMENT security-role (description?, role-name)>

<!--
The small-icon element specifies the URI for a small GIF or JPEG
icon image to represent the application in a GUI.
-->
<!ELEMENT small-icon (#PCDATA)>

<!--
The web element contains the web-uri and context-root of a web
application module.
-->
<!ELEMENT web (web-uri, context-root)>

<!--
The web-uri element specifies the URI of a web application file,
relative to the top level of the application package.
-->
<!ELEMENT web-uri (#PCDATA)>

<!--
The ID mechanism is to allow tools to easily make tool-specific
references to the elements of the deployment descriptor.
 -->
<!ATTLIST alt-dd id ID #IMPLIED>
<!ATTLIST application id ID #IMPLIED>
<!ATTLIST context-root id ID #IMPLIED>
<!ATTLIST description id ID #IMPLIED>
<!ATTLIST display-name id ID #IMPLIED>
<!ATTLIST ejb id ID #IMPLIED>
<!ATTLIST icon id ID #IMPLIED>
<!ATTLIST java id ID #IMPLIED>
<!ATTLIST large-icon id ID #IMPLIED>
<!ATTLIST module id ID #IMPLIED>
<!ATTLIST role-name id ID #IMPLIED>
<!ATTLIST security-role id ID #IMPLIED>
<!ATTLIST small-icon id ID #IMPLIED>
<!ATTLIST web id ID #IMPLIED>
<!ATTLIST web-uri id ID #IMPLIED>


Chapter J2EE.9. Application Clients

This chapter describes application clients in the Java™ 2 Platform, Enterprise Edition (J2EE).


J2EE.9.1 Overview

Application clients are first tier client programs that execute in their own Java™ virtual machines. Application clients follow the model for Java technology-based applications—they are invoked at their main method and run until the virtual machine is terminated. However, like other J2EE application components, application clients depend on a container to provide system services. The application client container may be very lightweight compared to other J2EE containers, providing only the security and deployment services described below


J2EE.9.2 Security

Application clients have the same authentication requirements and may use the same authentication techniques as other J2EE application components.

Unprotected web resources may be accessed without authentication. Authentication when accessing protected web resources may use HTTP basic authentication, SSL client authentication, or HTTP login form authentication. Lazy authentication may be used.

Authentication is required when accessing enterprise beans. The authentication mechanisms for enterprise beans are unspecified. Lazy authentication may be used.

The application client may authenticate its user in a number of ways. The techniques used are platform-dependent and not under control of the application client. The application client container may integrate with the platform's authentication system, providing a single signon capability. The application client container may authenticate the user when the application is started. The application client container may use lazy authentication, authenticating the user only when it needs to access a protected resource. This version of this specification does not describe the technique used to authenticate the user.

If the application client container needs to interact with the user to gather authentication data, the container will provide an appropriate user interface. In this specification, no mechanism is provided for the application client itself to provide a user interface for authentication. However, in the case of HTTP login form authentication, the user interface is provided by the server (in the form of an HTML page delivered in response to an HTTP request) and must be displayed by the application client.

In a future version of this specification, application clients will be able to use the Java™ Authentication and Authorization Service APIs to access information about the currently authenticated user, to write portable authentication user interfaces, and to participate in and control the authentication process. (See Section J2EE.11.7, "Security APIs.")

Application clients execute in an environment with a security manager installed and have similar security permission requirements as servlets. The security permission requirements are described fully in Chapter J2EE.6, "Application Programming Interface."


J2EE.9.3 Transactions

Application clients are not required to have direct access to the transaction facilities of the J2EE platform. A J2EE product is not required to provide a JTA UserTransaction object for use by application clients. Of course, application clients can invoke enterprise beans that start transaction, and they can use the transaction facilities of the JDBC API. If a JDBC API transaction is open when an application client invokes an enterprise bean, the transaction context is not required to be propagated to the EJB server.


J2EE.9.4 Naming

As with all J2EE components, application clients use JNDI to look up enterprise beans, get access to resource managers, access configurable parameters set at deployment time, etc. Application clients use the java: JNDI namespace to access these items; see Chapter J2EE.5, "Naming," for details.


J2EE.9.5 Application Programming Interfaces

Application clients have all the facilities of the Java™ 2 Platform, Standard Edition (subject to security restrictions), as well as various standard extensions, as described in Chapter J2EE.6, "Application Programming Interface." Each application client executes in its own Java virtual machine. Application clients start execution at the main method of the class specified in the Main-Class attribute in the manifest file of the application client's JAR file (although note that application client container code will typically execute before the application client itself, in order to prepare the environment of the container, install a SecurityManager, initialize the name service client library, etc.).


J2EE.9.6 Packaging and Deployment

Application clients are packaged in JAR files and include a deployment descriptor similar to other J2EE application components. The deployment descriptor describes the enterprise beans and external resources referenced by the application. As with other J2EE application components, access to resources must be configured at deployment time, names assigned for enterprise beans and resources, etc.

The tool used to deploy an application client, and the mechanism used to install the application client, is not specified. Very sophisticated J2EE products may allow the application client to be deployed on a J2EE server and automatically made available to some set of (usually intranet) clients. Other J2EE products may require the J2EE application bundle containing the application client to be manually deployed and installed on each client machine. And yet another approach would be for the deployment tool on the J2EE server to produce an installation package that could be taken to each client to install the application client. There are many possibilities here and this specification doesn't prescribe any one; it only defines the package format for the application client and the things that must be possible during the deployment process.

How an application client is invoked by an end user is unspecified. Typically a J2EE product provider will provide an application launcher that integrates with the application client machine's native operating system, but the level of such integration is unspecified.


J2EE.9.7 J2EE:application-client XML DTD

The XML grammar for a J2EE application client deployment descriptor is defined by the J2EE:application-client document type definition. The root element of the deployment descriptor for an application client is application-client. The content of the XML elements is in general case sensitive. This means, for example, that <res-auth>Container</res-auth> must be used, rather than <res-auth>container</res-auth>.

All valid application-client deployment descriptors must contain the following DOCTYPE declaration:

<!DOCTYPE application-client PUBLIC "-//Sun Microsystems,
Inc.//DTD J2EE Application Client 1.2//EN" "http://
java.sun.com/j2ee/dtds/application-client_1_2.dtd">

Figure J2EE.9-1 shows the structure of the J2EE: application-client XML DTD.

Figure J2EE.9-1. J2EE:application-client XML DTD Structure

<!--
The application-client element is the root element of an application
client deployment descriptor.
The application client deployment descriptor describes the EJB
components and external resources referenced by the application
client.
-->
<!ELEMENT application-client (icon?, display-name, description?,
env-entry*, ejb-ref*, resource-ref*)>

<!--
The description element is used to provide text describing the
parent element. The description element should include any
information that the application-client file producer wants to
provide to the consumer of the application-client file (i.e., to the
Deployer). Typically, the tools used by the application-client file
consumer will display the description when processing the parent
element that contains the description.
-->
<!ELEMENT description (#PCDATA)>

<!--
The display-name element contains a short name that is intended to
be displayed by tools.
-->
<!ELEMENT display-name (#PCDATA)>

<!--
The ejb-link element is used in the ejb-ref element to specify that
an EJB reference is linked to an enterprise bean in the encompassing
J2EE Application package. The value of the ejb-link element must be
the ejb-name of an enterprise bean in the same J2EE Application
package. Used in: ejb-ref
Example: <ejb-link>EmployeeRecord</ejb-link>
-->
<!ELEMENT ejb-link (#PCDATA)>

<!--
The ejb-ref element is used for the declaration of a reference to
an enterprise bean's home. The declaration consists of an optional
description; the EJB reference name used in the code of the
referencing application client; the expected type of the referenced
enterprise bean; the expected home and remote interfaces of the
referenced enterprise bean; and an optional ejb-link information.
The optional ejb-link element is used to specify the referenced
enterprise bean.
-->
<!ELEMENT ejb-ref (description?, ejb-ref-name, ejb-ref-type, home,
remote, ejb-link?)>

<!--
The ejb-ref-name element contains the name of an EJB reference. The
EJB reference is an entry in the application client's environment.
It is recommended that name is prefixed with "ejb/". Used in: ejb-ref
Example: <ejb-ref-name>ejb/Payroll</ejb-ref-name>
-->
<!ELEMENT ejb-ref-name (#PCDATA)>

<!--
The ejb-ref-type element contains the expected type of the
referenced enterprise bean. The ejb-ref-type element must be one of
the following:
<ejb-ref-type>Entity</ejb-ref-type>
<ejb-ref-type>Session</ejb-ref-type>
Used in: ejb-ref
-->
<!ELEMENT ejb-ref-type (#PCDATA)>

<!--
The env-entry element contains the declaration of an application
client's environment entries. The declaration consists of an
optional description, the name of the environment entry, and an
optional value.
-->
<!ELEMENT env-entry (description?, env-entry-name, env-entry-type,
env-entry-value?)>

<!--
The env-entry-name element contains the name of an application
client's environment entry. Used in: env-entry
Example: <env-entry-name>EmployeeAppDB</env-entry-name>
-->
<!ELEMENT env-entry-name (#PCDATA)>

<!--
The env-entry-type element contains the fully-qualified Java type
of the environment entry value that is expected by the application
client's code. The following are the legal values of env-entry-type:
java.lang.Boolean, java.lang.String, java.lang.Integer,
java.lang.Double, java.lang.Byte, java.lang.Short, java.lang.Long,
and java.lang.Float.

Used in: env-entry

Example:
<env-entry-type>java.lang.Boolean</env-entry-type>
-->
<!ELEMENT env-entry-type (#PCDATA)>

<!--
The env-entry-value element contains the value of an application
client's environment entry. The value must be a String that is valid
for the constructor of the specified type that takes a single String
parameter.

Used in: env-entry

Example:
<env-entry-value>/datasources/MyDatabase</env-entry-value>
-->
<!ELEMENT env-entry-value (#PCDATA)>

<!--
The home element contains the fully-qualified name of the enterprise
bean's home interface.
Used in: ejb-ref
Example: <home>com.aardvark.payroll.PayrollHome</home>
-->
<!ELEMENT home (#PCDATA)>

<!--
The icon element contains a small-icon and large-icon element which
specify the URIs for a small and a large GIF or JPEG icon image used
to represent the application client in a GUI tool.
-->
<!ELEMENT icon (small-icon?, 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 relative path within the
application-client jar file. 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.
Example:
<large-icon>lib/images/employee-service-icon32x32.jpg</large-icon>
-->
<!ELEMENT large-icon (#PCDATA)>

<!--
The remote element contains the fully-qualified name of the
enterprise bean's remote interface.
Used in: ejb-ref
Example:
<remote>com.wombat.empl.EmployeeService</remote>
-->
<!ELEMENT remote (#PCDATA)>

<!--
The res-auth element specifies whether the enterprise bean code
signs on programmatically to the resource manager, or whether the
container will sign on to the resource manager on behalf of the bean.
In the latter case, the container uses information that is supplied
by the deployer.
The value of this element must be one of the two following:
<res-auth>Application</res-auth>
<res-auth>Container</res-auth>
-->
<!ELEMENT res-auth (#PCDATA)>

<!--
The res-ref-name element specifies the name of the resource factory
reference name. The resource factory reference name is the name of
the application client's environment entry whose value contains the
JNDI name of the data source.
Used in: resource-ref
-->
<!ELEMENT res-ref-name (#PCDATA)>

<!--
The res-type element specifies the type of the data source. The type
is specified by the Java interface (or class) expected to be
implemented by the data source.
Used in: resource-ref
-->
<!ELEMENT res-type (#PCDATA)>

<!--
The resource-ref element contains a declaration of application
clients's reference to an external resource. It consists of an
optional description, the resource factory reference name, the
indication of the resource factory type expected by the application
client's code, and the type of authentication (bean or container).

Example:
<resource-ref>
<res-ref-name>EmployeeAppDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
-->
<!ELEMENT resource-ref (description?, res-ref-name, res-type,
res-auth)>
<!--
The small-icon element contains the name of a file containing a small
(16 x 16) icon image. The file name is a relative path within the
application-client jar file. 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.
Example:
<small-icon>lib/images/employee-service-icon16x16.jpg</small-icon>
-->
<!ELEMENT small-icon (#PCDATA)>

<!--
The ID mechanism is to allow tools to easily make tool-specific
references to the elements of the deployment descriptor.
 -->
<!ATTLIST application-client id ID #IMPLIED>
<!ATTLIST description id ID #IMPLIED>
<!ATTLIST display-name id ID #IMPLIED>
<!ATTLIST ejb-link id ID #IMPLIED>
<!ATTLIST ejb-ref id ID #IMPLIED>
<!ATTLIST ejb-ref-name id ID #IMPLIED>
<!ATTLIST ejb-ref-type id ID #IMPLIED>
<!ATTLIST env-entry id ID #IMPLIED>
<!ATTLIST env-entry-name id ID #IMPLIED>
<!ATTLIST env-entry-type id ID #IMPLIED>
<!ATTLIST env-entry-value id ID #IMPLIED>
<!ATTLIST home id ID #IMPLIED>
<!ATTLIST icon id ID #IMPLIED>
<!ATTLIST large-icon id ID #IMPLIED>
<!ATTLIST remote id ID #IMPLIED>
<!ATTLIST res-auth id ID #IMPLIED>
<!ATTLIST res-ref-name id ID #IMPLIED>
<!ATTLIST res-type id ID #IMPLIED>
<!ATTLIST resource-ref id ID #IMPLIED>
<!ATTLIST small-icon id ID #IMPLIED>


Chapter J2EE.10. Service Provider Interface

This version of Java™ 2 Platform, Enterprise Edition (J2EE) does not define the J2EE service provider interface.

Several APIs required in the current version of this specification have service provider interfaces. These are, of course, required to be present in the current version of the J2EE platform. Future versions of this specification will fully describe the execution environment available to such service providers, including which APIs are available to them, the security permissions they are likely to have, etc. In addition, future versions of this specification will define how to package and deploy a service provider.


Chapter J2EE.11. Future Directions

This first version of the Java™ 2 Platform, Enterprise Edition (J2EE) specification includes most of the basic facilities needed by enterprise applications. Still, there is always more to be done. This chapter briefly describes our plans for future versions of this specification. Please keep in mind that all of this is subject to change. Your feedback is encouraged.

The following sections describe additional facilities we would like to include in future versions of this specification or additional requirements we would like to add to future versions of this specification. Many of the APIs included in the J2EE platform will continue to evolve on their own and we will include the latest version of each API. In particular, many improvements are planned for the EJB specification, so please refer to that specification for additional details.


J2EE.11.1 Java™ Message Service API

A future version of this specification will require that the platform include service providers for JMS point-to-point and publish subscribe messaging as defined in the JMS specification. We will also specify the integration of the JMS API with the Enterprise JavaBeans architecture so that enterprise beans can be activated by JMS messages.


J2EE.11.2 Enterprise JavaBeans™ (EJB)/IIOP Protocol

As mentioned several times in this specification, a future version of this specification will require that enterprise beans be accessible using the IIOP protocol. Other proprietary protocols may be used between components in the same J2EE product or between products (typically from the same product provider), but IIOP will be required for interoperability between products from different providers. Before IIOP can be required, the industry must agree on standards for security propagation.


J2EE.11.3 J2EE SPI

Many of the APIs that make up the J2EE platform include an SPI layer that allows service providers or other system level components to be plugged in. This specification does not describe the execution environment for such service providers, nor the packaging and deployment requirements for service providers. Future versions of this specification will fully define the J2EE SPI. The J2EE SPI will include the JDBC 2.0 extension APIs for connection pooling and distributed transactions.


J2EE.11.4 Connectors

One of the most important SPI components is connectors to existing enterprise information systems. The ability to provide portable connectors will be critical to the success of the J2EE platform. The connector facility is planned to include the JTA support for resource managers and additional APIs for security integration. See Java Specification Request JSR-000016 (http://java.sun.com/aboutJava/communityprocess/jsr/jsr_016_connect.html).


J2EE.11.5 XML APIs

XML will be used for exchange of business data by many applications. A future version of this specification will include the DOM and SAX APIs for parsing and manipulating XML data, as well as other XML APIs defined as a part of the Java Specification Request JSR-000005 (http://java.sun.com/aboutJava/communityprocess/jsr/jsr_005_xml.html).


J2EE.11.6 JDBC RowSets

RowSets provide a standard way to send tabular data between the remote components of a distributed, enterprise application. The JDBC 2.0 Standard Extension API defines the RowSet APIs, and in the future will contain rowset implementations, as well. Future versions of this specification will require that the JDBC rowset implementations be supported. More information is available at http://java.sun.com/products/jdbc.


J2EE.11.7 Security APIs

It is a goal of the J2EE platform to separate security from business logic, providing declarative security controls for application components. However, some applications need more control over security than can be provided by this approach. A future version of this specification will include APIs to control authentication and authorization, most likely the APIs specified by the Java Authentication and Authorization Service (http://java.sun.com/security/jaas/index.html).


J2EE.11.8 Deployment APIs

This specification assumes that deployment tools will be provided with a J2EE product by the product provider. J2EE tool providers would also like to be able to provide deployment tools that could work with all J2EE products. Future versions of this specification may define deployment APIs to allow the creation of such tools.


J2EE.11.9 Management APIs

J2EE applications and J2EE products must be manageable. Future versions of this specification will include APIs to support management functions.


J2EE.11.10 SQLJ Part 0

SQLJ Part 0 supports embedding of SQL statements in programs written in the Java programming language. A compiler translates the program into a program that uses the SQLJ Part 0 runtime. The runtime supports access to a database using JDBC, while also allowing platform-dependent and database-specific optimizations of such access. The SQLJ Part 0 runtime classes can be packaged with a J2EE application that uses SQLJ Part 0, allowing that application to run on any J2EE platform. In a future version of this specification we expect to require the platform to provide the SQLJ Part 0 runtime classes so that they do not need to be packaged with the application. For information on SQLJ, see http://www.sqlj.org.


Appendix J2EE.A. Revision History

    Section J2EE.A.1. Changes Since Public Draft

    Section J2EE.A.2. Changes Since Public Release 1

    Section J2EE.A.3. Changes Since Public Release 2


J2EE.A.1 Changes Since Public Draft

J2EE.A.1.1 Additional Requirements

  • An application component that uses a JavaMail API javax.mail.Session object or a java.net.URL object should declare its need in a resource-ref element in its deployment descriptor, and access the Session through JNDI. A J2EE product must support this usage. See Section J2EE.5.4, "Resource Factory References" and Section J2EE.6.11, "JavaMail™ 1.1 Requirements."

  • The web container is required to propagate any active transaction context to web components called through the RequestDispatcher API. See Section J2EE.4.2.1, "Web Components."

  • The web container is required to ensure that newly created threads are not associated with any JTA transaction. See Section J2EE.4.2.1, "Web Components."

  • More clearly specified the requirements for transaction support in a web container. See Section J2EE.4.2.1, "Web Components."

  • More completely specified the required DOCTYPE declarations in deployment descriptors. See Chapter J2EE.8, "Application Assembly and Deployment."

  • Clarified requirement that the required database need not be accessible from applets. See Section J2EE.6.2.2.3, "JDBC ™ API."

  • Updated the application-client DTD to reflect the new child element of resource-ref, res-auth, and updated the env-entry element to include env-entry-type. See Section J2EE.9.7, "J2EE: application-client XML DTD."

J2EE.A.1.2 Removed Requirements

  • Removed JDBC API requirement for TYPE_SCROLL_INSENSITIVE result sets. See Section J2EE.6.2.2.3, "JDBC ™ API."

  • Reduced the number of cipher suites required to be supported to the most common two—SSL_RSA_EXPORT_WITH_RC4_40_MD5 and SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA. See Section J2EE.3.4.1.3, "Required Login Mechanisms."

J2EE.A.1.3 Editorial Changes

  • Consistently use the term RMI-IIOP.

  • Made it clear that application clients themselves, not the application client container, are required to display the HTML form login page, if they access a web resource using that form of authentication. See Section J2EE.9.2, "Security."

  • Consistently used the term "J2EE product" to refer to a product that is compatible with this specification.

  • Changed the name of role "platform provider" to "product provider" for consistency with above change.

  • Added definition of "application assembler" as used in Chapter J2EE.5 to list of platform roles in Chapter J2EE.2.

  • Consistently capitalized platform role names such as deployer.

  • Rewrote ambiguous sentences resolving uses of "it" and "that," converted from passive to active voice, etc.

  • Changed all self references to read "this specification."

  • Corrected syntax used to list methods, added interface or class references for method references. See Chapter J2EE.3, "Security."

  • Changed various terms for JSP components to "JSP pages" in conformance with the JSP specification.

  • Corrected method names isUserInRole and getUserPrincipal on the HttpServletRequest class to be consistent with the latest servlet specification. See Chapter J2EE.3, "Security."

  • Added Appendix J2EE.B, "Related Documents."


J2EE.A.2 Changes Since Public Release 1

J2EE.A.2.1 Additional Requirements

  • Added text clarifying requirements for unauthenticated users. See Section J2EE.3.4.1.4, "Unauthenticated Users," and Section J2EE.3.6, "Deployment Requirements."

  • Updated JDBC API requirement to support JDBC 2.1 core instead of 2.0. JDBC 2.1 is a maintenance release of the JDBC core specification that contains only the changes described in Section J2EE.6.2.2.3, "JDBC ™ API." These changes are based on feedback from database vendors and are intended to enhance compatibility between products. JDBC 2.1 is currently available for public review as a part of the Java Community Process. These changes have already been widely reviewed by database vendors. We expect the JDBC 2.1 specification to be finalized within a month. We also expect JDBC 2.1 to be incorporated into the J2SE 1.3 specification. The JDBC 2.1 specification is available at http://java.sun.com/products/jdbc/maintenance.html.

J2EE.A.2.2 Removed Requirements

  • Removed requirement to support installed extensions, which are also not required by J2SE. See Section J2EE.8.1.2, "Component Packaging: Composing a J2EE Module."

  • By requiring JDBC 2.1 instead of JDBC 2.0, we have effectively removed requirements on JDBC drivers in the areas of batch updates and SQL92 DROP TABLE support. See Section J2EE.6.2.2.3, "JDBC ™ API."

J2EE.A.2.3 Editorial Changes

  • Clarified that caller propagation is not required when the web container doesn't know the user's identity. See Section J2EE.3.5.2, "Caller Authorization."

  • Clarified that J2EE application packages may contain items not specified by this specification. See Section J2EE.8.1.3, "Application Assembly."

  • Clarified that J2EE modules are inserted into the J2EE .ear file in their packaged form, they are not unpackaged first. See step 5 in Section J2EE.8.2, "Application Assembly."

  • Clarified that the content of XML elements is in general case sensitive. See Section J2EE.8.4, "J2EE: application XML DTD," and Section J2EE.9.7, "J2EE:application-client XML DTD."

  • Corrected PUBLIC ID in application client DTD. See Section J2EE.9.7, "J2EE:application-client XML DTD."

  • Updated URL reference to Servlet 2.2 specification. See Section J2EE.6.6, "Servlet 2.2 Requirements."

  • Added URL reference to JSP 1.1 specification. See Section J2EE.6.7, "JavaServer Pages™ (JSP) 1.1 Requirements."

  • Updated URL reference to JAF 1.0 spec. See Section J2EE.6.12, "Java Beans™ Activation Framework 1.0 Requirements."

  • Updated URL references in Appendix J2EE.B, "Related Documents."


J2EE.A.3 Changes Since Public Release 2

J2EE.A.3.1 Additional Requirements

  • Added requirements related to HttpSession objects in distributable applications. See Section J2EE.6.6, "Servlet 2.2 Requirements."

  • Many JDBC drivers need access to system properties for configuration. To allow such drivers to work without modification in EJB containers, we added a requirement that enterprise beans are required to be able to read system properties. See Table J2EE.6-2.

J2EE.A.3.2 Removed Requirements

  • None.

J2EE.A.3.3 Editorial Changes

  • Changed terminology in Table J2EE.6-2 to match JDK 1.2 Security specification.

  • Updated JMS requirement to refer to latest JMS specification version. See Section J2EE.6.8, "Java™ Message Service (JMS) 1.0 Requirements."

  • Corrected trademark usage throughout the specification.

  • Added missing ATTLIST entry and fixed security role description to be optional in application DTD. Updated figure to correspond to DTD. See Section J2EE.8.4, "J2EE:application XML DTD."

  • Added missing ATTLIST entries in application client DTD. Updated figure to correspond to DTD. See Section J2EE.9.7, "J2EE:application-client XML DTD."


Appendix J2EE.B. Related Documents

This specification refers to the following documents. The terms used to refer to the documents in this specification are included in parentheses.

Java™ 2 Platform, Enterprise Edition Specification Version 1.2 (this specification). Copyright 1999, Sun Microsystems, Inc. Available at http://java.sun.com/j2ee/docs.html.

Java™ 2 Platform, Enterprise Edition Technical Overview (J2EE Overview). Copyright 1998, 1999, Sun Microsystems, Inc. Available at http://java.sun.com/j2ee/white.html.

Java™ 2 Platform, Standard Edition, v1.2.2 API Specification (J2SE specification). Copyright 1993–99, Sun Microsystems, Inc. Available at http://java.sun.com/products/jdk/1.2/docs/api/index.html.

Enterprise JavaBeans™ Specification, Version 1.1 (EJB specification). Copyright 1998, 1999, Sun Microsystems, Inc. Available at http://java.sun.com/products/ejb.

Enterprise JavaBeans™ to CORBA Mapping, Version 1.1 (EJB-CORBA mapping). Copyright 1998, 1999, Sun Microscystems, Inc. Available at http://java.sun.com/products/ejb.

JavaServer Pages™ Specification, Version 1.1 (JSP specification). Copyright 1998, 1999, Sun Microsystems, Inc. Available at http://java.sun.com/products/jsp.

Java™ Servlet Specification, Version 2.2 (Servlet specification). Copyright 1998, 1999, Sun Microsystems, Inc. Available at http://java.sun.com/products/servlet.

JDBC™ 2.0 API (JDBC specification). Copyright 1998, 1999, Sun Microsystems, Inc. Available at http://java.sun.com/products/jdbc.

JDBC™ 2.0 Standard Extension API (JDBC extension specification). Copyright 1998, 1999, Sun Microsystems, Inc. Available at http://java.sun.com/products/jdbc.

Java™ Naming and Directory Interface 1.2 Specification (JNDI specification). Copyright 1998, 1999, Sun Microsystems, Inc. Available at http://java.sun.com/products/jndi.

Java™ Message Service, Version 1.0.2 (JMS specification). Copyright 1998, Sun Microsystems, Inc. Available at http://java.sun.com/products/jms.

Java™ Transaction API, Version 1.0.1 (JTA specification). Copyright 1998, 1999, Sun Microsystems, Inc. Available at http://java.sun.com/products/jta.

Java™ Transaction Service, Version 0.95 (JTS specification). Copyright 1997– 1999, Sun Microsystems, Inc. Available at http://java.sun.com/products/jts.

JavaMail™ API Specification Version 1.1 (JavaMail specification). Copyright 1998, Sun Microsystems, Inc. Available at http://java.sun.com/products/javamail.

JavaBeans™ Activation Framework Specification Version 1.0.1 (JAF specification). Copyright 1998, Sun Microsystems, Inc. Available at http://java.sun.com/beans/glasgow/jaf.html.

IDL-To-Java Mapping Specification, Object Management Group. Available at http://www.omg.org/corba/clchpter.html.

Java-To-IDL Mapping Specification, Object Management Group. Available at http://www.omg.org/corba/clchpter.html.

The Java™ 2 Platform, Enterprise Edition Application Programming Model. Copyright 1999, Sun Microsystems, Inc. Available at http://java.sun.com/j2ee/apm.

The SSL Protocol, Version 3.0. Available at http://home.netscape.com/eng/ssl3.


Java™ Servlet Specification, v2.2 (SRV)

    Preface

    Chapter SRV.1. Overview

    Chapter SRV.2. Terms Used

    Chapter SRV.3. The Servlet Interface

    Chapter SRV.4. Servlet Context

    Chapter SRV.5. The Request

    Chapter SRV.6. The Response

    Chapter SRV.7. Sessions

    Chapter SRV.8. Dispatching Requests

    Chapter SRV.9. Web Applications

    Chapter SRV.10. Mapping Requests to Servlets

    Chapter SRV.11. Security

    Chapter SRV.12. Application Programming Interface

    Chapter SRV.13. Deployment Descriptor

    Chapter SRV.14. Futures


Preface

This document, the Java™ Servlet Specification, v2.2, specifies the Java servlet API. In addition to this specification, the Java servlet API has Javadoc documentation (referred to as the Java Servlet API Reference, v2.2) and a reference implementation available for public download at the following location:

http://java.sun.com/products/servlet/index.html

The reference implementation provides a behavioral benchmark. In the case of a discrepancy, the order of resolution is this specification, then the Java Servlet API Reference, v2.2, and finally the reference implementation.


SRV.P.1 Who Should Read This Specification

This document is intended for consumption by:

  • Web server and application server vendors that want to provide servlet engines that conform with this specification.

  • Web authoring tool developers that want to generate web applications that conform to this specification.

  • Sophisticated servlet authors who want to understand the underlying mechanisms of servlet technology.

Please note that this specification is not a user's guide and is not intended to be used as such.


SRV.P.2 API Reference

The Java Servlet API Reference, v2.2, provides the complete description of all the interfaces, classes, exceptions, and methods that compose the servlet API. Simplified method signatures are provided throughout the spec. Please refer to the API reference for complete method signatures.


SRV.P.3 Other Java™ Platform Specifications

The following Java API specifications are heavily referenced throughout this specification:

  • Java2 Platform Enterprise Edition, v1.2 (J2EE)

  • JavaServer Pages, v1.1 (JSP)

  • Java Naming and Directory Interface (JNDI)

These specifications may be found at the Java2 Enterprise Edition web site: http://java.sun.com/j2ee/


SRV.P.4 Other Important References

The following Internet specifications provide information relevant to the development and implementation of the servlet API and engines which support the servlet API:

  • RFC 1630 Uniform Resource Identifiers (URI)

  • RFC 1738 Uniform Resource Locators (URL)

  • RFC 1808 Relative Uniform Resource Locators

  • RFC 1945 Hypertext Transfer Protocol (HTTP/1.0)

  • RFC 2045 MIME Part One: Format of Internet Message Bodies

  • RFC 2046 MIME Part Two: Media Types

  • RFC 2047 MIME Part Three: Message Header Extensions for non-ASCII text

  • RFC 2048 MIME Part Four: Registration Procedures

  • RFC 2049 MIME Part Five: Conformance Criteria and Examples

  • RFC 2109 HTTP State Management Mechanism

  • RFC 2145 Use and Interpretation of HTTP Version Numbers

  • RFC 2324 Hypertext Coffee Pot Control Protocol (HTCPCP/1.0) [1]

    [1] This reference is mostly tongue-in-cheek although most of the concepts described in the HTCPCP RFC are relevant to all well-designed web servers.

  • RFC 2616 Hypertext Transfer Protocol (HTTP/1.1)

  • RFC 2617 HTTP Authentication: Basic and Digest Authentication

You can locate the online versions of any of these RFCs at:

http://www.rfc-editor.org/

The World Wide Web Consortium (http://www.w3.org/) is a definitive source of HTTP related information that affects this specification and its implementations.

The Extensible Markup Language (XML) is utilized by the deployment descriptors described in this specification. More information about XML can be found at the following web sites:

http://java.sun.com/

http://www.xml.org/


SRV.P.5 Providing Feedback

The success of the Java community process depends on your participation in the community. We welcome any and all feedback about this specification. Please e-mail your comments to:

servletapi-feedback@eng.sun.com

Please note that due to the volume of feedback that we receive, you will not normally receive a reply from an engineer. However, each and every comment is read, evaluated, and archived by the specification team.


SRV.P.6 Acknowledgments

Anselm Baird-Smith, Elias Bayeh, Vince Bonfanti, Larry Cable, Robert Clark, Daniel Coward, Satish Dharmaraj, Jim Driscoll, Shel Finkelstein, Mark Hapner, Jason Hunter, Rod McChesney, Stefano Mazzocchi, Craig McClanahan, Adam Messinger, Ron Monzillo, Vivek Nagar, Kevin Osborn, Bob Pasker, Eduardo Pelegri-Lopart, Harish Prabandham, Bill Shannon, Jon S. Stevens, James Todd, Spike Washburn, and Alan Williamson have all (in no particular order other than alphabetic) provided invaluable input into the evolution of this specification. Connie Weiss, Jeff Jackson, and Mala Chandra have provided incredible management assistance in supporting and furthering the servlet effort at Sun.

This specification is an ongoing and broad effort that includes contributions from numerous groups at Sun and at partner companies. Most notably the following companies and groups have gone the extra mile to help the servlet specification process: The Apache Developer Community, Art Technology Group, BEA Weblogic, Clear Ink, IBM, Gefion Software, Live Software, Netscape Communications, New Atlanta Communications, and Oracle.

And, of course, the ongoing specification review process has been extremely valuable. The many comments that we have received from both our partners and the general public have helped us to define and evolve the specification. Many thanks to all who have contributed feedback.


Chapter SRV.1. Overview

    Section SRV.1.1. What Is a Servlet?

    Section SRV.1.2. What Is a Servlet Container?

    Section SRV.1.3. An Example

    Section SRV.1.4. Comparing Servlets with Other Technologies

    Section SRV.1.5. Relationship to Java 2 Enterprise Edition

    Section SRV.1.6. Distributable Servlet Containers

    Section SRV.1.7. Changes Since Version 2.1


SRV.1.1 What Is a Servlet?

A servlet is a web component, managed by a container, that generates dynamic content. Servlets are small, platform-independent Java classes compiled to an architecture neutral bytecode that can be loaded dynamically into and run by a web server. Servlets interact with web clients via a request response paradigm implemented by the servlet container. This request-response model is based on the behavior of the hypertext transfer protocol (HTTP).


SRV.1.2 What Is a Servlet Container?

The servlet container, in conjunction with a web server or application server, provides the network services over which requests and responses are set, decodes MIME based requests, and formats MIME based responses. A servlet container also contains and manages servlets through their life cycle.

A servlet container can either be built into a host web server or installed as an add-on component to a web server via that server's native extension API. Servlet containers can also be built into or possibly installed into web-enabled application servers.

All servlet containers must support HTTP as a protocol for requests and responses, but may also support additional request/response based protocols such as HTTPS (HTTP over SSL). The minimum required version of the HTTP specification that a container must implement is HTTP/1.0. It is strongly suggested that containers implement the HTTP/1.1 specification as well.

A servlet container may place security restrictions on the environment that a servlet executes in. In a Java 2 Standard Edition 1.2 (J2SE) or Java 2 Enterprise Edition 1.2 (J2EE) environment, these restrictions should be placed using the permission architecture defined by the Java 2 platform. For example, high end application servers may limit certain actions, such as the creation of a Thread object, to ensure that other components of the container are not negatively impacted.


SRV.1.3 An Example

A client program, such as a web browser, accesses a web server and makes an HTTP request. This request is processed by the web server and is handed off to the servlet container. The servlet container determines which servlet to invoke based on its internal configuration and calls it with objects representing the request and response. The servlet container can run in the same process as the host web server, in a different process on the same host, or on a different host from the web server for which it processes requests.

The servlet uses the request object to find out who the remote user is, what HTML form parameters may have been sent as part of this request, and other relevant data. The servlet can then perform whatever logic it was programmed with and can generate data to send back to the client. It sends this data back to the client via the response object.

Once the servlet is done with the request, the servlet container ensures that the response is properly flushed and returns control back to the host web server.


SRV.1.4 Comparing Servlets with Other Technologies

In functionality, servlets lie somewhere between Common Gateway Interface (CGI) programs and proprietary server extensions such as the Netscape server API (NSAPI) or Apache modules.

Servlets have the following advantages over other server extension mechanisms:

  • They are generally much faster than CGI scripts because a different process model is used.

  • They use a standard API that is supported by many web servers.

  • They have all the advantages of the Java programming language, including ease of development and platform independence.

  • They can access the large set of APIs available for the Java platform.


SRV.1.5 Relationship to Java 2 Enterprise Edition

The servlet API is a required API of the Java 2 Platform, Enterprise Edition, v1.2. [1] The J2EE specification describes additional requirements for servlet containers, and servlets that are deployed into them, that are executing in a J2EE environment.

[1] Please see the Java 2 Platform Enterprise Edition specification, section J2EE, in this volume.


SRV.1.6 Distributable Servlet Containers

New in this version of the specification is the ability to mark a web application as distributable. This indication allows servlet container vendors to deploy the servlets in a web application across multiple Java virtual machines running on the same host or on different hosts. An application marked as distributable must obey a few restrictions so that containers that support distributable applications can implement features such as clustering and failover.

All web applications that may need to run in a high performance environment, one that allows for scalability, clustering, and failover (such as a compliant J2EE implementation), should be written as distributable web applications. This will allow applications to take maximum advantage of servers that provide these features. If a non-distributable application is deployed into such a server, then it cannot take full advantage of the features that are given by such servers.


SRV.1.7 Changes Since Version 2.1

The following major changes have been made to the specification since version 2.1:

  • The introduction of the web application concept

  • The introduction of the web application archive files

  • The introduction of response buffering

  • The introduction of distributable servlets

  • The ability to get a RequestDispatcher by name

  • The ability to get a RequestDispather using a relative path

  • Internationalization improvements

  • Many clarifications of distributed servlet engine semantics

The following changes have been made to the API:

  • Added the getServletName method to the ServletConfig interface to allow a servlet to obtain the name by which it is known to the system, if any.

  • Added the getInitParameter and getInitPaameterNames method to the ServletContext interface so that initialization parameters can be set at the application level to be shared by all servlets that are part of that application.

  • Added the getLocale method to the ServletRequest interface to aid in determining what locale the client is in.

  • Added the isSecure method to the ServletRequest interface to indicate whether or not the request was transmitted via a secure transport such as HTTPS.

  • Replaced the construction methods of UnavailableException as existing constructor signatures causing some amount of developer confusion. These constructors have been replaced by simpler signatures.

  • Added the getHeaders method to the HttpServletRequest interface to allow all the headers associated with a particular name to be retrieved from the request.

  • Added the getContextPath method to the HttpServletRequest interface so that the part of the request path associated with a web application can be obtained.

  • Added the isUserInRole and getUserPrinciple methods to the HttpServletRequest interface to allow servlets to use an abstract role based authentication.

  • Added the addHeader, addIntHeader, and addDateHeader methods to the HttpServletResponse interface to allow multiple headers to be created with the same header name.

  • Added the getAttribute, getAttributeNames, setAttribute, and removeAttribute methods to the HttpSession interface to improve the naming conventions of the API. The getValue, getValueNames, setValue, and removeValue methods are deprecated as part of this change.

In addition, a large number of clarifications have been made to spec.


Chapter SRV.2. Terms Used

These terms are widely used throughout the rest of this specification.


SRV.2.1 Basic Terms

SRV.2.1.1 Uniform Resource Locators

A uniform resource locator (URL) is a compact string representation of resources available via the network. Once the resource represented by a URL has been accessed, various operations may be performed on that resource. [1] URLs are a form of a uniform resource identifier (URI). URLs are typically of the form:

[1] See RFC 1738.

<protocol>//<servername>/<resource>

For the purposes of this specification, we are primarily interested in HTTP based URLs which are of the form:

http[s]://<servername>[:port]/<url-path>[?<query-string>]

For example:

http://java.sun.com/products/servlet/index.html

https://javashop.sun.com/purchase

In HTTP based URLs, the '/' character is reserved for use to separate a hierarchical path structure in the URL-path portion of the URL. The server is responsible for determining the meaning of the hierarchical structure. There is no correspondence between a URL-path and a given file system path.

SRV.2.1.2 Servlet Definition

A servlet definition is a unique name associated with a fully qualified class name of a class implementing the Servlet interface. A set of initialization parameters can be associated with a servlet definition.

SRV.2.1.3 Servlet Mapping

A servlet mapping is a servlet definition that is associated by a servlet container with a URL path pattern. All requests to that path pattern are handled by the servlet associated with the servlet definition.

SRV.2.1.4 Web Application

A web application is a collection of servlets, JavaServer Pages, [2] HTML documents, and other web resources which might include image files, compressed archives, and other data. A web application may be packaged into an archive or exist in an open directory structure.

[2] See the JavaServer Pages specification, Section JSP, in this volume.

All compatible servlet containers must accept a web application and perform a deployment of its contents into their runtime. This may mean that a container can run the application directly from a web application archive file or it may mean that it will move the contents of a web application into the appropriate locations for that particular container.

SRV.2.1.5 Web Application Archive

A web application archive is a single file which contains all of the components of a web application. This archive file is created by using standard JAR tools which allow any or all of the web components to be signed.

Web application archive files are identified by the .war extension. A new extension is used instead of .jar because that extension is reserved for files which contain a set of class files and that can be placed in the classpath or double clicked using a GUI to launch an application. As the contents of a web application archive are not suitable for such use, a new extension was in order.


SRV.2.2 Roles

The following roles are defined to aid in identifying the actions and responsibilities taken by various parties during the development, deployment, and running of a servlet based application. In some scenarios, a single party may perform several roles; in others, each role may be performed by a different party.

SRV.2.2.1 Application Developer

The application developer is the producer of a web based application. His or her output is a set of servlet classes, JSP pages, HTML pages, and supporting libraries and files (such as images, compressed archive files, etc.) for the web application. The application developer is typically an application domain expert. The developer is required to be aware of the servlet environment and its consequences when programming, including concurrency considerations, and create the web application accordingly.

SRV.2.2.2 Application Assembler

The application assembler takes the work done by the developer and ensures that it is a deployable unit. The input of the application assembler is the servlet classes, JSP pages, HTML pages, and other supporting libraries and files for the web application. The output of the application assembler is a web application archive or a web application in an open directory structure.

SRV.2.2.3 Deployer

The deployer takes one or more web application archive files or other directory structures provided by an application developer and deploys the application into a specific operational environment. The operational environment includes a specific servlet container and web server. The deployer must resolve all the external dependencies declared by the developer. To perform his role, the deployer uses tools provided by the servlet container.

The deployer is an expert in a specific operational environment. For example, the deployer is responsible for mapping the security roles defined by the application developer to the user groups and accounts that exist in the operational environment where the web application is deployed.

SRV.2.2.4 System Administrator

The system administrator is responsible for the configuration and administration of the servlet container and web server. The administrator is also responsible for overseeing the well-being of the deployed web applications at runtime.

This specification does not define the contracts for system management and administration. The administrator typically uses runtime monitoring and management tools provided by the container provider and server vendors to accomplish these tasks.

SRV.2.2.5 Servlet Container Provider

The servlet container provider is responsible for providing the runtime environment, namely the servlet container and possibly the web server, in which a web application runs as well as the tools necessary to deploy web applications.

The expertise of the container provider is in HTTP level programming. Since this specification does not specify the interface between the web server and the servlet container, it is left to the container provider to split the implementation of the required functionality between the container and the server.


SRV.2.3 Security Terms

SRV.2.3.1 Principal

A principal is an entity that can be authenticated by an authentication protocol. A principal is identified by a principal name and authenticated by using authentication data. The content and format of the principal name and the authentication data depend on the authentication protocol.

SRV.2.3.2 Security Policy Domain

A security policy domain is a scope over which security policies are defined and enforced by a security administrator of the security service. A security policy domain is also sometimes referred to as a realm.

SRV.2.3.3 Security Technology Domain

A security technology domain is the scope over which the same security mechanism, such as Kerberos, is used to enforce a security policy. Multiple security policy domains can exist within a single technology domain.

SRV.2.3.4 Role

A role is an abstract notion used by a developer in an application that can be mapped by the deployer to a user, or group of users, in a security policy domain.


Chapter SRV.3. The Servlet Interface

The Servlet interface is the central abstraction of the servlet API. All servlets implement this interface either directly, or more commonly, by extending a class that implements the interface. The two classes in the API that implement the Servlet interface are GenericServlet and HttpServlet. For most purposes, developers will typically extend HttpServlet to implement their servlets.


SRV.3.1 Request Handling Methods

The basic Servlet interface defines a service method for handling client requests. This method is called for each request that the servlet container routes to an instance of a servlet. Multiple request threads may be executing within the service method at any time.

SRV.3.1.1 HTTP Specific Request Handling Methods

The HttpServlet abstract subclass adds additional methods which are automatically called by the service method in the HttpServlet class to aid in processing HTTP based requests. These methods are:

  • doGet for handling HTTP GET requests

  • doPost for handling HTTP POST requests

  • doPut for handling HTTP PUT requests

  • doDelete for handling HTTP DELETE requests

  • doHead for handling HTTP HEAD requests

  • doOptions for handling HTTP OPTIONS requests

  • doTrace for handling HTTP TRACE requests

Typically, when developing HTTP based servlets, a servlet developer will only concern himself with the doGet and doPost methods. The rest of these methods are considered to be advanced methods for use by programmers very familiar with HTTP programming.

The doPut and doDelete methods allow servlet developers to support HTTP/1.1 clients which support these features. The doHead method in HttpServlet is a specialized method that will execute the doGet method but return only the headers produced by the doGet method to the client. The doOptions method automatically determines which HTTP methods are directly supported by the servlet and returns that information to the client. The doTrace method causes a response with a message containing all of the headers sent in the TRACE request.

In containers that support only HTTP/1.0, only the doGet, doHead, and doPost methods will be used as HTTP/1.0 does not define the PUT, DELETE, OPTIONS, and TRACE methods.

SRV.3.1.2 Conditional GET Support

The HttpServlet interface defines the getLastModified method to support conditional get operations. A conditional get operation is one in which the client requests a resource with the HTTP GET method and adds a header that indicates that the content body should be sent only if it has been modified since a specified time.

Servlets that implement the doGet method and that provide content that does not necessarily change from request to request should implement this method to aid in efficient utilization of network resources.


SRV.3.2 Number of Instances

By default, there must be only one instance of a servlet class per servlet definition in a container.

In the case of a servlet that implements the SingleThreadModel interface, the servlet container may instantiate multiple instances of that servlet so that it can handle a heavy request load while still serializing requests to a single instance.

In the case where a servlet was deployed as part of an application that is marked in the deployment descriptor as distributable, there is one instance of a servlet class per servlet definition per VM in a container. If the servlet implements the SingleThreadModel interface as well as being part of a distributable web application, the container may instantiate multiple instances of that servlet in each VM of the container.

SRV.3.2.1 Note About SingleThreadModel

The use of the SingleThreadModel interface guarantees that one thread at a time will execute through a given servlet instance's service method. It is important to note that this guarantee only applies to servlet instance. Objects that can be accessible to more than one servlet instance at a time, such as instances of HttpSession, may be available to multiple servlets, including those that implement SingleThreadModel, at any particular time.


SRV.3.3 Servlet Life Cycle

A servlet is managed through a well-defined life cycle that defines how it is loaded, instantiated and initialized, handles requests from clients, and how it is taken out of service. This life cycle is expressed in the API by the init, service, and destroy methods of the javax.servlet.Servlet interface that all servlets must, directly or indirectly through the GenericServlet or HttpServlet abstract classes, implement.

SRV.3.3.1 Loading and Instantiation

The servlet container is responsible for loading and instantiating a servlet. The instantiation and loading can occur when the engine is started or it can be delayed until the container determines that it needs the servlet to service a request.

First, a class of the servlet's type must be located by the servlet container. If needed, the servlet container loads a servlet using normal Java class loading facilities from a local file system, a remote file system, or other network services.

After the container has loaded the Servlet class, it instantiates an object instance of that class for use.

It is important to note that there can be more than one instance of a given Srvlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to use.

SRV.3.3.2 Initialization

After the servlet object is loaded and instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read any persistent configuration data, initialize costly resources (such as JDBC™ based connection), and perform any other one-time activities. The container initializes the servlet by calling the init method of the Servlet interface with a unique (per servlet definition) object implementing the ServletConfig interface. This configuration object allows the servlet to access name-value initialization parameters from the servlet container's configuration information. The configuration object also gives the servlet access to an object implementing the ServletContext interface which describes the runtime environment that the servlet is running within. See Chapter SRV.4, "Servlet Context," for more information about the ServletContext interface.

SRV.3.3.2.1 Error Conditions on Initialization

During initialization, the servlet instance can signal that it is not to be placed into active service by throwing an UnavailableException or ServletException. If a servlet instance throws an exception of this type, it must not be placed into active service and the instance must be immediately released by the servlet container. The destroy method is not called in this case as initialization was not considered to be successful.

After the instance of the failed servlet is released, a new instance may be instantiated and initialized by the container at any time. The only exception to this rule is if the UnavailableException is thrown by the failed servlet, which indicates the minimum time of unavailability. In this case, the container must wait for the minimum time of unavailability to pass before creating and initializing a new servlet instance.

SRV.3.3.2.2 Tool Considerations

When a tool loads and introspects a web application, it may load and introspect member classes of the web application. This will trigger static initialization methods to be executed. Because of this behavior, a developer should not assume that a servlet is in an active container runtime unless the init method of the Servlet interface is called. For example, this means that a servlet should not try to establish connections to databases or Enterprise JavaBeans™ component architecture containers when its static (class) initialization methods are invoked.

SRV.3.3.3 Request Handling

After the servlet is properly initialized, the servlet container may use it to handle requests. Each request is represented by a request object of type ServletRequest and the servlet can create a response to the request by using the provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface. In the case of an HTTP request, the container must provide the request and response objects as implementations of HttpServletRequest and HttpServletResponse.

It is important to note that a servlet instance may be created and placed into service by a servlet container but may handle no requests during its lifetime.

SRV.3.3.3.1 Multithreading Issues

During the course of servicing requests from clients, a servlet container may send multiple requests from multiple clients through the service method of the servlet at any one time. This means that the developer must take care to make sure that the servlet is properly programmed for concurrency.

If a developer wants to prevent this default behavior, he can program the servlet to implement the SingleThreadModel interface. Implementing this interface will guarantee that only one request thread at a time will be allowed in the service method. A servlet container may satisfy this guarantee by serializing requests on a servlet or by maintaining a pool of servlet instances. If the servlet is part of an application that has been marked as distributable, the container may maintain a pool of servlet instances in each VM that the application is distributed across.

If a developer defines a service method (or methods such as doGet or doPost which are dispatched from the service method of the HttpServlet abstract class) with the synchronized keyword, the servlet container will, by necessity of the underlying Java runtime, serialize requests through it. However, the container must not create an instance pool as it does for servlets that implement the SingleThreadModel. It is strongly recommended that developers not synchronize the service method or any of the HttpServlet service methods such as doGet, doPost, etc.

SRV.3.3.3.2 Exceptions During Request Handling

A servlet may throw either a ServletException or an UnavailableException during the service of a request. A ServletException signals that some error occurred during the processing of the request and that the container should take appropriate measures to clean up the request. An UnavailableException signals that the servlet is unable to handle requests either temporarily or permanently.

If a permanent unavailability is indicated by the UnavailableException, the servlet container must remove the servlet from service, call its destroy method, and release the servlet instance.

If temporary unavailability is indicated by the UnavailableException, then the container may choose not to route any requests through the servlet during the time period of the temporary unavailability. Any requests refused by the container during this period must be returned with a SERVICE_UNAVAILABLE (503) response status along with a Retry-After header indicating when the unavailability will terminate. The container may choose to ignore the distinction between a permanent and temporary unavailability and treat all UnavailableExceptions as permanent, thereby removing a servlet that throws any UnavailableException from service.

SRV.3.3.3.3 Thread Safety

A developer should note that implementations of the request and response objects are not guaranteed to be thread safe. This means that they should be used only in the scope of the request handling thread. References to the request and response objects should not be given to objects executing in other threads as the behavior may be nondeterministic.

SRV.3.3.4 End of Service

The servlet container is not required to keep a servlet loaded for any period of time. A servlet instance may be kept active in a servlet container for a period of only milliseconds, for the lifetime of the servlet container (which could be measured in days, months, or years), or for any amount of time in between.

When the servlet container determines that a servlet should be removed from service (for example, when a container wants to conserve memory resources, or when it itself is being shut down), it must allow the servlet to release any resources it is using and save any persistent state. To do this the servlet container calls the destroy method of the Servlet interface.

Before the servlet container can call the destroy method, it must allow any threads that are currently running in the service method of the servlet to either complete or exceed a server defined time limit before the container can proceed with calling the destroy method.

Once the destroy method is called on a servlet instance, the container may not route any more requests to that particular instance of the servlet. If the container needs to enable the servlet again, it must do so with a new instance of the servlet's class.

After the destroy method completes, the servlet container must release the servlet instance so that it is eligible for garbage collection.


Chapter SRV.4. Servlet Context

The ServletContext defines a servlet's view of the web application within which the servlet is running. The ServletContext also allows a servlet to access resources available to it. Using such an object, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. The container provider is responsible for providing an implementation of the ServletContext interface in the servlet container.

A ServletContext is rooted at a specific path within a web server. For example, a context could be located at http://www.mycorp.com/catalog. All requests that start with the /catalog request path, which is known as the context path, will be routed to this servlet context.

Only one instance of a ServletContext may be available to the servlets in a web application. In cases where the web application indicates that it is distributable, there must be only one instance of the ServletContext object in use per application per Java virtual machine.


SRV.4.1 Scope of a ServletContext

There is one instance of the ServletContext interface associated with each web application deployed into a container. In cases where the container is distributed over many virtual machines, there is one instance per web application per VM.

Servlets that exist in a container that were not deployed as part of a web application are implicitly part of a "default" web application and are contained by a default ServletContext. In a distributed container, the default ServletContext is non-distributable and must exist on only one VM.


SRV.4.2 Initialization Parameters

A set of context initialization parameters can be associated with a web application and are made available by the following methods of the ServletContext interface:

  • getInitParameter

  • getInitParameterNames

Initialization parameters can be used by an application developer to convey setup information, such as a webmaster's e-mail address or the name of a system that holds critical data.


SRV.4.3 Context Attributes

A servlet can bind an object attribute into the context by name. Any object bound into a context is available to any other servlet that is part of the same web application. The following methods of ServletContext interface allow access to this functionality:

  • setAttribute

  • getAttribute

  • getAttributeNames

  • removeAttribute

SRV.4.3.1 Context Attributes in a Distributed Container

Context attributes exist locally in the VM in which they were created and placed. This prevents the ServletContext from being used as a distributed shared memory store. If information needs to be shared between servlets running in a distributed environment, that information should be placed into a session (see Chapter SRV.7, "Sessions"), a database, or set in an Enterprise JavaBean.


SRV.4.4 Resources

The ServletContext interface allows direct access to the static document hierarchy of content documents, such as HTML, GIF, and JPEG files, that are part of the web application via the following methods of the ServletContext interface:

  • getResource

  • getResourceAsStream

Both the getResource and getResourceAsStream methods take a String argument giving the path of the resource relative to the root of the context.

It is important to note that these methods give access to static resources from whatever repository the server uses. This hierarchy of documents may exist in a file system, in a web application archive file, on a remote server, or at some other location. These methods are not used to obtain dynamic content. For example, in a container supporting the JavaServer Pages specification, [1] a method call of the form getResource("/index.jsp") would return the JSP source code and not the processed output. See Chapter SRV.8, "Dispatching Requests," for more information about accessing dynamic content.

[1] See the JavaServer Pages specification, Section JSP, in this volume.


SRV.4.5 Multiple Hosts and Servlet Contexts

Many web servers support the ability for multiple logical hosts to share the same IP address on a server. This capability is sometimes referred to as "virtual hosting." If a servlet container's host web server has this capability, each unique logical host must have its own servlet context or set of servlet contexts. A servlet context cannot be shared across virtual hosts.


SRV.4.6 Reloading Considerations

Many servlet containers support servlet reloading for ease of development. Reloading of servlet classes has been accomplished by previous generations of servlet containers by creating a new class loader to load the servlet which is distinct from class loaders used to load other servlets or the classes that they use in the servlet context. This can have the undesirable side effect of causing object references within a servlet context to point at a different class or object than expected, which can cause unexpected behavior.

Therefore, when a container provider implements a class reloading scheme for ease of development, they must ensure that all servlets, and classes that they may use, are loaded in the scope of a single class loader guaranteeing that the application will behave as expected by the developer.


SRV.4.7 Temporary Working Directories

It is often useful for application developers to have a temporary working area on the local file system. All servlet containers must provide a private temporary directory per servlet context and make it available via the context attribute of javax.servlet.context.tempdir. The object associated with the attribute must be of type java.io.File.


Chapter SRV.5. The Request

The request object encapsulates all information from the client request. In the HTTP protocol, this information is transmitted from the client to the server by the HTTP headers and the message body of the request.


SRV.5.1 Parameters

Request parameters are strings sent by the client to a servlet container as part of a request. When the request is a HttpServletRequest, the attributes are populated from the URI query string and possibly posted form data. The parameters are stored by the servlet container as a set of name-value pairs. Multiple parameter values can exist for any given parameter name. The following methods of the ServletRequest interface are available to access parameters:

  • getParameter

  • getParameterNames

  • getParameterValues

The getParameterValues method returns an array of String objects containing all the parameter values associated with a parameter name. The value returned from the getParameter method must always equal the first value in the array of String objects returned by getParameterValues.

All form data from both the query string and the post body are aggregated into the request parameter set. The order of this aggregation is that query string data takes precedence over post body parameter data. For example, if a request is made with a query string of a=hello and a post body of a=goodbye&a=world, the resulting parameter set would be ordered a=(hello, goodbye, world).

Posted form data is read from the input stream of the request and used to populate the parameter set only when all of the following conditions are met:

  1. The request is an HTTP or HTTPS request.

  2. The HTTP method is POST.

  3. The content type is application/x-www-form-urlencoded.

  4. The servlet calls any of the getParameter family of methods on the request object.

If any of the getParameter family of methods is not called, or not all of the above conditions are met, the post data must remain available for the servlet to read via the request's input stream.


SRV.5.2 Attributes

Attributes are objects associated with a request. Attributes may be set by the container to express information that otherwise could not be expressed via the API, or may be set by a servlet to communicate information to another servlet (via RequestDispatcher). Attributes are accessed with the following methods of the ServletRequest interface:

  • getAttribute

  • getAttributeNames

  • setAttribute

Only one attribute value may be associated with an attribute name. Attribute names beginning with the prefixes "java." and "javax." are reserved for definition by this specification. Similarly, attribute names beginning with the prefixes "sun." and "com.sun." are reserved for definition by Sun Microsystems. It is suggested that all attributes placed into the attribute set be named in accordance with the reverse package name convention suggested by the Java Programming Language Specification [1] for package naming.

[1] The Java Programming Language Specification is available at http://java.sun.com/docs/books/jls.


SRV.5.3 Headers

A servlet can access the headers of an HTTP request through the following methods of the HttpServletRequest interface:

  • getHeader

  • getHeaders

  • getHeaderNames

The getHeader method allows access to the value of a header given the name of the header. Multiple headers, such as the Cache-Control header, can be present in an HTTP request. If there are multiple headers with the same name in a request, the getHeader method returns the first header contained in the request. The getHeaders method allows access to all the header values associated with a particular header name returning an Enumeration of String objects.

Headers may contain data that is better expressed as an int or a Date object. The following convenience methods of the HttpServletRequest interface provide access to header data in one of these formats:

  • getIntHeader

  • getDateHeader

If the getIntHeader method cannot translate the header value to an int, a NumberFormatException is thrown. If the getDateHeader method cannot translate the header to a Date object, an IllegalArgumentException is thrown.


SRV.5.4 Request Path Elements

The request path that leads to a servlet servicing a request is composed of many important sections. The following elements are obtained from the request URI path and exposed via the request object:

  • Context path: The path prefix associated with the ServletContext that this servlet is a part of. If this context is the "default" context rooted at the base of the web server's URL namespace, this path will be an empty string. Otherwise, this path starts with a '/' character but does not end with a '/' character.

  • Servlet path: The path section that directly corresponds to the mapping which activated this request. This path starts with a '/' character.

  • Path info: The part of the request path that is not part of the context path or the servlet path.

The following methods exist in the HttpServletRequest interface to access this information:

  • getContextPath

  • getServletPath

  • getPathInfo

It is important to note that, except for URL encoding differences between the request URI and the path parts, the following equation is always true:

requestURI = contextPath + servletPath + pathInfo

To give a few examples to clarify the above points, consider Table SRV.5-1.

Table SRV.5-1. Example Context Setup

Context Path

/catalog

Servlet Mapping

Pattern: /lawn

Servlet: LawnServlet

Servlet Mapping

Pattern: /garden

Servlet: GardenServlet

Servlet Mapping

Pattern: *.jsp

Servlet: JSPServlet

The behavior in Table SRV.5-2 is observed.

Table SRV.5-2. Observed Path Element Behavior

Request Path

Path Elements

/catalog/lawn/index.html

ContextPath: /catalog

ServletPath: /lawn

PathInfo: /index.html

/catalog/garden/implements/

ContextPath: /catalog

ServletPath: /garden

PathInfo: /implements/

/catalog/help/feedback.jsp

ContextPath: /catalog

ServletPath: /help/feedback.jsp

PathInfo: null


SRV.5.5 Path Translation Methods

There are two convenience methods in the HttpServletRequest interface which allow the developer to obtain the file system path equivalent to a particular path. These methods are:

  • getRealPath

  • getPathTranslated

The getRealPath method takes a String argument and returns a String representation of a file on the local file system to which that path corresponds. The getPathTranslated method computes the real path of the pathInfo of this request.

In situations where the servlet container cannot determine a valid file path for these methods, such as when the web application is executed from an archive, on a remote file system not accessible locally, or in a database, these methods must return null.


SRV.5.6 Cookies

The HttpServletRequest interface provides the getCookies method to obtain an array of cookies that are present in the request. These cookies are data sent from the client to the server on every request that the client makes. Typically, the only information that the client sends back as part of a cookie is the cookie name and the cookie value. Other cookie attributes that can be set when the cookie is sent to the browser, such as comments, are not typically returned.


SRV.5.7 SSL Attributes

If a request has been transmitted over a secure protocol, such as HTTPS, this information must be exposed via the isSecure method of the ServletRequest interface.

In servlet containers that are running in a Java 2 Standard Edition, v1.2 or Java 2 Enterprise Edition, v1.2 environment, if there is an SSL certificate associated with the request, it must be exposed to the servlet programmer as an array of objects of type java.security.cert.X509Certificate and accessible via a ServletRequest attribute of javax.servlet.request.X509Certificate.

For a servlet container that is not running in a Java2 Standard Edition 1.2 environment, vendors may provide vendor specific request attributes to access SSL certificate information.


SRV.5.8 Internationalization

Clients may optionally indicate to a web server what language they would prefer the response be given in. This information can be communicated from the client using the Accept-Language header along with other mechanisms described in the HTTP/1.1 specification. The following methods are provided in the ServletRequest interface to determine the preferred locale of the sender:

  • getLocale

  • getLocales

The getLocale method will return the preferred locale that the client will accept content in. See Section 14.4 of RFC 2616 (HTTP/1.1) for more information about how the Accept-Language header must be interpreted to determine the preferred language of the client.

The getLocales method will return an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client.

If no preferred locale is specified by the client, the locale returned by the getLocale method must be the default locale for the servlet container and the getLocales method must contain an enumeration of a single locale element of the default locale.


Chapter SRV.6. The Response

The response object encapsulates all information to be returned from the server to the client. In the HTTP protocol, this information is transmitted from the server to the client either by HTTP headers or the message body of the request.


SRV.6.1 Buffering

In order to improve efficiency, a servlet container is allowed, but not required by default, to buffer output going to the client. The following methods are provided via the ServletResponse interface to allow a servlet access to, and the setting of, buffering information:

  • getBufferSize

  • setBufferSize

  • isCommitted

  • reset

  • flushBuffer

These methods are provided on the ServletResponse interface to allow buffering operations to be performed whether the servlet is using a ServletOutputStream or a Writer.

The getBufferSize method returns the size of the underlying buffer being used. If no buffering is being used for this response, this method must return the int value of 0 (zero).

The servlet can request a preferred buffer size for the response by using the setBufferSize method. The actual buffer assigned to this request is not required to be the same size as requested by the servlet, but must be at least as large as the buffer size requested. This allows the container to reuse a set of fixed size buffers, provid-ing a larger buffer than requested, if appropriate. This method must be called before any content is written using a ServletOutputStream or Writer. If any content has been written, this method must throw an IllegalStateException.

The isCommitted method returns a boolean value indicating whether or not any bytes from the response have yet been returned to the client. The flushBuffer method forces any content in the buffer to be written to the client.

The reset method clears any data that exists in the buffer as long as the response is not considered to be committed. All headers and the status code set by the servlet previous to the reset called must be cleared as well.

If the response is committed and the reset method is called, an IllegalStateException must be thrown. In this case, the response and its associated buffer will be unchanged.

When the buffer in use is filled, the container must immediatly flush the contents of the buffer to the client. If this is the first time for this request that data is sent to the client, the response is considered to be committed at this point.


SRV.6.2 Headers

A servlet can set headers of an HTTP response via the following methods of the HttpServletResponse interface:

  • setHeader

  • addHeader

The setHeader method sets a header with a given name and value. If a previous header exists, it is replaced by the new header. In the case where a set of header values exist for the given name, all values are cleared and replaced with the new value.

The addHeader method adds a header value to the set of headers with a given name. If there are no headers already associated with the given name, this method will create a new set.

Headers may contain data that is better expressed as an int or a Date object. The following convenience methods of the HttpServletResponse interface allow a servlet to set a header using the correct formatting for the appropriate data type:

  • setIntHeader

  • setDateHeader

  • addIntHeader

  • addDateHeader

In order to be successfully transmitted back to the client, headers must be set before the response is committed. Any headers set after the response is committed will be ignored by the servlet container.


SRV.6.3 Convenience Methods

The following convenience methods exist in the HttpServletResponse interface:

  • sendRedirect

  • sendError

The sendRedirect method will set the appropriate headers and content body to redirect the client to a different URL. It is legal to call this method with a relative URL path; however, the underlying container must translate the relative path to a fully qualified URL for transmission back to the client. If a partial URL is given and, for whatever reason, cannot be converted into a valid URL, then this method must throw an IllegalArgumentException.

The sendError method will set the appropriate headers and content body to return to the client. An optional String argument can be provided to the sendError method which can be used in the content body of the error.

These methods will have the side effect of committing the response, if it had not already been committed, and terminating it. No further output to the client should be made by the servlet after these methods are called. If data is written to the response after these methods are called, the data is ignored.

If data has been written to the response buffer, but not returned to the client (i.e., the response is not committed), the data in the response buffer must be cleared and replaced with the data set by these methods. If the response is committed, these methods must throw an IllegalStateException.


SRV.6.4 Internationalization

In response to a request by a client to obtain a document of a particular language, or perhaps due to preference setting by a client, a servlet can set the language attributes of a response back to a client. This information is communicated via the Content-Language header along with other mechanisms described in the HTTP/1.1 specification. The language of a response can be set with the setLocale method of the ServletResponse interface. This method must correctly set the appropriate HTTP headers to accurately communicate the locale to the client.

For maximum benefit, the setLocale method should be called by the developer before the getWriter method of the ServletResponse interface is called. This will ensure that the returned PrintWriter is configured appropriately for the target Locale.

If the setContentType method is called after the setLocale method and there is a charset component to the given content type, the charset specified in the content type overrides the value set via the call to setLocale.


SRV.6.5 Closure of Response Object

A number of events can indicate that the servlet has provided all of the content to satisfy the request and that the response object can be considered to be closed. The events are:

  • The termination of the service method of the servlet.

  • When the amount of content specified in the setContentLength method of the response has been written to the response.

  • The sendError method is called.

  • The sendRedirect method is called.

When a response is closed, all content in the response buffer, if any remains, must be immediately flushed to the client.


Chapter SRV.7. Sessions

The hypertext transfer protocol (HTTP) is by design a stateless protocol. To build effective web applications, it is imperative that a series of different requests from a particular client can be associated with each other. Many strategies for session tracking have evolved over time, but all are difficult or troublesome for the programmer to use directly.

This specification defines a simple HttpSession interface that allows a servlet container to use any number of approaches to track a user's session without involving the developer in the nuances of any one approach.


SRV.7.1 Session Tracking Mechanisms

SRV.7.1.1 URL Rewriting

URL rewriting is the lowest common denominator of session tracking. In cases where a client will not accept a cookie, URL rewriting may be used by the server to establish session tracking. URL rewriting involves adding data to the URL path that can be interpreted by the container on the next request to associate the request with a session.

The session id must be encoded as a path parameter in the resulting URL string. The name of the parameter must be jsessionid. Here is an example of a URL containing encoded path information:

http://www.myserver.com/catalog/index.html;jsessionid=1234

SRV.7.1.2 Cookies

Session tracking through HTTP cookies is the most used session tracking mechanism and is required to be supported by all servlet containers. The container sends a cookie to the client. The client will then return the cookie on each subsequent request to the server unambiguously associating the request with a session. The name of the session tracking cookie must be JSESSIONID.

SRV.7.1.3 SSL Sessions

Secure sockets layer, the encryption technology which is used in the HTTPS protocol, has a mechanism built into it allowing multiple requests from a client to be unambiguously identified as being part of an accepted session. A servlet container can easily use this data to serve as the mechanism for defining a session.


SRV.7.2 Creating a Session

Because HTTP is a request-response based protocol, a session is considered to be new until a client "joins" it. A client joins a session when session tracking information has been successfully returned to the server indicating that a session has been established. Until the client joins a session, it cannot be assumed that the next request from the client will be recognized as part of the session.

The session is considered to be "new" if either of the following is true:

  • The client does not yet know about the session.

  • The client chooses not to join a session. This implies that the servlet container has no mechanism by which to associate a request with a previous request.

A servlet developer must design their application to handle a situation where a client has not, cannot, or will not join a session.


SRV.7.3 Session Scope

HttpSession objects must be scoped at the application/servlet context level. The underlying mechanism, such as the cookie used to establish the session, can be shared between contexts, but the object exposed, and more importantly the attributes in that object, must not be shared between contexts.


SRV.7.4 Binding Attributes into a Session

A servlet can bind an object attribute into an HttpSession implementation by name. Any object bound into a session is available to any other servlet that belongs to the same ServletContext and that handles a request identified as being a part of the same session.

Some objects may require notification when they are placed into, or removed from, a session. This information can be obtained by having the object implement the HttpSessionBindingListener interface. This interface defines the following methods that will signal an object being bound into, or being unbound from, a session.

  • valueBound

  • valueUnbound

The valueBound method must be called before the object is made available via the getAttribute method of the HttpSession interface. The valueUnbound method must be called after the object is no longer available via the getAttribute method of the HttpSession interface.


SRV.7.5 Session Timeouts

In the HTTP protocol, there is no explicit termination signal when a client is no longer active. This means that the only mechanism that can be used to indicate when a client is no longer active is a timeout period.

The default timeout period for sessions is defined by the servlet container and can be obtained via the getMaxInactiveInterval method of the HttpSession interface. This timeout can be changed by the developer using the setMaxInactiveInterval of the HttpSession interface. The timeout period used by these methods is defined in seconds. If the timeout period for a session is set to -1, the session will never expire.


SRV.7.6 Last Accessed Times

The getLastAccessedTime method of the HttpSession interface allows a servlet to determine the last time the session was accessed before the current request. The session is considered to be accessed when a request that is part of the session is handled by the servlet context.


SRV.7.7 Important Session Semantics

SRV.7.7.1 Threading Issues

Multiple servlets executing request threads may have active access to a single session object at the same time. The developer has the responsibility to synchronize access to resources stored in the session as appropriate.

SRV.7.7.2 Distributed Environments

Within an application that is marked as distributable, all requests that are part of a session can be handled on only a single VM at any one time. In addition, all objects placed into instances of the HttpSession class using the setAttribute or putValue methods must implement the Serializable interface. The servlet container may throw an IllegalArgumentException if a non-serializable object is placed into the session.

These restrictions mean that the developer is ensured that there are no additional concurrency issues beyond those encountered in a non-distributed container. In addition, the container provider can ensure scalability by having the ability to move a session object, and its contents, from any active node of the distributed system to a different node of the system.

SRV.7.7.3 Client Semantics

Due to the fact that cookies or SSL certificates are typically controlled by the web browser process and are not associated with any particular window of the browser, requests from all windows of a client application to a servlet container might be part of the same session. For maximum portability, the developer should always assume that all windows of a client are participating in the same session.


Chapter SRV.8. Dispatching Requests

When building a web application, it is often useful to forward processing of a request to another servlet, or to include the output of another servlet in the response. The RequestDispatcher interface provides a mechanism to accomplish this.


SRV.8.1 Obtaining a RequestDispatcher

An object implementing the RequestDispather interface may be obtained from the ServletContext via the following methods:

  • getRequestDispatcher

  • getNamedDispatcher

The getRequestDispatcher method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext. This path is used to look up a servlet, wrap it with a RequestDispatcher object, and return it. If no servlet can be resolved based on the given path, a RequestDispatcher is provided that simply returns the content for that path.

The getNamedDispatcher method takes a String argument indicating the name of a servlet known to the ServletContext. If a servlet is known to the ServletContext by the given name, it is wrapped with a RequestDispatcher object and returned. If no servlet is associated with the given name, the method must return null.

To allow RequestDispatcher objects to be obtained using relative paths, paths which are not relative to the root of the ServletContext but instead are relative to the path of the current request, the following method is provided in the ServletRequest interface:

  • getRequestDispatcher

The behavior of this method is similar to the behavior of the method of the same name in the ServletContext; however, it does not require a complete path within the context to be given as part of the argument to operate. The servlet container can use the information in the request object to transform the given relative path to a complete path. For example, in a context rooted at '/', a request to /garden/tools.html, a request dispatcher obtained via ServletRequest.getRequestDispatcher("header.html") will behave exactly like a call to ServletContext.getRequestDispatcher("/garden/header.html").

SRV.8.1.1 Query Strings in Request Dispatcher Paths

In the ServletContext and ServletRequest methods which allow the creation of a RequestDispatcher using path information, optional query string information may be attached to the path. For example, a developer may obtain a RequestDispatcher by using the following code:

String path = "/raisons.jsp?orderno=5";
RequestDispatcher rd = context.getRequestDispatcher(path);
rd.include(request, response);

The contents of the query string are added to the parameter set that the included servlet has access to. The parameters are ordered so that any parameters specified in the query string used to create the RequestDispatcher take precedence. The parameters associated with a RequestDispatcher are scoped only for the duration of the include or forward call.


SRV.8.2 Using a Request Dispatcher

To use a request dispatcher, a developer needs to call either the include or forward method of the RequestDispatcher interface using the request and response arguments that were passed in via the service method of the Servlet interface.

The container provider must ensure that the dispatch to a target servlet occurs in the same thread of the same VM as the original request.


SRV.8.3 include

The include method of the RequestDispatcher interface may be called at any time. The target servlet has access to all aspects of the request object, but can only write information to the ServletOutputStream or Writer of the response object as well as the ability to commit a response by either writing content past the end of the response buffer or explicitly calling the flush method of the ServletResponse interface. The included servlet cannot set headers or call any method that affects the headers of the response. Any attempt to do so should be ignored.

SRV.8.3.1 Included Request Parameters

When a servlet is being used from within an include, it is sometimes necessary for that servlet to know the path by which it was invoked and not the original request paths. The following request attributes are set:

javax.servlet.include.request_uri
javax.servlet.include.context_path
javax.servlet.include.servlet_path
javax.servlet.include.path_info
javax.servlet.include.query_string

These attributes are accessible from the included servlet via the getAttribute method on the ServletRequest object.

If the included servlet was obtained by using a NamedDispatcher, these attributes are not set.


SRV.8.4 forward

The forward method of the RequestDispatcher interface may be called by the calling servlet only if no output has been committed to the client. If output exists in the response buffer that has not been committed, it must be reset (clearing the buffer) before the target servlet's service method is called. If the response has been committed, an IllegalStateException must be thrown.

The path elements of the request object exposed to the target servlet must reflect the path used to obtain the RequestDispatcher. The only exception to this is if the RequestDispatcher was obtained via the getNamedDispatcher method. In this case, the path elements of the request object reflect those of the original request.

Before the forward method of the RequestDispatcher interface returns, the response must be committed and closed by the servlet container.


SRV.8.5 Error Handling

Only runtime exceptions and checked exceptions of type ServletException or IOException should be propagated to the calling servlet if thrown by the target of a request dispatcher. All other exceptions should be wrapped as a ServletException and the root cause of the exception set to the original exception.


Chapter SRV.9. Web Applications

A web application is a collection of servlets, HTML pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors. A web application is rooted at a specific path within a web server. For example, a catalog application could be located at http://www.mycorp.com/catalog. All requests that start with this prefix will be routed to the ServletContext which represents the catalog application.

A servlet container can also establish rules for automatic generation of web applications. For example, a ~user/ mapping could be used to map to a web application based at /home/user/public_html/.

By default an instance of a web application must be run on only one VM at any one time. This behavior can be overridden if the application is marked as "distributable" via its deployment descriptor. When an application is marked as distributable, the developer must obey a more restrictive set of rules than is expected of a normal web application. These specific rules are called out throughout this specification.


SRV.9.1 Relationship to ServletContext

The servlet container must enforce a one-to-one correspondence between a web application and a ServletContext. A ServletContext object can be viewed as a servlet's view onto its application.


SRV.9.2 Elements of a Web Application

A web application may consist of the following items:

  • Servlets

  • JavaServer Pages [1]

    [1] See the JavaServer Pages specification, Section JSP, in this volume.

  • Utility classes

  • Static documents (HTML, images, sounds, etc.)

  • Client side applets, beans, and classes

  • Descriptive meta information which ties all of the above elements together


SRV.9.3 Distinction Between Representations

This specification defines a hierarchical structure which can exist in an open file system, an archive file, or some other form for deployment purposes. It is recommended, but not required, that servlet containers support this structure as a runtime representation.


SRV.9.4 Directory Structure

A web application exists as a structured hierarchy of directories. The root of this hierarchy serves as a document root for serving files that are part of this context. For example, for a web application located at /catalog in a web server, the index.html file located at the base of the web application hierarchy can be served to satisfy a request to /catalog/index.html.

A special directory exists within the application hierarchy named "WEB-INF." This directory contains all things related to the application that aren't in the document root of the application. It is important to note that the WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client.

The contents of the WEB-INF directory are:

  • /WEB-INF/web.xml deployment descriptor.

  • /WEB-INF/classes/* directory for servlet and utility classes. The classes in this directory are used by the application class loader to load classes from.

  • /WEB-INF/lib/*.jar area for Java ARchive files which contain servlets, beans, and other utility classes useful to the web application. All such archive files are used by the web application class loader to load classes from.

SRV.9.4.1 Sample Web Application Directory Structure

Illustrated here is a listing of all the files in a sample web application:

/index.html
/howto.jsp
/feedback.jsp
/images/banner.gif
/images/jumping.gif
/WEB-INF/web.xml
/WEB-INF/lib/jspbean.jar
/WEB-INF/classes/com/mycorp/servlets/MyServlet.class
/WEB-INF/classes/com/mycorp/util/MyUtils.class


SRV.9.5 Web Application Archive File

Web applications can be packaged and signed, using the standard Java archive tools, into a Web ARchive format (WAR) file. For example, an application for issue tracking could be distributed in an archive with the filename issuetrack.war.

When packaged into such a form, a META-INF directory will be present which contains information useful to the Java archive tools. If this directory is present, the servlet container must not allow it be served as content to a web client's request.


SRV.9.6 Web Application Configuration Descriptor

The following types of configuration and deployment information exist in the web application deployment descriptor:

  • ServletContext init parameters

  • Session configuration

  • Servlet/JSP definitions

  • Servlet/JSP mappings

  • Mime type mappings

  • Welcome file list

  • Error pages

  • Security

All of these types of information are conveyed in the deployment descriptor (see Chapter SRV.13, "Deployment Descriptor").


SRV.9.7 Replacing a Web Application

Applications evolve and must occasionally be replaced. In a long running server it is ideal to be able to load a new web application and shut down the old one without restarting the container. When an application is replaced, a container should provide a robust approach to preserving session data within that application.


SRV.9.8 Error Handling

A web application may specify that when errors occur, other resources in the application are used. These resources are specified in the deployment descriptor (see Chapter SRV.13, "Deployment Descriptor"). If the location of the error handler is a servlet or a JSP, the following request attributes can be set:

  • javax.servlet.error.status_code

  • javax.servlet.error.exception_type

  • javax.servlet.error.message

These attributes allow the servlet to generate specialized content depending on the status code, exception type, and message of the error.


SRV.9.9 Web Application Environment

Java 2 Platform Enterprise Edition, v1.2 defines a naming environment that allows applications to easily access resources and external information without the explicit knowledge of how the external information is named or organized.

As servlets are an integral component type of J2EE, a provision has been made in the web application deployment descriptor for specifying information allowing a servlet to obtain references to resources and enterprise beans. The deployment elements that contain this information are:

  • env-entry

  • ejb-ref

  • resource-ref

The env-entry element contains information to set up basic environment entry names relative to the java:comp/env context, the expected Java type of the environment entry value (the type of object returned from the JNDI lookup method), and an optional environment entry value. The ejb-ref element contains the information needed to allow a servlet to locate the home interfaces of an enterprise bean. The resource-ref element contains the information needed to set up a resource factory.

The requirements of the J2EE environment with regard to setting up the environment are described in Chapter 5 of the Java 2 Platform Enterprise Edition v 1.2 specification. [2] Servlet containers that are not part of a J2EE compliant implementation are encouraged, but not required, to implement the application environment functionality described in the J2EE specification.

[2] The J2EE specification is available in Section J2EE of this volume.


Chapter SRV.10. Mapping Requests to Servlets

Previous versions of this specification have allowed servlet containers a great deal of flexibility in mapping client requests to servlets by merely suggesting a set of mapping techniques. This specification now requires a set of mapping techniques to be used for web applications which are deployed via the web application deployment mechanism. Just as it is highly recommended that servlet containers use the deployment representations as their runtime representation, it is highly recommended that they use these path mapping rules in their servers for all purposes and not just as part of deploying a web application.


SRV.10.1 Use of URL Paths

Servlet containers must use URL paths to map requests to servlets. The container uses the RequestURI from the request, minus the context path, as the path to map to a servlet. The URL path mapping rules are as follows (where the first match wins and no further rules are attempted):

  1. The servlet container will try to match the exact path of the request to a servlet.

  2. The container will then try to recursively match the longest path prefix mapping. This process occurs by stepping down the path tree a directory at a time, using the '/' character as a path separator, and determining if there is a match with a servlet.

  3. If the last node of the url-path contains an extension (.jsp for example), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the path after the last '.' character.

  4. If neither of the previous two rules results in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a "default" servlet is defined for the application, it will be used in this case.


SRV.10.2 Specification of Mappings

In the web application deployment descriptor, the following syntax is used to define mappings:

  • A string beginning with a '/' character and ending with a '/*' postfix is used as a path mapping.

  • A string beginning with a '*.' prefix is used as an extension mapping.

  • All other strings are used as exact matches only.

  • A string containing only the '/' character indicates that the servlet specified by the mapping becomes the "default" servlet of the application.

SRV.10.2.1 Implicit Mappings

If the container has an internal JSP container, the *.jsp extension is implicitly mapped to it so that JSP pages may be executed on demand. If the web application defines a *.jsp mapping, its mapping takes precedence over this implicit mapping.

A servlet container is allowed to make other implicit mappings as long as explicit mappings take precedence. For example, an implicit mapping of *.shtml could be mapped by a container to a server side including functionality.

SRV.10.2.2 Example Mapping Set

Consider the set of mappings in Table SRV.10-1.

Table SRV.10-1. Example Set of Maps

Path Pattern

Servlet

/foo/bar/*

servlet1

/baz/*

servlet2

/catalog

servlet3

*.bop

servlet4

The behavior in Table SRV.10-2 would result.

Table SRV.10-2. Incoming Paths Applied to Example Maps

Incoming Path

Servlet Handling Request

/foo/bar/index.html

servlet1

/foo/bar/index.bop

servlet1

/baz

servlet2

/baz/index.html

servlet2

/catalog

servlet3

/catalog/index.html

"default" servlet

/catalog/racecar.bop

servlet4

/index.bop

servlet4

Note that in the case of /catalog/index.html and /catalog/racecar.bop, the servlet mapped to "/catalog" is not used as it is not an exact match and the rule doesn't include the '*' character.


Chapter SRV.11. Security

Web applications are created by a developer, who then gives, sells, or otherwise transfers the application to the deployer for installation into a runtime environment. It is useful for the developer to communicate attributes about how the security should be set up for a deployed application.

As with the web application directory layout and deployment descriptor, the elements of this section are required only as a deployment representation, not a runtime representation. However, it is recommended that containers implement these elements as part of their runtime representation.


SRV.11.1 Introduction

A web application contains many resources that can be accessed by many users. Sensitive information often traverses unprotected open networks, such as the Internet. In such an environment, there is a substantial number of web applications that have some level of security requirements. Most servlet containers have the specific mechanisms and infrastructure to meet these requirements. Although the quality assurances and implementation details may vary, all of these mechanisms share some of the following characteristics:

  • Authentication: The mechanism by which communicating entities prove to one another that they are acting on behalf of specific identities.

  • Access control for resources: The mechanism by which interactions with resources are limited to collections of users or programs for the purpose of enforcing availability, integrity, or confidentiality.

  • Data integrity: The mechanism used to prove that information could not have been modified by a third party while in transit.

  • Confidentiality or data privacy: The mechanism used to ensure that the information is made available only to users who are authorized to access it and is not compromised during transmission.


SRV.11.2 Declarative Security

Declarative security refers to the means of expressing an application's security structure, including roles, access control, and authentication requirements in a form external to the application. The deployment descriptor is the primary vehicle for declarative security in web applications.

The deployer maps the application's logical security requirements to a representation of the security policy that is specific to the runtime environment. At runtime, the servlet container uses the security policy that was derived from the deployment descriptor and configured by the deployer to enforce authentication.


SRV.11.3 Programmatic Security

Programmatic security is used by security aware applications when declarative security alone is not sufficient to express the security model of the application. Programmatic security consists of the following methods of the HttpServletRequest interface:

  • getRemoteUser

  • isUserInRole

  • getUserPrincipal

The getRemoteUser method returns the user name that the client authenticated with. The isUserInRole queries the underlying security mechanism of the container to determine if a particular user is in a given security role. The getUserPrincipal method returns a java.security.Principal object.

These APIs allow servlets to make business logic decisions based on the logical role of the remote user. They also allow the servlet to determine the principal name of the current user.

If getRemoteUser returns null (which means that no user has been authenticated), the isUserInRole method will always return false, and the getUserPrincipal will always return null.


SRV.11.4 Roles

A role is an abstract logical grouping of users that is defined by the application developer or assembler. When the application is deployed, these roles are mapped by a deployer to security identities, such as principals or groups, in the runtime environment.

A servlet container enforces declarative or programmatic security for the principal associated with an incoming request based on the security attributes of that calling principal. For example,

  1. When a deployer has mapped a security role to a user group in the operational environment, the user group to which the calling principal belongs is retrieved from its security attributes. If the principal's user group matches the user group in the operational environment that the security role has been mapped to, the principal is in the security role.

  2. When a deployer has mapped a security role to a principal name in a security policy domain, the principal name of the calling principal is retrieved from its security attributes. If the principal is the same as the principal to which the security role was mapped, the calling principal is in the security role.


SRV.11.5 Authentication

A web client can authenticate a user to a web server using one of the following mechanisms:

  • HTTP basic authentication

  • HTTP digest authentication

  • HTTPS client authentication

  • Form based authentication

SRV.11.5.1 HTTP Basic Authentication

HTTP basic authentication is the authentication mechanism defined in the HTTP/1.1 specification. This mechanism is based on a username and password. A web server requests a web client to authenticate the user. As part of the request, the web server passes the string called the realm of the request in which the user is to be authenticated. It is important to note that the realm string of the basic authentication mechanism does not have to reflect any particular security policy domain (which, confusingly, can also be referred to as a realm). The web client obtains the username and the password from the user and transmits them to the web server. The web server then authenticates the user in the specified realm.

Basic authentication is not a secure authentication protocol as the user password is transmitted with a simple base64 encoding and the target server is not authenticated. However, additional protection, such as applying a secure transport mechanism (HTTPS) or using security at the network level (such as the IPSEC protocol or VPN strategies), can alleviate some of these concerns.

SRV.11.5.2 HTTP Digest Authentication

Like HTTP basic authentication, HTTP digest authentication authenticates a user based on a username and a password. However the authentication is performed by transmitting the password in an encrypted form which is much more secure than the simple base64 encoding used by basic authentication. This authentication method is not as secure as any private key scheme such as HTTPS client authentication. As digest authentication is not currently in widespread use, servlet containers are not required, but are encouraged, to support it.

SRV.11.5.3 Form Based Authentication

The look and feel of the "login screen" cannot be controlled with an HTTP browser's built-in authentication mechanisms. Therefore this specification defines a form based authentication mechanism which allows a developer to control the look and feel of the login screens.

The web application deployment descriptor contains entries for a login form and error page to be used with this mechanism. The login form must contain fields for the user to specify username and password. These fields must be named 'j_username' and 'j_password', respectively.

When a user attempts to access a protected web resource, the container checks if the user has been authenticated. If so, and dependent on the user's authority to access the resource, the requested web resource is activated and returned. If the user is not authenticated, all of the following steps occur:

  1. The login form associated with the security constraint is returned to the client. The URL path which triggered the authentication is stored by the container.

  2. The client fills out the form, including the username and password fields.

  3. The form is posted back to the server.

  4. The container processes the form to authenticate the user. If authentication fails, the error page is returned.

  5. The authenticated principal is checked to see if it is in an authorized role for accessing the original web request.

  6. The client is redirected to the original resource using the original stored URL path.

If the user is not successfully authenticated, the error page is returned to the client. It is recommended that the error page contains information that allows the user to determine that the authorization failed.

Like basic authentication, this is not a secure authentication protocol as the user password is transmitted as plain text and the target server is not authenticated. However, additional protection, such as applying a secure transport mechanism (HTTPS) or using security at the network level (IPSEC or VPN), can alleviate some of these concerns.

SRV.11.5.3.1 Login Form Notes

Form based login and URL based session tracking can be problematic to implement. It is strongly recommended that form based login be used only when the session is being maintained by cookies or by SSL session information.

In order for the authentication to proceed appropriately, the action of the login form must always be "j_security_check." This restriction is made so that the login form will always work no matter what the resource is that requests it and avoids requiring that the server process the outbound form to correct the action field.

Here is an HTML sample showing how the form should be coded into the HTML page:

<form method="POST" action="j_security_check">
<input type="text" name="j_username">
<input type="password" name="j_password">
</form>

SRV.11.5.4 HTTPS Client Authentication

End user authentication using HTTPS (HTTP over SSL) is a strong authentication mechanism. This mechanism requires the user to possess a public key certificate (PKC). Currently, PKCs are useful in e-commerce applications and also for single-signon from within the browser in an enterprise. Servlet containers that are not J2EE compliant are not required to support the HTTPS protocol.


SRV.11.6 Server Tracking of Authentication Information

As the underlying security identities (such as users and groups) to which roles are mapped in a runtime environment are environment specific rather than application specific, it is desirable to:

  1. Make login mechanisms and policies a property of the environment the web application is deployed in.

  2. Be able to use the same authentication information to represent a principal to all applications that are deployed in the same container.

  3. Require the user to re-authenticate only when crossing a security policy domain.

Therefore, a servlet container is required to track authentication information at the container level and not at the web application level, allowing a user who is authenticated against one web application to access any other resource managed by the container which is restricted to the same security identity.


SRV.11.7 Specifying Security Constraints

Security constraints are a declarative way of annotating the intended protection of web content. A constraint consists of the following elements:

  • Web resource collection

  • Authorization constraint

  • User data constraint

A web resource collection is a set of URL patterns and HTTP methods that describe a set of resources to be protected. All requests that contain a request path that matches the URL pattern described in the web resource collection is subject to the constraint.

An authorization constraint is a set of roles that users must be a part of to access the resources described by the web resource collection. If the user is not part of an allowed role, the user is denied access to that resource.

A user data constraint indicates that the transport layer of the client server communication process satisfies the requirement of either guaranteeing content integrity (preventing tampering in transit) or guaranteeing confidentiality (preventing reading while in transit).

SRV.11.7.1 Default Policies

By default, authentication is not needed to access resources. Authentication is needed only for requests in a specific web resource collection when specified by the deployment descriptor.


Chapter SRV.12. Application Programming Interface

This is a listing of the interfaces, classes, and exceptions that compose the Servlet API. For detailed descriptions of these members and their methods, please see the Java Servlet API Reference, v2.2 (see the SRV Preface for the URL).

Items in boldface are new in this version of the specification.

Table SRV.12-1. Servlet API Package Summary

Package javax.servlet

Package javax.serlvet.http

RequestDispatcher

HttpServletRequest

Servlet

HttpServletResponse

ServletConfig

HttpSession

ServletContext

HttpSessionBindingListener

ServletRequest

HttpSessionContext

ServletResponse

Cookie

SingleThreadModel

HttpServlet

GenericServlet

HttpSessionBindingEvent

ServletInputStream

HttpUtils

ServletOutputStream

ServletException

UnavailableException


SRV.12.1 Package javax.servlet

SRV.12.1.1 RequestDispatcher

public interface RequestDispatcher

public void forward(ServletRequest req, ServletResponse res);
public void include(ServletRequest req, ServletResponse res);

SRV.12.1.2 Servlet

public interface Servlet

public void init(ServletConfig config) throws ServletException;
public ServletConfig getServletConfig();
public void service(ServletRequest req, ServletResponse res)
    throws IOException, ServletException;
public String getServletInfo();
public void destroy();

SRV.12.1.3 ServletConfig

public interface ServletConfig

public ServletContext getServletContext();
public String getInitParameter(String name);
public Enumeration getInitParameterNames();
public String getServletName();

SRV.12.1.4 ServletContext

public interface ServletContext

public String getMimeType(String filename);
public URL getResource(String path) throws MalformedURLException;
public InputStream getResourceAsStream(String path);
public RequestDispatcher getRequestDispatcher(String path);
public RequestDispatcher getNamedDispatcher(String name);
public String getRealPath(String path);
public ServletContext getContext(String uripath);
public String getServerInfo();
public String getInitParameter(String name);
public Enumeration getInitParameterNames();
public Object getAttribute(String name);
public Enumeration getAttributeNames();
public void setAttribute(String name, Object attribute);
public void removeAttribute(String name);
public int getMajorVersion();
public int getMinorVersion();
public void log(String message);
public void log(String message, Throwable cause);

// deprecated methods
public Servlet getServlet(String name) throws ServletException;
public Enumeration getServlets();
public Enumeration getServletNames();
public void log(Exception exception, String message);

SRV.12.1.5 ServletRequest

public interface ServletRequest

public Object getAttribute(String name);
public Object setAttribute(String name, Object attribute);
public Enumeration getAttributeNames();
public void removeAttribute(String name);
public Locale getLocale();
public Enumeration getLocales();
public String getCharacterEncoding();
public int getContentLength();
public String getContentType();
public ServletInputStream getInputStream() throws IOException;
public String getParameter(String name);
public String getParameterNames();
public String getParameterValues();
public String getProtocol();
public String getScheme();
public String getServerName();
public int getServerPort();
public BufferedReader getReader() throws IOException;
public String getRemoteAddr();
public String getRemoteHost();
public boolean isSecure();
public RequestDispatcher getRequestDispatcher(String path);

// deprecated methods
public String getRealPath();

SRV.12.1.6 ServletResponse

public interface ServletResponse

public String getCharacterEncoding();
public ServletOutputStream getOutputStream() throws IOException
public PrintWriter getWriter throws IOException
public void setContentLength(int length);
public void setContentType(String type);
public void setBufferSize(int size);
public int getBufferSize();
public void reset();
public boolean isCommitted();
public void flushBuffer() throws IOException;
public void setLocale(Locale locale);
public Locale getLocale();

SRV.12.1.7 SingleThreadModel

public interface SingleThreadModel

// no methods

SRV.12.1.8 GenericServlet

public abstract class GenericServlet implements Servlet

public GenericServlet();

public String getInitParameter();
public Enumeration getInitParameterNames();
public ServletConfig getServletConfig();
public ServletContext getServletContext();
public String getServletInfo();
public void init();
public void init(ServletConfig config) throws ServletException;
public void log(String message);
public void log(String message, Throwable cause);
public abstract void service(ServletRequest req,
  ServletResponse res) throws ServletException, IOException.;
public void destroy();

SRV.12.1.9 ServletInputStream

public abstract class ServletInputStream extends InputStream

public ServletInputStream();

public int readLine(byte[] buffer, int offset, int length)
  throws IOException;

SRV.12.1.10 ServletOutputStream

public abstract class ServletOutputStream extends OutputStream

public ServletOutputStream();

public void print(String s) throws IOException;
public void print(boolean b) throws IOException;
public void print(char c) throws IOException;
public void print(int i) throws IOException;
public void print(long l) throws IOException;
public void print(float f) throws IOException;
public void print(double d) throws IOException;
public void println() throws IOException;
public void println(String s) throws IOException;
public void println(boolean b) throwsIOException;
public void println(char c) throws IOException;
public void println(int i) throws IOException;
public void println(long l) throws IOException;
public void println(float f) throws IOException;
public void println(double d) throws IOException;

SRV.12.1.11 ServletException

public class ServletException extends Exception;

public ServletException();
public ServletException(String message);
public ServletException(String message, Throwable cause);
public ServletException(Throwable cause);

public Throwable getRootCause();

SRV.12.1.12 UnavailableException

public class UnavailableException extends ServletException

public UnavailableException(String message);
public UnavailableException(String message, int sec);

public int getUnavailableException();
public boolean isPermanent();

// newly deprecated methods
public UnavailableException(Servlet servlet, String message);
public UnavailableException(int sec, Servlet servlet, String msg);

public Servlet getServlet();

SRV.12.2 Package javax.servlet.http

interface HttpServletRequest
interface HttpServletResponse
interface HttpSession
interface HttpSessionBindingListener
interface HttpSessionContext

class Cookie
class HttpServlet
class HttpSessionBindingEvent
class HttpUtils

SRV.12.2.1 HttpServletRequest

public interface HttpServletRequest extends ServletRequest;

public String getAuthType();
public Cookie[] getCookies();
public long getDateHeader(String name);
public String getHeader(String name);
public Enumeration getHeaders(String name);
public Enumeration getHeaderNames();
public int getIntHeader(String name);
public String getMethod();
public String getContextPath();
public String getPathInfo();
public String getPathTranslated();
public String getQueryString();
public String getRemoteUser();
public boolean isUserInRole(String role);
public java.security.Principal getUserPrincipal();
public String getRequestedSessionId();
public boolean isRequestedSessionIdValid();
public boolean isRequestedSessionIdFromCookie();
public boolean isRequestedSessionIdFromURL();
public String getRequestURI();
public String getServletPath();
public HttpSession getSession();
public HttpSession getSession(boolean create);

// deprecated methods

public boolean isRequestSessionIdFromUrl();

SRV.12.2.2 HttpServletResponse

public interface HttpServletResponse extends ServletResponse
<<< STATUS CODES 416 AND 417 REPORTED MISSING>>>

public static final int SC_CONTINUE;
public static final int SC_SWITCHING_PROTOCOLS;
public static final int SC_OK;
public static final int SC_CREATED;
public static final int SC_ACCEPTED;
public static final int SC_NON_AUTHORITATIVE_INFORMATION;
public static final int SC_NO_CONTENT;
public static final int SC_RESET_CONTENT;
public static final int SC_PARTIAL_CONTENT;
public static final int SC_MULTIPLE_CHOICES;
public static final int SC_MOVED_PERMANENTLY;
public static final int SC_MOVED_TEMPORARILY;
public static final int SC_SEE_OTHER;
public static final int SC_NOT_MODIFIED;
public static final int SC_USE_PROXY;
public static final int SC_BAD_REQUEST;
public static final int SC_UNAUTHORIZED;
public static final int SC_PAYMENT_REQUIRED;
public static final int SC_FORBIDDEN;
public static final int SC_NOT_FOUND;
public static final int SC_METHOD_NOT_ALLOWED;
public static final int SC_NOT_ACCEPTABLE;
public static final int SC_PROXY_AUTHENTICATION_REQUIRED;
public static final int SC_REQUEST_TIMEOUT;
public static final int SC_CONFLICT;
public static final int SC_GONE;
public static final int SC_LENGTH_REQUIRED;
public static final int SC_PRECONDITION_FAILED;
public static final int SC_REQUEST_ENTITY_TOO_LARGE;
public static final int SC_REQUEST_URI_TOO_LONG;
public static final int SC_UNSUPPORTED_MEDIA_TYPE;
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE;
public static final int SC_EXPECTATION_FAILED;
public static final int SC_INTERNAL_SERVER_ERROR;
public static final int SC_NOT_IMPLEMENTED;
public static final int SC_BAD_GATEWAY;
public static final int SC_SERVICE_UNAVAILABLE;
public static final int SC_GATEWAY_TIMEOUT;
public static final int SC_VERSION_NOT_SUPPORTED;

public void addCookie(Cookie cookie);
public boolean containsHeader(String name);
public String encodeURL(String url);
public String encodeRedirectURL(String url);
public void sendError(int status) throws IOException;
public void sendError(int status, String message)
       throws IOException;
public void sendRedirect(String location) throws IOException;
public void setDateHeader(String headername, long date);
public void setHeader(String headername, String value);
public void addHeader(String headername, String value);
public void addDateHeader(String headername, long date);
public void addIntHeader(String headername, int value);
public void setIntHeader(String headername, int value);
public void setStatus(int statuscode);

// deprecated methods
public void setStatus(int statuscode, String message);
public String encodeUrl(String url);
public String encodeRedirectUrl(String url);

SRV.12.2.3 HttpSession

public interface HttpSession

public long getCreationTime();
public String getId();
public long getLastAccessedTime();
public boolean isNew();
public int getMaxInactiveInterval();
public void setMaxInactiveInterval(int interval);
public Object getAttribute(String name);
public Enumeration getAttributeNames();
public void setAttribute(String name, Object attribute);
public void removeAttribute(String name);
public void invalidate();

// deprecated methods
public Object getValue(String name);
public String[] getValueNames();
public void putValue(String name, Object value);
public void removeValue(String name);
public HttpSessionContext getSessionContext();

SRV.12.2.4 HttpSessionBindingListener

public interface HttpSessionBindingListener extends EventListener

public void valueBound(HttpSessionBindingEvent event);
public void valueUnbound(HttpSessionBindingEvent event);

SRV.12.2.5 HttpSessionContext

// deprecated
public abstract interface HttpSessionContext

// deprecated methods
public void Enumeration getIds();
public HttpSession getSession(String id);

SRV.12.2.6 Cookie

public class Cookie implements Cloneable

public Cookie(String name, String value);
public void setComment(String comment);
public String getComment();
public void setDomain(String domain);
public String getDomain();
public void setMaxAge(int expiry);
public int getMaxAge();
public void setPath(String uriPath);
public String getPath();
public void setSecure();
public boolean getSecure();
public String getName();
public void setValue(String value);
public String getValue();
public int getVersion();
public void setVersion(int version);
public Object clone();

SRV.12.2.7 HttpServlet

public abstract class HttpServlet extends GenericServlet
    implements Serializable

public HttpServlet();
protected void doGet(HttpServletRequest req,
    HttpServletResponse res) throws ServletException, IOException;
protected void doPost(HttpServletRequest req,
    HttpServletResponse res) throws ServletException, IOException;
protected void doPut(HttpServletRequest req,
    HttpServletResponse res) throws ServletException, IOException;
protected void doDelete(HttpServletRequest req,
    HttpServletResponse res) throws ServletException, IOException;
protected void doOptions(HttpServletRequest req,
    HttpServletResponse res) throws ServletException, IOException;
protected void doTrace(HttpServletRequest req,
    HttpServletResponse res) throws ServletException, IOException;
protected void service(HttpServletRequest req,
    HttpServletResponse res) throws ServletException, IOException;
public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException;
protected long getLastModifed(HttpServletRequest req);

SRV.12.2.8 HttpSessionBindingEvent

public class HttpSessionBindingEvent extends EventObject

public HttpSessionBindingEvent(HttpSession session, String name);

public String getName();
public HttpSession getSession();

SRV.12.2.9 HttpUtils

public class HttpUtils

public HttpUtils();

public static Hashtable parseQueryString(String queryString);
public static Hashtable parsePostData(int length,
    ServletInputStream in);
public static StringBuffer getRequestURL(HttpServletRequest req);


Chapter SRV.13. Deployment Descriptor

The deployment descriptor conveys the elements and configuration information of a web application between developers, assemblers, and deployers.


SRV.13.1 Deployment Descriptor Elements

The following types of configuration and deployment information exist in the web application deployment descriptor:

  • ServletContext init parameters

  • Session configuration

  • Servlet/JSP definitions

  • Servlet/JSP mappings

  • Mime type mappings

  • Welcome file list

  • Error pages

  • Security

See the DTD comments for further description of these elements.

SRV.13.1.1 Deployment Descriptor DOCTYPE

All valid web application deployment descriptors must contain the following DOCTYPE declaration:

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.
//DTD Web Application 2.2
//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">


SRV.13.2 DTD

The DTD that follows defines the XML grammar for a web application deployment descriptor.

<!--
The web-app element is the root of the deployment descriptor for a
web application
-->

<!ELEMENT web-app (icon?, display-name?, description?,
distributable?, context-param*, servlet*, servlet-mapping*,
session-config?, mime-mapping*, welcome-file-list?, error-page*,
taglib*, resource-ref*, security-constraint*, login-config?,
security-role*, env-entry*, ejb-ref*)>

<!--
The icon element contains a small-icon and a large-icon element
which specify the location within the web application for a small
and large image used to represent the web application in a GUI
tool. At a minimum, tools must accept GIF and JPEG format images.
-->

<!ELEMENT icon (small-icon?, large-icon?)>

<!--
The small-icon element contains the location within the web
application of a file containing a small (16x16 pixel) icon image.
-->

<!ELEMENT small-icon (#PCDATA)>

<!--
The large-icon element contains the location within the web
application of a file containing a large (32x32 pixel) icon image.
-->

<!ELEMENT large-icon (#PCDATA)>

<!--
The display-name element contains a short name that is intended to
be displayed by GUI tools
-->

<!ELEMENT display-name (#PCDATA)>

<!--
The description element is used to provide descriptive text about
the parent element.
-->

<!ELEMENT description (#PCDATA)>

<!--
The distributable element, by its presence in a web application
deployment descriptor, indicates that this web application is
programmed appropriately to be deployed into a distributed servlet
container
-->

<!ELEMENT distributable EMPTY>

<!--
The context-param element contains the declaration of a web
application's servlet context initialization parameters.
-->

<!ELEMENT context-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)>

<!--
The servlet element contains the declarative data of a servlet. If
a jsp-file is specified and the load-on-startup element is
present, then the JSP should be precompiled and loaded.
-->

<!ELEMENT servlet (icon?, servlet-name, display-name?,
description?, (servlet-class|jsp-file), init-param*, load-on-
startup?, security-role-ref*)>

<!--
The servlet-name element contains the canonical name of the
servlet.
-->

<!ELEMENT servlet-name (#PCDATA)>

<!--
The servlet-class element contains the fully qualified class name
of the servlet.
-->

<!ELEMENT servlet-class (#PCDATA)>

<!--
The jsp-file element contains the full path to a JSP file within
the web application.
-->

<!ELEMENT jsp-file (#PCDATA)>

<!--
The init-param element contains a name/value pair as an
initialization param of the servlet
-->

<!ELEMENT init-param (param-name, param-value, description?)>

<!--
The load-on-startup element indicates that this servlet should be
loaded on the startup of the web application. The optional
contents of these elements must be a positive integer indicating
the order in which the servlet should be loaded. Lower integers
are loaded before higher integers. If no value is specified, or if
the value specified is not a positive integer, the container is
free to load it at any time in the startup sequence.
-->

<!ELEMENT load-on-startup (#PCDATA)>

<!--
The servlet-mapping element defines a mapping between a servlet
and a url pattern
-->

<!ELEMENT servlet-mapping (servlet-name, url-pattern)>

<!--
The url-pattern element contains the url pattern of the
mapping. Must follow the rules specified in Section 10 of the
Servlet API Specification.
-->

<!ELEMENT url-pattern (#PCDATA)>

<!--
The session-config element defines the session parameters for
this web application.
-->

<!ELEMENT session-config (session-timeout?)>

<!--
The session-timeout element defines the default session timeout
interval for all sessions created in this web application. The
specified timeout must be expressed in a whole number of minutes.
-->

<!ELEMENT session-timeout (#PCDATA)>

<!--
The mime-mapping element defines a mapping between an extension
and a mime type.
-->

<!ELEMENT mime-mapping (extension, mime-type)>

<!--
The extension element contains a string describing an
extension. example: "txt"
-->

<!ELEMENT extension (#PCDATA)>

<!--
The mime-type element contains a defined mime type. example:
"text/plain"
-->

<!ELEMENT mime-type (#PCDATA)>

<!--
The welcome-file-list contains an ordered list of welcome file
elements.
-->

<!ELEMENT welcome-file-list (welcome-file+)>

<!--
The welcome-file element contains file names to use as a default
welcome file, such as index.html
-->

<!ELEMENT welcome-file (#PCDATA)>

<!--
The taglib element is used to describe a JSP tag library.
-->

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

<!--
The taglib-uri element describes a URI, relative to the location
of the web.xml document, identifying a tag library used in the web
application.
-->

<!ELEMENT taglib-uri (#PCDATA)>

<!--
the taglib-location element contains the location (as a resource
relative to the root of the web application) where to find the tag
libary description file for the tag library.
-->

<!ELEMENT taglib-location (#PCDATA)>

<!--
The error-page element contains a mapping between an error code
or exception type to the path of a resource in the web application
-->

<!ELEMENT error-page ((error-code | exception-type), location)>

<!--
The error-code contains an HTTP error code, ex: 404
-->

<!ELEMENT error-code (#PCDATA)>

<!--
The exception type contains a fully qualified class name of a
Java exception type.
-->

<!ELEMENT exception-type (#PCDATA)>

<!--
The location element contains the location of the resource in the
web application
-->

<!ELEMENT location (#PCDATA)>

<!--
The resource-ref element contains a declaration of a web
application's reference to an external resource.
-->

<!ELEMENT resource-ref (description?, res-ref-name, res-type, res-auth)>

<!--
The res-ref-name element specifies the name of the resource
factory reference name.
-->

<!ELEMENT res-ref-name (#PCDATA)>

<!--
The res-type element specifies the (Java class) type of the data
source.
-->

<!ELEMENT res-type (#PCDATA)>

<!--
The res-auth element indicates whether the application component
code performs resource signon programmatically or whether the
container signs onto the resource based on the principle mapping
information supplied by the deployer. Must be CONTAINER or SERVLET
-->

<!ELEMENT res-auth (#PCDATA)>

<!--
The security-constraint element is used to associate security
constraints with one or more web resource collections
-->

<!ELEMENT security-constraint (web-resource-collection+,
auth-constraint?, user-data-constraint?)>

<!--
The web-resource-collection element is used to identify a subset
of the resources and HTTP methods on those resources within a web
application to which a security constraint applies. If no HTTP
methods are specified, then the security constraint applies to all
HTTP methods.
-->

<!ELEMENT web-resource-collection (web-resource-name,
description?, url-pattern*, http-method*)>

<!--
The web-resource-name contains the name of this web resource
collection
-->

<!ELEMENT web-resource-name (#PCDATA)>

<!--
The http-method contains an HTTP method (GET | POST |...)
-->

<!ELEMENT http-method (#PCDATA)>

<!--
The user-data-constraint element is used to indicate how data
communicated between the client and container should be protected
-->

<!ELEMENT user-data-constraint (description?, transport-guarantee)>

<!--
The transport-guarantee element specifies that the communication
between client and server should be NONE, INTEGRAL, or
CONFIDENTIAL. NONE means that the application does not require any
transport guarantees. A value of INTEGRAL means that the
application requires that the data sent between the client and
server be sent in such a way that it can't be changed in transit.
CONFIDENTIAL means that the application requires that the data be
transmitted in a fashion that prevents other entities from
observing the contents of the transmission. In most cases, the
presence of the INTEGRAL or CONFIDENTIAL flag will indicate that
the use of SSL is required.
-->

<!ELEMENT transport-guarantee (#PCDATA)>
<!--
The auth-constraint element indicates the user roles that should
be permitted access to this resource collection. The role used
here must appear in a security-role-ref element.
-->

<!ELEMENT auth-constraint (description?, role-name*)>

<!--
The role-name element contains the name of a security role.
-->

<!ELEMENT role-name (#PCDATA)>

<!--
The login-config element is used to configure the authentication
method that should be used, the realm name that should be used for
this application, and the attributes that are needed by the form
login mechanism.
-->

<!ELEMENT login-config (auth-method?, realm-name?, form-login-
config?)>

<!--
The realm name element specifies the realm name to use in HTTP
basic authorization
-->

<!ELEMENT realm-name (#PCDATA)>

<!--
The form-login-config element specifies the login and error pages
that should be used in form based login. If form based
authentication is not used, these elements are ignored.
-->

<!ELEMENT form-login-config (form-login-page, form-error-page)>

<!--
The form-login-page element defines the location in the web app
where the page that can be used for login can be found
-->

<!ELEMENT form-login-page (#PCDATA)>

<!--
The form-error-page element defines the location in the web app
where the error page that is displayed when login is not
successful can be found
-->

<!ELEMENT form-error-page (#PCDATA)>

<!--
The auth-method element is used to configure the authentication
mechanism for the web application. As a prerequisite to gaining
access to any web resources which are protected by an
authorization constraint, a user must have authenticated using the
configured mechanism. Legal values for this element are "BASIC,"
"DIGEST," "FORM," or "CLIENT-CERT."
-->

<!ELEMENT auth-method (#PCDATA)>

<!--
The security-role element contains the declaration of a security
role which is used in the security-constraints placed on the web
application.
-->

<!ELEMENT security-role (description?, role-name)>

<!--
The role-name element contains the name of a role. This element
must contain a non-empty string.
-->

<!ELEMENT security-role-ref (description?, role-name, role-link)>

<!--
The role-link element is used to link a security role reference
to a defined security role. The role-link element must contain the
name of one of the security roles defined in the security-role
elements.
-->

<!ELEMENT role-link (#PCDATA)>

<!--
The env-entry element contains the declaration of an application's
environment entry. This element is required to be honored in J2EE
compliant servlet containers.
-->

<!ELEMENT env-entry (description?, env-entry-name, env-entry-
value?,
env-entry-type)>

<!--
The env-entry-name contains the name of an application's
environment entry
-->

<!ELEMENT env-entry-name (#PCDATA)>

<!--
The env-entry-value element contains the value of an
application's environment entry
-->

<!ELEMENT env-entry-value (#PCDATA)>

<!--
The env-entry-type element contains the fully qualified Java type
of the environment entry value that is expected by the application
code. The following are the legal values of env-entry-type:
java.lang.Boolean, java.lang.String, java.lang.Integer,
java.lang.Double, java.lang.Float.
-->

<!ELEMENT env-entry-type (#PCDATA)>

<!--
The ejb-ref element is used to declare a reference to an
enterprise bean.
-->

<!ELEMENT ejb-ref (description?, ejb-ref-name, ejb-ref-type, home,
remote, ejb-link?)>

<!--
The ejb-ref-name element contains the name of an EJB reference.
This is the JNDI name that the servlet code uses to get a
reference to the enterprise bean.
-->

<!ELEMENT ejb-ref-name (#PCDATA)>

<!--
The ejb-ref-type element contains the expected java class type of
the referenced EJB.
-->

<!ELEMENT ejb-ref-type (#PCDATA)>

<!--
The ejb-home element contains the fully qualified name of the
EJB's home interface
-->

<!ELEMENT home (#PCDATA)>

<!--
The ejb-remote element contains the fully qualified name of the
EJB's remote interface
-->

<!ELEMENT remote (#PCDATA)>

<!--
The ejb-link element is used in the ejb-ref element to specify
that an EJB reference is linked to an EJB in an encompassing Java2
Enterprise Edition (J2EE) application package. The value of the
ejb-link element must be the ejb-name of and EJB in the J2EE
application package.
-->

<!ELEMENT ejb-link (#PCDATA)>

<!--
The ID mechanism is to allow tools to easily make tool-specific
references to the elements of the deployment descriptor. This
allows tools that produce additional deployment information (i.e
information beyond the standard deployment descriptor information)
to store the non-standard information in a separate file, and
easily refer from these tools-specific files to the information in
the standard web-app deployment descriptor.
-->

<!ATTLIST web-app id ID #IMPLIED>
<!ATTLIST icon id ID #IMPLIED>
<!ATTLIST small-icon id ID #IMPLIED>
<!ATTLIST large-icon id ID #IMPLIED>
<!ATTLIST display-name id ID #IMPLIED>
<!ATTLIST description id ID #IMPLIED>
<!ATTLIST distributable id ID #IMPLIED>
<!ATTLIST context-param id ID #IMPLIED>
<!ATTLIST param-name id ID #IMPLIED>
<!ATTLIST param-value id ID #IMPLIED>
<!ATTLIST servlet id ID #IMPLIED>
<!ATTLIST servlet-name id ID #IMPLIED>
<!ATTLIST servlet-class id ID #IMPLIED>
<!ATTLIST jsp-file id ID #IMPLIED>
<!ATTLIST init-param id ID #IMPLIED>
<!ATTLIST load-on-startup id ID #IMPLIED>
<!ATTLIST servlet-mapping id ID #IMPLIED>
<!ATTLIST url-pattern id ID #IMPLIED>
<!ATTLIST session-config id ID #IMPLIED>
<!ATTLIST session-timeout id ID #IMPLIED>
<!ATTLIST mime-mapping id ID #IMPLIED>
<!ATTLIST extension id ID #IMPLIED>
<!ATTLIST mime-type id ID #IMPLIED>
<!ATTLIST welcome-file-list id ID #IMPLIED>
<!ATTLIST welcome-file id ID #IMPLIED>
<!ATTLIST taglib id ID #IMPLIED>
<!ATTLIST taglib-uri id ID #IMPLIED>
<!ATTLIST taglib-location id ID #IMPLIED>
<!ATTLIST error-page id ID #IMPLIED>
<!ATTLIST error-code id ID #IMPLIED>
<!ATTLIST exception-type id ID #IMPLIED>
<!ATTLIST location id ID #IMPLIED>
<!ATTLIST resource-ref id ID #IMPLIED>
<!ATTLIST res-ref-name id ID #IMPLIED>
<!ATTLIST res-type id ID #IMPLIED>
<!ATTLIST res-auth id ID #IMPLIED>
<!ATTLIST security-constraint id ID #IMPLIED>
<!ATTLIST web-resource-collection id ID #IMPLIED>
<!ATTLIST web-resource-name id ID #IMPLIED>
<!ATTLIST http-method id ID #IMPLIED>
<!ATTLIST user-data-constraint id ID #IMPLIED>
<!ATTLIST transport-guarantee id ID #IMPLIED>
<!ATTLIST auth-constraint id ID #IMPLIED>
<!ATTLIST role-name id ID #IMPLIED>
<!ATTLIST login-config id ID #IMPLIED>
<!ATTLIST realm-name id ID #IMPLIED>
<!ATTLIST form-login-config id ID #IMPLIED>
<!ATTLIST form-login-page id ID #IMPLIED>
<!ATTLIST form-error-page id ID #IMPLIED>
<!ATTLIST auth-method id ID #IMPLIED>
<!ATTLIST security-role id ID #IMPLIED>
<!ATTLIST security-role-ref id ID #IMPLIED>
<!ATTLIST role-link id ID #IMPLIED>
<!ATTLIST env-entry id ID #IMPLIED>
<!ATTLIST env-entry-name id ID #IMPLIED>
<!ATTLIST env-entry-value id ID #IMPLIED>
<!ATTLIST env-entry-type id ID #IMPLIED>
<!ATTLIST ejb-ref id ID #IMPLIED>
<!ATTLIST ejb-ref-name id ID #IMPLIED>
<!ATTLIST ejb-ref-type id ID #IMPLIED>
<!ATTLIST home id ID #IMPLIED>
<!ATTLIST remote id ID #IMPLIED>
<!ATTLIST ejb-link id ID #IMPLIED>


SRV.13.3 Examples

The following examples illustrate the usage of the definitions listed above DTD.

SRV.13.3.1 A Basic Example

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.
//DTD Web Application 2.2
//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
  <display-name>A Simple Application</display-name>
  <context-param>
    <param-name>Webmaster</param-name>
    <param-value>webmaster@mycorp.com</param-value>
  </context-param>
  <servlet>
    <servlet-name>catalog</servlet-name>
    <servlet-class>com.mycorp.CatalogServlet</servlet-class>
    <init-param>
      <param-name>catalog</param-name>
      <param-value>Spring</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>catalog</servlet-name>
    <url-pattern>/catalog/*</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  <mime-mapping>
    <extension>pdf</extension>
    <mime-type>application/pdf</mime-type>
  </mime-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
  <welcome-file-list>
  <error-page>
    <error-code>404</error-code>
    <location>/404.html</location>
  </error-page>
</web-app>

SRV.13.3.2 An Example of Security

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.
//DTD Web Application 2.2
//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
  <display-name>A Secure Application</display-name>
  <security-role>
    <role-name>manager</role-name>
  </security-role>
  <servlet>
    <servlet-name>catalog</servlet-name>
    <servlet-class>com.mycorp.CatalogServlet</servlet-class>
    <init-param>
      <param-name>catalog</param-name>
      <param-value>Spring</param-value>
    </init-param>
    <security-role-ref>
      <role-name>MGR</role-name> <!-- role name used in code -->
      <role-link>manager</role-link>
    </security-role-ref>
  </servlet>
  <servlet-mapping>
    <servlet-name>catalog</servlet-name>
    <url-pattern>/catalog/*</url-pattern>
  </servlet-mapping>
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>SalesInfo</web-resource-name>
      <url-pattern>/salesinfo/*</url-pattern>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
      <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
      </user-data-constraint>
      <auth-constraint>
        <role-name>manager</role-name>
      </auth-constraint>
    </web-resource-collection>
  </security-constraint>
</web-app>


Chapter SRV.14. Futures

Many excellent suggestions for additions to this specification have been made by contributors from both our partners, and the general public. As time to market considerations constrain the amount of work that can be done for any particular revision of the specification, some of these suggestions cannot be incorporated in this version of the specification. However, by including these items as future directions, we indicate that we will be considering them for inclusion into a future revision of the specification.

The following are items under consideration:

  • Filtering of response content

  • Allowing easy access to internationalized content via the getResource method of the ServletContext interface

  • Internationalization of web application content

  • WebDAV integration

  • Application event handlers

  • HTTP extensions framework integration

Please note that inclusion of an item on this list is not a commitment for inclusion in a future revision of this specification; it means only that the item is under serious consideration and may be included in a future revision.


JavaServer Pages™ Specification, v1.1 (JSP)

    Preface

    Chapter JSP.1. Overview

    Chapter JSP.2. Standard Syntax and Semantics

    Chapter JSP.3. The JSP Container

    Chapter JSP.4. Scripting

    Chapter JSP.5. Tag Extensions

    Chapter JSP.6. JSP Technology Classes

    Chapter JSP.7. JSP Pages as XML Documents

    Appendix JSP.A. Examples

    Appendix JSP.B. Implementation Notes

    Appendix JSP.C. Packaging JSP Pages

    Appendix JSP.D. Future

    Appendix JSP.E. Changes


Preface

This is the final version of the JavaServer Pages™ 1.1 Specification. This specification has been developed following the Java Community Process (JCP). Comments from experts, participants, and the public have been reviewed and incorporated into the specification where applicable.

JSP 1.1 extends JSP 1.0 by:

  • Using Servlet 2.2 as the foundation for its semantics.

  • Enabling the delivery of translated JSP pages into JSP containers.

  • Providing a portable tag extension mechanism.

Details on the conditions under which this document is distributed are described in the license found in the front matter of this book.


JSP.P.1 Who Should Read This Document

This document is intended for:

  • Web server and application server vendors that want to provide JSP containers that conform to the tag extensions specification.

  • Web authoring tool vendors that want to generate JSP pages that conform to the tag extensions specification.

  • Service providers that want to deliver functionality as tag libraries.

  • Sophisticated JSP page authors that want to define new tag libraries for their use, or who are responsible for creating tag libraries for the use of a group.

  • Eager JSP page authors who do not want to or cannot wait for web authoring tools, or even a user's guide.

This document is not a user's guide, but it contains some positioning and explanatory material.


JSP.P.2 Related Documents

JSP 1.1 requires only JDK™ 1.1 but it can take advantage of the Java 2 Platform, Standard Edition.

Implementors of JSP containers and authors of JSP pages will be interested in a number of other documents, of which those in Table JSP.P-1 are worth mentioning explicitly.

Table JSP.P-1. Some Related Documents

JSP Home Page

http://java.sun.com/products/jsp

Servlet Home Page

http://java.sun.com/products/servlet

JDK 1.1

http://java.sun.com/products/jdk/1.1

Java 2 Platform, Standard Edition

http://java.sun.com/products/jdk/1.2

Java 2 Platform, Enterprise Edition

http://java.sun.com/j2ee

XML in the Java Platform home page

http://java.sun.com/xml

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


JSP.P.3 Acknowledgments

Many people contributed to the JavaServer Pages specifications. In addition to the people who helped with the JSP 1.0 specification and reference implementation, we want to thank a few individuals for their special effort on the JSP 1.1 specification.

We want to thank the following people from Sun Microsystems: Suzanne Ahmed, Janet Breuer, Abhishek Chauhan, James Davidson, Chris Ferris, Michaela Gubbels, Mark Hapner, Jim Inscore, Costin Manalache, Rajiv Mordani, Mandar Raje, Bill Shannon, James Todd, Vanitha Venkatraman, Anil Vijendran, Connie Weiss, and Cara Zanoff France.

The success of the Java platform depends on the process used to define and evolve it. This open process permits the development of high quality specifications in Internet time and involves many individuals and corporations. Although it is impossible to list all the individuals who have contributed, we would like to give thanks explicitly to the following individuals: JJ Allaire, Elias Bayeh, Hans Bergsten, Vince Bonfanti, Bjorn Carlston, Shane Claussen, Mike Conner, Scott Ferguson, Bob Foster, Mike Freedman, Chris Gerken, Sanjeev Kumar, Craig McClanahan, Rod Magnuson, Stefano Mazzocchi, Rod McChesney, Dave Navas, Tom Reilly, Simeon Simeonov, and Edwin Smith. Apologies to any we may have missed.

Last, but certainly not least important, we thank the software developers, web authors, and members of the general public who have read this specification, used the reference implementation, and shared their experience. You are the reason the JavaServer Pages technology exists.


Chapter JSP.1. Overview

This chapter provides an overview of the JavaServer Pages technology.


JSP.1.1 The JavaServer Pages™ Technology

JavaServer Pages™ technology is the Java™ platform technology for building applications containing dynamic web content such as HTML, DHTML, XHTML, and XML. The JavaServer Pages technology enables the authoring of web pages that create dynamic content easily but with maximum power and flexibility.

The JavaServer Pages technology offers a number of advantages:

  • Write Once, Run Anywhere™ properties

    The JavaServer Pages technology is platform independent, in its dynamic web pages, its web servers, and its underlying server components. You can author JSP pages on any platform, run them on any web server or web enabled application server, and access them from any web browser. You can also build the server components on any platform and run them on any server.

  • High quality tool support

    The Write Once, Run Anywhere properties of JSP allow the 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.

  • 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 in interactive tools for component development and page composition. This saves considerable development time while giving the cross-platform power and flexibility of the Java programming language and other scripting languages.

  • Separation of dynamic and static content

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

  • Support for scripting and actions

    The JavaServer Pages technology supports scripting elements as well as actions. Actions permit the encapsulation of useful functionality in a convenient form that can also be manipulated by tools; scripts provide a mechanism to glue together this functionality in a per-page manner.

  • 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), which brings Java technology to enterprise computing. You can now develop powerful middle-tier server applications, using a web site that uses JavaServer Pages technology as a front end to Enterprise JavaBeans components in a J2EE compliant environment.


JSP.1.2 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 some dynamic actions and leverages on the Java platform.

The features in the JSP technology support a number of different paradigms for authoring of dynamic content; some of them are described in Section JSP.1.6. The next couple of examples only attempt to present the technical components of the JSP specification and are not prescribing "good" or "bad" paradigms.

JSP.1.2.1 An Example Using Scripting and Beans

A simple example of a JSP page is shown in Figure JSP.1-1. The example shows the response page, which is intended to be a short list with the day of the month and year at the moment when the request is received. The page itself contains fixed template text and additional elements described by the JSP specification that are shown underlined in the figure. As the request reaches the page, the response is created based on the template text. As the first element is reached, a server-side bean object is created with name clock and type calendar.jspCalendar. This object can be used and modified later in the page. In particular, the next two elements access properties of the object and insert these values into the response page as strings.

Figure JSP.1-1. A JSP Page Using Beans and Scripting

JSP.1.2.2 An Example Using a Tag Library

Figure JSP.1-2 is another example of a JSP page. This page uses custom actions to create the server-side object and then to produce the response data. In the example, a taglib directive first makes available into this page a tag library for database queries. The directive indicates the tag library to use and provides a prefix to use locally in this page to name those actions.

Figure JSP.1-2 A JSP Page Using Custom Actions
<html>
<%@ taglib uri="http://acme.com/taglibs/simpleDB.tld" prefix="x" %>
<x:queryBlock connData="conData1">
    <x:queryStatement>
        SELECT ACCOUNT, BALANCE FROM ...
    </x:queryStatement>
    The top 10 accounts and balances are:
    <table>
        <tr><th>ACCOUNT</th><th>BALANCE</th></tr>
        <x:queryCreateRows from="1" to="10">
            <td><x:queryDisplay field="ACCOUNT"/></td>
            <td><x:queryDisplay field="BALANCE"/></td>
        </x:queryCreateRows>
    </table>
</x:queryBlock>
</html>

Designing tag libraries is a delicate effort, analogous to that of designing a language; we are making no special effort here to define tags that are useful for any but pedagogical purposes. For the purposes of this example, we will assume that this fictitious tag library introduces four actions:

A queryBlock action introduces a database connection; it can contain queryStatement actions and queryCreateRow actions. The connData attribute refers to connection-specific data, like login and password, that are to be defined elsewhere.

A queryStatement action must be enclosed in a queryBlock. A queryStatement's body is a SQL statement; it will use the connection data defined in the enclosing queryBlock.

A queryCreateRows action must be enclosed in a queryBlock action. A queryCreateRows action will iterate over the results of the last executed query and will generate up to as many rows as requested.

A queryDisplay action must be enclosed in a queryCreateRows action. A queryDisplay action will access the requested field from the current iteration in queryCreateRows and insert the value into the out object.

In this example:

  • The x:queryCreateRows action implicitly refers to the object created by the x:queryStatement within the same x:queryBlock.

  • The x:queryDisplay actions refer to the current row in the query result that is being iterated over by x:queryCreateRows.

  • The code that locates a connection (perhaps from a connection pool), performs the JDBC™ API query, and navigates through the result of this query is hidden in the implementation of the custom actions. This encourages division of labor and isolation from changes.

JSP.1.2.3 Components and Containers

The JavaServer Pages technology builds on the servlet standard extension. JavaServer Pages is a standard extension that is defined extending the concepts in the servlet standard extension. JSP 1.1 uses the classes from Java Servlet 2.2 specification.

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.

JSP 1.1 and Servlet 2.2 rely only on features in the Java Runtime Environment 1.1, although they are compatible with, and can take advantage of, the Java 2 Runtime Environment.


JSP.1.3 Features in JSP 1.1

The JavaServer Pages specification includes:

  • Standard directives

  • Standard actions

  • Script language declarations, scriptlets, and expressions

  • A portable tag extension mechanism

Most of the integration of JSP pages within the J2EE platform is inherited from the reliance on the Servlet 2.2 specification.


JSP.1.4 Overview of JSP Page Semantics

This section provides an overview of the semantics of JSP pages.

JSP.1.4.1 Translating and Executing JSP Pages

A JSP page is executed in a JSP container, which is installed on a web server, or on a web enabled application server. The JSP container delivers requests from a client to a JSP page and responses from the JSP page to the client. The semantic model underlying JSP pages is that of a servlet: a JSP page describes how to create a response object from a request object for a given protocol, possibly creating and/or using in the process some other objects.

All JSP containers must support HTTP as a protocol for requests and responses, but a container may also support additional request/response protocols. The default request and response objects are of type HttpServletRequest and HttpServletResponse, respectively.

A JSP page may also indicate how some events are to be handled. In JSP 1.1 only init and destroy events can be described: the first time a request is delivered to a JSP page a jspInit() method, if present, will be called to prepare the page. Similarly, a JSP container can reclaim the resources used by a JSP page at any time that a request is not being serviced by the JSP page by invoking first its jspDestroy() method; this is the same life cycle as that of servlets.

A JSP page is represented at request-time by a JSP page implementation class that implements the javax.servlet.Servlet interface. JSP pages are often implemented using a JSP page translation phase that is done only once, followed by some request processing phase that is done once per request. The translation phase creates the JSP page implementation class. If the JSP page is delivered to the JSP container in source form, the translation of a JSP source page can occur at any time between initial deployment of the JSP page into the runtime environment of a JSP container and the receipt and processing of a client request for the target JSP page.

A JSP page contains some declarations, some fixed template data, some (perhaps nested) action instances, and some scripting elements. When a request is delivered to a JSP page, all these pieces are used to create a response object that is then returned to the client. Usually, the most important part of this response object is the result stream.

JSP.1.4.2 Compiling JSP Pages

JSP pages may be compiled into its JSP page implementation class plus some deployment information. This enables the use of JSP page authoring tools and JSP tag libraries to author a servlet. This has several benefits:

  • Removal of the start-up lag that occurs when a JSP page delivered as source receives the first request.

  • Reduction of the footprint needed to run a JSP container, as the Java compiler is not needed.

If a JSP page implementation class depends on some support classes in addition to the JSP 1.1 and Servlet 2.2 classes, the support classes will have to be included in the packaged WAR so it will be portable across all JSP containers.

JSP.C contains two examples of packaging of JSP pages. One shows a JSP page that is delivered in source form (probably the most common case) within a WAR. The other shows how a JSP page is translated into a JSP page implementation class plus deployment information indicating the classes needed and the mapping between the original URL that was directed to the JSP page and the location of the servlet.

JSP.1.4.3 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.2.8, "Implicit Objects"); other objects are created explicitly through actions; objects can also be created directly using scripting code, although this is less common. The 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 the scripting elements through some scripting-level variables (see Section JSP.1.4.7, "Objects and Variables").

Each action and declaration defines, as part of its semantics, what objects it defines, with what scope attribute, and whether they are available to the scripting elements.

Objects are always created within some JSP page instance that is responding to some 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 somewhere else. References to objects with page scope are stored in the pageContext object.

  • request— Objects with request scope are accessible from pages processing the same request where they were created. All references to the object shall be released 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 requests that are in the same session as the one in which they were created. It is not legal to define an object with session scope from within a page that is not session-aware (see Section JSP.2.7.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 processing requests that are in the same application as the one in which they were created. All references to the object shall be released when the runtime environment reclaims the ServletContext. Objects with application scope can be defined (and reached) from pages that are not session-aware. References to objects with application scope are stored in the application object associated with a page activation.

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

JSP.1.4.4 Fixed Template Data

Fixed template data is used to describe those pieces that are to be used verbatim either in the response or as input to JSP actions. For example, if the JSP page is creating a presentation in HTML of a list of, say, books that match some search conditions, the template data may include things like the <ul>, </ul>, and something like <li>The following book....

This fixed template data is written (in lexical order) unchanged onto the output stream (referenced by the implicit out variable) of the response to the requesting client.

JSP.1.4.5 Directives and Actions

There may be two types of elements in a JSP page: directives or actions. Directives provide global information that is conceptually valid independent of any specific request received by the JSP page. For example, a directive can be used to indicate the scripting language to use in a JSP page. Actions may, and often will, depend on the details of the specific request received by the JSP page. If a JSP container uses a compiler or translator, the directives can be seen as providing information for the compilation/translation phase, while actions are information for the subsequent request processing phase.

An action may create some objects and may make them available to the scripting elements through some scripting-specific variables.

Directive elements have a syntax of the form

<%@ directive ...%>

Action elements follow the syntax of XML elements, i.e., have a start tag, a body, and an end tag:

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

or an empty tag

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

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.1.4.5.1 Tag Extension Mechanism

An element type abstracts some functionality by defining a specialized (sub)language that allows more natural expression of the tasks desired, can be read and written more easily by tools, and also can even contribute specialized yet portable tool support to create them.

The JSP specification provides a tag extension mechanism (see Chapter JSP.5) that enables the addition of new actions, thus allowing the JSP page "language" to be easily extended in a portable fashion. A typical example would be elements to support embedded database queries. Tag libraries can be used by JSP page authoring tools and can be distributed along with JSP pages to any JSP container like web and application servers.

The tag extension mechanism can be used from JSP pages written using any valid scripting language, although the mechanism itself only assumes a Java runtime environment. Custom actions provide access to the attribute values and to their body; they can be nested and their bodies can include scripting elements.

JSP.1.4.6 Scripting Languages

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. 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. Scriplets that are program fragments can also be used to do things like iterations and conditional execution of other elements in the JSP page. Expressions are complete expressions in the scripting language that get evaluated at response time; commonly the result is converted into a string and then inserted into the output stream.

All JSP containers must support scripting elements based on the Java programming language. Additionally, JSP containers may support other scripting languages. All such scripting languages must support:

  • Manipulation of Java language objects

  • Invocation of methods on Java language 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.4.

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.

JSP.1.4.7 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 in two places: after its start tag and after its end tag. The variables will contain at process request-time a reference to the object defined by the element, although other references exist depending on the scope of the object (see Section JSP.1.4.3, "Objects and Scopes").

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 are available directly in the JavaScript™ programming language.

The exact rules for the visibility of the variables are scripting language specific. Chapter JSP.4 defines the rules for when the language attribute of the page directive is "java."

JSP.1.4.8 Scripts, Actions, and Beans

Scripting elements, actions, and beans are all mechanisms that can be used to describe dynamic behavior in JSP pages. Different authors and authoring tools can use these mechanisms in different ways based on their needs and their preferences. The JSP specification does not restrict their use but this section provides some guidelines that may be useful to understand their relative strengths.

Beans are a well-known and well-supported component framework for the Java platform that can be accessed easily from the Java programming language and other JSP page scripting languages. Some JSP page authors, or their support organizations, may create or reuse bean components to use from their JSP pages.

Actions provide an abstraction that can be used to easily encapsulate common actions. Actions typically create and/or act on (server-side) objects, often beans.

The JSP specification provides some standard actions that can be used to interact with any bean. If the bean is extended so it implements the Tag interface, then the bean becomes a tag handler and it can be used directly in the JSP page with improved integration into the template data.

Scripting elements are very flexible; that is their power but also their danger as they can make hard understanding and maintaining a page that uses them extensively; they may also make it hard for an authoring tool. In some development contexts, JSP pages will mostly contain only actions (standard or custom) with scripting elements only used as a "gluing" mechanism that can be used to "fill-in" the actions that are described using actions (and beans and EJB components). In other development contexts JSP pages may contain significant amounts of scripting elements.

JSP.1.4.9 JSP, HTML, and XML

The JSP specification is designed to support the dynamic creation of several types of structured documents, especially those using HTML and XML.

In general, a JSP page uses some data sent to the server in an HTTP request (for example, by a QUERY argument or a POST method) to interact with information already stored on the server, and then dynamically creates some content which is then sent back to the client. The content can be organized in some standard format (like HTML, DHTML, XHTML, XML, etc.), in some ad-hoc structured text format, or not at all.

There is another relationship between JSP and XML: a JSP page has a standard translation into a valid XML document. This translation is useful because it provides a standard mechanism to use XML tools and APIs to read, manipulate, and author JSP documents. The translation is defined in Chapter JSP.7. JSP 1.1 processors are not required to accept JSP pages in this standard XML syntax, but this may be required in a future version of the JSP specification.


JSP.1.5 Web Applications

A prototypical 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) (downloadable via the Plugin) running in client(s)

JSP 1.1 supports portable packaging and deployment of web applications through the Servlet 2.2 specification. The JavaServer Pages specification inherits from the servlet specification the concepts of applications, ServletContexts, sessions, requests, and responses. See that specification for more details.


JSP.1.6 Application Model

JSP pages can be used in combination with servlets, HTTP, HTML, XML, applets, JavaBeans components, and Enterprise JavaBeans components, to implement a broad variety of application architecture(s) or models.

JSP.1.6.1 Simple 21/2-Tier Application

The simple 2-tier model (accessing a database in Figure JSP.1-3) describes the cgi-bin replacement architecture that the servlet model first enabled. This allows a JSP (or a servlet) to directly access some external resource (such as a database or legacy application) to service a client's request. The advantage of such a scheme is that it is simple to program, and allows the page author to easily generate dynamic content based upon the request and state of the resource(s). However, this architecture does not scale for a large number of simultaneous clients since each must establish or share (ad-hoc) a (potentially scarce/expensive) connection to the resource(s) in question.

Figure JSP.1-3. 2-Tier DataAccess Model

JSP.1.6.2 N-Tier Application

In this model (Figure JSP.1-4) the application is composed of (n>=3) tiers, where the middle tier, the JSP, interacts with the back end resources via an Enterprise JavaBeans component. The Enterprise JavaBeans server and the EJB provide managed access to resources, thus addressing the performance issues. An EJB server will also support transactions and access to underlying security mechanisms to simplify programming. This is the programming model supported by the Java 2 Platform Enterprise Edition (J2EE).

Figure JSP.1-4. Multi-Tier DataAccess Model

JSP.1.6.3 Loosely Coupled Applications

In this model (Figure JSP.1-5) we have two loosely coupled applications (either on the same Intranet or over an Extranet or the Internet). These applications may be peers, or act as client or server for the other. A common example of this is supply chain applications between vendor enterprises. In such situations it is important that each participant be isolated from changes in the implementation of its dependents. In order to achieve this loose coupling the applications do not communicate using a fine grain imperative interface contract like those provided for by RMI/IIOP or Java IDL. The applications communicate with each other via HTTP, using either HTML or XML to/from a JSP page.

Figure JSP.1-5. Loosely Coupled Application Model

JSP.1.6.4 Using XML with JSP Technology

The JavaServer Pages technology is an ideal way to describe processing of XML input and output (Figure JSP.1-6). Simple XML generation can be done by just writing the XML as static template portions within the JSP page. Dynamic generation will be done through JavaBeans components, Enterprise JavaBeans components, or via custom actions that generate XML. Similarly, input XML can be received from POST or QUERY arguments and then sent directly to JavaBeans components, Enterprise JavaBeans components, or custom actions or manipulated via the scripting.

Figure JSP.1-6. XML Input/Output Model

There are two attributes of the JSP technology that make it specially suited for describing XML processing. One is that XML fragments can be described directly in the JSP page either as templates for input into some XML-consuming component or as templates for output to be extended with some other XML fragments. Another attribute is that the tag extension mechanism enables the creation of specific actions and directives that are targeted at useful XML manipulation operations.

Future versions of the JSP specification may include several standard actions that will support XML manipulation, including the transformation of the XML produced by the given JSP page using XTL/XSL.

JSP.1.6.5 Redirecting Requests

It is common that the data to be sent to the client varies significantly depending on properties of the client that are either directly encoded in the request object or can be discovered based on some user/client profile (e.g., stored in a login database). In this case it is very convenient to have the initial JSP page determine details about the request, perhaps create and/or update some server-side objects, and then, if necessary, redirect the request to a different JSP page.

This programming model (Figure JSP.1-7) is supported by the underlying servlet APIs. The properties of the HTTP protocol are such that the redirect cannot be done if the response stream has started being sent back to the client; this characteristic makes the description of some common situations quite inconvenient. To address this, the JSP specification by default indicates buffering on the output stream. The JSP page can redirect the request at any point before flushing the output buffer.

Figure JSP.1-7. Request Redirection Model

Buffering is also very convenient for error page handling, since that is done by redirecting the request.

JSP.1.6.5.1 Presentation JSP Pages and Front JSP Pages

In a slight variation of this model, the front component (a servlet or a JSP) only creates and/or updates the server-side objects. In this organization, the front component does no presentation at all; instead all presentation is done by a presentation component. Although the front component could be written as a servlet since it does no presentation, writing it as a JSP page enables the use of custom actions for the creation and update of the server-side objects. The presentation component will in almost all cases be a JSP page, and it will most likely access the server-side objects through custom actions. [1]

[1] Readers of the original JSP 0.92 draft will recognize the combination "front component is servlet and presentation component is JSP" as the model 2 mentioned in that draft.

JSP.1.6.6 Including Requests

Another useful application model (Figure JSP.1-8) involves request includes. In this model, the request reaches an initial JSP page. The page may start generating/composing some result but at some point it may want to dynamically include the contents of some other page. These contents may be static but may also be dynamically generated by some other JSP page, servlet class, or some legacy mechanism like ASP.

Figure JSP.1-8. Request Inclusion Model

Although in some cases this inclusion model is applicable to presentation-dependent contents, it is most often used in the context of a presentation-independent content, as when the data generated is actually XML (which may be converted later into some other format using, say, XSL).


Chapter JSP.2. Standard Syntax and Semantics

This chapter describes the core syntax and semantics of the JavaServer Pages (JSP) 1.1 Specification, including the standard actions.


JSP.2.1 General Syntax Rules

The following general syntax rules apply to all elements in JSP pages.

JSP.2.1.1 Elements and Template Data

A JSP page has some elements and some template data. The elements are instances of some element types that are known to the JSP container; template data is everything else, i.e., anything that the JSP container does not understand.

The type of an element describes its syntax and its semantics. If the element has attributes, the type also 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.

There are three types of elements: directive elements, scripting elements, and action elements; the corresponding syntax is described below. Template data is uninterpreted; it is usually passed through to the client, or to some processing component.

JSP.2.1.2 Element Syntax

Most of the JSP syntax is based on XML. Elements based on the XML syntax have either a start tag (including the element name) possibly with attributes, an optional body and a matching end tag, or they have an empty tag possibly with attributes:

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

and

<mytab attr1="attribute value" .../>

JSP tags are case-sensitive, as in XML and XHTML.

Scripting elements and directives are written using a syntax that is easier to author by hand. Elements using the alternative syntax are of the form <%.....%>.

All JSP pages have an equivalent valid XML document. A future JSP specification may require JSP containers to accept JSP pages as well as their equivalent XML documents. Chapter JSP.7 describes the XML equivalent syntax for the scripting elements and directives; these XML element types are not intended to be used within a JSP page but in the equivalent XML document.

JSP.2.1.3 Start and End Tags

Elements that have distinct start and end tags (with enclosed body) must start and end in the same file. You cannot begin a tag in one file and end it in another.

This applies also 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.

JSP.2.1.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.

JSP.2.1.5 Attribute Values

Following the XML specification, attribute values always appear quoted. Both single and double quotes can be used. The entities &apos; and &quot; are available to describe single and double quotes.

See also Section JSP.2.12.1, "Request-Time Attribute Values."

JSP.2.1.6 White Space

In HTML and XML, white space is usually not significant, with some exceptions. One exception is that an XML file must start with the characters <?xml, with no leading white space characters.

This specification follows the white space behavior defined for XML; that is, all white space within the body text of a document is not significant, but is preserved.

For example, since directives generate no data and apply globally to the JSP page, the following input file is translated into the corresponding result file:

For this input,

this is the default value

<?xml version="1.0" ?>
<%@ page buffer="8kb" %>
The rest of the document goes here

The result is

note the empty line

<?xmlversion="1.0" ?>

The rest of the document goes here

As another example, for this input,

note no white between the two elements

<% response.setContentType("....");
whatever... %><?xml version="1.0" ?>
<%@ page buffer="8kb" %>
The rest of the document goes here

The result is

no leading space

note the empty line

<?xml version="1.0" ?>

The rest of the document goes here


JSP.2.2 Error Handling

There are two logical phases in the life cycle/processing of a JavaServer Page source file:

  • Translation (or compilation) from JSP page source into a JSP page implementation class file.

  • Per client request processing by an instance of the JSP page implementation class.

Errors may occur at any point during processing of either phase. This section describes how such errors are treated by a compliant implementation.

JSP.2.2.1 Translation Time Processing Errors

The translation of a JSP page source into a corresponding JSP page implementation class using the Java technology by a JSP container can occur at any time between initial deployment of the JSP page into the runtime environment of a JSP container and the receipt and processing of a client request for the target JSP page. If translation occurs prior to the JSP container receiving a client request for the target (untranslated) JSP page, then error processing and notification are implementation dependent. Fatal translation failures shall result in subsequent client requests for the translation target also to be failed with the appropriate error; for HTTP protocols, error status code 500 (server error).

JSP.2.2.2 Client Request Time Processing Errors

During the processing of client requests, arbitrary runtime errors can occur either in the body of the JSP page implementation class or in some other code (Java or other implementation programming language) called from the body of the JSP page implementation class. Such errors are realized in the page implementation using the Java programming language exception mechanism to signal their occurrence to caller(s) of the offending behavior. [1]

[1] Note that this is independent of scripting language; this requires that unhandled errors occurring in a scripting language environment used in a JSP container implementation be signaled to the JSP page implementation class via the Java programming language exception mechanism.

These exceptions may be caught and handled (as appropriate) in the body of the JSP page implementation class.

However, any uncaught exceptions thrown from 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 offending 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 putAttribute() 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 used by the servlet and JSP specifications.

If the errorPage attribute of a page directive names a URL that refers to another JSP, and that JSP indicates that it is an error page (by setting the page directive's isErrorPage attribute to true), then the "exception" implicit scripting language variable of that page is initialized to the offending Throwable reference.


JSP.2.3 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.2.3.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.2.3.2 JSP Comments

A JSP comment is of the form

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

The body of the content is ignored completely. Comments are useful for documentation but also to "comment out" some portions of a JSP page. Note that JSP comments do not nest.

Note that an alternative way to place a "comment" in JSP is to do so by using the comment mechanism of the scripting language. For example:

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


JSP.2.4 Quoting and Escape Conventions

The following quoting conventions apply to JSP pages. Anything else is not processed.

Quoting in Scripting Elements

- A literal "%>" is quoted by %\>

Quoting in Template Text

- A literal "<%" is quoted by <\%

Quoting in Attributes

- A ' is quoted as \'

- A " is quoted as \"

- A \ is quoted as \\

- A %> is quoted as %\>

- A <% is quoted as <\%

XML Representation

The quoting conventions are different from those of XML. Chapter JSP.7 describes the details of the transformation.


JSP.2.5 Overview of Semantics

A 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. A JSP page is executed by a JSP container; requests sent to a JSP page are delivered by the JSP container to some JSP page implementation instance that is a subclass of servlet (see Chapter JSP.3).

JSP.2.5.1 Web Applications

A web application is a collection of resources that are available through some URLs. The resources include JSP pages, Java servlet classes, static pages, and other Java technology-based resources and classes to be used at the server-side as well as Java resources and classes (like applets, JavaBeans components, and others) which are to be downloaded for use by the client. A web application is described in more detail in Chapter SRV.9 of the Servlet 2.2 specification.

A web application contains a deployment descriptor web.xml that contains information about the JSP pages, servlets, and other resources used in the web application. The deployment descriptor is described in detail in Chapter SRV.13 of the Servlet 2.2 specification.

JSP 1.1 requires that all these resources are to be implicitly associated with and accessible through a unique ServletContext instance, which is available as the application implicit object (Section JSP.2.8). The JSP specification inherits the notions of a web application from the Servlet 2.2 specification.

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.2.7.6)

  • The jsp:include action element (Section JSP.2.13.4)

  • The jsp:forward action (Section JSP.2.13.5)

JSP.2.5.2 Relative URL Specifications Within an Application

Elements may use relative URL specifications, which are called "URI paths" in the Servlet 2.1 specification. These paths are as in RFC 2396 specification, i.e., only the path part, no scheme or authority. Some examples are:

"myErrorPage.jsp"
"/errorPages/SyntacticError.jsp"
"/templates/CopyrightTemplate.html"

When such a path starts with a "/", it is to be interpreted by the application to which the JSP page belongs; i.e., its ServletContext object provides the base context URL. We call these paths "context-relative paths."

When such a path does not start with a "/", it is to be interpreted relative to the current JSP page: the current page is denoted by some path starting with "/" which is then modified by the new specification to produce a new path that starts with "/"; this final path is the one interpreted through the ServletContext object. We call these paths "page-relative paths."

The JSP specification uniformly interprets all these paths in the context of the web server where the JSP page is deployed; i.e., the specification goes through a map translation. The semantics applies to translation-time phase (i.e., include directives, Section JSP.2.7.6), and to request-time phase (i.e., to include, Section JSP.2.13.4, and forward, Section JSP.2.13.5, actions).

If a specific tool can ascertain by some mechanism the status of the URL to resource maps at deployment time, the tool can take advantage of this information.

With the appropriate assertions, the translation phase might be performed before deploying the JSP page into the JSP container.

JSP.2.5.3 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. The term web container is synonymous with JSP container.

A web component is either a servlet or a JSP page. A web component may use the services of its container. The servlet element in a web.xml deployment descriptor is used to describe both types of web components; note that most JSP page components are defined implicitly in the deployment descriptor through the use of an implicit.jsp extension mapping.

JSP.2.5.4 JSP Pages

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.4. Most details are not language specific and are described in this chapter.

Most of the content of a JSP page is devoted to describing what data is written into the output stream of the response (usually sent back to the client). The description is based on a JspWriter object that is exposed through the implicit object out (see Section JSP.2.8, "Implicit Objects"). Its value varies:

  • Initially, out is a new JspWriter object. This object may be different from the stream object from response.getWriter(), and may be considered to be interposed on the latter in order to implement buffering (see Section JSP.2.7.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.

  • Within the body of some actions, out may be temporarily re-assigned to a different (nested) instance of JspWriter object. Whether this is or is not the case depends on the details of the action semantics. Typically, the content, or the results of processing the content, of these temporary streams is appended to the stream previously referred to by out, and out is subsequently reassigned to refer to that previous (nesting) stream. Such nested streams are always buffered and require explicit flushing to a nesting stream or discarding of their contents.

  • If the initial out JspWriter object is buffered, then depending upon the value of the autoFlush attribute of the page directive, either the content of that buffer will be automatically flushed out to the ServletResponse output stream to obviate 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 directly through to the ServletResponse output stream.

A JSP page can also describe what should happen when some specific events occur. In JSP 1.1, the only events that can be described are initialization and destruction of the page; these are described using "well-known method names" in declaration elements (see Section JSP.3.1.2). Future specifications will likely define more events as well as a more structured mechanism for describing the actions to take.


JSP.2.6 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.2.4, "Quoting and Escape Conventions."


JSP.2.7 Directives

Directives are messages to the JSP container. In JSP 1.1, 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.7 describes the mapping of directives into XML elements.

Directives do not produce any output into the current out stream.

The remainder of this section describes the standard directives that are available on all conforming JSP 1.1 implementations.

JSP.2.7.1 The page Directive

The page directive defines a number of page-dependent attributes and communicates these to the JSP container.

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 V1.1" %>

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 16K should be used.

<%@ page language="java" import="com.myco.*" buffer="16k" %>
JSP.2.7.1.1 Syntax
<%@ page page_directive_attr_list %>
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"        }

The details of the attributes are given in Table JSP.2-1.

Table JSP.2-1. Attributes of the page Directive

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 1.1, 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.4.

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.2.8, "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.3).

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.5.8.1 for an alternate way to introduce objects into a JSP page that does not have this drawback.

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 one 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 defined only 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.

If a buffer size is specified (e.g., 12kb) then output is buffered with a buffer size not less than that specified.

Depending upon the value of the "autoFlush" attribute, either the contents of this buffer are 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.

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 page shared state.

Default is "true."

Note that even if the isThreadSafe attribute is "false," the JSP page author must ensure that access to any shared objects shared in either the ServletContext or the HttpSession are properly synchronized. See Section JSP.2.7.2

info

Defines an arbitrary string that is incorporated into the translated page, that can subsequently be obtained from the page's implementation of the 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."

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

The resource named has to be a JSP page in this version of the specification.

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 JspWriter have been flushed to the ServletResponse output stream, any subsequent attempt to dispatch an uncaught exception from the offending page to an errorPage may fail.

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"; the default value for the character encoding is ISO-8859-1.

See Section JSP.2.7.4 for complete details on character encodings.

JSP.2.7.2 Synchronization Issues

JSP Pages inherit the servlet semantics as described in the Servlet 2.2 specification. In this section we briefly summarize the threading and distribution issues from that specification, as they apply to JSP pages.

A distributed container is one capable of distributing web components that are tagged as distributable across different multiple Java virtual machines, perhaps running in different hosts. A distributable application is one tagged as such in its web deployment descriptor. A distributable JSP page is one in a distributable application.

By default, there must be only one instance of a JSP page implementation class per JSP page definition in a container (Section SRV.3.2 of Servlet 2.2 spec). By default, an instance of a web application must be run on only one Java virtual machine at any one time. This behavior can be overridden by declaring the application to be distributable (Chapter SRV.9 of Servlet 2.2. specification).

A single threaded JSP page is one with a false value for its isThreadSafe attribute of a page directive. If isThreadSafe="false," the JSP page implementation shall implement javax.servlet.SingleThreadModel, thus indicating that all requests dispatched to that instance shall be delivered serially to the service() method of the page implementation class (Section SRV.3.3.3.1 of Servlet 2.2 spec).

However, some implementations may additionally use a pool consisting of multiple page implementation class instances to do load balancing. Therefore, even when indicating that the page is not thread safe, a page author cannot assume that all requests mapped to a particular JSP page shall be delivered to the same instance of that page's implementation class. The consequence of this is that an author must assume that any mutable resources not private/unique to a particular page's instance may be accessed/updated simultaneously by two or more instances; thus any static field values, objects with session or application scope, or objects shared through some other (unspecified) mechanism by such instances must be accessed appropriately synchronized to avoid non-deterministic behaviors (Section SRV.3.2.1 of Servlet 2.2 spec).

In the case of a distributable JSP page, there is one instance of its JSP page implementation class per web component definition per Java virtual machine in a distributed container (Section SRV.3.2 of Servlet 2.2 spec).

If multiple web component definitions in the deployment descriptor indicate the same JSP page, there will be multiple instances of the JSP page implementation class, with different initialization parameters (Section SRV.3.3.1 of Servlet 2.2 spec).

There is only one instance of the ServletContext interface associated with each web application deployed into a web container. In cases where the container is distributed over many Java virtual machines, there is one instance per web application per Java virtual machine (Section SRV.4.1 of Servlet 2.2 spec).

Context attributes exist locally to the Java virtual machine in which they were created and placed. This prevents the ServletContext from being used as a distributed shared memory store. If information needs to be shared between servlets run-ning in a distributed environment, that information should be placed in a session, a database, or in an Enterprise JavaBean (Section SRV.4.3.1 of Servlet 2.2 spec).

Within an application that is marked as distributable, all requests that are part of a session can be handled on only a single Java virtual machine at any one time. In addition, all objects placed into the session must implement the Serializable interface. The servlet container may throw an IllegalArgumentException if a non-serializable object is placed into the session (Section SRV.7.7.2 in Servlet 2.2 spec).

JSP.2.7.3 Specifying Content Types

A JSP page can use the contentType attribute of the page directive to indicate the content type of the response it provides to requests. Since this value is part of a directive, 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.

A registry of content type names is kept by IANA. See:

ftp://venera.isi.edu/in-notes/iana/assignments/media-types/media-types

JSP.2.7.4 Delivering Localized Content

The Java platform support for localized content is based on a uniform representation of text internally as Unicode 2.0 (ISO010646) characters and the support for a number of character encodings to and from Unicode.

Any 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

The JSP 1.1 specification assumes that JSP pages that will deliver content in a given character encoding will be written in that character encoding. In particular, the contentType attribute of the page directive describes both the character encoding of the JSP page and the character encoding of the resulting stream.

The valid names to describe the character encodings are those of IANA. They are described at:

ftp://venera.isi.edu/in-notes/iana/assignments/character-sets

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

The default character set encoding is ISO-8859-1 (also known as latin-1).

A JSP container may use some implementation-dependent heuristics and/or structure to determine the expected character encoding of a JSP page and then verify that contentType attribute is as expected.

A JSP container will raise a translation-time error if an unsupported character encoding is requested.

See Section JSP.B.1 for some implementation notes.

JSP.2.7.5 Including Data in JSP Pages

Including data is a significant part of the tasks in a JSP page. Accordingly, the JSP 1.1 specification has two include mechanisms suited to different tasks. A summary of their semantics is shown in Table JSP.2-2.

Table JSP.2-2. Summary of Include Mechanisms in JSP 1.1

Syntax

What

Phase

Spec

Object

Description

Section

<%@ include file=... %>

directive

translation-time

virtual

static

Content is parsed by JSP container.

JSP.2.7.6

<jsp:include page= />

action

request-time

virtual

static and dynamic

Content is not parsed; it is included in place.

JSP.2.13.4

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

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.

JSP.2.7.6 The include Directive

The include directive is used to substitute text and/or code at JSP page translation 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 control available to the JSP container. The file attribute is as in Section JSP.2.5.2.

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 1.1 specification does not have a way of directing the JSP container that included files have changed.

Examples

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

<%@ include file="copyright.html" %>
JSP.2.7.6.1 Syntax
<%@ include file="relativeURLspec" %>

JSP.2.7.7 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.

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. A common mechanism is to encode the version of a tag library into its URI.

If a JSP container implementation cannot locate (following the rules described in Section JSP.5.3.1) a tag library description for a given URI, a fatal translation error shall result.

It is a fatal translation error for the taglib directive to appear after actions using the prefix introduced by the taglib directive.

See Chapter JSP.5 for more specification details, and Section JSP.B.2 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>
JSP.2.7.7.1 Syntax
<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>

where the attributes are given in Table JSP.2-3.

Table JSP.2-3. Attributes of the taglib Directive

uri

Either an absolute URI or a relative URI specification to be interpreted as in Section JSP.2.5.2 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 JSP.5.

tagPrefix

Defines the prefix string in <prefix>:<tagname> that is used to distinguish a custom action, e.g., <myPrefix:myTag>.

Prefixes jsp:, jspx:, java:, javax:, servlet:, sun:, and sunw: are reserved. 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 introduced using the taglib directive, and Name is not recognized by the corresponding tag library.


JSP.2.8 Implicit Objects

When you author JSP pages, you have access to certain implicit objects that are always available for use within scriptlets and expressions, without being declared first. All scripting languages are required to provide access to these objects.

Each implicit object has a class or interface type defined in a core Java technology or Java servlet API package, as shown in Table JSP.2-4.

Table JSP.2-4. Implicit Objects Available in JSP Pages

Implicit Variable

Of Type

What It Represents

Scope

request

protocol dependent subtype of: javax.servlet.ServletRequest e.g.: javax.servlet.HttpServletRequest

The request triggering the service invocation.

request

response

protocol dependent subtype of: javax.servlet.ServletResponse e.g.: javax.servlet.HttpServletResponse

The response to the request.

page

pageContext

javax.servlet.jsp.PageContext

The page context for this JSP page.

page

session

javax.servlet.http.HttpSession

The session object created for the requesting client (if any). This variable is valid only for Http protocols.

session

application

javax.servlet.ServletContext

The servlet context obtained from the servlet configuration object (as in the call getServletConfig().getContext())

application

out

javax.servlet.jsp.JspWriter

An object that writes into the output stream.

page

config

javax.servlet.ServletConfig

The ServletConfig for this JSP page.

page

page

java.lang.Object

The instance of this page's implementation class processing the current request. [a]

page

[a] When the scripting language is "java" then "page" is a synonym for "this" in the body of the page.

In addition, in an error page, you can access the exception implicit object, described in Table JSP.2-5.

Table JSP.2-5. Implicit Objects Available in Error Pages

Implicit Variable

Of Type

What It Represents

scope

exception

java.lang.Throwable

The uncaught Throwable that resulted in the error page being invoked.

page

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

See Section JSP.5.8.1 for some non-normative conventions for the introduction of new implicit objects.


JSP.2.9 The PageContext Object

A PageContext provides an object that 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 implementation-specific improvements like high performance JspWriters. Generating such an implementation is not a requirement of JSP 1.1 compliant containers, although providing the PageContext implicit object is.

See Chapter JSP.6 for more details.


JSP.2.10 Scripting Elements

The JSP 1.1 specification describes three scripting language elements—declarations, scriptlets, and expressions. A scripting language precisely defines the semantics for these elements but, informally, a declaration declares elements, a scriptlet is a statement fragment, and an expression is a complete language expression. The scripting language used in the current page is given by the value of the language directive (see Section JSP.2.7.1, "The page Directive"). In JSP 1.1, the only value defined is "java."

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

JSP.2.10.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 and initializes it to zero; the second declaration declares a method.

<%! int i = 0; %>
<%! public String f(int i) { if (i<3) return("..."); ... } %>
Syntax
<%! declaration(s) %>

JSP.2.10.2 Scriptlets

Scriptlets can contain any code fragments that are valid for the scripting language specified in the language directive. Whether the code fragment is legal depends on the details of the scripting language; see Chapter JSP.4.

Scriptlets are executed at request-processing time. Whether or not they produce any output into the out stream depends on the actual code in the scriptlet. Scriptlets can have side effects, modifying the objects visible in them.

When all scriptlet fragments in a given translation unit are combined in the order in which they appear in the JSP page, they shall yield a valid statement or sequence thereof, in the specified scripting language.

If you want to use the %> character sequence as literal characters in a scriptlet, rather than to end the scriptlet, you can 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
<% } %>
Syntax
<% scriptlet %>

JSP.2.10.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 which is subsequently emitted into the current out JspWriter object.

If the result of the expression cannot be coerced to a String, then either a translation time error shall occur or, if the coercion cannot be detected during translation, a ClassCastException shall be raised at request time.

A scripting language may support side effects in expressions. If so, they take effect when the expression is evaluated. Expressions are evaluated left to right in the JSP page. If the expressions appear in more than one runtime 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 contents of an expression must be a complete expression in the scripting language in which they are 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

In the next example, the current date is inserted.

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


JSP.2.11 Actions

Actions may affect the current out stream and use, modify, and/or create objects. Actions may, and often will, depend on the details of the specific request object received by the JSP page.

The JSP specification includes some action types that are standard and must be implemented by all conforming JSP containers. New action types are introduced using the taglib directive.

The syntax for action elements is based on XML; the only transformation needed is due to quoting conventions.


JSP.2.12 Tag Attribute Interpretation Semantics

Generally, all custom and standard action attributes and their values either remain uninterpreted by, or have well-defined action-type specific semantics known to, a conforming JSP container. However, there are two exceptions to this general rule: some attribute values represent request-time attribute values and are processed by a conforming JSP container, and the id and scope attributes have special interpretations.

JSP.2.12.1 Request-Time Attribute Values

Action elements (both standard and custom) can define named attributes and associated values. Typically a JSP page treats these values as fixed and immutable, but the JSP 1.1 provides a mechanism to describe a value that is computed at request time.

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 be used only in actions. If there is more than one such attribute in a tag, the expressions are evaluated left to right.

Only attribute values can be denoted in this way (e.g., the name of the attribute is always an explicit name), and the expression must appear by itself (e.g., multiple expressions and mixing of expressions and string constants are not permitted; instead perform these operations within the expression).

The resulting value of the expression depends upon the expected type of the attribute's value. The type of an action element indicates the valid Java programming language type for each attribute value; the default is java.lang.String.

By default, all attributes have page translation-time semantics. Attempting to specify a scriptlet expression as a value for an attribute that has page translation time semantics is illegal and will result in a fatal translation error. The type of an action element indicates whether a given attribute will accept request-time attribute values.

Most attributes in the actions defined in the JSP 1.1 specification have page translation-time semantics.

The following attributes accept request-time attribute expressions:

  • The value and beanName attributes of jsp:setProperty (JSP.2.13.2)

  • The page attribute of jsp:include (JSP.2.13.4)

  • The page attribute of jsp:forward (JSP.2.13.5)

  • The value attribute of jsp:param (JSP.2.13.6)

JSP.2.12.2 The id Attribute

The id="name" attribute/value tuple in an element has special meaning to a JSP container, both 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 translation error.

  • In addition, if the action type creates one or more object instances at client request processing time, one of these objects will usually be associated by the JSP container with the named value and can be accessed via that name in various contexts through the pagecontext object described later in this specification. Furthermore, the name is also used to expose a variable (name) in the page's scripting language environment. The scope of this scripting language dependent variable is dependent upon the scoping rules and capabilities of the actual scripting language used in the page. Note that this implies that the name value syntax shall comply with the variable naming syntax rules of the scripting language used in the page.

Chapter JSP.4 provides details for the case where the language attribute is "java."

For example, the <jsp:usebean id="name" class="className" .../> action defined later herein uses this mechanism in order to possibly instantiate and subsequently expose the named JavaBeans component to a page at client request processing time.

For example:

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

JSP.2.12.3 The scope Attribute

The scope="page|request|session|application" attribute/value tuple is associated with and modifies the behavior of the id attribute described above (it has both translation time and client request processing time semantics). In particular, it describes the namespace, the implicit life cycle of the object reference associated with the name, and the APIs used to access this association, as in Table JSP.2-6.

Table JSP.2-6. Value of the scope Attribute

page

The named object is available from the javax.servlet.jsp.PageContext for the current page.

This reference shall be discarded upon completion of the current request by the page body.

It is illegal to change the instance object associated, such that its runtime type is a subset of the type of the current object previously associated.

request

The named object is available from the current page's ServletRequest object using the getAttribute(name) method. This reference shall be discarded upon completion of the current client request.

It is illegal to change the value of an instance object so associated, such 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 getValue(name) method.

This reference shall be discarded upon invalidation of the current session.

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.

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 Section JSP.2.7.1) that it does not participate in a session.

application

The named object is available from the current page's ServletContext 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.


JSP.2.13 Standard Actions

The JSP 1.1 specification defines some standard action types that are always available, regardless of the version of the JSP container or web server the developer uses. The standard action types are in addition to any custom types specific to a given JSP container implementation.

JSP.2.13.1 <jsp:useBean>

A jsp:useBean action associates an instance of a Java programming language object defined within a given scope available with a given id via a newly declared scripting variable of the same id.

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 it is not found it will attempt to create the object using the other attributes. It is also possible to use this action only 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 (in the Java platform sense) to type; failure to do so is a translation-time error.

The attribute beanName is the name of a bean, as specified in the JavaBeans specification for an argument to the instantiate() method in java.beans.Beans. That is, it is 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.

The actions performed are:

  1. Attempt to locate an object based on the attribute values (id, scope). The inspection is done appropriately synchronized per scope namespace to avoid non-deterministic behavior.

  2. Define a scripting language variable with the given id in the current lexical scope of the scripting language of the specified type (if given) or class (if type is not given).

  3. If the object is found, the variable's value is initialized with a reference to the located object, cast to the specified type. If the cast fails, a java.lang.ClassCastException shall occur. This completes the processing of this useBean action.

    If the jsp:useBean element had a non-empty body, it is ignored. This completes the processing of this useBean action.

  4. If the object is not found in the specified scope and neither class nor beanName is given, a java.lang.InstantiationException shall occur. This completes the processing of this useBean action.

  5. If the object is not found in the specified scope, and the class specified names a non-abstract class that defines a public no-args constructor, then that class is instantiated, and 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 performed.

    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.InstantiationException shall occur. This completes the processing of this useBean action.

  6. If the object is not found in the specified scope, and beanName is given, then the method instantiate() of java.beans.Beans will be invoked with the ClassLoader of the servlet object and the beanName as arguments. If the method succeeds, 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 performed.

  7. If the jsp:useBean element has a non-empty body, the body is processed. The variable is initialized and available within the scope of the body. The text of the body is treated as elsewhere; if there is template text it 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 instance; in that case the body will likely contain jsp:setProperty actions and scriptlets. This completes the processing of this useBean action.
Examples

In the following example, a bean with name "connection" of type "com.myco.myapp.Connection" is available after this element, either because it was already created or because it is newly created.

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

In this next example, the timeout property is set to 33 if the bean was instantiated.

<jsp:useBean id="connection" class="com.myco.myapp.Connection">
     <jsp:setProperty name="connection" property="timeout"
  value="33">
</jsp:useBean>

In our 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"/>
JSP.2.13.1.1 Syntax

This action may or may 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 content of the body is not restricted.

The <jsp:useBean> tag has the attributes in Table JSP.2-7.

Table JSP.2-7. Attributes of the jsp:useBean Tag

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, that 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.

JSP.2.13.2 <jsp:setProperty>

The jsp:setProperty action sets the value of properties in a bean. The name attribute denotes an object that 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 setter and getter methods.

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 setProperty. The only types of properties that can be assigned to from String constants and request parameter values are those listed in Table JSP.2-8; the conversion applied is that shown in the table. Request-time expressions can be assigned to properties of any type; no automatic conversions will be performed.

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; the error may be at translation or at request-time.

Table JSP.2-8. Valid Assignments in jsp:setProperty

Property Type

Conversion on String Value

boolean or Boolean

As indicated in java.lang.Boolean.valueOf(String)

byte or Byte

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

char or Character

As indicated in java.lang.Character.valueOf(String)

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)

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 %>" />
JSP.2.13.2.1 Syntax
<jsp:setProperty name="beanName" prop_expr />
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.2.12.1, "Request-Time Attribute Values."

propertyValue ::= expr_scriptlet[2]

[2] See syntax for expression scriptlet "<%= ... %>."

The <jsp:setProperty> element has the attributes in Table JSP.2-9.

Table JSP.2-9. Attributes of the jsp:setProperty Tag

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 (in JSP 1.1 only a <jsp:useBean> 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.

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.2.13.3 <jsp:getProperty>

An <jsp:getProperty> action places the value of a bean instance property, converted 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 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.

Examples
<jsp:getProperty name="user" property="name" />
JSP.2.13.3.1 Syntax
<jsp:getProperty name="name" property="propertyName" />

The attributes are in Table JSP.2-10

Table JSP.2-10. Attributes of the jsp:getProperty Tag

name

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

property

Names the property to get.

JSP.2.13.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.E2-2 for a summary of include facilities.

The resource is specified using a relative URLspec that is interpreted in the context of the web server (i.e., it is mapped). See Section JSP.2.5.2.

An included page has access only to the JspWriter object and it cannot set headers. This precludes invoking methods like setCookie(). A request-time Exception will be raised if this constraint is not satisfied. 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.

If the page output is buffered then the buffer is flushed prior to the inclusion. See Section JSP.B.4 for an implementation note. See Section JSP.5.4.5 for limitations on flushing when out is not the top-level JspWriter.

Examples
<jsp:include page="/templates/copyright.html"/>
JSP.2.13.4.1 Syntax
<jsp:include page="urlSpec" flush="true"/>

and

<jsp:include page="urlSpec" flush="true">
     { <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.

The valid attributes are given in Table JSP.2-11.

Table JSP.2-11. Attributes of the jsp:include Tag

page

The URL is a relative urlSpec as in Section JSP.2.5.2.

Accepts a request-time attribute value (which must evaluate to a string that is a relative URL specification).

flush

Mandatory boolean attribute. If the value is "true," the buffer is flushed. A "false" value is not valid in JSP 1.1.

JSP.2.13.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.2.5.2.

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, then the buffer is cleared prior to forwarding.

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 %>' />
JSP.2.13.5.1 Syntax
<jsp:forward page="relativeURLspec" />

and

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

This tag allows the page author to cause the current request processing to be effected by the specified attributes as in Table JSP.2-12

Table JSP.2-12. Attributes of the jsp:forward Tag

page

The URL is a relative urlSpec is as in Section JSP.2.5.2.

Accepts a request-time attribute value (which must evaluate to a string that is a relative URL specification).

JSP.2.13.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:plugin elements.

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 a 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 SRV.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.2.13.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; value, which may be a request-time expression, indicates its value.

JSP.2.13.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 execution 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 Table JSP.2-13.

Table JSP.2-13. Attributes of the jsp:plugin Tag

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

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.1."

name

As defined by HTML spec

vspace

As defined by HTML spec

title

As defined by HTML spec

width

As defined by HTML spec

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.

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.

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>
JSP.2.13.7.1 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>


Chapter JSP.3. The JSP Container

This chapter provides details of the contracts between a JSP container and a JSP page.

This chapter is independent on the scripting language used in the JSP page. Chapter JSP.4 provides the details specific to when the language directive has "java" as its value.

This chapter also presents the precompilation protocol (see Section JSP.3.4).

JSP page implementation classes should use the JspFactory and PageContext classes so they will take advantage of platform-specific implementations.


JSP.3.1 The JSP Page Model

As indicated in Section JSP.1.4, "Overview of JSP Page Semantics," a JSP page is executed by a JSP container, which is installed on a web server or web enabled application server. The JSP container delivers requests from a client to a JSP page and responses from the JSP page to the client. The semantic model underlying JSP pages is that of a servlet: a JSP page describes how to create a response object from a request object for a given protocol, possibly creating and/or using in the process some other objects. A JSP page may also indicate how some events (in JSP 1.1 only init and destroy events) are to be handled.

JSP.3.1.1 The Protocol Seen by the Web Server

The entity that processes request objects creating response objects should behave as if it were a Java technology-based class; in this specification we will simply assume it is so. This class must implement the servlet protocol. It is the role of the JSP container to first locate the appropriate instance of such a class and then deliver requests to it according to the servlet protocol. As indicated elsewhere, a JSP container may need to create such a class dynamically from the JSP page source before delivering request and response objects to it.

Thus, servlet defines the contract between the JSP container and the JSP page implementation class. When the HTTP protocol is used, the contract is described by the HttpServlet class. Most pages use the HTTP protocol, but other protocols are allowed by this specification.

JSP.3.1.2 The Protocol Seen by the JSP Page Author

The JSP specification also defines the contract between the JSP container and the JSP page author. This is, what assumptions can an author 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.4.

The contract also describes how a JSP author can indicate that some actions must be taken when the init() and destroy() methods of the page implementation occur. In JSP 1.1 this is done by defining methods with name jspInit() and jspDestroy() in a declaration scripting element in the JSP page. Before the first time a request is delivered to a JSP page a jspInit() method, if present, will be called to prepare the page. Similarly, a JSP container can reclaim the resources used by a JSP page at any time that a request is not being serviced by the JSP page by invoking first its jspDestroy() method, if present.

A JSP page author may not (re)define any of the servlet methods through a declaration scripting element.

The JSP specification reserves the semantics of methods and variables starting with jsp, _jsp, jspx, and _jspx, in any combination of upper- and lower-case.

JSP.3.1.3 The HttpJspPage Interface

The enforcement of the contract between the JSP container and the JSP page author is aided by requiring that the servlet class corresponding to the JSP page implement the HttpJspPage interface (or the JspPage interface if the protocol is not HTTP).

The involved contracts are shown in Figure JSP.3-1. We now revisit this whole process in more detail.

Figure JSP.3-1. Contracts Between a JSP Page and a JSP Container


JSP.3.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 creation of the implementation class for a JSP page may be done solely by the JSP container, or it may involve a superclass provided by the JSP page author through the use of the extends attribute in the jsp directive. The extends mechanism is available for sophisticated users and it should be used with extreme care as it restricts some of the decisions that a JSP container can take, e.g., to improve performance.

The JSP page implementation class will implement Servlet and the Servlet protocol will be used to deliver requests to the class.

A JSP page implementation class may depend on some support classes; if it does, and the JSP page implementation class is packaged into a WAR, those classes will have to be included in the packaged WAR so that 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 then 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.3.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 specification for details.

The contract between the JSP container and the JSP page author is described in Table JSP.3-1. The responsibility for adhering to this contract rests only on the JSP container implementation if the JSP page does not use the extends attribute of the jsp directive; otherwise, the JSP page author guarantees that the superclass given in the extends attribute supports this contract.

Table JSP.3-1. How the JSP Container Processes JSP Pages

Comments

Methods the JSP Container Invokes

Method is optionally defined in JSP page. Method is invoked when the JSP page is initialized. When method is called, all the methods in servlet, including getServletConfig(), are available.

void jspInit()

Method is optionally defined in JSP page. Method is invoked before destroying the page.

void jspDestroy()

Method may not be defined in JSP page. The JSP container automatically generates this method, based on the contents of the JSP page. Method invoked at each client request.

void _jspService(<ServletRequestSubtype>, <ServletResponseSubtype>) throws IOException, ServletException

JSP.3.2.2 Request and Response Parameters

As shown in Table JSP.3-1, the methods in the contract between the JSP container 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.ServletResponse. 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 contract for HTTP 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.

Note

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.3.2.3 Omitting the extends Attribute

If the extends attribute of the language directive (see Section JSP.2.7.1, "The page Directive") in a JSP page is not used, the JSP container can generate any class that satisfies the contract described in Table JSP.3-1 when it transforms the JSP page.

In the following code examples, Code Example JSP.3-1 illustrates a generic HTTP superclass named ExampleHttpSuper. Code Example JSP.3-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 need not discover if the JSP page includes a declaration with jspInit() or jspDestroy(); this simplifies the implementation very significantly.

Code Example 3.2 A Generic HTTP Superclass
imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;

/**
 * An example of a superclass for an HTTP JSP class
 */

abstract class ExampleHttpSuper implements HttpJspPage {
     private ServletConfig config;

final public void init(ServletConfig config) throws
ServletException {
     this.config = config;
     jspInit();
}
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?
}
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 3.3 The Java Class Generated from a JSP Page
imports javax.servlet.*;
imports javax.servlet.http.*;
imports javax.servlet.jsp.*;

/**
 * An example of a class generated for a JSP.
 *
 * The name of the class is unpredictable.
 * We are assuming that this is an HTTP JSP page
 * (like almost all are)
 */

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
          HttpSession session = request.getSession();
          ServletContext context =
               getServletConfig().getServletContext();

          // for this example, we assume a buffered directive

          JSPBufferedWriter out = new
               JSPBufferedWriter(response.getWriter());

          // next is code from scriptlets, expressions,
          // and static text.

     }

}

JSP.3.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.3-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.3.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 until the flush method is executed and the headers are sent.

JSP 1.1 includes a class that buffers and sends output, javax.servlet.jsp.JspWriter. The JspWriter class is used in the _jspPageService method as in the following example:

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 Section JSP.6.1.2.

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.3.4 Precompilation

A JSP page that is using the HTTP protocol will receive HTTP requests. JSP 1.1 compliant containers must support a simple precompilation protocol, as well as some basic reserved parameter names. Note that the precompilation protocol should not be confused with the notion of compiling a JSP page into a Servlet class (Appendix JSP.C).

JSP.3.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.

All JSP pages should ignore (not depend on) any parameter that starts with "jsp_."

JSP.3.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 value "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 hint to the JSP container to precompile the JSP page into its JSP page implementation class. The hint is conveyed by giving the parameter the value "true" or no value, but note that the request can just be ignored in all cases.

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 be delivered to the page with no changes.

  6. ?jsp_precompile="foo"

This is illegal and will generate an HTTP error; 500 (server error).


Chapter JSP.4. Scripting

This chapter describes the details of the scripting elements when the language 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 details of the relationship between the scripting declarations, scriptlets, and scripting expressions and the Java programming language are explained in detail in the following sections. The description is in terms of the structure of the JSP page implementation class; recall that a JSP container need not necessarily generate the JSP page implementation class but it must behave as if one existed.


JSP.4.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 just language fragments, not complete language statements.

JSP.4.1.1 Valid JSP Page

A JSP page is valid for a Java platform if and only if the JSP page implementation class defined by Table JSP.4-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.

Sun Microsystems reserves all names of the form {_} jsp_* and {_}jspx_*, in any combination of upper- and lowercase, for the JSP specification. Names of this form that are not defined in this specification are reserved by Sun for future expansion.

Table JSP.4-1. Structure of the Java Programming Language Class

Optional imports clause as indicated via jsp directive

import name1

SuperClass is selected either by the JSP container or by the JSP author via jsp directive.

Name of class (_jspXXX) is implementation dependent.

class _jspXXX extends SuperClass

Start of body of JSP page implementation class

{

(1) Declaration Section

// declarations ...

Signature for generated method

public void _jspService(<ServletRequestSubtype>
request,
     <ServletResponseSubtype> response)
      throws ServletException, IOException {

(2) Implicit Objects Section

// code that defines and initializes request,
response, page, pageContext etc.

(3) Main Section

// code that defines request/response mapping

Close of _jspService method

}

Close of _jspXXX

}

JSP.4.1.2 Implementation Flexibility

The transformations described in this chapter need not be performed literally; an implementation may want to implement things differently to provide better performance, lower memory footprint, or other implementation attributes.


JSP.4.2 Declarations Section

The declarations section corresponds to the declaration elements.

The contents of this section are determined by concatenating all the declarations in the page in the order in which they appear.


JSP.4.3 Initialization Section

This section defines and initializes the implicit objects available to the JSP page. See Section JSP.2.8, "Implicit Objects."


JSP.4.4 Main Section

This section provides the main mapping between a request and a response object.

The contents of code segment 2 in Table JSP.4-1 are determined from scriptlets, expressions, and the text body of the JSP page. These elements are processed sequentially; a translation for each one is determined as indicated below, and its translation is inserted into this section. The translation depends on the element type:

  1. Template data is transformed into code that will place the template data into the stream currently named by the implicit variable out. All white space is preserved.

    Ignoring quotation issues and performance issues, this corresponds to a statement of the form:

    out.print(template);

  2. A scriptlet is transformed into its Java statement fragment.

  3. 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 currently named 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:

    out.print(expression);

  4. An action defining one or more objects is transformed into one or more variable declarations for these objects, together with code that initializes these variables. The visibility of these variables is affected by other constructs, like the scriptlets.

The semantics of the action type determines the name of the variables (usually that of the id attribute, if present) and their type. The only standard action in the JSP 1.1 specification that defines objects is the jsp:useBean action; the name of the variable introduced is that of the id attribute, its type is that of the class attribute.

Note that the value of the scope attribute does not affect the visibility of the variables within the generated program; it affects only where (and thus for how long) there will be additional references to the object denoted by the variable.


Chapter JSP.5. Tag Extensions

This chapter describes the mechanisms for defining new actions in a portable way and for introducing new actions into a JSP page.


JSP.5.1 Introduction

A tag library abstracts some functionality by defining a specialized (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, and can then be used in the page using the prefix given by the directive. An action can create new objects that can then be passed to other actions or can be manipulated programmatically through a scripting element in the JSP page.

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 and modify a JSP page.

  • Present the JSP page to the end user.

The JSP 1.1 specification mostly includes the first kind of information, plus basic information of the other two kinds. Later releases of the JSP specification may provide additional information; in the meanwhile, vendors may use vendor-specific information to address their needs.

A tag library is described via a tag library descriptor, an XML document that is described further below.

No custom directives can be described using the JSP 1.1 specification.

JSP.5.1.1 Goals

The tag extension mechanism described in this chapter addresses the following goals:

Portable: An action described in a tag library must be usable in any JSP container.

Simple: Unsophisticated users must be able to understand and use this mechanism. We would like to make it very easy for vendors of functionality to expose it through actions.

Expressive: We want to enable a wide range of actions to be described in this mechanism, including:

- Nested actions

- Scripting elements inside the body

- Creation, use, and updating of scripting variables

Usable from different scripting languages: Although the JSP specification currently only defines the semantics for scripting based on the Java programming language, we want to leave open other scripting languages.

Building upon existing concepts and machinery: We do not want to reinvent machinery that exists elsewhere. Also, we want to avoid future conflicts whenever we can predict them.

JSP.5.1.2 Overview

The basic mechanism for defining the semantics of an action is that of a tag handler. A tag handler is a Java class that implements the Tag or BodyTag interfaces and that is the runtime representation of a custom action.

The JSP page implementation class instantiates (or reuses) a tag handler object for each action in the JSP page. This handler object 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 two main interfaces: Tag and BodyTag.

  • Tag defines the basic methods that are needed in all tag handlers. These methods include setter methods to initialize a tag handler with context data and with the attribute values of the corresponding action and the two methods doStartTag() and doEndTag().

  • BodyTag provides two additional methods for when the tag handler wants to manipulate its body. The two new methods are doInitBody() and doAfterBody().

The use of interfaces simplifies taking an existing Java object and making it a tag handler. There are also two support classes that can be used as base classes: TagSupport and BodyTagSupport.

JSP.5.1.2.1 Simple Actions

In many cases, the tag handler needs only to use the tag handler's method doStartTag() which is invoked when the start tag is encountered. This method needs to access the attributes of the tag and may also want to access information on the state of the JSP page; this information is passed to the Tag object before the call to doStartTag() through several setter method calls.

The doEndTag() is similar to doStartTag(), 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.

A particularly simple and frequent action is one that has an empty body (no text between the start and the end tag). The tag library descriptor can be used to indicate that the tag is always intended to be empty; this leads to better error checking at translation time and to better code quality in the JSP page implementation class.

JSP.5.1.2.2 Actions with Body

Recall that, in general, the body of an action may contain other custom and core actions and scripting elements, as well as uninterpreted template text.

In some cases, an action is interested only in "passing through" the content of the body. This can be done using the simple Tag interface by using a special return value in doStartTag().

If an action element can have a non-empty body and is interested in the content of that body, the methods doInitBody() and doAfterBody(), defined in the BodyTag interface, are involved.

The control of the evaluation is actually done based on the result of method invocations as follows. The doStartTag() method is always invoked first and returns an int value that indicates if the body of the action should be evaluated or not. If so (EVAL_BODY_TAG return), a nested stream of type BodyContent is created and is passed to the BodyTag object through setBodyContent. Then doInitBody is invoked. Next the body is evaluated, with the result going into the newly created BodyContent object. Finally, the doAfterBody() method of the tag handler object is invoked.

If the invocation to doStartTag() returned SKIP_BODY, the body is not evaluated at all.

The doBody() method may use the BodyContent object as it sees fit. For example, it may convert it into a string and use it as an argument, or it may do some filter action to it before passing it through to the out stream, or it may something else.

A doAfterBody() invocation returns an indication of whether further reevaluations of the body text should be done by the JSP page; as in the case of doStartTag(), if EVAL_BODY_TAG is returned, the body is reevaluated, while a return value of SKIP_BODY will stop reevaluations. Note that, since server-side objects (accessible via pageContext or through nested handlers) may have changed, each evaluation may produce very different content to be added to the BodyContent object.

JSP.5.1.2.3 Cooperating Actions

Often the best way to describe some functionality is through several cooperating actions. For example, an action may be used to describe information that leads to the creation of some server-side object, while another action may use that object elsewhere in the page. One way for these actions to cooperate is explicitly, via using scripting variables: One action creates an object and gives it a name, the other refers to it through this name. Scripting variables are discussed briefly below.

Two actions can also cooperate implicitly using different conventions. For example, perhaps the last action applies, or perhaps there is only one action of a given type per JSP page. A more flexible and very convenient mechanism for action cooperation is using the nesting structure to describe scoping. Each tag handler is told of its parent tag handler (if any) using a setter method; the findAncestorWithClass static method in TagSupport can then be used to locate a tag handler with some given properties.

JSP.5.1.2.4 Actions Defining Scripting Variables

A custom action may create some server-side objects and make them available to the scripting elements by creating or updating some scripting variables. The spe-cific variables thus effected may vary with the action instance. The details of this are described through subclasses of javax.servlet.jsp.tagext.TagExtraInfo which are used at JSP page translation time. The TagExtraInfo class provides methods that will indicate the names and types of the scripting variables that will be assigned objects (at request time) by the action. These methods are passed to a TagData instance that describes the attributes of a given action. The responsibility of the tag library author is to faithfully indicate this information in the TagExtraInfo class; the corresponding Tag object must add the objects to the pageContext object. It is the responsibility of the JSP page translator to automatically supply all the required code to do the "synchronization" between the pageObject values and the scripting variables.

JSP.5.1.3 Examples

This section outlines some simple, and common, uses of the tag extension mechanism. See Appendix JSP.A for more details on these examples and for additional examples of custom actions.

JSP.5.1.3.1 Call Functionality, No Body

This is probably the simplest example: just collect attributes and call into some action. The only action involved is foo, and in this case it should have no body. That is, something like:

<x:foo att1="..." att2="..." att3="..." />

In this case we would define a FooTag tag handler that extends TagSupport only redefining doStartTag. The doStartTag method would take the attribute information, perhaps interact with the PageContext data, and invoke into the appropriate functionality.

The entry for this tag in the tag library descriptor should indicate that the action must have no body; no TagExtraInfo class is needed.

JSP.5.1.3.2 Call Functionality, No Body, Define Object

In a simple variation of the previous example the action defines an object.

<x:bar id="mybar" att1="..." att2="..." att3="..." />

After this, an object with name mybar is available to the scripting language.

The semantics of the doStartTag() invocation is as before except that additionally it should insert the appropriate object for the mybar entry into the pageContext.

The tag library descriptor entry for this action needs to mention a TagExtraInfo class that will be used to determine the scripting variables that will be created by the action; in this case "mybar" (note that id must be a translation-time attribute).

JSP.5.1.3.3 Call Functionality, Define Object by Scope

In some cases, the previous example can also be described without using a TagExtraInfo by having the bar action enclose the actions that would use the created object. In this case, the defining action needs not indicate any id attribute but it must have a body:

<x:bar att1="..." att2="..." att3="...">
  BODY
</x:bar>

The nesting actions will invoke findAncestorWithClass to locate the bar handler object.

JSP.5.1.3.4 Template Mechanisms

There are a number of template mechanisms in server-side frameworks. The simplest of these mechanisms will take a token and replace it by some fixed replacement text (that can be changed easily); more sophisticated mechanisms compute the replacement text, and can pass arguments for that computation. These mechanisms can be subsumed directly into an empty-bodied action invocation, perhaps using attributes to describe the template and/or the arguments for the computation.

JSP.5.1.3.5 An HTML Quoting Action

The final example is an action that takes its body and performs HTML quoting. In this case, the doStartTag() method will save away the value of the out implicit object and request the evaluation of the body. The doAfterBody() method will take the nested stream, perform the quoting, and send it down to the saved out stream.

JSP.5.1.3.6 A useBean as in the JSP 0.92 Specification

The 0.92 public draft of the JSP specification included a version of a useBean action with a variation: if the bean created included a processRequest(ServletRequest) method then the method would be invoked. Observant readers will notice that a processRequest() is a special case of a doStartTag() as the request object is one of the objects available in pageContext.


JSP.5.2 Tag Library

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 via a taglib directive that identifies the tag library via a URI (universal resource identifier).

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. A common mechanism is to encode the version of a tag library into its URI.

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.5.3 below.

JSP.5.2.1 Packaged Tag Libraries

JSP page authoring tools are required to accept a tag library that is packaged as a JAR file. When packaged so, the JAR file must have a tag library descriptor file named META-INF/taglib.tld.

JSP.5.2.2 Location of Java Classes

The request-time Tag handler classes and the translation-time TagExtraInfo classes are just Java classes. In a web application they must reside in the standard locations for Java classes: either in a JAR file in the WEB-INF/lib directory or in a directory in the WEB-INF/classes directory.

The previous rule indicates that a JAR containing 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.5.3.2). The mapping between the URI and the TLD is explained further below.

JSP.5.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 that will distinguish usage of the actions in the library.

If a JSP container implementation cannot locate (following the rules described in Section JSP.5.3.1) a tag library description for a given URI, a fatal translation error shall result.

It is a fatal translation error for the taglib directive to appear after actions using the prefix introduced by the taglib directive.


JSP.5.3 Tag Library Descriptor

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.

Each action in the library is described by giving its name, the class for its tag handler, optional information on a TagExtraInfo class, and information on all the attributes of the action. Each valid attribute is mentioned explicitly, with indication of whether it is mandatory or not, whether it can accept request-time expressions, and additional information.

A TLD file is useful as a descriptive mechanism for providing information on a tag library. It has the advantage that it can be read by tools without having to instantiate objects or load classes. The approach we follow conforms to the conventions used in other J2EE technologies.

The DTD to 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. An alternative approach, based on XML name spaces, has some interesting properties but it was not pursued in part for consistency with the rest of the J2EE descriptors.

The official DTD is described at "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd."

JSP.5.3.1 Locating a Tag Library Descriptor

The URI describing a tag library is mapped to a tag library descriptor file though two mechanisms: a map in web.xml described using the taglib element, and a default mapping.

JSP.5.3.1.1 taglib Map in web.xml

The map in web.xml is described using the taglib element of the web application deployment descriptor in WEB-INF/web.xml, as described in the Servlet 2.2 spec and in "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd."

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

taglib

A taglib is a subelement of web-app:

<!ELEMENT web-app .... taglib* .... >

The taglib element provides information on a tag library that is used by a JSP page within the web application.

A taglib element has two subelements and one attribute:

<!ELEMENT taglib ( taglib-uri, taglib-location ) >
<!ATTLIST taglib id ID #IMPLIED>

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. It may be either an absolute URI
specification, or a relative URI as in Section JSP.2.5.2.

taglib-location

A taglib-location contains the location (as a resource) where the tag library descriptor file for this tag library can be found.

<!ELEMENT taglib-location (#PCDATA) >
PCDATA ::= a resource location, as indicated in Section JSP.2.5.2,
where to find the tag library descriptor file.
Example

The use of relative URI specifications enables very short names in the taglib directive. For example:

<%@ taglib uri="/myPRlibrary" prefix="x" %>

and then

<taglib>
  <taglib-uri>/myPRlibrary</taglib-uri>
  <taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib-uri>
</taglib>
JSP.5.3.1.2 Default Location

If there is no taglib-uri subelement that matches the URI used in a taglib directive, the tag library descriptor will be searched in the location indicated by the URI itself.

This rule applies only to URIs that are relative URI specifications (as in Section JSP.2.5.2).

Example

This 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="/tlds/PRlibrary_1_4.tld" prefix="x" %>

JSP.5.3.2 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 through the use of the class-path attribute in the META-INF/MANIFEST file of these JAR files.

JSP.5.3.3 Assembling a Web Application

As part of the process of assembling a web application, the application assembler will create a WEB-INF/ directory, with appropriate lib/ and classes/ subdirectories, place JSP pages, servlet classes, auxiliary classes, and tag libraries in the proper places and then create a WEB-INF/web.xml that ties everything together.

Tag libraries that have been delivered in the standard format can be dropped directly into WEB-INF/lib. 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.5.8.3.

JSP.5.3.4 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 the same 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.

If there is no mapping for a given URI and the URI is not well-known to the JSP container, a translation-time error will occur.

There is no guarantee that this "well-known URI" mechanism will be preserved in later releases of the JSP specification. As experience accumulates on how to use tag extensions, the JSP specification may incorporate new functionality that will make the "well-known URI" mechanism unnecessary; at that point it may be removed.

JSP.5.3.5 The Tag Library Descriptor Format

This section describes the DTD for the tag library descriptor. This is the same DTD as "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd" except for some formatting changes to extract comments and make them more readable.

Notation
<!NOTATION WEB-JSPTAGLIB.1_1 PUBLIC "-//Sun Microsystems, Inc.//DTD
JSP Tag Library 1.1//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/j2ee/dtds/web-jsptaglibrary_1_1.dtd"
>

A taglib element also has several subelements that define:

tlibversion | the version of the tag library implementation
jspversion | the version of JSP specification the tag library depends upon
shortname | a simple default short name that could be used by a JSP page authoring tool to create names with a mnemonic value; for example, it may be used as the preferred prefix value in taglib directives.
uri | a uri uniquely identifying this taglib.
info | a string describing the "use" of this taglib

<!ELEMENT taglib
   (tlibversion, jspversion?,
    shortname, uri?, info?,
    tag+) >

tlibversion

Describes this version (number) of the tag library.

The syntax is:

<!ELEMENT tlibversion (#PCDATA) >
#PCDATA ::= [0-9]*{ "."[0-9] }0..3

jspversion

Describes the JSP specification version (number) this tag library requires in order to function. The default is 1.1

The syntax is:

<!ELEMENT jspversion  (#PCDATA) >
#PCDATA ::= [0-9]*{ "."[0-9] }0..3.

shortname

Defines a simple default short name that could be used by a JSP page authoring tool to create names with a mnemonic value; for example, 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

<!ELEMENT shortname    (#PCDATA) >
#PCDATA ::= NMTOKEN

uri

Defines a public URI that uniquely identifies this version of the tag library. It is recommended that the URI identifying a tag library is actually a URL to the tag library descriptor for this specific version of the tag library.

<!ELEMENT uri       (#PCDATA) >

info

Defines an arbitrary text string describing the tag library.

<!ELEMENT info      (#PCDATA) >

tag

The tag defines an action in this tag library. It has one attribute:

<!ATTLIST tag id ID #IMPLIED >

The tag may have several subelements defining:

name | the unique action name
tagclass | the tag handler class implementing javax.servlet.jsp.tagext.Tag
teiclass | an optional subclass of javax.servlet.jsp.tagext.TagExtraInfo
bodycontent | the body content type
info | optional tag-specific information
attribute | all attributes of this action

The element syntax is as follows:

<!ELEMENT tag
   (name, tagclass, teiclass?,
    bodycontent?, info?, attribute*) >

tagclass

Defines the tag handler class implementing the javax.serlvet.jsp.tagext.Tag interface. This element is required.

The syntax is:

<!ELEMENT tagclass (#PCDATA) >
#PCDATA ::= fully qualified Java class name.

teiclass

Defines the subclass of javax.servlet.jsp.tagext.TagExtraInfo for this tag. This element is optional.

The syntax is:

<!ELEMENT teiclass (#PCDATA) >
 #PCDATA ::= fully qualified Java class name

bodycontent

Provides a hint as to the content of the body of this action. Primarily intended for use by page composition tools.

There are currently three values specified:

tagdependent | The body of the action is 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.
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 bodycontent (#PCDATA) >
#PCDATA ::=  tagdependent | JSP | empty.

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 attribute's 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)

The syntax is:

<!ELEMENT attribute
   (name, required?,
   rtexprvalue?) >

name

Defines the canonical name of a tag or attribute being defined

The syntax is:

<!ELEMENT name      (#PCDATA) >
#PCDATA ::= NMTOKEN

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.


JSP.5.4 Tag Handlers

A tag handler is a runtime server-side object that is created to help evaluate actions during the execution of a JSP page. A tag handler supports a runtime protocol that facilitates passing information from the JSP page to the handler.

A tag handler is a server-side invisible JavaBeans component, but it implements an additional interface to indicate that it has a richer runtime protocol. There are two interfaces that describe a tag handler: Tag is used for simple tag handlers that are not interested in manipulating their body content (if any); BodyTag is an extension of Tag and gives a tag handler access to its body. The TagSupport and BodyTagSupport classes can be used as base classes when creating new tag handlers.

JSP.5.4.1 Properties

A tag handler has some properties that are set by the JSP container (usually through the JSP page implementation class) using setter methods:

  • The pageContext object for the JSP page where the tag is located; this object can be used to access defined objects.

  • The parent tag handler for the enclosing action.

A tag handler may have additional properties, as any other JavaBean component. These properties will have setters and getter methods, as described in the JavaBeans component specification and used throughout the Java platform.

All attributes of a custom action must be JavaBeans component properties, although some properties may not be exposed as attributes in the tag library descriptor.

Additional translation time information (TagExtraInfo) associated with the action indicates the name of the variables it introduces, their types, and their scope. At specific moments (after processing the start tag; after processing the end tag), the JSP container can automatically synchronize the PageContext information with variables in the scripting language so they can be made available directly through the scripting elements.

JSP.5.4.2 Basic Protocol: Tag Interface

This section describes the Tag interface which defines the basic contract for all tag handlers. See Section JSP.5.4.7 for a summary of the life-cycle issues.

A tag handler has some properties that must be initialized before it can be used. It is the responsibility of the JSP container to invoke the appropriate setter methods to initialize these properties. Once properly set, these 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 need not set it again. These properties include the properties in the Tag interface as well as other properties.

Once initialized, the doStartTag and doEndTag methods can be invoked on the tag handler. Between these invocations, the tag handler is assumed to hold a state that must be preserved. After the doEndTag invocation, the tag handler is available for further invocations (and it is expected to have retained its properties). Once all invocations on the tag handler are completed, the release method is invoked on it. Once a release method is invoked, all properties are assumed to have been reset to an unspecified value.

Properties

All tag handlers must have the following properties: pageContext and parent. When setting properties, the order is always pageContext and parent. The Tag interface specifies the setter methods for all properties and the getter method for parent.

setPageContext(PageContext) | Sets the pageContext property of a tag handler.
setParent(Tag) | Sets the parent tag for a tag handler.
Tag getParent() | Get the parent tag for a tag handler. This method is used by the findAncestorWithClass static method in TagSupport.

Methods

There are two main action methods and one method for releasing all resources owned by a tag handler.

doStartTag()

Process the start tag of this action. 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 evaluated.

At the end of this method invocation some scripting variables may be assigned from the pageContext object, as indicated by the optional TagExtraInfo class (at translation time).

This method returns an indication of whether the body of the action should be evaluated (EVAL_BODY_INCLUDE or EVAL_BODY_TAG) or not (SKIP_BODY). See below for more details.

EVAL_BODY_INCLUDE is not valid if the tag handler implements BodyTag; EVAL_BODY_TAG is not valid if the tag handler implements Tag and does not implement BodyTag.

This method may throw a JspException.

doEndTag()

Process the end tag of this action. 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.

At the end of this method invocation some scripting variables may be assigned from the pageContext object, as indicated by the optional TagExtraInfo class (at translation time).

If this method returns EVAL_PAGE, the rest of the page continues to be evaluated. If this method returns SKIP_PAGE, the rest of the page is not evaluated and the request is completed. If this request was forwarded or included from another page (or servlet), only the current page evaluation is completed.

This method may throw a JspException.

release()

Release a tag instance.

Simple Actions with Non-Empty Bodies

If a tag library descriptor maps an action with a non-empty body to a tag handler that implements the Tag interface, the tag handler cannot manipulate this body because there is no mechanism for the tag handler to access that body. To make the situation more explicit, the return value of doStartTag is either SKIP_BODY, EVAL_BODY_INCLUDE or EVAL_BODY_TAG. The meanings are as follows:

  • SKIP_BODY means do not process the body of the action (if it exists).

  • EVAL_BODY_INCLUDE means process the body of the action but do not create a new BodyContent (see below) nor change the value of the out implicit object.

  • EVAL_BODY_TAG means create a new BodyContent, change the value of the out implicit object, and process the body of the action.

A typical use for EVAL_BODY_INCLUDE could be a conditional inclusion action tag. Since the body is to be passed through directly, there is no need for the tag handler to manipulate it, and thus the tag handler need not implement BodyTag.

To help in catching errors, EVAL_BODY_INCLUDE is not valid in a tag handler that implements BodyTag, while EVAL_BODY_TAG is not valid in a tag handler that implements Tag but does not implement BodyTag.

JSP.5.4.3 The TagSupport Base Class

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 interface and adds additional convenience methods including getter methods for the properties in Tag. TagSupport has one static method that is included to facilitate coordination among cooperating tags.

Tag findAncestorWithClass(Tag, class)

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.

The return value of the doStartTag() method is SKIP_BODY. The return value of the doEndTag() method is EVAL_PAGE.

JSP.5.4.4 Body Protocol: BodyTag Interface

The BodyTag interface extends Tag with methods to manipulate the body of an action. These methods act on the bodyContent property of a BodyTag instance.

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 bodyContent.writeOut method.

A tag handler that implements BodyTag is treated as one that implements Tag, except that the doStartTag method can return either SKIP_BODY or EVAL_BODY_TAG, not EVAL_BODY_INCLUDE. If EVAL_BODY_TAG is returned, then a bodyContent object will be created to capture the body evaluation. This object is obtained by calling the pushBody method of the current pageContext, which additionally has the effect of saving the previous out value. The object is returned through a call to the popBody method of the PageContext class; the call also restores the value of out.

Properties

There is only one additional property: bodyContent

setBodyContent(BodyContent)

Set the bodyContent property. It will be invoked at most once per action invocation. It will be invoked before doInitBody and it will not be invoked if there is no body evaluation.

When setBodyContent is invoked, the value of the implicit object out has already been changed in the pageContext object. The body passed will not have data on it.

Methods

There are two action methods:

doInitBody()

Invoked before the first time the body is to be evaluated. Not invoked in empty tags or in tags returning SKIP_BODY in doStartTag().

Depending on TagExtraInfo values, the JSP container will resynchronize some variable values after the doInitBody invocation.

This method may throw a JspException.

doAfterBody()

Invoked after every body evaluation. Not invoked in empty tags or in tags returning SKIP_BODY in doStartTag. If doAfterBody returns EVAL_BODY_TAG, a new evaluation of the body will happen (followed by another invocation of doAfterBody). If doAfterBody returns SKIP_BODY no more body evaluations will occur, the value of out will be restored using the popBody method in pageContext, and then doEndTag will be invoked.

The method re-invocations may lead to different actions because there might have been some changes to shared state, or because of external computation.

Depending on TagExtraInfo values, the JSP container will resynchronize some variable values after every doAfterBody invocation (so a reevaluation of the body will return a different value).

This method may throw a JspException.

JSP.5.4.5 The BodyContent Class

The BodyContent is a subclass of JspWriter that can be used to process body evaluations so they can be retrieved later on. The class has methods to convert its contents into a String, to read its contents, 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. This means that it is not legal to do a jsp:include when out is not bound to the top-level JspWriter.

Instances of this class 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.

The BodyContent type contains four main methods:

clearBody() | This is a version of the clear() method from JspWriter that is guaranteed not to throw exceptions.
getReader() | Get a reader into the contents of this instance.
getString() | As getReader() but returns a String.
writeOut(Writer) | Write out the content of this instance into the provided Writer.
getEnclosingWriter() | Get the JspWriter enclosing this BodyContent.

JSP.5.4.6 The BodyTagSupport Base Class

The BodyTagSupport class is a utility class intended to be used as the base class for new tag handlers implementing BodyTag. The BodyTagSupport class implements the BodyTag interface and adds additional convenience methods including getter methods for the bodyContent property and methods to get at the previous out JspWriter.

The return value of the doStartTag() method is EVAL_BODY_TAG. The return value of the doEndTag() method is EVAL_PAGE. The return value of the doAfterBody() method is SKIP_BODY.

JSP.5.4.7 Life-Cycle Considerations

At execution time the implementation of a JSP page will use an available Tag instance with the appropriate prefix and name that is not being used, initialize it, and then follow the protocol described below. Afterwards, it will release the instance and make it available for further use. This approach reduces the number of instances that are needed at a time.

Initialization is done by setting the properties pageContext and parent, in that order, while release is done by invoking release().

An Execution Trace

The following example shows the runtime trace for two actions supported by a tag handler implementing BodyTag; setters are in italics, while actions are not. The inner boxes highlight the portion of the protocol used to interact with the body of the tag. In this example, we are assuming that the second action has the same parent but one different attribute values.

     h.setPageContext(pageContext);
     h.setParent(parent);
     h.setAttribute1(value1);
     h.setAttribute2(value2);...
     h.doStartTag()
 _______________________________________________
|                                               |
|    out = pageContext.pushBody()               |
|    h.setBodyContent(out)                      |
|    h.doInitBody()                             |
|    [BODY]                                     |
|    h.doAfterBody()                            |
|    ....                                       |        Body Actions
|    [BODY]                                     |
|    h.doAfterBody()                            |
|    ......                                     |
|    out = pageContext.popBody()                |
|_______________________________________________|

     h.doEndTag();

     h.setAttribute2(value3);
     h.doStartTag()
 _______________________________________________
|                                               |
|    out = pageContext.pushBody()               |
|    h.setBodyContent(out)                      |
|    h.doInitBody()                             |
|    [BODY]                                     |
|    h.doAfterBody()                            |
|    ....                                       |        Body Actions
|    [BODY]                                     |
|    h.doAfterBody()                            |
|    ......                                     |
|    out = pageContext.popBody()                |
|_______________________________________________|

     h.doEndTag();

     h.release()


JSP.5.5 Scripting Variables

The JSP specification supports scripting variables that can be declared within a scriptlet and can be used in another. The actions in a JSP page also can be used to define scripting variables so they can be used in scripting elements, or in other actions; for example, the jsp:useBean standard action may define an object which can later be used through a scripting variable.

Since the logic that decides whether an action instance will define a scripting variable may be quite complex, this information is not encoded in the Tag Library Descriptor directly; rather, the name of a TagExtraInfo class is given in the TLD and the getVariableInfo method 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.

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 (Figure JSP.5-1).

Figure JSP.5-1. Scope of Scripting Variables

The defined values for scope are:

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

  • AT_END, if the scripting variable is available after the end tag of the action that defines it until the end of the page.

The scope value for a variable implies what methods may affect its value and thus, in lack of additional information, where synchronization is needed:

  • For NESTED, after doInitBody and doAfterBody for a tag handler implementing 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.


JSP.5.6 Cooperating Actions

Often two actions in a JSP page want to cooperate, perhaps by one action creating some server-side object that is used by the other. There are two basic mechanisms in the JSP specification to achieve this.

JSP.5.6.1 Ids and PageContext

One mechanism for supporting cooperation among actions is by giving the object a name within the JSP page; the first action creates and names the object while the second action uses the name to retrieve the object.

For example, in the following JSP page fragment the foo action creates a server-side object and give it the name "myObject." Then the bar action accesses that server-side object and takes some action.

<x:foo id="myObject" />
<x:bar ref="myObject" />

In a JSP container implementation, the mapping between the name and the 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 that is needed is to know the name under which the information is stored into the pageContext.

JSP.5.6.2 Run-Time 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 page 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 findAncestorWithClass(Tag, Class) static method of the Tag class, which uses a reference to parent tag kept by each Tag instance, which effectively provides a runtime execution stack.


JSP.5.7 Validation

Frequently there are constraints on how actions are to be used, and when these constraints are not kept an error should be reported to the user. There are several mechanisms in the JSP 1.1 specification to describe syntactic and semantic constraints among actions; future specifications may add additional mechanisms.

JSP.5.7.1 Syntactic Information on the TLD

The tag library descriptor contains some basic syntactic information. In particular, the attributes are described including their name, whether they are optional or mandatory, and whether they accept request-time expressions. Additionally the bodycontent attribute 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.5.7.2 Syntactic Information in a TagExtraInfo Class

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.

JSP.5.7.3 Raising an Error at Action Time

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 JspError can be thrown. If uncaught, this object will invoke the error page mechanism of the JSP specification.


JSP.5.8 Conventions and Other Issues

This section is not normative, although it reflects good design practices.

JSP.5.8.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; this action will define the desired objects.

Then the JSP page can make these objects available as follows:

<%@ tablig prefix="me" uri="......" %>
<me:defineObjects />
....start using the objects....

This approach has the advantage of requiring no new machinery and of making the dependency very explicit.

In some cases there may be some implementation dependency in making these objects available; for example, they may be providing access to some functionality that exists only in some implementation. This can be done by having the tag extension class test at runtime for the existence of some implementation dependent feature and raise a runtime error (this, of course, makes the page not J2EE compliant, but that is a different discussion).

This mechanism, together with the access to metadata information, allows 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.5.8.2 Access to Vendor-Specific information

If a vendor wants to associate with some tag library some information that is not described in the current version of the TLD, it can do so by inserting the information in a document it controls, inserting the document in the WEB-INF portion of the JAR file where the tag library resides, and using the standard Servlet 2.2 mechanisms to access that information.

The vendor can now use the ID machinery to refer to the element within the TLD.

JSP.5.8.3 Customizing a Tag Library

A tag library can be customized at assembly and deployment time. For example, 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 customization information A standardized mechanism is probably going to be part of a forthcoming 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 WEB-INF/ portion of the web application and access it via the getResource() call on the ServletContext.


Chapter JSP.6. JSP Technology Classes

This chapter describes the packages that are part of the JSP 1.1 specification. The packages may be used in a number of situations, including within scripting elements, by base classes, and in implementations of tag extensions.

There are two packages

  • javax.servlet.jsp

  • javax.servlet.jsp.tagext.

The javadoc documents that accompany this specification [1] provide detailed description of the packages. This chapter provides an overview, context, and usage guidelines.

[1] All JSP-related specifications are available from http://java.sun.com/products/jsp.


JSP.6.1 Package javax.servlet.jsp

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.6.1.1 JspPage and HttpJspPage

Two interfaces describe the interaction between a class implementing a JSP page and the JSP container: HttpJspPage and JspPage. Chapter JSP.3 describes the role of these two interfaces in detail. The JspPage contract is not described further here; see the javadoc documentation for details.

The large majority of the JSP pages use the HTTP protocol and thus are based on the HttpJspPage contract. This interface has three methods, two of which can be redefined by the JSP author using a declaration scripting element:

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 getServletConfig() method will return the desired value.

A JSP page can override this method by including a definition for it in a declaration element.

The signature of this method is void jspInit().

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.

The signature of this method is void jspDestroy().

_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 Section JSP.3.2.4.

The signature of this method is public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException.

JSP.6.1.2 JspWriter

The actions and template data in a JSP page is written using the JspWriter object that is referenced by the implicit variable out. This variable is initialized by code generated automatically by the JSP container (see the PageContext object in Section JSP.6.1.4).

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 when the buffer is flushed, and operations like setContentType() are legal. Since this flexibility simplifies programming substantially, 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; a case may be when the data is sent for immediate display through a browser. Each application will need to consider its specific needs.

An alternative considered was to make the buffer size unbounded, but this has the disadvantage that runaway computations may consume an unbounded amount of resources.

The JspWriter interface includes behaviors from java.io.BufferedWriter and java.io.PrintWriter APIs but incorporates buffering and does not consume IOExceptions as PrintWriter does. If a particular use requires a PrintWriter, as in the case of desiring to insert an exception stack trace, one can be obtained by wrapping the JspWriter with a PrintWriter.

The usual methods found in PrintWriter are available with the only modification being that the JspWriter methods do not consume IOExceptions. The additional methods are:

clear() | This method is used to clear the buffer of data. It is illegal to invoke it if the JspWriter is not buffered. An exception will be raised if the buffer has been autoFlushed and clear() is invoked. Also see clearBuffer(). The method signature is void clear().
clearBuffer() | This method is like clear() except that no exception will be raised if the buffer has been autoFlushed(). The method signature is void clearBuffer().
flush() | This method is used to flush the buffer of data. The method may be invoked indirectly if the buffer size is exceeded. The underlying PrintWriter object is guaranteed to be created exactly the first time data is flushed to it. The method signature is void flush().
close() | This method can be used to close the stream. It need not be invoked explicitly for the initial JspWriter as the code generated by the JSP container will automatically include a call to close(). The method signature is void close().
getBufferSize() | This method returns the size of the buffer used by the JspWriter. The method signature is int getBufferSize().
getRemaining() | This method returns the number of unused bytes in the buffer. The method signature is int getRemaining().
isAutoFlush() | This method indicates whether the JspWriter is autoFlushing. The method signature is boolean isAutoFlush().

JSP.6.1.3 JspException and JspError

JspException is a generic exception class. It currently has one subclass: JspError.

A JspError has a message and it reflects an unexpected error that has been found during the execution of a JSP page. If uncaught, the error will result in an invocation of the error page machinery.

JSP.6.1.4 PageContext

A PageContext provides an object that encapsulates implementation-dependent features and provides convenience methods. A JSP page implementation class that uses a PageContext as shown in Figure JSP.6-1 will run unmodified in any compli-ant JSP container taking advantage of implementation-specific improvements like high performance JspWriters. JSP 1.1 compliant containers must generate JSP page implementation classes that use this PageContext object to provide insulation from platform implementation details.

Figure JSP.6-1 Using PageContext to Provide Implementation Independence
public void _jspService(HttpServletRequest request,
                HttpServletResponse response)
           throws IOException, ServletException {

   JSPFactory  factory     = JSPFactory.getDefaultFactory();
   // Get the page context object for this page
   PageContext pageContext = factory.getPageContext(
                            this,
                            request,
                            response,
                            null, // e.g. no errorPageURL,
                            false, // e.g. no session
                            JspWriter.DEFAULT_BUFFER,
                            true // autoflush=true
                            );
   // Initialize implicit variables for scripting
   HttpSession session = pageContext.getSession();
   JspWriter   out     = pageContext.getOut();
   Object      page    = this;
   try {
           // body of JSP here ...
   } catch (Exception e) {
           out.clear();
           pageContext.handlePageException(e);
   } finally {
           out.close();
           factory.releasePageContext(pageContext);
   }
}

A PageContext object is initialized by a JSP container implementation early on in the processing of the _jspService() method. The PageContext implementation itself is implementation dependent, and is obtained via a creation method on the JspFactory.

The PageContext provides a number of facilities, including:

  • A single API that manages the operations available over various scope namespaces (page, request, session, application) such as setAttribute(), getAttribute(), removeAttribute(), etc.

  • A mechanism for obtaining a platform-dependent implementation of the JspWriter that is assigned to the "out" implicit scripting variable.

  • A number of simple convenience getter APIs for obtaining references to various request-time objects.

  • Mechanisms to forward or include the current request being processed to other components in the application.

JSP.6.1.4.1 Creation

The PageContext class is an abstract class, designed to be extended by conforming JSP container runtime environments to provide implementation-dependent implementations.

An instance of a PageContext is created by a JSP container-specific implementation class at the beginning of its _jspService() method via an implementation-specific default JspFactory, as shown in Figure JSP.6-1:

JSP.6.1.4.2 Usage

The PageContext object provides access to multiple functionality.

Uniform Access to Multiple Scopes

These methods provide uniform access to the diverse scope objects. The implementation must use the underlying servlet machinery corresponding to that scope, so information can be passed back and forth between servlets and JSP pages.

getAttribute() | Access an attribute in the page scope, or null if not found.
getAttribute() | Overload of previous method to access an attribute in a given scope or null if not found.
findAttribute() | Searches for the named attribute in page, request, session (if valid), and application scopes in order and returns the value associated or null.
getAttributeNamesInScope() | Enumerate all the attributes in a given scope.
getAttributesScope() | Get the scope where a given attribute is defined.
removeAttribute() | Remove the object reference associated with the given name, look in all scopes in the scope order.
removeAttribute() | Overload of previous method to remove the object reference associated with the given name in the given scope.
setAttribute() | Register the given name and object in the page scope.
setAttribute() | Overload of previous method to register the given name and object in the given scope.

Access to Implicit Objects

These methods provide convenience access to implicit objects and other objects that can be obtained by different ways.

getOut() | The current value of the out object (a JspWriter).
getException() | The current value of the exception object (an Exception).
getPage() | The current value of the page object (a Servlet).
getRequest() | The current value of the request object (a ServletRequest).
getResponse() | The current value of the response object (a ServletResponse).
getSession() | The current value of the session object (an HttpSession).
getServletConfig() | The ServletConfig instance.
getServletContext() | The ServletContext instance.

Management of Nested Scopes

These methods enable the management of nested JspWriter streams to implement tag extensions. Note that pushBody() returns a BodyContent, while popBody() returns a JspWriter, which will need to be casted into a BodyContent in all but the top level.

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

Management of PageContext Object

The following two methods provide management of the PageContext object itself. These methods are not intended to be used by the JSP page author.

initialize() | Initialize a PageContext with the given data.
release() | Release a PageContext object.

Forward and Include

These methods encapsulate forwarding and inclusion.

forward()

This method is used to forward the current ServletRequest and ServletResponse to another component in the application.

The signature of this method is void forward(String relativeUrlPath) throws ServletException, IOException.

include()

This method causes the resource specified to be processed as part of the current ServletRequest and ServletResponse being processed by the calling Thread.

The signature of this method is void include(String relativeUrlPath) throws ServletException, IOException.

handlePageException()

Process an unhandled page level exception by performing a redirect.

The signature of this method is void handlePageException(Exception e) throws ServletException, IOException.

JSP.6.1.5 JspEngineInfo

The JspEngineInfo class provides information on the JSP container implementation. The only method currently available is:

getSpecificationVersion()

Returns a String <deleted> in Dewey decimal format </deleted> describing the highest version of the JSP specification implemented by the JSP container. See the java.lang.Package class in the Java 2 platform for other methods that may appear in this class in future specifications.

JSP.6.1.6 JspFactory

The JspFactory provides a mechanism to instantiate platform-dependent objects in a platform-independent manner. The PageContext class and the JspEngineInfo class are the only implementation-dependent classes that can be created from the factory.

Typically, at initialization time, a JSP container will call the static setDefaultFactory() method in order to register its own factory implementation. JSP page implementation classes will use the getDefaultFactory() method in order to obtain this factory and use it to construct PageContext instances in order to process client requests.

JspFactory objects are not intended to be used by JSP page authors.


JSP.6.2 Package javax.servlet.jsp.tagext

The classes in the javax.servlet.jsp.tagext package are related to the tag extension mechanism. They are described in detail in Chapter JSP.5. In this section we will just briefly review and group them.

A brief description of the classes follows. Classes whose name ends in Info are translation-time classes. Instances that are initialized from the tag library descriptor are in bold italics:

BodyContent | Encapsulates the evaluation of a tag body.
Tag | The interface of a tag handler for an action that does not want to manipulate its body.
BodyTag | The interface of a tag handler for an action that wants to manipulate its body.
TagSupport | A base class for defining new tag handlers implementing Tag.
BodyTagSupport | A base class for defining new tag handlers implementing BodyTag.
TagAttributeInfo: | Information on the attributes of a tag.
TagData: | The attribute/value information for a tag instance. Used at translation time only.
TagExtraInfo | Tag author-provided class to describe additional translation-time information.
TagInfo: | Information needed by the JSP container at page compilation time.
TagLibraryInfo: | Information on a tag library.
VariableInfo | Information on scripting variables.


Chapter JSP.7. JSP Pages as XML Documents

This chapter defines a standard XML document for each JSP page.

The JSP page to XML document mapping is not visible to JSP 1.1 containers; it will receive substantial emphasis in the next releases of the JSP specification. Since the mapping has not received great usage, we particularly encourage feedback in this area.


JSP.7.1 Why an XML Representation

There are a number of reasons why it would be impractical to define JSP pages as XML documents when the JSP page is to be authored manually:

  • An XML document must have a single top element; a JSP page is conveniently organized as a sequence of template text and elements.

  • In an XML document all tags are "significant"; to "pass through" a tag, it needs to be escaped using a mechanism like CDATA. In a JSP page, tags that are undefined by the JSP specification are passed through automatically.

  • Some very common programming tokens like "<" are significant to XML; the JSP specification provides a mechanism (the <% syntax) to "pass through" these tokens.

On the other hand, the JSP specification is not gratuitously inconsistent with XML: All features have been made XML-compliant as much as possible.

The hand-authoring friendliness of JSP pages is very important for the initial adoption of the JSP technology; this is also likely to remain important in later time frames, but tool manipulation of JSP pages will take a stronger role then. In that context, there is an ever growing collection of tools and APIs that support manipulation of XML documents.

The JSP 1.1 specification addresses both requirements by providing a friendly syntax and also defining a standard XML document for a JSP page. A JSP 1.1-compliant tool need not do anything special with this document.


JSP.7.2 Document Type

JSP.7.2.1 The jsp:root Element

An XML document representing a JSP page has jsp:root as its root element type. The root is also the place where taglibs will insert their namespace attributes. The top element has an xmlns attribute that enables the use of the standard elements defined in the JSP 1.1 specification.

<jsp:root
   xmlns:jsp="http://java.sun.com/products/jsp/dtd/jsp_1_0.dtd">
           remainder of transformed JSP page
</jsp:root>

JSP.7.2.2 Public ID

The proposed document type declaration is:

<!  DOCTYPE root
   PUBLIC  "-//Sun Microsystems Inc.//DTD JavaServer Pages Version
1.1//EN"
           "http://java.sun.com/products/jsp/dtd/jspcore_1_0.dtd">


JSP.7.3 Directives

A directive in a JSP page is of the form:

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

Most directives get translated into an element of the form:

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

JSP.7.3.1 The page Directive

In the XML document corresponding to JSP pages, the page directive is represented using the syntax:

<jsp:directive.page page_directive_attr_list />

See Section JSP.2.7.1 for description of page_directive_attr_list.

Example

The directive:

<%@ page info="my latest JSP Example V1.1" %>

corresponds to the XML element:

<jsp:directive.page info="my latest JSP Example V1.1" />

JSP.7.3.2 The include Directive

In the XML document corresponding to JSP pages, the include directive is represented using the syntax:

<jsp:directive.include file="relativeURLspec" flush="true|false" />
Examples

Below are two examples, one in JSP syntax, the other using XML syntax:

<%@ include file="copyright.hmtl" %>
<jsp:directive.include file="htmldocs/logo.html" />

JSP.7.3.3 The taglib Directive

In the XML document corresponding to JSP pages, the taglib directive is represented as an xmlns: attribute within the root element of the JSP page document.


JSP.7.4 Scripting Elements

The JSP 1.1 specification has three scripting language elements—declarations, scriptlets, and expressions. The scripting elements have a "<%"-based syntax as follows:

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

JSP.7.4.1 Declarations

In the XML document corresponding to JSP pages, declarations are represented using the syntax:

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

For example, the second example from SectionJSP.2.10.1:

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

is translated using a CDATA statement to avoid having to quote the "<" inside the jsp:declaration.

<jsp:declaration> <![CDATA[ public String f(int i) { if (i<3)
return("..."); } ]]> </jsp:declaration>
DTD Fragment
<!ELEMENT jsp:declaration (#PCDATA) >

JSP.7.4.2 Scriptlets

In the XML document corresponding to JSP pages, scriplets are represented using the syntax:

<jsp:scriptlet> code fragment goes here </jsp:scriptlet>
DTD Fragment
<!ELEMENT jsp:scriptlet (#PCDATA) >

JSP.7.4.3 Expressions

In the XML document corresponding to JSP pages, expressions are represented using the syntax:

<jsp:expression> expression goes here </jsp:expression>
DTD Fragment
<!ELEMENT jsp:expression (#PCDATA) >


JSP.7.5 Actions

The syntax for action elements is based on XML; the only transformations needed are due to quoting conventions and the syntax of request-time attribute expressions.


JSP.7.6 Transforming a JSP Page into an XML Document

The standard XML document for a JSP page is defined by transformation of the JSP page.

  • Add a <jsp:root> element as the root. Enable a "jsp" namespace prefix for the standard tags within this root.

  • Convert all the <% elements into valid XML elements as described in Section JSP.7.4.1 and following sections.

  • Convert the quotation mechanisms appropriately.

  • Convert the taglib directive into namespace attributes of the <jsp:root> element.

  • Create CDATA elements for all segments of the JSP page that do not correspond to JSP elements.

A quick summary of the transformation is shown in Table JSP.7-1:

Table JSP.7-1. XML Standard Tags for Directives and Scripting Elements

JSP Page Element

XML Equivalent

<%@ page ... %>

<jsp:directive.page ... />

<%@ taglib ... %>

jsp:root element is annotated with namespace information.

<%@ include ... %>

<jsp:directive.include .../>

<%! ... %>

<jsp:declaration> .... </jsp:declaration>

<% ... %>

<jsp:scriptlet> .... </jsp:scriptlet>

<%= .... %>

<jsp:expression> .... </jsp:expression>

JSP.7.6.1 Quoting Conventions

The quoting rules for the JSP 1.1 specification are designed to be friendly for hand authoring, they are not valid XML conventions.

Quoting conventions are converted in the generation of the XML document from the JSP page. This is not yet described in this version of the specification.

JSP.7.6.2 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.7.7 DTD for the XML Document

Figure JSP.7-1 is a DTD for the current XML mapping:

Figure JSP.7-1 DTD for the XML Document
<!ENTITY % jsp.body "
(#PCDATA
|jsp:directive.page
|jsp:directive.include
|jsp:scriptlet
|jsp:declaration
|jsp:expression
|jsp:include
|jsp:forward
|jsp:useBean
|jsp:setProperty
|jsp:getProperty
|jsp:plugin
|jsp:fallback
|jsp:params
|jsp:param)*
">
<!ELEMENT jsp:useBean %jsp.body;>
<!ATTLIST jsp:useBean
id         ID       #REQUIRED
class      CDATA    #REQUIRED
scope      (page|session|request|application) "page">
<!ELEMENT jsp:setProperty EMPTY>
<!ATTLIST jsp:setProperty
name       IDREF    #REQUIRED
property   CDATA    #REQUIRED
value      CDATA    #IMPLIED
param      CDATA    #IMPLIED>
<!ELEMENT jsp:getProperty EMPTY>
<!ATTLIST jsp:getProperty
name       IREF     #REQUIRED
property   CDATA    #REQUIRED>
<!ELEMENT  jsp:includeEMPTY>
<!ATTLIST  jsp:include
flush      (true|false) "false"
page       CDATA    #REQUIRED>
<!ELEMENT jsp:forward EMPTY>
<!ATTLIST jsp:forward
page      CDATA    #REQUIRED>
<!ELEMENT jsp:scriptlet (#PCDATA)>
<!ELEMENT jsp:declaration (#PCDATA)>
<!ELEMENT jsp:expression (#PCDATA)>
<!ELEMENT jsp:directive.page EMPTY>
<!ATTLIST jsp:directive.page
languageCDATA      "java"
extendsCDATA       #IMPLIED
contentTypeCDATA   "text/html; ISO-8859-1"
import   CDATA     #IMPLIED
session  (true|false)"true"
buffer   CDATA     "8kb"
autoFlush(true|false)"true"
isThreadSafe(true|false)"true"
info     CDATA     #IMPLIED
errorPageCDATA#IMPLIED
isErrorPage (true|false) "false">
<!ELEMENT jsp:directive.include EMPTY>
<!ATTLIST jsp:directive.include
file CDATA #REQUIRED>
<!ELEMENT jsp:root %jsp.body;>
<!ATTLIST jsp:root
xmlns:jspCDATA#FIXED "http://java.sun.com/products/jsp/dtd/jsp_1_0.dtd">


Appendix JSP.A. Examples

This appendix describes some examples of custom actions defined using the tag extension mechanism. Refer to the JSP technology web site (http://java.sun.com/products/jsp) to retrieve a copy of the examples.

Each example is described briefly and the methods that are defined are explained and justified.


JSP.A.1 Simple Examples

Most tags are likely to be simple encapsulations of some functionality. The first set of examples are of this type and were already introduced in Section JSP.5.1.3; here they are described in some more detail.

JSP.A.1.1 Call Functionality, No Body

The example of Section JSP.5.1.3.1 is the simplest example:

<x:foo att1="..." att2="..." att3="..." />

In this case:

Tag Library Descriptor

Indicates there are 3 mandatory attributes that are only translation-time, and that FooTag is the handler for tag "foo."

FooTag

FooTag needs only to provide a method for doStartTag(). The method doStartTag performs the desired actions, possibly interacting with the PageContext data.

The attribute values are exposed as attributes and their values are set automatically by the JSP container.

JSP.A.1.2 Call Functionality, No Body, Define Object

The example of Section JSP.5.1.3.2 is a simple variation of the previous example:

<x:bar id="mybar" att1="..." att2="..." att3="..." />

In this case:

Tag Library Descriptor

Indicates there are 3 mandatory attributes that are only translation-time, and that BarTag is the handler for tag "bar." For the example, assume that id is optional, in which case the TLD also indicates that as being the case.

The TLD also needs to indicate that BarExtraInfo is the name of the class that will provide information on the scripting variables introduced; see below.

BarTag

BarTag needs only provide a method for doStartTag(). The method will interact with the PageContext data to register the created object with a name that is the value of the id attribute.

The attribute values are exposed as attributes and their values are set automatically by the JSP container.

BarExtraInfo

This class, to be instantiated at translation time, needs only define a getVariableInfo() method. This method will look at the TagData object it is passed and will return either null or an array of VariableInfo objects of size 1, with the value corresponding to the scripting variable with name given by the id attribute.

JSP.A.1.3 Template Mechanisms

Section JSP.5.1.3.4 refers to a family of template mechanisms that have been used in the past. All of these mechanisms take some information and replace a token in the template page by either some fixed expansion or the result of some computation.

These mechanisms can be implemented through an empty-bodied action that is mapped to Tag handler that uses the desired information to locate the wanted resource and pushes the information into the JspWriter.

JSP.A.1.4 A 0.92-like useBean

In future releases of this specification, the useBean of 0.92 will be described. Note that the implementation will not be as efficient as ideal due to the need to do some computation at request evaluation time.


JSP.A.2 A Set of SQL Tags

The following is a possible set of SQL tags. Note that this specific syntax is only used for pedagogical reasons, no endorsement is implied.

JSP.A.2.1 connection, userid, and password

The connection tag creates a connection using some userid and password information. To show tag communication, userid and password are actually subelements of connection.

<x:connection id="con01"
    ref="connection.xml">
  <x:userid><%=session.getUserid()%></x:userid>
  <x:password><%=session.getPassword()%><x:password>
</x:connection>

In this example the "con01" object is available after the element.

This example uses the runtime stack so userid and password can locate their enclosing connection tag and can update userid and password data in there. This example also uses PageContext to register the SQL connection object with the page context using "con01" so it can be retrieved later.

Tag Library Descriptor | Indicates the names of the tags and their attributes. It associates Tag handlers with the tags. It also associates the ConnectionExtraInfo as the TagExtraInfo for connection.
UserIdTag | UserIdTag needs access to its body; this it can do by defining a doAfterBody() method. This method will take the BodyContent and convert it into a String. Then it will use the findAncestorWithClass() static method on Tag to locate the enclosing connection tag instance and will set the desired userid information on that object.
PasswordTag | This Tag handler is equivalent to UserIdTag.
ConnectionTag | This Tag handler provides methods to setUserId() and to setPassword() that will be used by the enclosed actions; it also provides a getConnection() method that on-demand computes the desired SQL connection. This tag handler needs not be concerned with the body computation, but it will need to register the SQL connection object with the pageContext object if an ID is provided.
ConnectionExtraInfo | This class is identical to BarExtraInfo from a previous example.

JSP.A.2.2 Query

The connection can now be used to make a query. The query element takes the body of the tag and makes a query on it. The result gets inserted in place.

<x:query id="balances" connection="con01">
   SELECT account, balance FROM acct_table
   where customer_number = <%= request.getCustno()%>
</x:query>

The implementation highlights are:

Tag Library Descriptor | Query has two mandatory attributes (in our example), and they are described as so in the TLD. The TLD also associates QueryTag as the Tag handler class, and QueryExtraInfo as the TagExtraInfo for the query tag.
QueryTag | QueryTag needs access to its body; this it can do by defining a doAfterBody() method. This method will take the BodyContent and convert it into a String. Then it will use the PageContext object to locate an SQL connection that was registered using the id that is the value to the connection attribute. The result of the query will be registered in the PageContext with the value of the id attribute as its name.
QueryExtraInfo | This class is identical to BarExtraInfo from a previous example.

JSP.A.2.3 Iteration

Finally the query result can later be used to present the data by dynamically creating a series of <li> elements.

<ul>
<x:foreach iterate="row" in="balances">
<li>The balance for
account <%= row.getAccount()%> is <%= row.getBalance()%>
</x:foreach>
</ul>

Unlike query and connection, the foreach element does not define a new object for later use but it defines (and redefines) a "row" object that is accessible within its start and end tags.

The implementation of this tag requires the repeated evaluation of the body of the tag.

Tag Library Descriptor

foreach has two mandatory attributes (in our example), and they are described as so in the TLD. The TLD also associates ForEachTag as the Tag handler class, and ForEachExtraInfo as the TagExtraInfo for the foreach tag.

ForEachTag.doStartTag()

ForEachTag needs to define a doStartTag() method to extract the value of the in and iterate attributes from the attribute values. The value of in ("balances" in this example) is used to get at the result data. The value of iterate ("row" in this example) is used as the key on which to store the iteration value.

The current value of the "out" variable is stored away so it can be used in doBody(). This method returns EVAL_BODY so as to force the evaluation of the body.

ForEachTag.doAfterBody()

The BodyContent (obtained from getBodyContent()) contains the evaluation of the body of the element where the evaluation has been done in a context where the variable "row" is assigned the different rows of the query. This method now inserts this content into the surrounding out stream (obtained from getPreviousOut()).

This method now updates the binding of "row" and will return EVAL_BODY or SKIP_BODY depending on whether there were any more rows in the result set.

ForEachTag.doEndTag()

Just clean up.

ForEachExtraInfo()

The translation-time information indicates that this action defines a new scripting variable, with scope NESTED and name corresponding to the value of the "row" attribute.


Appendix JSP.B. Implementation Notes

This appendix provides implementation notes on the JSP technology. The notes are not normative and should only reinforce information described elsewhere. In particular, smarter but valid implementations are always welcome!


JSP.B.1 Delivering Localized Content

The definition in Section JSP.2.7.4 enables but does not mandate the following implementation strategy:

  • Translate the JSP page into a servlet class source using the character encoding of the JSP page.

  • Compile the servlet source using the -encoding switch. This produces a Servlet class file that has a number of (probably static) Unicode strings.

  • Run the servlet with the JspWriter configured to generate output in the encoding of the JSP page.


JSP.B.2 Processing taglib Directives

A strict 1-pass implementation would make custom actions visible only after their corresponding taglib directive appears. But this semantics can lead to the situation where a JSP page author is staring at a JSP page fragment with the assumption that a taglib directive appears before, when it really is included after. The semantics of Section JSP.2.7.7 are designed to support an efficient implementation while minimizing JSP page author mistakes.

An implementation can still work in a 1-pass manner; it only needs to remember all the prefixes it has found and make the assumption that taglib directives appear before their use. But, if it later discovers that a taglib directive is defining a prefix that was used previously, then it can cause a translation error.


JSP.B.3 Processing Tag Libraries

We describe some details of how to compile tag libraries and show a sketch of some code implementing a JSP page.

JSP.B.3.1 Processing a Tag Library Descriptor

The tag library descriptor is read and information is extracted from it. Some of the actions to be performed include:

  • Record the mapping from tag to tag handler class.

  • Record the tag as a known to the JSP container so a taglib directive will introduce new actions.

  • Record information on what tags must have an empty body, to be checked on individual pages later on.

  • Record what the valid attributes are and which ones can have request-time values.

  • Record the TagExtraInfo classes, if any, associated with given tags.

  • Can be used to perform reflection on the tag handler classes to determine if the class implements Tag or BodyTag.

  • Can be used to perform introspection on the tag handler classes to determine their properties and their setter methods.

JSP.B.3.2 Processing a JSP Page

When the JSP container processes a JSP page, it will perform analysis, validation, and generation of code. Actions include:

  • Validate that actions who must have an empty body do.

  • Validate that the only attributes that appear are those indicated in the TLD.

  • Validate that the only attributes with request-time values are those indicated in the TLD.

  • If there is a TagExtraInfo class associated in the TLD, a TagData object will be created with the appropriate attribute/value entries, and will be passed to the isValid method to determine if the attributes are valid.

  • If there is a TagExtraInfo class associated in the TLD, a TagData object will be created with the appropriate attribute/value entries, and will be passed to the getVariableInfo method to determine if any scripting variables will be updated by this action at request time.

JSP.B.3.3 Generating the JSP Page Implementation Class

The JSP page implementation class generated by the JSP container includes code that:

  • Generates the appropriate setter method invocations to set values for attributes.

  • Reuses tag handlers that are not being used to reduce the number of tag handler creations.

  • Assumes that a tag handler object retains its set properties to reduce the number of method invocations.

  • Attempts to do some reorganization of setter method invocation so statically determined properties are not reset on a tag handler unnecessarily.

JSP.B.3.4 An Example

We now describe a simple example.

JSP.B.3.4.1 JSP Page Example

We will use a JSP page fragment as in Figure JSP.B-1, where "chunk" is some uninterpreted template text.

Figure JSP.B-1 A JSP Page Fragment
chunk1
<x:foo id="myFoo" ...>
                 chunk2
                 <x:bar id="myBar" ...>
                                  chunk3
                 </x:bar>
                 chunk4
</x:foo>
chunk5
<x:baz ref="myFoo" .../>

For the example, we will assume the TLD and TagExtraInfo provide the information in Table JSP.B-1.

Table JSP.B-1. TagInfo for the Example

Tag

Handler

Variable Info (name, type, scope)

foo

FooTag

myFoo, FooResult, AT_END

bar

BarTag

myBar, BarResult, AT_END

baz

BazTag

none

JSP.B.3.4.2 Implementation Code Fragment

The following code fragment can be used to implement the page fragment of Figure JSP.B-1.

static {   JspFactory _fact = JspFactory.getDefaultFactory();
}
_jspService(HttpServetRequest req, HttpServletResponse res) {

           PageContext pc = _fact.getPageContext(...); // once
           Object tempObject = null;
           int tempReturn;

           // just as an example, let's initialize
           // all the Tag handlers
           FooTag footag = new FooTag();
           BarTag bartag = new BarTag()
           BazTag baztag = new BazTag();
           JspWriter out = pageContext.getOut(); // initial out
           // -- ditto for all other implicit objects

           EVAL chunk1;
 _______________________________________________
|                                               |
|  Evaluate <x:foo>...</x:foo>                  |
|_______________________________________________|

           EVAL chunk5;

           baztag.setPageContext(pc);
           baztag.setParent(null);
           baztag.setRef("myFoo");
           try {
               (void)baztag.doStartTag();
               tempReturn = baztag.doEndTag();
           } finally {
               baztag.release();
           }
           if (tempReturn == SKIP_PAGE) {
               goto endOfPage; // pseudo-code
           };
endOfPage:
}

where the evaluation of <foo>...</foo> is:

footag.setPageContext(pc);
footag.setParent(null);
footag.setId("myFoo");
try {
           if (footag.doStartTag() == EVAL_BODY_TAG) {
               try {
                   out = pc.pushBody();
                   foobag.setBodyContent(out);
                   footag.doInitBody();

               repeat2:

                   EVAL chunk2;
             _______________________________________________
            |                                               |
            |    Evaluate <x:foo>...</x:foo>                |
            |_______________________________________________|

                   EVAL chunk4;
                   if (footag.doAfterBody() == EVAL_BODY_TAG) {
                       goto repeat2; // pseudo-code
                   }
               } finally {
                   out = pc.popBody();
               }
           }
           tempResult = footag.doEndTag();
           tempObject = pc.getAttribute("myFoo");
} finally {
           footag.release();
}
FooResult myFoo = (FooResult) tempObject;
if (tempResult == SKIP_PAGE) {
           goto endOfPage; // pseudo-code
}

and the evaluation of <bar>...</bar> is essentially the same:

bartag.setPageContext(pc);
bartag.setParent(footag);
bartag.setId("myBar");

try {
           if (bartag.doStartTag() == EVAL_BODY_TAG) {
               try {
                   out = pc.pushBody();
                   bartag.setBodyContent(out);
                   bartag.doInitBody();

               repeat3:

                   EVAL chunk3;
                   if (bartag.doAfterBody() == EVAL_BODY_TAG) {
                       goto repeat3; // pseudo-code
                   }
               } finally {
                   out = pc.popBody();
               }
           }
           tempResult = bartag.doEndTag();
           tempObject = pc.getAttribute("myBar");
} finally {
           bartag.release();
}
BarResult myBar = (BarResult) tempObject;
if (tempResult == SKIP_PAGE) {
           goto endOfPage; // pseudo-code
}


JSP.B.4 Implementing Buffering

Although the Servlet 2.2 specification provides for buffering, its semantics are autoflush=true. Buffering could be done without using the Servlet buffered stream, but this implementation does not allow for forwarding into a page that is not a JSP page. This is problematic for the implementation of jsp:include actions (see Section JSP.2.13.4) since the goal is for jsp:include to be totally transparent to how the data is computed dynamically. Due to this, the only semantics we can use at this point still remains "flush on include" as it was in the JSP 1.0 specification.


Appendix JSP.C. 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 delivered 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.2 and JSP 1.1 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 than to the Servlet 2.2 capabilities to the JSP 1.1 capabilities. The appendix is included here as this is a feature that JSP page authors and JSP page authoring tools are interested in.


JSP.C.1 A 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.C.2 The 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:

<!DOCTYPE webapp
   SYSTEM "http://java.sun.com/j2ee/dtds/web-app_1_2.dtd">
<webapp>
   <session-config>
           <session-timeout> 1 </session-timeout>
   </session-config>
</webapp>


JSP.C.3 The 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 depends only on the JSP 1.1 and Servlet 2.2 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
   {
            Object   page = this;
            HttpSessionsession= request.getSession();
            ServletConfigconfig= getServletConfig();
            ServletContextapplication = config.getServletContext();

            PageContextpageContext
                = _factory.getPageContext(this,
                             request,
                             response,
                             (String)NULL,
                             true,
                             JspWriter.DEFAULT_BUFFER,
                             true
                             );
            JspWriter out = 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.C.4 The Web Application Descriptor

The servlet is made to look as a JSP page with the following web.xml:

<!DOCTYPE webapp
   SYSTEM "http://java.sun.com/j2ee/dtds/web-app_1_2.dtd">
<webapp>
   <servlet>
           <servlet-name> HelloWorld </servlet-name>
           <servlet-class> HelloWorld.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.C.5 The WAR for the Compiled JSP Page

Finally, everything is packaged together into a WAR:

/WEB-INF/web.xml
/WEB-INF/classes/HelloWorld.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.


Appendix JSP.D. Future

This appendix provides some information on future directions of the JSP technology.


JSP.D.1 Meta-Tag Information

A tag extension mechanism can include information:

  • To execute a JSP page that uses the tag library.

  • To edit a JSP page.

  • To present the JSP page to the end user.

The JSP 1.1 specification concentrates on the first type of information providing some small amount of the other type of information; future specifications may address the other pieces.


JSP.D.2 Standard Tags

The tag extension mechanism enables the creation of tag libraries; some application domains have widespread applicability and there is substantial interest in defining standard tags for these domains.


JSP.D.3 Additional Application Support

We are investigating the benefits and costs of adding additional support for applications into the JSP specification.


JSP.D.4 JSP, XML, and XSL Technologies

The JSP 1.0 and JSP 1.1 specification started in the direction of XML representations of JSP pages. At the time of the design of the JSP 1.0 and JSP 1.1 specifications the Java platform was lacking in APIs for the manipulation of XML documents; this deficiency is being corrected and we expect to exploit the interaction of XML and JSP technologies more fully in future specifications.


Appendix JSP.E. Changes

This appendix lists the changes in the JavaServer Pages specification.


JSP.E.1 Changes Between 1.1 PR2 and 1.1 Final

JSP.E.1.1 Changes

  • Updated the license.

  • Consistent use of the JSP page, JSP container, and similar terms. Some other minor editorial changes.

  • Clarified the return values of the methods in the TagSupport and BodyTagSupport classes.

  • Normalized the throws clause in the methods in Tag, BodyTag, TagSupport, and BodyTagSupport. These methods now throw JspException.

  • Added a missing throws IOException to the writeOut() method in BodyContent.

  • Renamed JspError to JspTagException.

  • The getTagId() and setTagId() methods in TagSupport were renamed to getId() and setId() to be consistent with the switch to properties.

  • Spelled out some consequences of (the unchanged) specification that flush() on BodyContent raises an exception.

  • Clarified the interpretation of the uri attribute in the taglib directive.


JSP.E.2 Changes Between 1.1 PR1 and PR2

JSP.E.2.1 Additions

  • Added a glossary.

  • Normalized use of container and component terminology; including changing the name of Chapter JSP.3.

  • Described the relationship of this specification to the servlet and J2EE specifications.

  • Expanded on some of the organizational models in Chapter JSP.1 so as to cover 0.92's "model 1" and "model 2."

  • Expanded Section JSP.2.7.2 to summarize the implications of threading and distribution from the servlet specification and to define the notion of a distributable JSP page.

  • Added a description of how to package a JSP page within a WAR; changed the title of Appendix JSP.C to reflect the new material.

JSP.E.2.2 Changes

  • A tag handler is now a JavaBean component; attributes are properties that have been explicitly marked as attributes in the TLD.

  • The type subelement of attribute in the TLD is now defined by the type of the corresponding JavaBean component property, and has been removed from the TLD.

  • Clarified implicit import list in Section JSP.2.7.1. Clarified details on Section JSP.2.12.1, Section JSP.2.13.6 and Section JSP.3.4.2.

  • The names of the DTDs have changed to reflect that the JSP and servlet specifications have a separate release vehicle to J2EE. The new names are web-jsptaglibrary_1_1.dtd and web-app_2_2.dtd.

  • Decomposed the Tag abstract class into two interfaces and two support classes.

  • Adjusted the semantics of the uri attribute in taglib, and the mechanism by which a tag library descriptor is located.

  • Normalized the terminology on the tag extension mechanism.

  • Indicated that a "compiled" JSP page should be packaged with any support classes it may use.

  • BodyJspWriter is now BodyContent to clarify its meaning; this is similar to the PD name. The name BodyJspWriter was confusing some readers.

  • Corrected implementation examples to show how a JSP page implementation class invokes getDefaultFactory only statically.

  • Reorganized the material in Section JSP.B.3 for accuracy and presentation.


JSP.E.3 Changes Between 1.1 PD1 and PR1

JSP.E.3.1 Additions

  • Added a tag library descriptor (TLD) file.

  • Added parameters to jsp:include and jsp:forward.

  • Added JspException and JspError classes.

  • Added a parent field to the Tag class to provide a runtime stack.

  • Added pushBody() and popBody() to PageContext.

  • Added appendix with an example of compiling a simple JSP page into a servlet that is delivered within a WAR.

  • Upgraded the javadoc documentation.

  • Upgraded all the examples.

  • Added a precompilation protocol.

  • Reserved all request parameters starting with "jsp."

JSP.E.3.2 Changes

  • Most Info classes are not to be subclassed; instead their information is now derived completely from the TLD file; TagExtraInfo is the exception.

  • BodyEvaluation is now called BodyJspWriter and it is a subclass of JspWriter.

  • Tag is now an abstract class; TagSupport has been removed. NodeData is now called TagData.

  • Split doBody() into doBeforeBody() and doAfterBody() to simplify programming.

  • The semantics of the nested JspWriter have changed: now there is only at most one BodyJspWriter per invocation of the action, regardless of how many times the body is evaluated.

  • Return type of doStartTag() is now an int for better documentation and ease of extensibility.

  • Added initialize() and release() methods to Tag class; clarified life-cycle requirements.

  • Substantial cleanup of presentation; revisions to many classes.

JSP.E.3.3 Deletions

  • Removed the ChildrenMap mechanism.

  • Removed the flush="false" option in jsp:include as it cannot be implemented on Servlet 2.2.

  • Removed the proposal for a standard servlet tag for now. Will probably be available in a "utils" tag library.


JSP.E.4 Changes Between 1.0 and 1.1 PD1

The JSP 1.1 specification builds on the JSP 1.0 specification.

JSP.E.4.1 Additions

  • Enabled the compilation of JSP pages into Servlet classes that can be transported from one JSP container to another.

  • Added a portable tag extension mechanism.

  • Flush is now an optional attribute of jsp:include, and a false value is valid and the default.

JSP.E.4.2 Changes

  • Use Servlet 2.2 instead of Servlet 2.1 (as clarified in Appendix JSP.B); Servlet 2.2 is still being finalized, but the specification is intended to be upward compatible.

  • jsp:plugin no longer can be implemented by just sending the contents of jsp:fallback to the client.

JSP.E.4.3 Removals

  • None so far.


Enterprise JavaBeans™ Specification, v1.1 (EJB)

    Chapter EJB.1. Introduction

    Chapter EJB.2. Goals

    Chapter EJB.3. EJB Architecture Roles and Scenarios

    Chapter EJB.4. Overview

    Chapter EJB.5. Client View of a Session Bean

    Chapter EJB.6. Session Bean Component Contract

    Chapter EJB.7. Example Session Scenario

    Chapter EJB.8. Client View of an Entity

    Chapter EJB.9. Entity Bean Component Contract

    Chapter EJB.10. Example Entity Scenario

    Chapter EJB.11. Support for Transactions

    Chapter EJB.12. Exception Handling

    Chapter EJB.13. Support for Distribution

    Chapter EJB.14. Enterprise Bean Environment

    Chapter EJB.15. Security Management

    Chapter EJB.16. Deployment Descriptor

    Chapter EJB.17. EJB JAR File

    Chapter EJB.18. Runtime Environment

    Chapter EJB.19. Responsibilities of EJB Architecture Roles

    Chapter EJB.20. Enterprise JavaBeans™ API Reference

    Chapter EJB.21. Related Documents

    Appendix EJB.A. Features Deferred to Future Releases

    Appendix EJB.B. Frequently Asked Questions

    Appendix EJB.C. Revision History


Chapter EJB.1. Introduction

This is the specification of the Enterprise JavaBeans™ architecture. The Enterprise JavaBeans architecture is a component architecture for the development and deployment of component-based distributed business applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and multi-user secure. These applications may be written once, and then deployed on any server platform that supports the Enterprise JavaBeans specification.


EJB.1.1 Target Audience

The target audiences for this specification are the vendors of transaction processing platforms, vendors of enterprise application tools, and other vendors who want to support the Enterprise JavaBeans™ (EJB) technology in their products.

Many concepts described in this document are system-level issues that are transparent to the Enterprise JavaBeans application programmer.


EJB.1.2 What Is New in EJB 1.1

We have tightened the entity bean specification, and made support for entity beans mandatory for container providers.

The other changes in the EJB 1.1 specification were made to improve the support for the development, application assembly, and deployment of ISV-produced enterprise beans. The specification includes the following primary changes:

  • Enhanced support for the enterprise bean's environment. The bean provider must specify all the bean's environmental dependencies using entries in a JNDI naming context.

  • Added support for application assembly in the deployment descriptor.

  • Clearly separated the responsibilities of the bean provider and application assembler.

  • Removed the EJB 1.0 deployment descriptor features that describe the deployer's output. the role of the deployment descriptor is to describe the information that is the input to the deployer, not the deployer's output.

The changes affected mainly Chapters EJB.11, EJB.14, EJB.15, and EJB.16. We minimized the impact on the server vendors who implemented support for EJB 1.0 in their runtime. The only change to the runtime API of the EJB container is the replacement of the java.security.Identity class with the java.security.Principal interface, necessitated by changes in JDK 1.2.

We have also added a number of clarifications and corrections to the specification based on the input that we have received from the reviewers.


EJB.1.3 Application Compatibility and Interoperability

EJB 1.1 attempts to provide a high degree of application compatibility for enterprise beans that were written for the EJB 1.0 specification. Principally, the deployment descriptor of EJB 1.0 based enterprise beans must be converted to the EJB 1.1 XML format. However, the EJB 1.0 enterprise bean code does not have to be changed or re-compiled to run in an EJB 1.1 container, except in the following situations:

  • The bean uses the javax.jts.UserTransaction interface. The package name of the javax.jts interface has changed to javax.transaction, and there have been minor changes to the exceptions thrown by the methods of this interface. An enterprise bean that uses the javax.jts.

    UserTransaction interface needs to be modified to use the new name javax.transaction.UserTransaction.

  • The bean uses the getCallerIdentity() or isCallerInRole(Identity identity) methods of the javax.ejb.EJBContext interface. These methods were deprecated in EJB 1.1 because the class java.security.

    Identity is deprecated in Java 2 platform. While a container provider may choose to provide a backward compatible implementation of these two methods, the container provider is not required to do so. An enterprise bean written to the EJB 1.0 specification needs to be modified to use the new methods to work in all EJB 1.1. containers.

  • The bean is an entity bean with container-managed persistence. The required return value of ejbCreate(...) is different in EJB 1.1 than in EJB 1.0. An enterprise bean with container-managed persistence written to the EJB 1.0 specification needs to be recompiled to work with all EJB 1.1 compliant containers.

  • The bean is an entity bean whose finders do not define the FinderException in the methods' throws clauses. EJB 1.1 requires that all finders define the FinderException.

  • The bean is an entity bean that uses the UserTransaction interface. In EJB 1.1, an entity bean must not use the UserTransaction interface.

  • The bean uses the UserTransaction interface and implements the SessionSynchronization interface at the same time. This is disallowed in EJB 1.1.

  • The bean violates any of the additional semantic restrictions defined in EJB 1.1 but which were not defined in EJB 1.0.

The client view of an enterprise bean is the same in EJB 1.0 and EJB 1.1. This means that enterprise beans written to EJB 1.1 can seamlessly interoperate with those written to EJB 1.0, and vice versa.


EJB.1.4 Acknowledgments

Rick Cattell, Linda DeMichiel, Shel Finkelstein, Graham Hamilton, Li Gong, Rohit Garg, Susan Cheung, Hans Hrasna, Sanjeev Krishnan, Kevin Osborn, Bill Shannon, Anil Vijendran, and Larry Cable have provided invaluable input to the design of Enterprise JavaBeans architecture.

The Enterprise JavaBeans architecture is a broad effort that includes contributions from numerous groups at Sun and at partner companies. The ongoing specification review process has been extremely valuable, and the many comments that we have received helped us to define the specification.

We would also like to thank all the reviewers who sent us feedback during the public review period. Their input helped us to improve the specification.


EJB.1.5 Organization

Chapter EJB.2, "Goals," discusses the advantages of Enterprise JavaBeans architecture.

Chapter EJB.3, "Roles and Scenarios," discusses the responsibilities of the bean provider, application assembler, deployer, ejb container and server providers, and system administrators with respect to the Enterprise JavaBeans architecture.

Chapter EJB.4, "Fundamentals," defines the scope of the Enterprise JavaBeans specification.

Chapters EJB.5 through EJB.7 define session beans: Chapter EJB.5 discusses the client view, Chapter EJB.6 presents the session bean component contract, and Chapter EJB.7 outlines an example session bean scenario.

Chapters EJB.8 through EJB.10 define entity beans: Chapter EJB.8 discusses the client view, Chapter EJB.9 presents the entity bean component contract, and Chapter EJB.10 outlines an example entity bean scenario.

Chapters EJB.11 through EJB.15 discuss transactions, exceptions, distribution, environment, and security.

Chapters EJB.16 and EJB.17 describe the format of the EJB JAR file and its deployment descriptor.

Chapter EJB.18 defines the runtime APIs that a compliant EJB container must provide to the enterprise bean instances at runtime. The chapter also specifies the programming restrictions for portable enterprise beans.

Chapter EJB.19 summarizes the responsibilities of the individual EJB roles.

Chapter EJB.20 is the Enterprise JavaBeans API Reference.

Chapter EJB.21 provides a list of related documents.


EJB.1.6 Document Conventions

The regular Times font is used for information that is prescriptive by the EJB specification and for paragraphs that contain descriptive information, such as notes describing typical use, or notes clarifying the text with prescriptive specification.

The Lucida Sans font is used for code examples.


Chapter EJB.2. Goals

    Section EJB.2.1. Overall Goals

    Section EJB.2.2. Goals for Release 1.0

    Section EJB.2.3. Goals for Release 1.1


EJB.2.1 Overall Goals

We have set the following goals for the Enterprise JavaBeans (EJB) architecture:

  • The Enterprise JavaBeans architecture will be the standard component architecture for building distributed object-oriented business applications in the Java™ programming language. The Enterprise JavaBeans architecture will make it possible to build distributed applications by combining components developed using tools from different vendors.

  • The Enterprise JavaBeans architecture will make it easy to write applications: Application developers will not have to understand low-level transaction and state management details, multi-threading, connection pooling, and other complex low-level APIs.

  • Enterprise JavaBeans applications will follow the "Write Once, Run Anywhere™" philosophy of the Java programming language. An enterprise bean can be developed once, and then deployed on multiple platforms without recompilation or source code modification.

  • The Enterprise JavaBeans architecture will address the development, deployment, and runtime aspects of an enterprise application's life cycle.

  • The Enterprise JavaBeans architecture will define the contracts that enable tools from multiple vendors to develop and deploy components that can interoperate at runtime.

  • The Enterprise JavaBeans architecture will be compatible with existing server platforms. Vendors will be able to extend their existing products to support Enterprise JavaBeans.

  • The Enterprise JavaBeans architecture will be compatible with other Java programming language APIs.

  • The Enterprise JavaBeans architecture will provide interoperability between enterprise beans and non-Java programming language applications.

  • The Enterprise JavaBeans architecture will be compatible with the CORBA protocols.


EJB.2.2 Goals for Release 1.0

In Release 1.0, we focused on the following:

  • Defined the distinct "EJB Roles" that are assumed by the component architecture.

  • Defined the client view of enterprise beans.

  • Defined the enterprise bean developer's view.

  • Defined the responsibilities of an EJB container provider and server provider; together these make up a system that supports the deployment and execution of enterprise beans.

  • Defined the format of the EJB JAR file, EJB's unit of deployment.


EJB.2.3 Goals for Release 1.1

In the EJB 1.1 Release, we focus on the following aspects:

  • Provide better support for application assembly and deployment.

  • Specify in greater detail the responsibilities of the individual EJB roles.


Chapter EJB.3. EJB Architecture Roles and Scenarios

    Section EJB.3.1. EJB Architecture Roles

    Section EJB.3.2. Scenario: Development, Assembly, and Deployment


EJB.3.1 EJB Architecture Roles

The Enterprise JavaBeans architecture defines six distinct roles in the application development and deployment life cycle. Each EJB role may be performed by a different party. The EJB architecture specifies the contracts that ensure that the product of each EJB role is compatible with the product of the other EJB architecture roles. The EJB specification focuses on those contracts that are required to support the development and deployment of ISV-written enterprise beans.

Note

In some scenarios, a single party may perform several EJB architecture roles. For example, the container provider and the EJB server provider may be the same vendor. Or a single programmer may perform the two EJB architecture roles of the enterprise bean provider and the application assembler.

The following sections define the six EJB architecture roles.

EJB.3.1.1 Enterprise Bean Provider

The enterprise bean provider (bean provider for short) is the producer of enterprise beans. His or her output is an EJB JAR file that contains one or more enterprise beans. The bean provider is responsible for the Java classes that implement the enterprise bean's business methods, the definition of the bean's remote and home interfaces, and the bean's deployment descriptor. The deployment descriptor includes the structural information (e.g., the name of the enterprise bean class) of the enterprise bean and declares all the enterprise bean's external dependencies (e.g., the names and types of the resource managers that the enterprise bean uses).

The enterprise bean provider is typically an application domain expert. The bean provider develops reusable enterprise beans that typically implement business tasks or business entities.

The bean provider is not required to be an expert at system-level programming. Therefore, the bean provider usually does not program transactions, concurrency, security, distribution, or other services into the enterprise beans. The bean provider relies on the EJB container for these services.

A bean provider of multiple enterprise beans often performs the EJB architecture role of the application assembler.

EJB.3.1.2 Application Assembler

The application assembler combines enterprise beans into larger deployable application units. The input to the application assembler is one or more EJB JAR files produced by the bean provider(s). The application assembler outputs one or more EJB JAR files that contain the enterprise beans along with their application assembly instructions. The application assembler has inserted the application assembly instruction into the deployment descriptors.

The application assembler can also combine enterprise beans with other types of application components (e.g., Java ServerPages™) when composing an application.

The EJB specification describes the case in which the application assembly step occurs before the deployment of the enterprise beans. However, the EJB architecture does not preclude the case that application assembly is performed after the deployment of all or some of the enterprise beans.

The application assembler is a domain expert who composes applications that use enterprise beans. The application assembler works with the enterprise bean's deployment descriptor and the enterprise bean's client-view contract. Although the assembler must be familiar with the functionality provided by the enterprise beans' remote and home interfaces, he or she does not need to have any knowledge of the enterprise beans' implementation.

EJB.3.1.3 Deployer

The deployer takes one or more EJB JAR files produced by a bean provider or application assembler and deploys the enterprise beans contained in the EJB JAR files in a specific operational environment. The operational environment includes a specific EJB server and container.

The deployer must resolve all the external dependencies declared by the bean provider (e.g., the deployer must ensure that all resource manager connection factories used by the enterprise beans are present in the operational environment, and he or she must bind them to the resource manager connection factory references declared in the deployment descriptor), and must follow the application assembly instructions defined by the application assembler. To perform his role, the deployer uses tools provided by the EJB container provider.

The deployer's output is enterprise beans (or an assembled application that includes enterprise beans) that have been customized for the target operational environment, and that are deployed in a specific EJB container.

The deployer is an expert at a specific operational environment and is responsible for the deployment of enterprise beans. For example, the deployer is responsible for mapping the security roles defined by the application assembler to the user groups and accounts that exist in the operational environment in which the enterprise beans are deployed.

The deployer uses tools supplied by the EJB container provider to perform the deployment tasks. The deployment process is typically two-stage:

  • The deployer first generates the additional classes and interfaces that enable the container to manage the enterprise beans at runtime. These classes are container-specific.

  • The deployer performs the actual installation of the enterprise beans and the additional classes and interfaces into the EJB container.

In some cases, a qualified deployer may customize the business logic of the enterprise beans at their deployment. Such a deployer would typically use the container tools to write relatively simple application code that wraps the enterprise bean's business methods.

EJB.3.1.4 EJB Server Provider

The EJB server provider is a specialist in the area of distributed transaction management, distributed objects, and other lower-level system-level services. A typical EJB server provider is an OS vendor, middleware vendor, or database vendor.

The current EJB architecture assumes that the EJB server provider and the EJB container provider roles are the same vendor. Therefore, it does not define any interface requirements for the EJB server provider.

EJB.3.1.5 EJB Container Provider

The EJB container provider (container provider for short) provides

  • The deployment tools necessary for the deployment of enterprise beans.

  • The runtime support for the deployed enterprise beans' instances.

From the perspective of the enterprise beans, the container is a part of the target operational environment. The container runtime provides the deployed enterprise beans with transaction and security management, network distribution of clients, scalable management of resources, and other services that are generally required as part of a manageable server platform.

The "EJB container provider's responsibilities" defined by the EJB architecture are meant to be requirements for the implementation of the EJB container and server. Since the EJB specification does not architect the interface between the EJB container and server, it is left up to the vendor how to split the implementation of the required functionality between the EJB container and server.

The expertise of the container provider is system-level programming, possibly combined with some application-domain expertise. The focus of a container provider is on the development of a scalable, secure, transaction-enabled container that is integrated with an EJB server. The container provider insulates the enterprise bean from the specifics of an underlying EJB server by providing a simple, standard API between the enterprise bean and the container. This API is the Enterprise JavaBeans component contract.

For entity beans with container-managed persistence, the entity container is responsible for persistence of the entity beans installed in the container. The container provider's tools are used to generate code that moves data between the enterprise bean's instance variables and a database or an existing application.

The container provider typically provides support for versioning the installed enterprise bean components. For example, the container provider may allow enterprise bean classes to be upgraded without invalidating existing clients or losing existing enterprise bean objects.

The container provider typically provides tools that allow the system administrator to monitor and manage the container and the beans running in the container at runtime.

EJB.3.1.6 System Administrator

The system administrator is responsible for the configuration and administration of the enterprise's computing and networking infrastructure that includes the EJB server and container. The system administrator is also responsible for overseeing the well-being of the deployed enterprise beans applications at runtime.

The EJB architecture does not define the contracts for system management and administration. The system administrator typically uses runtime monitoring and management tools provided by the EJB server and container providers to accomplish these tasks.


EJB.3.2 Scenario: Development, Assembly, and Deployment

Aardvark Inc. specializes in application integration. Aardvark developed the AardvarkPayroll enterprise bean, which is a generic payroll access component that allows Java technology-enabled applications to access the payroll modules of the leading ERP systems. Aardvark packages the AardvarkPayroll enterprise bean in a standard EJB JAR file and markets it as a customizable enterprise bean to application developers. In the terms of the EJB architecture, Aardvark is the bean provider of the AardvarkPayroll bean.

Wombat Inc. is a web-application development company. Wombat developed an employee self-service application. The application allows a target enterprise's employees to access and update employee record information. The application includes the EmployeeService, EmployeeServiceAdmin, and EmployeeRecord enterprise beans. The EmployeeRecord bean is a container-managed entity that allows deployment-time integration with an enterprise's existing human resource applications. In terms of the EJB architecture, Wombat is the bean provider of the EmployeeService, EmployeeServiceAdmin, and EmployeeRecord enterprise beans.

In addition to providing access to employee records, Wombat would like to provide employee access to the enterprise's payroll and pension plan systems. To provide payroll access, Wombat licenses the AardvarkPayroll enterprise bean from Aardvark, and includes it as part of the Wombat application. Because there is no available generic enterprise bean for pension plan access, Wombat decides that a suitable pension plan enterprise bean will have to be developed at deployment time. The pension plan bean will implement the necessary application integration logic, and it is likely that the pension plan bean will be specific to each Wombat customer.

In order to provide a complete solution, Wombat also develops the necessary non-EJB components of the employee self-service application, such as the Java ServerPages (JSP) that invoke the enterprise beans and generate the HTML presentation to the clients. Both the JSP pages and enterprise beans are custom-izable at deployment time because they are intended to be sold to a number of target enterprises that are Wombat customers.

The Wombat application is packaged as a collection of JAR files. A single EJB JAR file contains all the enterprise beans developed by Wombat and also the AardvarkPayroll enterprise bean developed by Aardvark; the other JAR files contain the non-EJB application components, such as the JSP components. The EJB JAR file contains the application assembly instructions describing how the enterprise beans are composed into an application. In terms of the EJB architecture, Wombat performs the role of the application assembler.

Acme Corporation is a server software vendor. Acme developed an EJB server and container. In terms of the EJB architecture, Acme performs the EJB container provider and EJB server provider roles.

The ABC Enterprise wants to enable its employees to access and update employee records, payroll information, and pension plan information over the Web. The information is stored in ABC's ERP system. ABC buys the employee self-service application from Wombat. To host the application, ABC buys the EJB container and server from Acme. ABC's Information Technology (IT) department, with the help of Wombat's consulting services, deploys the Wombat self-service application. In terms of the EJB architecture, ABC's IT department and Wombat consulting services perform the deployer role. ABC's IT department also develops the ABCPensionPlan enterprise bean that provides the Wombat application with access to ABC's existing pension plan application.

ABC's IT staff is responsible for configuring the Acme product and integrating it with ABC's existing network infrastructure. The IT staff is responsible for the following tasks: security administration, such as adding and removing employee accounts; adding employees to user groups such as the payroll department; and mapping principals from digital certificates that identify employees on VPN connections from home computers to the Kerberos user accounts that are used on ABC's intranet. ABC's IT staff also monitors the well-being of the Wombat application at runtime, and is responsible for servicing any error conditions raised by the application. In terms of the EJB architecture, ABC's IT staff performs the role of the system administrator.

Figure EJB.3-1 illustrates the products of the various EJB architecture roles.

Figure EJB.3-1. Development, Assembly, and Deployment Scenarios

Table EJB.3-1 summarizes the EJB architecture roles of the organizations involved in the scenario.

Table EJB.3-1. EJB Architecture Roles in the Example Scenarios

Organization

EJB Architecture Roles

Aardvark Inc.

Bean provider

Wombat Inc.

Bean provider

Application assembler

Acme Corporation

EJB container provider

EJB server provider

ABC Enterprise's IT staff

Deployer

Bean provider (of ABCPensionPlan)

System administrator


Chapter EJB.4. Overview

This chapter provides an overview of the Enterprise JavaBeans specification.


EJB.4.1 Enterprise Beans as Components

The Enterprise JavaBeans architecture is an architecture for component-based distributed computing. Enterprise beans are components of distributed transaction-oriented enterprise applications.

EJB.4.1.1 Component Characteristics

The essential characteristics of an enterprise bean are:

  • An enterprise bean typically contains business logic that operates on the enterprise's data.

  • An enterprise bean's instances are created and managed at runtime by a container.

  • An enterprise bean can be customized at deployment time by editing its environment entries.

  • Various services information, such as a transaction and security attributes, are separate from the enterprise bean class. This allows the services information to be managed by tools during application assembly and deployment.

  • Client access is mediated by the container in which the enterprise bean is deployed.

  • If an enterprise bean uses only the services defined by the EJB specification, the enterprise bean can be deployed in any compliant EJB container. Specialized containers can provide additional services beyond those defined by the EJB specification. An enterprise bean that depends on such a service can be deployed only in a container that supports that service.

  • An enterprise bean can be included in an assembled application without requiring source code changes or recompilation of the enterprise bean.

  • The bean provider defines a client view of an enterprise bean. The bean provider can manually define the client view or it can be generated automatically by application development tools. The client view is unaffected by the container and server in which the bean is deployed. This ensures that both the beans and their clients can be deployed in multiple execution environments without changes or recompilation.

EJB.4.1.2 Flexible Component Model

The enterprise bean architecture is flexible enough to implement components such as the following:

  • An object that represents a stateless service.

  • An object that represents a conversational session with a particular client. Such session objects automatically maintain their conversational state across multiple client-invoked methods.

  • An entity object that represents a business object that can be shared among multiple clients.

Enterprise beans are intended to be relatively coarse-grained business objects (e.g., purchase order, employee record). Fine-grained objects (e.g., line item on a purchase order, employee's address) should not be modeled as enterprise bean components.

While the state management protocol defined by the Enterprise JavaBeans architecture is simple, it provides an enterprise bean developer great flexibility in managing a bean's state.

A client always uses the same API for object creation, lookup, method invocation, and removal, regardless of how an enterprise bean is implemented or what function it provides to the client.


EJB.4.2 Enterprise JavaBeans Architecture Contracts

This section provides an overview of the Enterprise JavaBeans architecture contracts. The contracts are described in detail in the following chapters of this document.

EJB.4.2.1 Client-View Contract

This is a contract between a client and a container. The client-view contract provides a uniform development model for applications using enterprise beans as components. This uniform model enables the use of higher level development tools and allows greater reuse of components.

The enterprise bean client view is remotable—both local and remote programs can access an enterprise bean using the same view of the enterprise bean.

A client of an enterprise bean can be another enterprise bean deployed in the same or different container. Or it can be an arbitrary Java technology-enabled program, such as an application, applet, or servlet. The client view of an enterprise bean can also be mapped to non-Java client environments, such as CORBA clients that are not written in the Java programming language.

The enterprise bean provider and the container provider cooperate to create the enterprise bean's client view. The client view includes:

  • Home interface

  • Remote interface

  • Object identity

  • Metadata interface

  • Handle

The enterprise bean's home interface defines the methods for the client to create, remove, and find EJB objects of the same type (i.e., they are implemented by the same enterprise bean). The home interface is specified by the bean provider; the container creates a class that implements the home interface. The home interface extends the javax.ejb.EJBHome interface.

A client can locate an enterprise bean home interface through the standard Java Naming and Directory Interface™ (JNDI) API.

An EJB object is accessible via the enterprise bean's remote interface. The remote interface defines the business methods callable by the client. The remote interface is specified by the bean provider; the container creates a class that implements the remote interface. The remote interface extends the javax.ejb.

EJBObject interface. The javax.ejb.EJBObject interface defines the operations that allow the client to access the EJB object's identity and create a persistent handle for the EJB object.

Each EJB object lives in a home, and has a unique identity within its home. For session beans, the container is responsible for generating a new unique identifier for each session object. The identifier is not exposed to the client. However, a client may test if two object references refer to the same session object. For entity beans, the bean provider is responsible for supplying a primary key at entity object creation time; [1] the container uses the primary key to identify the entity object within its home. A client may obtain an entity object's primary key via the javax.ejb.EJBObject interface. The client may also test if two object references refer to the same entity object.

[1] In special situations, the primary key type can be specified at deployment time (see subsection EJB.9.4.7.3).

A client may also obtain the enterprise bean's metadata interface. The metadata interface is typically used by clients who need to perform dynamic invocation of the enterprise bean. (Dynamic invocation is needed if the classes that provide the enterprise client view were not available at the time the client program was compiled.)

EJB.4.2.2 Component Contract

This subsection describes the contract between an enterprise bean and its container. The main requirements of the contract follow. (This is only a partial list of requirements defined by the specification.)

  • The requirement for the bean provider to implement the business methods in the enterprise bean class. The requirement for the container provider to delegate the client method invocation to these methods.

  • The requirement for the bean provider to implement the ejbCreate, ejbPostCreate, and ejbRemove methods, and to implement the ejbFind<METHOD> methods if the bean is an entity with bean-managed persistence. The requirement for the container provider to invoke these methods during an EJB object creation, removal, and lookup.

  • The requirement for the bean provider to define the enterprise bean's home and remote interfaces. The requirement for the container provider to provide classes that implement these interfaces.

  • For sessions, the requirement for the bean provider to implement the container callbacks defined in the javax.ejb.SessionBean interface, and optionally the javax.ejb.SessionSynchronization interfaces. The requirement for the container to invoke these callbacks at the appropriate times.

  • For entities, the requirement for the bean provider to implement the container callbacks defined in the javax.ejb.EntityBean interface. The requirement for the container to invoke these callbacks at the appropriate times.

  • The requirement for the container provider to implement persistence for entity beans with container-managed persistence.

  • The requirement for the container provider to provide the javax.ejb.SessionContext interface to session bean instances, and the javax.ejb.EntityContext interface to entity bean instances. The context interface allows the instance to obtain information from the container.

  • The requirement for the container to provide to the bean instances the JNDI API context that contains the enterprise bean's environment.

  • The requirement for the container to manage transactions, security, and exceptions on behalf of the enterprise bean instances.

  • The requirement for the bean provider to avoid programming practices that would interfere with the container's runtime management of the enterprise bean instances.

EJB.4.2.3 EJB JAR File

An EJB JAR file is a standard format used by EJB tools for packaging enterprise beans with their declarative information. The EJB JAR file is intended to be processed by application assembly and deployment tools.

The EJB JAR file is a contract used both between the bean provider and the application assembler, and between the application assembler and the deployer.

The EJB JAR file includes:

  • Java class files for the enterprise beans and their remote and home interfaces.

  • An XML deployment descriptor. The deployment descriptor provides both the structural and application assembly information about the enterprise beans in the EJB JAR file. The application assembly information is optional. (Typically, only EJB JAR files with assembled applications include this information.)

EJB.4.2.4 Contracts Summary

Figure EJB.4-1 illustrates the Enterprise JavaBeans contracts.

Figure EJB.4-1. Enterprise JavaBeans Architecture Contracts

Note that while the figure illustrates only a remote client running outside the container, the client-view API is also applicable to clients that are enterprise beans deployed in the same container.


EJB.4.3 Session and Entity Objects

The Enterprise JavaBeans architecture defines two types of enterprise bean objects:

  • A session object

  • An entity object

EJB.4.3.1 Session Objects

A typical session object has the following characteristics:

  • Executes on behalf of a single client.

  • Can be transaction-aware.

  • Updates shared data in an underlying database.

  • Does not represent directly shared data in the database, although it may access and update such data.

  • Is relatively short-lived.

  • Is removed when the EJB container crashes. The client has to reestablish a new session object to continue computation.

A typical EJB container provides a scalable runtime environment to execute a large number of session objects concurrently.

Session beans are intended to be stateful. The EJB specification also defines a stateless session bean as a special case of a session bean. There are minor differences in the API between stateful (normal) session beans and stateless session beans.

EJB.4.3.2 Entity Objects

A typical entity object has the following characteristics:

  • Provides an object view of data in the database.

  • Allows shared access from multiple users.

  • Can be long-lived (lives as long as the data in the database).

  • The entity, its primary key, and its remote reference survive the crash of the EJB container. If the state of an entity was being updated by a transaction at the time the container crashed, the entity's state is automatically reset to the state of the last committed transaction. The crash is not fully transparent to the client—the client may receive an exception if it calls an entity in a container that has experienced a crash.

A typical EJB container and server provide a scalable runtime environment for a large number of concurrently active entity objects.


EJB.4.4 Standard Mapping to CORBA Protocols

To help interoperability for EJB environments that include systems from multiple vendors, we define a standard mapping of the Enterprise JavaBeans architecture client-view contract to the CORBA protocols.

The use of the EJB architecture to CORBA mapping by the EJB server is not a requirement for EJB 1.1 compliance. A later release of the J2EE platform is likely to require that the J2EE platform vendor implement the EJB architecture to CORBA mapping.

The EJB-to-CORBA mapping covers:

  1. Mapping of the EJB architecture remote and home interfaces to RMI-IIOP. This mapping is an identity mapping because every remote and home interface is an RMI-IIOP interface.

  2. Propagation of transaction context over IIOP.

  3. Propagation of security context over IIOP.

  4. Interoperable naming service.

The EJB-to-CORBA mapping not only enables on-the-wire interoperability among multiple vendors' implementations of the EJB container, but also enables clients written in languages other than the Java progamming language to access server-side applications written as enterprise beans through standard CORBA APIs.

The EJB-to-CORBA mapping depends on the standard CORBA object services protocols for the propagation of the transaction and security context.

The CORBA mapping is defined in a separate document.

While the EJB-to-CORBA mapping defines the mapping of the EJB application interfaces and transaction interoperability, the mapping must be used in conjunction with other CORBA standards to ensure full "on-the-wire" interoperability. For example, multiple EJB servers must agree on the security protocol to achieve seamless interoperability.

Figure EJB.4-2 illustrates a heterogeneous environment that includes systems from five different vendors.

Figure EJB.4-2. Heterogeneous EJB Environment


Chapter EJB.5. Client View of a Session Bean

This chapter describes the client view of a session bean. The session bean itself implements the business logic. The bean's container provides functionality for remote access, security, concurrency, transactions, and so forth.

While classes implemented by the container provide the client view of the session bean, the container itself is transparent to the client.


EJB.5.1 Overview

For a client, a session object is a non-persistent object that implements some business logic running on the server. One way to think of a session object is as a logical extension of the client program that runs on the server. A session object is not shared among multiple clients.

A client accesses a session object through the session bean's remote interface. The Java object that implements this remote interface is called a session EJBObject. A session EJBObject is a remote Java object accessible from a client through the standard Java APIs for remote object invocation.

From its creation until destruction, a session object lives in a container. Transparently to the client, the container provides security, concurrency, transactions, swapping to secondary storage, and other services for the session object.

Each session object has an identity which, in general, does not survive a crash and restart of the container, although a high-end container implementation can mask container and server crashes to the client.

The client view of a session bean is location-independent. A client running in the same JVM as the session object uses the same API as a client running in a different JVM on the same or different machine.

A client of an session bean can be another enterprise bean deployed in the same or different container; or it can be an arbitrary Java program, such as an application, applet, or servlet. The client view of a session bean can also be mapped to non-Java client environments, such as CORBA clients that are not written in the Java programming language.

Multiple enterprise beans can be installed in a container. The container allows the clients to look up the home interfaces of the installed enterprise beans via JNDI API. A session bean's home interface provides methods to create and remove the session objects of a particular session bean.

The client view of an session object is the same, irrespective of the implementation of the session bean and the container.


EJB.5.2 EJB Container

An EJB container (container for short) is a system that functions as the "container" for enterprise beans. Multiple enterprise beans can be deployed in the same container. The container is responsible for making the home interfaces of its deployed enterprise beans available to the client through JNDI API extension. Thus, the client can look up the home interface for a specific enterprise bean using JNDI API.

EJB.5.2.1 Locating a Session Bean's Home Interface

A client locates a session bean's home interface using JNDI API. For example, the home interface for the Cart session bean can be located using the following code segment:

Context initialContext = new InitialContext();
CartHome cartHome =
(CartHome)javax.rmi.PortableRemoteObject.narrow(
   initialContext.lookup("java:comp/env/ejb/cart"),
   CartHome.class);

A client's JNDI name space may be configured to include the home interfaces of enterprise beans installed in multiple EJB containers located on multiple machines on a network. The actual locations of an enterprise bean and EJB container are, in general, transparent to the client using the enterprise bean.

The life cycle of the distributed object implementing the home interface (the EJBHome object) is container-specific. A client application should be able to obtain a home interface, and then use it multiple times, during the client application's lifetime.

A client can pass a home interface object reference to another application. The receiving application can use the home interface in the same way that it would use a home interface object reference obtained via JNDI API.

EJB.5.2.2 What a Container Provides

Figure EJB.5-1 illustrates the view that a container provides to clients of session beans.

Figure EJB.5-1. Client View of Session Beans Deployed in a Container


EJB.5.3 Home Interface

A container implements the home interface of the enterprise bean installed in the container. The object that implements a session bean's home interface is called a session EJBHome object. The container makes the session beans' home interfaces available to the client through JNDI API.

The home interface allows a client to do the following:

  • Create a new session object.

  • Remove a session object.

  • Get the javax.ejb.EJBMetaData interface for the session bean. The javax.ejb.EJBMetaData interface is intended to allow application assembly tools to discover information about the session bean, and to allow loose client/server binding and client-side scripting.

  • Obtain a handle for the home interface. The home handle can be serialized and written to stable storage. Later, possibly in a different JVM, the handle can be deserialized from stable storage and used to obtain back a reference of the home interface.

EJB.5.3.1 Creating a Session Object

A home interface defines one or more create(...) methods, one for each way to create a session object. The arguments of the create methods are typically used to initialize the state of the created session object.

The following example illustrates a home interface that defines a single create(...) method:

public interface CartHome extends javax.ejb.EJBHome {
   Cart create(String customerName, String account)
           throws RemoteException, BadAccountException,
               CreateException;
}

The following example illustrates how a client creates a new session object using a create(...) method of the CartHome interface:

cartHome.create("John", "7506");

EJB.5.3.2 Removing a Session Object

A client may remove a session object using the remove() method on the javax.ejb.EJBObject interface, or the remove(Handle handle) method of the javax.ejb.EJBHome interface.

Because session objects do not have primary keys that are accessible to clients, invoking the javax.ejb.Home.remove(Object primaryKey) method on a session results in the javax.ejb.RemoveException.


EJB.5.4 EJBObject

A client never directly accesses instances of the session bean's class. A client always uses the session bean's remote interface to access a session bean's instance. The class that implements the session bean's remote interface is provided by the container; its instances are called session EJBObjects.

A session EJBObject supports:

  • The business logic methods of the object. The session EJBObject delegates invocation of a business method to the session bean instance.

  • The methods of the javax.ejb.EJBObject interface. These methods allow the client to:

    - Get the session object's home interface.

    - Get the session object's handle.

    - Test if the session object is identical with another session object.

    - Remove the session object.

The implementation of the methods defined in the javax.ejb.EJBObject interface is provided by the container. They are not delegated to the instances of the session bean class.


EJB.5.5 Session Object Identity

Session objects are intended to be private resources used only by the client that created them. For this reason, session objects, from the client's perspective, appear anonymous. In contrast to entity objects, which expose their identity as a primary key, session objects hide their identity. As a result, the EJBObject.getPrimaryKey() and EJBHome.remove(Object primaryKey) methods result in a java.rmi.RemoteException if called on a session bean. If the EJBMetaData.getPrimaryKeyClass()method is invoked on a EJBMetaData object for a session bean, the method throws the java.lang.RuntimeException.

Since all session objects hide their identity, there is no need to provide a finder for them. The home interface of a session bean must not define any finder methods.

A session object handle can be held beyond the life of a client process by serializing the handle to persistent store. When the handle is later deserialized, the session object it returns will work as long as the session object still exists on the server. (An earlier timeout or server crash may have destroyed the session object.)

The client code must use the javax.rmi.PortableRemoteObject.narrow(...)method to convert the result of the getEJBObject() method invoked on a handle to the remote interface type.

A handle is not a capability, in the security sense, that would automatically grant its holder the right to invoke methods on the object. When a reference to a session object is obtained from a handle, and then a method on the session object is invoked, the container performs the usual access checks based on the caller's principal.


EJB.5.6 Client View of Session Object's Life Cycle

From a client point of view, the life cycle of a session object is illustrated in Figure EJB.5-2.

Figure EJB.5-2. Life Cycle of a Session Object

A session object does not exist until it is created. When a client creates a session object, the client has a reference to the newly created session object's remote interface.

A client that has a reference to a session object can then do any of the following:

  • Invoke business methods defined in the session object's remote interface.

  • Get a reference to the session object's home interface.

  • Get a handle for the session object.

  • Pass the reference as a parameter or return value within the scope of the client.

  • Remove the session object. A container may also remove the session object automatically when the session object's lifetime expires.

It is invalid to reference a session object that does not exist. Attempted invocations on a session object that does not exist result in java.rmi.NoSuchObjectException.


EJB.5.7 Creating and Using a Session Object

An example of the session bean runtime objects is illustrated by the Figure EJB.5-3.

Figure EJB.5-3. Session Bean Example Objects

A client creates a Cart session object (which provides a shopping service) using a create(...) method of the Cart's home interface. The client then uses this session object to fill the cart with items and to purchase its contents.

Suppose that the end-user wishes to start the shopping session, suspend the shopping session temporarily for a day or two, and later complete the session. The client might implement this feature by getting the session object's handle, saving the serialized handle in persistent storage, then using it later to reestablish access to the original Cart.

For the following example, we start by looking up the Cart's home interface in JNDI. We then use the home interface to create a Cart session object and add a few items to it:

CartHome cartHome =
(CartHome)javax.rmi.PortableRemoteObject.narrow(
   initialContext.lookup(...), CartHome.class);
Cart cart = cartHome.create(...);
cart.addItem(66);
cart.addItem(22);

Next we decide to complete this shopping session at a later time so we serialize a handle to this Cart session object and store it in a file:

Handle cartHandle = cart.getHandle();
serialize cartHandle, store in a file...

Finally we deserialize the handle at a later time, re-create the reference to the cart session object, and purchase the contents of the shopping cart:

Handle cartHandle = deserialize from a file...
Cart cart = (Cart)javax.rmi.PortableRemoteObject.narrow(
             cartHandle.getEJBObject(), Cart.class);
cart.purchase();
cart.remove();


EJB.5.8 Object Identity

EJB.5.8.1 Stateful Session Beans

A stateful session object has a unique identity that is assigned by the container at create time.

A client can determine if two object references refer to the same session object by invoking the isIdentical(EJBObject otherEJBObject) method on one of the references.

The following example illustrates the use of the isIdentical method for a stateful session object.

FooHome fooHome = ...;       // obtain home of a stateful session bean
Foo foo1 = fooHome.create(...);
Foo foo2 = fooHome.create(...);

if (foo1.isIdentical(foo1)) {// this test must return true
   ...
}

if (foo1.isIdentical(foo2)) {// this test must return false
   ...
}

EJB.5.8.2 Stateless Session Beans

All session objects of the same stateless session bean within the same home have the same object identity, which is assigned by the container. If a stateless session bean is deployed multiple times (each deployment results in the creation of a distinct home), session objects from different homes will have a different identity.

The isIdentical(EJBObject otherEJBObject) method always returns true when used to compare object references of two session objects of the same stateless session bean.

The following example illustrates the use of the isIdentical method for a stateless session object.

FooHome fooHome = ...;      // obtain home of a stateless session bean
Foo foo1 = fooHome.create();
Foo foo2 = fooHome.create();

if (foo1.isIdentical(foo1)) {// this test returns true
   ...
}

if (foo1.isIdentical(foo2)) {// this test returns true
   ...
}

EJB.5.8.3 getPrimaryKey()

The object identifier of a session object is, in general, opaque to the client. The result of getPrimaryKey() on a session EJBObject reference results in java.rmi.RemoteException.


EJB.5.9 Type Narrowing

A client program that is intended to be interoperable with all compliant EJB container implementations must use the javax.rmi.PortableRemoteObject.narrow(...) method to perform type-narrowing of the client-side representations of the home and remote interface.

Note

Programs using the cast operator for narrowing the remote and home interfaces are likely to fail if the container implementation uses RMI-IIOP as the underlying communication transport.


Chapter EJB.6. Session Bean Component Contract

This chapter specifies the contract between a session bean and its container. It defines the life cycle of the session bean instances.

This chapter defines the developer's view of session bean state management and the container's responsibility for managing session bean state.


EJB.6.1 Overview

A session bean instance is an instance of the session bean class. It holds the session object's state.

By definition, a session bean instance is an extension of the client that creates it:

  • Its fields contain a conversational state on behalf of the session object's client. This state describes the conversation represented by a specific client/session object pair.

  • It typically reads and updates data in a database on behalf of the client. Within a transaction, some of this data may be cached in the instance.

  • Its lifetime is controlled by the client.

    A container may also terminate a session bean instance's life after a deployer-specified timeout or as a result of the failure of the server on which the bean instance is running. For this reason, a client should be prepared to recreate a new session object if it loses the one it is using.

Typically, a session object's conversational state is not written to the database. A session bean developer simply stores it in the session bean instance's fields and assumes its value is retained for the lifetime of the instance.

On the other hand, the session bean must explicitly manage cached database data. A session bean instance must write any cached database updates prior to a transaction completion, and it must refresh its copy of any potentially stale database data at the beginning of the next transaction.


EJB.6.2 Goals

The goal of the session bean model is to make developing a session bean as simple as developing the same functionality directly in a client.

The container manages the life cycle of the session bean instances. It notifies the instances when bean action may be necessary, and it provides a full range of services to ensure that the session bean implementation is scalable and can support a large number of clients.

The remainder of this section describes the session bean life cycle in detail and the protocol between the bean and its container.


EJB.6.3 A Container's Management of Its Working Set

To efficiently manage the size of its working set, a session bean container may need to temporarily transfer the state of an idle stateful session bean instance to some form of secondary storage. The transfer from the working set to secondary storage is called instance passivation. The transfer back is called activation.

A container may only passivate a session bean instance when the instance is not in a transaction.

To help the container manage its state, a session bean is specified at deployment as having one of the following state management modes:

  • STATELESS— The session bean instances contain no conversational state between methods; any instance can be used for any client.

  • STATEFUL— The session bean instances contain conversational state which must be retained across methods and transactions.


EJB.6.4 Conversational State

The conversational state of a stateful session object is defined as the session bean instance's field values, plus the transitive closure of the objects from the instance's fields reached by following references to objects in the Java programming language.

In advanced cases, a session object's conversational state may contain open resources, such as open sockets and open database cursors. A container cannot retain such open resources when a session bean instance is passivated. A developer of such a session bean must close and open the resources in the ejbPassivate and ejbActivate notifications.

EJB.6.4.1 Instance Passivation and Conversational State

The bean provider is required to ensure that the ejbPassivate method leaves the instance fields ready to be serialized by the container. The objects that are assigned to the instance's non- transient fields after the ejbPassivate method completes must be one of the following:

  • A serializable object. [1]

    [1] Note that the Java programming language serialization protocol dynamically determines whether or not an object is serializable. This means that it is possible to serialize an object of a serializable subclass of a non-serializable declared field type.

  • A null.

  • An enterprise bean's remote interface reference, even if the stub class is not serializable.

  • An enterprise bean's home interface reference, even if the stub class is not serializable.

  • A reference to the SessionContext object, even if it is not serializable.

  • A reference to the environment naming context (that is, the java:comp/env JNDI context) or any of its subcontexts.

  • A reference to the UserTransaction interface.

  • An object that is not directly serializable, but becomes serializable by replacing the references to an enterprise bean's remote and home interfaces, the references to the SessionContext object, the references to the java:comp/env JNDI context and its subcontexts, and the references to the UserTransaction interface by serializable objects during the object's serialization.

This means, for example, that the bean provider must close all JDBC™ API connections in ejbPassivate and assign the instance's fields storing the connections to null.

The last bulleted item covers cases such as storing collections of remote interfaces in the conversational state.

The bean provider must assume that the content of transient fields may be lost between the ejbPassivate and ejbActivate notifications. Therefore, the bean provider should not store in a transient field a reference to any of the following objects: SessionContext object; environment JNDI naming context and any its subcontexts; home and remote interfaces; and the UserTransaction interface.

The restrictions on the use of transient fields ensure that containers can use Java programming language serialization during passivation and activation.

The following are the requirements for the container.

The container performs the Java programming language serialization (or its equivalent) of the instance's state after it invokes the ejbPassivate method on the instance.

The container must be able to properly save and restore the reference to the remote and home interfaces of the enterprise beans stored in the instance's state even if the classes that implement the object references are not serializable.

The container may use, for example, the object replacement technique that is part of the java.io.ObjectOutputStream and java.io.ObjectInputStream protocol to externalize the remote and home references.

If the session bean instance stores in its conversational state an object reference to the javax.ejb.SessionContext interface passed to the instance in the setSessionContext(...) method, the container must be able to save and restore the reference across the instance's passivation. The container can replace the original SessionContext object with a different and functionally equivalent SessionContext object during activation.

If the session bean instance stores in its conversational state an object reference to the java:comp/env JNDI context or its subcontext, the container must be able to save and restore the object reference across the instance's passivation. The container can replace the original object with a different and functionally equivalent object during activation.

If the session bean instance stores in its conversational state an object reference to the UserTransaction interface, the container must be able to save and restore the object reference across the instance's passivation. The container can replace the original object with a different and functionally equivalent object during activation.

The container may destroy a session bean instance if the instance does not meet the requirements for serialization after ejbPassivate.

While the container is not required to use the serialization protocol for the Java programming language to store the state of a passivated session instance, it must achieve the equivalent result. The one exception is that containers are not required to reset the value of transient fields during activation. [2] Declaring the session bean's fields as transient is, in general, discouraged.

[2] This is to allow the container to swap out an instance's state through techniques other than the Java programming language serialization protocol. For example, the container's Java virtual machine implementation may use a block of memory to keep the instance's variables, and the container swaps the whole memory block to the disk instead of performing Java programming language serialization on the instance.

EJB.6.4.2 The Effect of Transaction Rollback on Conversational State

A session object's conversational state is not transactional. It is not automatically rolled back to its initial state if the transaction in which the object has participated rolls back.

If a rollback could result in an inconsistency between a session object's conversational state and the state of the underlying database, the bean developer (or the application development tools used by the developer) must use the afterCompletion notification to manually reset its state.


EJB.6.5 Protocol Between a Session Bean Instance and Its Container

Containers themselves make no actual service demands on the session bean instances. The container makes calls on a bean instance to provide it with access to container services and to deliver notifications issued by the container.

EJB.6.5.1 The Required SessionBean Interface

All session beans must implement the SessionBean interface.

The bean's container calls the setSessionContext method to associate a session bean instance with its context maintained by the container. Typically, a session bean instance retains its session context as part of its conversational state.

The ejbRemove notification signals that the instance is in the process of being removed by the container. In the ejbRemove method, the instance typically releases the same resources that it releases in the ejbPassivate method.

The ejbPassivate notification signals the intent of the container to passivate the instance. The ejbActivate notification signals the instance it has just been reactivated. Because containers automatically maintain the conversational state of a session bean instance when it is passivated, most session beans can ignore these notifications. Their purpose is to allow session beans to maintain those open resources that need to be closed prior to an instance's passivation and then reopened during an instance's activation.

EJB.6.5.2 The SessionContext Interface

A container provides the session bean instances with a SessionContext, which gives the session bean instance access to the instance's context maintained by the container. The SessionContext interface has the following methods:

  • The getEJBObject method returns the session bean's remote interface.

  • The getEJBHome method returns the session bean's home interface.

  • The getCallerPrincipal method returns the java.security.Principal that identifies the invoker of the bean instance's EJB object.

  • The isCallerInRole method tests if the session bean instance's caller has a particular role.

  • The setRollbackOnly method allows the instance to mark the current transaction such that the only outcome of the transaction is a rollback. Only instances of a session bean with container-managed transaction demarcation can use this method.

  • The getRollbackOnly method allows the instance to test if the current transaction has been marked for rollback. Only instances of a session bean with container-managed transaction demarcation can use this method.

  • The getUserTransaction method returns the javax.transaction.UserTransaction interface. The instance can use this interface to demarcate transactions and to obtain transaction status. Only instances of a session bean with bean-managed transaction demarcation can use this method.

EJB.6.5.3 The Optional SessionSynchronization Interface

A session bean class can optionally implement the javax.ejb.SessionSynchronization interface. This interface provides the session bean instances with transaction synchronization notifications. The instances can use these notifications, for example, to manage database data they may cache within transactions.

The afterBegin notification signals a session bean instance that a new transaction has begun. The container invokes this method before the first business method within a transaction (which is not necessarily at the beginning of the transaction). The afterBegin notification is invoked with the transaction context. The instance may do any database work it requires within the scope of the transaction.

The beforeCompletion notification is issued when a session bean instance's client has completed work on its current transaction but prior to committing the resource managers used by the instance. At this time, the instance should write out any database updates it has cached. The instance can cause the transaction to roll back by invoking the setRollbackOnly method on its session context.

The afterCompletion notification signals that the current transaction has completed. A completion status of true indicates that the transaction has committed; a status of false indicates that a rollback has occurred. Since a session bean instance's conversational state is not transactional, it may need to manually reset its state if a rollback occurred.

All container providers must support SessionSynchronization. It is optional only for the bean implementor. If a bean class implements SessionSynchronization, the container must invoke the afterBegin, beforeCompletion and afterCompletion notifications as required by the specification.

Only a stateful session bean with container-managed transaction demarcation may implement the SessionSynchronization interface. A stateless session bean must not implement the SessionSynchronization interface.

There is no need for a session bean with bean-managed transaction to rely on the synchronization callbacks because the bean is in control of the commit—the bean knows when the transaction is about to be committed and it knows the outcome of the transaction commit.

EJB.6.5.4 Business Method Delegation

The session bean's remote interface defines the business methods callable by a client. The session bean's remote interface is implemented by the session EJBObject class generated by the container tools. The session EJBObject class delegates an invocation of a business method to the matching business method that is implemented in the session bean class.

EJB.6.5.5 Session Bean's ejbCreate(...) Methods

A client creates a session bean instance using one of the create methods defined in the session bean's home interface. The session bean's home interface is provided by the bean developer; its implementation is generated by the deployment tools provided by the container provider.

The container creates an instance of a session bean in three steps. First, the container calls the bean class' newInstance method to create a new session bean instance. Second, the container calls the setSessionContext method to pass the context object to the instance. Third, the container calls the instance's ejbCreate method whose signature matches the signature of the create method invoked by the client. The input parameters sent from the client are passed to the ejbCreate method.

Each session bean class must have at least one ejbCreate method. The number and signatures of a session bean's create methods are specific to each session bean class.

Since a session bean represents a specific, private conversation between the bean and its client, its create parameters typically contain the information the client uses to customize the bean instance for its use.

EJB.6.5.6 Serializing Session Bean Methods

A container serializes calls to each session bean instance. Most containers will support many instances of a session bean executing concurrently; however, each instance sees only a serialized sequence of method calls. Therefore, a session bean does not have to be coded as reentrant.

The container must serialize all the container-invoked callbacks (that is, the methods ejbPassivate, beforeCompletion, and so on), and it must serialize these callbacks with the client-invoked business method calls.

Clients are not allowed to make concurrent calls to a session object. If a client-invoked business method is in progress on an instance when another client-invoked call, from the same or different client, arrives at the same instance, the container must throw the java.rmi.RemoteException to the second client. One implication of this rule is that it is illegal to make a "loopback" call to a session bean instance. An example of a loopback call is when a client calls instance A, instance A calls instance B, and B calls A. The loopback call attempt from B to A would result in the container throwing the java.rmi.RemoteException to B.

EJB.6.5.7 Transaction Context of Session Bean Methods

The implementation of a business method defined in the remote interface is invoked in the scope of a transaction determined by the transaction attribute specified in the deployment descriptor.

A session bean's afterBegin and beforeCompletion methods are always called with the same transaction context as the business methods executed between the afterBegin and beforeCompletion methods.

A session bean's newInstance, setSessionContext, ejbCreate, ejbRemove, ejbPassivate, ejbActivate, and afterCompletion methods are called with an unspecified transaction context. Refer to Section EJB.11.6.3 for how the container executes methods with an unspecified transaction context.

For example, it would be wrong to perform database operations within a session bean's ejbCreate or ejbRemove method and to assume that the operations are part of the client's transaction. The ejbCreate and ejbRemove methods are not controlled by a transaction attribute because handling rollbacks in these methods would greatly complicate the session instance's state diagram.


EJB.6.6 Stateful Session Bean State Diagram

Figure EJB.6-1 illustrates the life cycle of a stateful session bean instance.

Figure EJB.6-1. Life Cycle of a Stateful Session Bean Instance

The following steps describe the life cycle of a stateful session bean instance:

  • A session bean instance's life starts when a client invokes a create(...) method on the session bean's home interface. This causes the container to invoke newInstance() on the session bean class to create a new session bean instance. Next, the container calls setSessionContext() and ejbCreate(...) on the instance and returns the remote reference of the session object to the client. The instance is now in the method ready state.

  • The session bean instance is now ready for client's business methods. Based on the transaction attributes in the session bean's deployment descriptor and the transaction context associated with the client's invocation, a business method is executed either in a transaction context or with an unspecified transaction context (shown as tx method and non-tx method in the diagram). See Chapter EJB.11 for how the container deals with transactions.

  • A non-transactional method is executed while the instance is in the method ready state.

  • An invocation of a transactional method causes the instance to be included in a transaction. When the session bean instance is included in a transaction, the container issues the afterBegin() method on it. The afterBegin is delivered to the instance before any business method is executed as part of the transaction. The instance becomes associated with the transaction and will remain associated with the transaction until the transaction completes.

  • Session bean methods invoked by the client in this transaction can now be delegated to the bean instance. An error occurs if a client attempts to invoke a method on the session object and the deployment descriptor for the method requires that the container invoke the method in a different transaction context than the one with which the instance is currently associated or in an unspecified transaction context.

  • If a transaction commit has been requested, the transaction service notifies the container of the commit request before actually committing the transaction, and the container issues a beforeCompletion on the instance. When beforeCompletion is invoked, the instance should write any cached updates to the database. If a transaction rollback had been requested instead, the rollback status is reached without the container issuing a beforeCompletion. The container may not call the beforeCompletion method if the transaction has been marked for rollback (nor does the instance write any cached updates to the database).

  • The transaction service then attempts to commit the transaction, resulting in either a commit or rollback.

  • When the transaction completes, the container issues afterCompletion on the instance, specifying the status of the completion (either commit or rollback). If a rollback occurred, the bean instance may need to reset its conversational state back to the value it had at the beginning of the transaction.

  • The container's caching algorithm may decide that the bean instance should be evicted from memory (this could be done at the end of each method, or by using an LRU policy). The container issues ejbPassivate on the instance. After this completes, the container saves the instance's state to secondary storage. A session bean can be passivated only between transactions, and not within a transaction.

  • While the instance is in the passivated state, the container may remove the session object after the expiration of a timeout specified by the deployer. All object references and handles for the session object become invalid. If a client attempts to invoke the session object, the container will throw the java.rmi.NoSuchObjectException to the client.

  • If a client invokes a session object whose session bean instance has been passivated, the container will activate the instance. To activate the session bean instance, the container restores the instance's state from secondary storage and issues ejbActivate on it.

  • The session bean instance is again ready for client methods.

  • When the client calls remove on the home or remote interface to remove the session object, the container issues ejbRemove() on the bean instance. This ends the life of the session bean instance and the associated session object. Any subsequent attempt by its client to invoke the session object causes the java.rmi.NoSuchObjectException to be thrown (this exception is a subclass of java.rmi.RemoteException). The ejbRemove() method cannot be called when the instance is participating in a transaction. An attempt to remove a session object while the object is in a transaction will cause the container to throw the javax.ejb.RemoveException to the client. Note that a container can also invoke the ejbRemove() method on the instance without a client call to remove the session object after the lifetime of the EJB object has expired.

Note

The container must call the afterBegin, beforeCompletion, and afterCompletion methods if the session bean class implements, directly or indirectly, the SessionSynchronization interface. The container does not call these methods if the session bean class does not implement the SessionSynchronization interface.

EJB.6.6.1 Operations Allowed in the Methods of a Stateful Session Bean Class

Table EJB.6-1 defines the methods of a stateful session bean class from which the session bean instances can access the methods of the javax.ejb.SessionContext interface, the java:comp/env environment naming context, resource managers, and other enterprise beans.

If a session bean instance attempts to invoke a method of the SessionContext interface, and that access is not allowed in Table EJB.6-1, the container must throw the java.lang.IllegalStateException.

If a session bean instance attempts to access a resource manager or an enterprise bean, and that access is not allowed in Table EJB.6-1, the behavior is undefined by the EJB architecture.

Table EJB.6-1. Operations Allowed in the Methods of a Stateful Session Bean

Bean Method

Bean Method Can Perform the Following Operations

Container-Managed Transaction Demarcation

Bean-Managed Transaction Demarcation

constructor

—

—

setSessionContext

SessionContext methods:

getEJBHome

JNDI access to java:comp/env

SessionContext methods:

getEJBHome

JNDI access to java:comp/env

ejbCreate

ejbRemove

ejbActivate

ejbPassivate

SessionContext methods:

getEJBHome, getCallerPrincipal, isCallerInRole, getEJBObject

JNDI access to java:comp/env Resource manager access Enterprise bean access

SessionContext methods:

getEJBHome, getCallerPrincipal, isCallerInRole, getEJBObject, getUserTransaction

UserTransaction methods JNDI access to java:comp/env Resource manager access Enterprise bean access

business method from remote interface

SessionContext methods:

getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject

JNDI access to java:comp/env Resource manager access Enterprise bean access

SessionContext methods:

getEJBHome, getCallerPrincipal, isCallerInRole, getEJBObject, getUserTransaction

UserTransaction methods JNDI access to java:comp/env Resource manager access Enterprise bean access

afterBegin

beforeCompletion

SessionContext methods:

getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject

JNDI access to java:comp/env Resource manager access Enterprise bean access

N/A (a bean with bean-managed transaction demarcation cannot implement the SessionSynchronization interface)

afterCompletion

SessionContext methods:

getEJBHome, getCallerPrincipal, isCallerInRole, getEJBObject

JNDI access to java:comp/env

Notes:

  • The ejbCreate, ejbRemove, ejbPassivate, and ejbActivate methods of a session bean with container-managed transaction demarcation execute with an unspecified transaction context. Refer to Section EJB.11.6.3 for how the Container executes methods with an unspecified transaction context.

Additional restrictions:

  • The getRollbackOnly and setRollbackOnly methods of the SessionContext interface should be used only in the session bean methods that execute in the context of a transaction. The Container must throw the java.lang.IllegalStateException if the methods are invoked while the instance is not associated with a transaction.

The reasons for disallowing the operations in Table EJB.6-1 follow:

  • Invoking the getEJBObject methods is disallowed in the session bean methods in which there is no session object identity established for the instance.

  • Invoking the getCallerPrincipal and isCallerInRole methods is disallowed in the session bean methods for which the container does not have a client security context.

  • Invoking the getRollbackOnly and setRollbackOnly methods is disallowed in the session bean methods for which the container does not have a meaningful transaction context, and to all session beans with bean-managed transaction demarcation.

  • Accessing resource managers and enterprise beans is disallowed in the session bean methods for which the container does not have a meaningful transaction context or client security context.

  • The UserTransaction interface is unavailable to enterprise beans with container-managed transaction demarcation.

EJB.6.6.2 Dealing with Exceptions

A RuntimeException thrown from any method of the session bean class (including the business methods and the callbacks invoked by the container) results in the transition to the "does not exist" state. Exception handling is described in detail in Chapter EJB.12.

From the client perspective, the corresponding session object does not exist any more. Subsequent invocations through the remote interface will result in java.rmi.NoSuchObjectException.

EJB.6.6.3 Missed ejbRemove() Calls

The bean provider cannot assume that the container will always invoke the ejbRemove() method on a session bean instance. The following scenarios result in ejbRemove() not being called on an instance:

  • A crash of the EJB container.

  • A system exception thrown from the instance's method to the container.

  • A timeout of client inactivity while the instance is in the passive state. The timeout is specified by the deployer in an EJB container implementation specific way.

If the session bean instance allocates resources in the ejbCreate(...) method and/or in the business methods, and normally releases the resources in the ejbRemove() method, these resources will not be automatically released in the above scenarios. The application using the session bean should provide some cleanup mechanism to periodically clean up the unreleased resources.

For example, if a shopping cart component is implemented as a session bean, and the session bean stores the shopping cart content in a database, the application should provide a program that runs periodically and removes "abandoned" shopping carts from the database.

EJB.6.6.4 Restrictions for Transactions

The state diagram implies the following restrictions on transaction scoping of the client invoked business methods. The restrictions are enforced by the container and must be observed by the client programmer.

  • A session bean instance can participate in at most a single transaction at a time.

  • If a session bean instance is participating in a transaction, it is an error for a client to invoke a method on the session object such that the transaction attribute in the deployment descriptor would cause the container to execute the method in a different transaction context or in an unspecified transaction context. The container throws the java.rmi.RemoteException to the client in such a case.

  • If a session bean instance is participating in a transaction, it is an error for a client to invoke the remove method on the session object's remote or home interface object. The container must detect such an attempt and throw the javax.ejb.RemoveException to the client. The container should not mark the client's transaction for rollback, thus allowing the client to recover.


EJB.6.7 Object Interaction Diagrams for a Stateful Session Bean

This section contains object interaction diagrams (OIDs) that illustrate the interaction of the classes.

EJB.6.7.1 Notes

The object interaction diagrams illustrate a box labeled "container-provided classes." These are either classes that are part of the container, or classes that were generated by the container tools. These classes communicate with each other through protocols that are container-implementation specific. Therefore, the communication between these classes is not shown in the diagrams.

The classes shown in the diagrams should be considered as an illustrative implementation rather than as a prescriptive one.

EJB.6.7.2 Creating a Session Object

Figure EJB.6-2 illustrates the creation of a session object.

Figure EJB.6-2. OID for Creation of a Session Object

EJB.6.7.3 Starting a Transaction

Figure EJB.6-3 illustrates the protocol performed at the beginning of a transaction.

Figure EJB.6-3. OID for Session Object at Start of a Transaction

EJB.6.7.4 Committing a Transaction

Figure EJB.6-4 illustrates the transaction synchronization protocol for a session object.

Figure EJB.6-4. OID for Session Object Transaction Synchronization

EJB.6.7.5 Passivating and Activating an Instance Between Transactions

Figure EJB.6-5 illustrates the passivation and reactivation of a session bean instance. Passivation typically happens spontaneously based on the needs of the container. Activation typically occurs when a client calls a method.

Figure EJB.6-5. OID for Passivation and Activation of a Session Object

EJB.6.7.6 Removing a Session Object

Figure EJB.6-6 illustrates the removal of a session object.

Figure EJB.6-6. OID for the Removal of a Session Object


EJB.6.8 Stateless Session Beans

Stateless session beans are session beans whose instances have no conversational state. This means that all bean instances are equivalent when they are not involved in serving a client-invoked method.

The term "stateless" signifies that an instance has no state for a specific client. However, the instance variables of the instance can contain the state across client-invoked method calls. Examples of such states include an open database connection and an object reference to an EJB object.

The home interface of a stateless session bean must have one create method that takes no arguments and returns the session bean's remote interface. There can be no other create methods in the home interface. The session bean class must define a single ejbCreate method that takes no arguments.

Because all instances of a stateless session bean are equivalent, the container can choose to delegate a client-invoked method to any available instance. This means, for example, that the container may delegate the requests from the same client within the same transaction to different instances, and that the container may interleave requests from multiple transactions to the same instance.

A container only needs to retain the number of instances required to service the current client load. Due to client "think time," this number is typically much smaller than the number of active clients. Passivation is not needed for stateless sessions. The container creates another stateless session bean instance if one is needed to handle an increase in client work load. If a stateless session bean is not needed to handle the current client work load, the container can destroy it.

Because stateless session beans minimize the resources needed to support a large population of clients, depending on the implementation of the container, applications that use stateless session beans may scale somewhat better than those using stateful session beans. However, this benefit may be offset by the increased complexity of the client application that uses the stateless beans.

Clients use the create and remove methods on the home interface of a stateless session bean in the same way as on a stateful session bean. To the client, it appears as if the client controls the life cycle of the session object. However, the container handles the create and remove calls without necessarily creating and removing an EJB instance.

There is no fixed mapping between clients and stateless instances. The container simply delegates a client's work to any available instance that is method-ready.

A stateless session bean must not implement the javax.ejb.SessionSynchronization interface.

EJB.6.8.1 Stateless Session Bean State Diagram

When a client calls a method on a stateless session object, the container selects one of its method-ready instances and delegates the method invocation to it.

Figure EJB.6-7 illustrates the life cycle of a stateless session bean instance.

Figure EJB.6-7. Life Cycle of a Stateless Session Bean

The following steps describe the life cyle of a session bean instance:

  • A stateless session bean instance's life starts when the container invokes newInstance() on the session bean class to create a new instance. Next, the container calls setSessionContext() followed by ejbCreate() on the instance. The container can perform the instance creation at any time—there is no relationship to a client's invocation of the create() method.

  • The session bean instance is now ready to be delegated a business method call from any client.

  • When the container no longer needs the instance (usually when the container wants to reduce the number of instances in the method-ready pool), the container invokes ejbRemove() on it. This ends the life of the stateless session bean instance.

EJB.6.8.2 Operations Allowed in the Methods of a Stateless Session Bean Class

Table EJB.6-2 defines the methods of a stateless session bean class in which the session bean instances can access the methods of the javax.ejb.SessionContext interface, the java:comp/env environment naming context, resource managers, and other enterprise beans.

If a session bean instance attempts to invoke a method of the SessionContext interface, and the access is not allowed in Table EJB.6-2, the container must throw the java.lang.IllegalStateException.

If a session bean instance attempts to access a resource manager or an enterprise bean and the access is not allowed in Table EJB.6-2, the behavior is undefined by the EJB architecture.

Table EJB.6-2. Operations Allowed in the Methods of a Stateless Session Bean

Bean Method

Bean Method Can Perform the Following Operations

Container-Managed Transaction Demarcation

Bean-Managed Transaction Demarcation

constructor

—

—

setSessionContext

SessionContext methods:

getEJBHome

JNDI access to java:comp/env

SessionContext methods:

getEJBHome

JNDI access to java:comp/env

ejbCreate

ejbRemove

SessionContext methods:

getEJBHome, getEJBObject

JNDI access to java:comp/env

SessionContext methods:

getEJBHome, getEJBObject, getUserTransaction

UserTransaction methods JNDI access to java:comp/env

business method from remote interface

SessionContext methods:

getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject

JNDI access to java:comp/env Resource manager access Enterprise bean access

SessionContext methods:

getEJBHome, getCallerPrincipal, isCallerInRole, getEJBObject, getUserTransaction

UserTransaction methods JNDI access to java:comp/env Resource manager access Enterprise bean access

Additional restrictions:

  • The getRollbackOnly and setRollbackOnly methods of the SessionContext interface should be used only in the session bean methods that execute in the context of a transaction. The container must throw the java.lang.IllegalStateException if the methods are invoked while the instance is not associated with a transaction.

The reasons for disallowing operations in Table EJB.6-2:

  • Invoking the getEJBObject method is disallowed in the session bean methods in which there is no session object identity associated with the instance.

  • Invoking the getCallerPrincipal and isCallerInRole methods is disallowed in the session bean methods for which the container does not have a client security context.

  • Invoking the getRollbackOnly and setRollbackOnly methods is disallowed in the session bean methods for which the container does not have a meaningful transaction context, and for all session beans with bean-managed transaction demarcation.

  • Accessing resource managers and enterprise beans is disallowed in the session bean methods for which the container does not have a meaningful transaction context or client security context.

  • The UserTransaction interface is unavailable to session beans with container-managed transaction demarcation.

EJB.6.8.3 Dealing with Exceptions

A RuntimeException thrown from any method of the enterprise bean class (including the business methods and the callbacks invoked by the container) results in the transition to the "does not exist" state. Exception handling is described in detail in Chapter EJB.12.

From the client perspective, the session object continues to exist. The client can continue accessing the session object because the container can delegate the client's requests to another instance.


EJB.6.9 Object Interaction Diagrams for a Stateless Session Bean

This section contains object interaction diagrams that illustrate the interaction of the classes.

EJB.6.9.1 Client-Invoked create()

Figure EJB.6-8 illustrates the creation of a stateless session object.

Figure EJB.6-8. OID for Creation of a Stateless Session Object

EJB.6.9.2 Business Method Invocation

Figure EJB.6-9 illustrates the invocation of a business method.

Figure EJB.6-9. OID for Invocation of Business Method on a Stateless Session Object

EJB.6.9.3 Client-Invoked remove()

Figure EJB.6-10 illustrates the destruction of a stateless session object.

Figure EJB.6-10. OID for Removal of a Stateless Session Object

EJB.6.9.4 Adding Instance to the Pool

Figure EJB.6-11 illustrates the sequence for a container adding an instance to the method-ready pool.

Figure EJB.6-11. OID for Container Adding Instance of a Stateless Session Bean to a Method-Ready Pool

Figure EJB.6-12 illustrates the sequence for a container removing an instance from the method-ready pool.

Figure EJB.6-12. OID for a Container Removing an Instance of a Stateless Session Bean from Ready Pool


EJB.6.10 The Responsibilities of the Bean Provider

This section describes the responsibilities of session bean provider to ensure that a session bean can be deployed in any EJB container.

EJB.6.10.1 Classes and Interfaces

The session bean provider is responsible for providing the following class files:

  • Session bean class

  • Session bean's remote interface

  • Session bean's home interface

EJB.6.10.2 Session Bean Class

The following are the requirements for session bean class:

  • The class must implement, directly or indirectly, the javax.ejb.SessionBean interface.

  • The class must be defined as public, must not be final, and must not be abstract.

  • The class must have a public constructor that takes no parameters. The container uses this constructor to create instances of the session bean class.

  • The class must not define the finalize() method.

  • The class may, but is not required to, implement the session bean's remote interface. [3]

    [3] If the session bean class does implement the remote interface, care must be taken to avoid passing of this as a method argument or result. This potential error can be avoided by choosing not to implement the remote interface in the session bean class.

  • The class must implement the business methods and the ejbCreate methods.

  • If the class is a stateful session bean, it may optionally implement the javax.ejb.SessionSynchronization interface.

  • The session bean class may have superclasses and/or superinterfaces. If the session bean has superclasses, then the business methods, the ejbCreate methods, the methods of the SessionBean interface, and the methods of the optional SessionSynchronization interface may be defined in the session bean class, or in any of its superclasses.

  • The session bean class is allowed to implement other methods (for example, helper methods invoked internally by the business methods) in addition to the methods required by the EJB specification.

EJB.6.10.3 ejbCreate Methods

The session bean class must define one or more ejbCreate(...) methods whose signatures must follow these rules:

  • The method name must be ejbCreate.

  • The method must be declared as public.

  • The method must not be declared as final or static.

  • The return type must be void.

  • The method arguments must be legal types for RMI-IIOP.

  • The throws clause may define arbitrary application exceptions, possibly including the javax.ejb.CreateException.

Compatibility Note

EJB 1.0 allowed the ejbCreate method to throw the java.rmi.RemoteException to indicate a non-application exception. This practice is deprecated in EJB 1.1—an EJB 1.1 compliant enterprise bean should throw the javax.ejb.EJBException or another RuntimeException to indicate non-application exceptions to the container (see Section EJB.12.2.2).

EJB.6.10.4 Business Methods

The session bean class may define zero or more business methods whose signatures must follow these rules:

  • The method names can be arbitrary, but they must not start with "ejb" to avoid conflicts with the callback methods used by the EJB architecture.

  • The business method must be declared as public.

  • The method must not be declared as final or static.

  • The argument and return value types for a method must be legal types for RMI-IIOP.

  • The throws clause may define arbitrary application exceptions.

Compatibility Note

EJB 1.0 allowed the business methods to throw the java.rmi.RemoteException to indicate a non-application exception. This practice is deprecated in EJB 1.1—an EJB 1.1 compliant enterprise bean should throw the javax.ejb.EJBException or another RuntimeException to indicate non-application exceptions to the container (see Section EJB.12.2.2).

EJB.6.10.5 Session Bean's Remote Interface

The following are the requirements for the session bean's remote interface:

  • The interface must extend the javax.ejb.EJBObject interface.

  • The methods defined in this interface must follow the rules for RMI-IIOP. This means that their argument and return values must be of valid types for RMI-IIOP, and their throws clause must include the java.rmi.RemoteException.

  • The remote interface is allowed to have superinterfaces. Use of interface inheritance is subject to the RMI-IIOP rules for the definition of remote interfaces.

  • For each method defined in the remote interface, there must be a matching method in the session bean's class. The matching method must have:

    - The same name.

    - The same number and types of arguments, and the same return type.

    - All the exceptions defined in the throws clause of the matching method of the session bean class must be defined in the throws clause of the method of the remote interface.

EJB.6.10.6 Session Bean's Home Interface

The following are the requirements for the session bean's home interface:

  • The interface must extend the javax.ejb.EJBHome interface.

  • The methods defined in this interface must follow the rules for RMI-IIOP. This means that their argument and return values must be of valid types for RMI-IIOP, and that their throws clause must include the java.rmi.RemoteException.

  • The home interface is allowed to have superinterfaces. Use of interface inheritance is subject to the RMI-IIOP rules for the definition of remote interfaces.

  • A session bean's home interface must define one or more create(...) methods.

  • Each create method must be named "create," and it must match one of the ejbCreate methods defined in the session bean class. The matching ejbCreate method must have the same number and types of arguments. (Note that the return type is different.)

  • The return type for a create method must be the session bean's remote interface type.

  • All the exceptions defined in the throws clause of an ejbCreate method of the session bean class must be defined in the throws clause of the matching create method of the home interface.

  • The throws clause must include javax.ejb.CreateException.

EJB.6.11 The Responsibilities of the Container Provider

This section describes the responsibilities of the container provider to support a session bean. The container provider is responsible for providing the deployment tools and for managing the session bean instances at runtime.

Because the EJB specification does not define the API between deployment tools and the container, we assume that the deployment tools are provided by the container provider. Alternatively, the deployment tools may be provided by a different vendor who uses the container vendor's specific API.

EJB.6.11.1 Generation of Implementation Classes

The deployment tools provided by the container are responsible for the generation of additional classes when the session bean is deployed. The tools obtain the information that they need for generation of the additional classes by introspecting the classes and interfaces provided by the enterprise bean provider and by examining the session bean's deployment descriptor.

The deployment tools must generate the following classes:

  • A class that implements the session bean's home interface (session EJBHome class).

  • A class that implements the session bean's remote interface (session EJBObject class).

The deployment tools may also generate a class that mixes some container-specific code with the session bean class. This code may, for example, help the container to manage the bean instances at runtime. The tools can use subclassing, delegation, and code generation.

The deployment tools may also allow the generation of additional code that wraps the business methods and is used to customize the business logic to an existing operational environment. For example, a wrapper for a debit function on the AccountManager bean may check that the debited amount does not exceed a certain limit.

EJB.6.11.2 Session EJBHome Class

The session EJBHome class, which is generated by the deployment tools, implements the session bean's home interface. This class implements the methods of the javax.ejb.EJBHome interface and the create methods specific to the session bean.

The implementation of each create(...) method invokes a matching ejbCreate(...) method.

EJB.6.11.3 Session EJBObject Class

The session EJBObject class, which is generated by the deployment tools, implements the session bean's remote interface. It implements the methods of the javax.ejb.EJBObject interface and the business methods specific to the session bean.

The implementation of each business method must activate the instance (if the instance is in the passive state) and invoke the matching business method on the instance.

EJB.6.11.4 Handle Classes

The deployment tools are responsible for implementing the handle classes for the session bean's home and remote interfaces.

EJB.6.11.5 EJBMetaData Class

The deployment tools are responsible for implementing the class that provides meta-data to the client view contract. The class must be a valid RMI Value class and must implement the javax.ejb.EJBMetaData interface.

EJB.6.11.6 Non-Reentrant Instances

The container must ensure that only one thread can be executing an instance at any time. If a client request arrives for an instance while the instance is executing another request, the container must throw the java.rmi.RemoteException to the second request.

Note

A session object is intended to support only a single client. Therefore, it would be an application error if two clients attempted to invoke the same session object.

One implication of this rule is that an application cannot make loopback calls to a session bean instance.

EJB.6.11.7 Transaction Scoping, Security, Exceptions

The container must follow the rules with respect to transaction scoping, security checking, and exception handling, as described in Chapters EJB.11, EJB.15, and EJB.12, respectively.


Chapter EJB.7. Example Session Scenario

This chapter describes an example development and deployment scenario of a session bean. We use the scenario to explain the responsibilities of the bean provider and those of the container provider.

The classes generated by the container provider's tools in this scenario should be considered illustrative rather than prescriptive. Container providers are free to implement the contract between a session bean and its container in a different way, provided that it achieves an equivalent effect (from the perspectives of the bean provider and the client-side programmer).


EJB.7.1 Overview

Wombat Inc. has developed the CartBean session bean. The CartBean is deployed in a container provided by the Acme Corporation.


EJB.7.2 Inheritance Relationship

An example of the inheritance relationship between the interfaces and classes is illustrated in Figure EJB.7-1.

Figure EJB.7-1. Example of Inheritance Relationships Between EJB Classes

EJB.7.2.1 What the Session Bean Provider Is Responsible For

Wombat Inc. is responsible for providing the following:

  • Define the session bean's remote interface (Cart). The remote interface defines the business methods callable by a client. The remote interface must extend the javax.ejb.EJBObject interface, and follow the standard rules for an RMI-IIOP remote interface. The remote interface must be defined as public.

  • Write the business logic in the session bean class (CartBean). The enterprise bean class may, but is not required to, implement the enterprise bean's remote interface (Cart). The enterprise bean must implement the javax.ejb.SessionBean interface, and define the ejbCreate(...) methods invoked at an EJB object creation.

  • Define a home interface (CartHome) for the enterprise bean. The home interface must be defined as public, extend the javax.ejb.EJBHome interface, and follow the standard rules for RMI-IIOP remote interfaces.

  • Define a deployment descriptor specifying any declarative metadata that the session bean provider wishes to pass with the bean to the next stage of the development/deployment workflow.

EJB.7.2.2 Classes Supplied by Container Provider

The following classes are supplied by the container provider Acme Corp:

  • The AcmeHome class provides the Acme implementation of the javax.ejb.EJBHome methods.

  • The AcmeRemote class provides the Acme implementation of the javax.ejb.EJBObject methods.

  • The AcmeBean class provides additional state and methods to allow Acme's container to manage its session bean instances. For example, if Acme's container uses an LRU algorithm, then AcmeBean may include the clock count and methods to use it.

  • The AcmeMetaData class provides the Acme implementation of the javax.ejb.EJBMetaData methods.

EJB.7.2.3 What the Container Provider Is Responsible For

The tools provided by Acme Corporation are responsible for the following:

  • Generate the class (AcmeRemoteCart) that implements the session bean's remote interface. The tools also generate the classes that implement the communication protocol specific artifacts for the remote interface.

  • Generate the implementation of the session bean class suitable for the Acme container (AcmeCartBean). AcmeCartBean includes the business logic from the CartBean class mixed with the services defined in the AcmeBean class. Acme tools can use inheritance, delegation, and code generation to achieve a mix-in of the two classes.

  • Generate the class (AcmeCartHome) that implements the session bean's home interface. The tools also generate the classes that implement the communication protocol specific artifacts for the home interface.

  • Generate the class (AcmeCartMetaData) that implements the javax.ejb.EJBMetaData interface for the Cart bean.

Many of the above classes and tools are container-specific (i.e., they reflect the way Acme Corp implemented them). Other container providers may use different mechanisms to produce their runtime classes, and these classes will likely be different from those generated by Acme's tools.


Chapter EJB.8. Client View of an Entity

This chapter describes the client view of an entity bean. It is actually a contract fulfilled by the container in which the entity bean is deployed. Only the business methods are supplied by the enterprise bean itself.

Although the client view of the deployed entity beans is provided by classes implemented by the container, the container itself is transparent to the client.


EJB.8.1 Overview

For a client, an entity bean is a component that represents an object-oriented view of some entities stored in a persistent storage, such as a database, or entities that are implemented by an existing enterprise application.

A client accesses an entity bean through the entity bean's remote and home interfaces. The container provides classes that implement the entity bean's remote and home interfaces. The objects that implement the home and remote objects are remote Java objects, and are accessible from a client through the standard Java APIs for remote object invocation.

From its creation until its destruction, an entity object lives in a container. Transparently to the client, the container provides security, concurrency, transactions, persistence, and other services for the entity objects that live in the container. The container is transparent to the client—there is no API that a client can use to manipulate the container.

Multiple clients can access an entity object concurrently. The container in which the entity bean is deployed properly synchronizes access to the entity object's state using transactions.

Each entity object has an identity which, in general, survives a crash and restart of the container in which the entity object has been created. The object identity is implemented by the container with the cooperation of the enterprise bean class.

The client view of an entity bean is location independent. A client running in the same JVM as an entity bean instance uses the same API to access the entity bean as a client running in a different JVM on the same or different machine.

A client of an entity object can be another enterprise bean deployed in the same or different container; or a client can be an arbitrary Java program, such as an application, applet, or servlet. The client view of an entity bean can also be mapped to non-Java client environments, such as CORBA clients not written in the Java programming language.

Multiple enterprise beans can be deployed in a container. For each entity bean deployed in a container, the container provides a class that implements the entity bean's home interface. The home interface allows the client to create, find, and remove entity objects within the enterprise bean's home. A client can look up the entity bean's home interface through JNDI API; it is the responsibility of the container to make the entity bean's home interface available in the JNDI API name space.

A client view of an entity bean is the same, irrespective of the implementation of the entity bean and its container. This ensures that a client application is portable across all container implementations in which the entity bean might be deployed.


EJB.8.2 EJB Container

An EJB container (container for short) is a system that functions as a runtime container for enterprise beans.

Multiple enterprise beans can be deployed in a single container. For each entity bean deployed in a container, the container provides a home interface that allows the client to create, find, and remove entity objects that belong to the entity bean. The container makes the entity beans' home interfaces (defined by the bean provider and implemented by the container provider) available in the JNDI API name space for clients.

An EJB server may host one or multiple EJB containers. The containers are transparent to the client: There is no client API to manipulate the container, and there is no way for a client to tell in which container an enterprise bean is installed.

EJB.8.2.1 Locating an Entity Bean's Home Interface

A client locates an entity bean's home interface using JNDI. For example, the home interface for the Account entity bean can be located using the following code segment:

Context initialContext = new InitialContext();
AccountHome accountHome = (AccountHome)
     javax.rmi.PortableRemoteObject.narrow(
           initialContext.lookup("java:comp/env/ejb/accounts"),
                            AccountHome.class);

A client's JNDI name space may be configured to include the home interfaces of enterprise beans deployed in multiple EJB containers located on multiple machines on a network. The actual location of an EJB container is, in general, transparent to the client.

EJB.8.2.2 What a Container Provides

Figure EJB.8-1 illustrates the view that a container provides to the clients of the entity beans deployed in the container.

Figure EJB.8-1. Client View of Entity Beans Deployed in a Container


EJB.8.3 Entity Bean's Home Interface

The container provides the implementation of the home interface for each entity bean deployed in the container. The container makes the home interface of every entity bean deployed in the container accessible to the clients through JNDI API. An object that implements an entity bean's home interface is called an EJBHome object.

The entity bean's home interface allows a client to do the following:

  • Create new entity objects within the home.

  • Find existing entity objects within the home.

  • Remove an entity object from the home.

  • Get the javax.ejb.EJBMetaData interface for the entity bean. The javax.ejb.EJBMetaData interface is intended to allow application assembly tools to discover the meta-data information about the entity bean. The metadata information allows loose client/server binding and scripting.

  • Obtain a handle for the home interface. The home handle can be serialized and written to stable storage; later, possibly in a different JVM, the handle can be deserialized from stable storage and used to obtain a reference to the home interface.

An entity bean's home interface must extend the javax.ejb.EJBHome interface and follow the standard rules for Java programming language remote interfaces.

EJB.8.3.1 create Methods

An entity bean's home interface can define zero or more create(...) methods, one for each way to create an entity object. The arguments of the create methods are typically used to initialize the state of the created entity object.

The return type of a create method is the entity bean's remote interface.

The throws clause of every create method includes the java.rmi.RemoteException and the javax.ejb.CreateException. It may include additional application-level exceptions.

The following home interface illustrates two possible create methods:

public interface AccountHome extends javax.ejb.EJBHome {
   public Account create(String firstName, String lastName,
      double initialBalance)
       throws RemoteException, CreateException;
   public Account create(String accountNumber,
      double initialBalance)
       throws RemoteException, CreateException,
         LowInitialBalanceException;
    ...
}

The following example illustrates how a client creates a new entity object:

AccountHome accountHome = ...;
Account account = accountHome.create("John", "Smith", 500.00);

EJB.8.3.2 finder Methods

An entity bean's home interface defines one or more finder methods, [1] one for each way to find an entity object or collection of entity objects within the home. The name of each finder method starts with the prefix find, such as findLargeAccounts(...). The arguments of a finder method are used by the entity bean implementation to locate the requested entity objects. The return type of a finder method must be the entity bean's remote interface, or a type representing a collection of objects that implement the entity bean's remote interface (see Section EJB.9.1.8).

[1] The findByPrimaryKey(primaryKey) method is mandatory for all entity beans.

The throws clause of every finder method includes the java.rmi.RemoteException and the javax.ejb.FinderException.

The home interface of every entity bean includes the findByPrimaryKey(primaryKey) method that allows a client to locate an entity object using a primary key. The name of the method is always findByPrimaryKey; it has a single argument that is the same type as the entity bean's primary key type, and its return type is the entity bean's remote interface. The implementation of the findByPrimaryKey(primaryKey) method must ensure that the entity object exists.

The following example shows the findByPrimaryKey method:

public interface AccountHome extends javax.ejb.EJBHome {
    ...
   public Account findByPrimaryKey(String AccountNumber)
      throws RemoteException, FinderException;
}

The following example illustrates how a client uses the findByPrimaryKey method:

AccountHome = ...;
Account account = accountHome.findByPrimaryKey("100-3450-3333");

EJB.8.3.3 remove Methods

The javax.ejb.EJBHome interface defines several methods that allow the client to remove an entity object.

public interface EJBHome extends Remote {
   void remove(Handle handle) throws RemoteException,
      RemoveException;
   void remove(Object primaryKey) throws RemoteException,
      RemoveException;
}

After an entity object has been removed, subsequent attempts to access the entity object by a client result in the java.rmi.NoSuchObjectException.


EJB.8.4 Entity Object's Life Cycle

This section describes the life cycle of an entity object from the perspective of a client.

Figure EJB.8-2 illustrates a client's point of view of an entity object life cycle. (The term referenced in the diagram means that the client program has a reference to the entity object's remote interface.)

Figure EJB.8-2. Client View of Entity Object Life Cycle

An entity object does not exist until it is created. Until it is created, it has no identity. After it is created, it has identity. A client creates an entity object using the entity bean's home interface whose class is implemented by the container. When a client creates an entity object, the client obtains a reference to the newly created entity object.

In an environment with legacy data, entity objects may "exist" before the container and entity bean are deployed. In addition, an entity object may be "created" in the environment via a mechanism other than by invoking a create(...) method of the home interface (e.g., by inserting a database record), but still may be accessible by a container's clients via the finder methods. Also, an entity object may be deleted directly using other means than the remove() operation (e.g., by deletion of a database record). The "direct insert" and "direct delete" transitions in the diagram represent such direct database manipulation.

A client can get a reference to an existing entity object's remote interface in any of the following ways:

  • Receive the reference as a parameter in a method call (input parameter or result).

  • Find the entity object using a finder method defined in the entity bean's home interface.

  • Obtain the reference from the entity object's handle (see Section EJB.8.7).

A client that has a reference to an entity object's remote interface can do any of the following:

  • Invoke business methods on the entity object through the remote interface.

  • Obtain a reference to the enterprise bean's home interface.

  • Pass the reference as a parameter or return value of a remote method call.

  • Obtain the entity object's primary key.

  • Obtain the entity object's handle.

  • Remove the entity object.

All references to an entity object that does not exist are invalid. All attempted invocations on an entity object that does not exist result in a java.rmi.NoSuchObjectException being thrown.

All entity objects are considered persistent objects. The lifetime of an entity object is not limited by the lifetime of the Java virtual machine process in which the entity bean instance executes. While a crash of the Java virtual machine may result in a rollback of current transactions, it does not destroy previously created entity objects nor invalidate the references to the remote and home interfaces held by clients.

Multiple clients can access the same entity object concurrently. Transactions are used to isolate the clients' work from each other.


EJB.8.5 Primary Key and Object Identity

Every entity object has a unique identity within its home. If two entity objects have the same home and the same primary key, they are considered identical.

The Enterprise JavaBeans architecture allows a primary key class to be any class that is a legal Value type in RMI-IIOP, subject to the restrictions defined in Section EJB.9.2.9. The primary key class may be specific to an entity bean class (i.e., each entity bean class may define a different class for its primary key, but it is possible that multiple entity beans use the same primary key class).

A client that holds a reference to an entity object's remote interface can determine the entity object's identity within its home by invoking the getPrimaryKey() method on the reference. The object identity associated with a reference does not change over the lifetime of the reference. (That is, getPrimaryKey() always returns the same value when called on the same entity object reference.)

A client can test whether two entity object references refer to the same entity object by using the isIdentical(EJBObject) method. Alternatively, if a client obtains two entity object references from the same home, it can determine if they refer to the same entity by comparing their primary keys using the equals method.

The following code illustrates using the isIdentical method to test if two object references refer to the same entity object:

Account acc1 = ...;
Account acc2 = ...;

if (acc1.isIdentical(acc2)) {
   acc1 and acc2 are the same entity object
} else {
   acc2 and acc2 are different entity objects
}

A client that knows the primary key of an entity object can obtain a reference to the entity object by invoking the findByPrimaryKey(key) method on the entity bean's home interface.

Note that the Enterprise JavaBeans architecture does not specify "object equality" (i.e., use of the == operator) for entity object references. The result of comparing two object references using the Java programming language Object.equals(Object obj) method is unspecified. Performing the Object.hashCode() method on two object references that represent the entity object is not guaranteed to yield the same result. Therefore, a client should always use the isIdentical method to determine if two entity object references refer to the same entity object.


EJB.8.6 Entity Bean's Remote Interface

A client accesses an entity object through the entity bean's remote interface. An entity bean's remote interface must extend the javax.ejb.EJBObject interface. A remote interface defines the business methods that are callable by clients.

The following example illustrates the definition of an entity bean's remote interface:

public interface Account extends javax.ejb.EJBObject {
   void debit(double amount)
      throws java.rmi.RemoteException,
         InsufficientBalanceException;
   void credit(double amount)
      throws java.rmi.RemoteException;
   double getBalance()
      throws java.rmi.RemoteException;
}

The javax.ejb.EJBObject interface defines the methods that allow the client to perform the following operations on an entity object's reference:

  • Obtain the home interface for the entity object.

  • Remove the entity object.

  • Obtain the entity object's handle.

  • Obtain the entity object's primary key.

The container provides the implementation of the methods defined in the javax.ejb.EJBObject interface. Only the business methods are delegated to the instances of the enterprise bean class.

Note that the entity object does not expose the methods of the javax.ejb.EnterpriseBean interface to the client. These methods are not intended for the client—they are used by the container to manage the enterprise bean instances.


EJB.8.7 Entity Bean's Handle

An entity object's handle is an object that identifies the entity object on a network. A client that has a reference to an entity object's remote interface can obtain the entity object's handle by invoking the getHandle() method on the remote interface.

Since a handle class extends java.io.Serializable, a client may serialize the handle. The client may use the serialized handle later, possibly in a different process or even system, to re-obtain a reference to the entity object identified by the handle.

The client code must use the javax.rmi.PortableRemoteObject.narrow(...) method to convert the result of the getEJBObject() method invoked on a handle to the entity bean's remote interface type.

The lifetime and scope of a handle are specific to the handle implementation. At the minimum, a program running in one Java virtual machine must be able to obtain and serialize the handle, and another program running in a different Java virtual machine must be able to deserialize it and re-create an object reference. An entity handle is typically implemented to be usable over a long period of time—it must be usable at least across a server restart.

Containers that store long-lived entities will typically provide handle implementations that allow clients to store a handle for a long time (possibly many years). Such a handle will be usable even if parts of the technology used by the container (e.g., ORB, DBMS, server) have been upgraded or replaced while the client has stored the handle. Support for this "quality of service" is not required by the EJB specification.

An EJB container is not required to accept a handle that was generated by another vendor's EJB container.

The use of a handle is illustrated by the following example:

// A client obtains a handle of an account entity object and
// stores the handle in stable storage.
//
ObjectOutputStream stream = ...;
Account account = ...;
Handle handle = account.getHandle();
stream.writeObject(handle);

// A client can read the handle from stable storage, and use the
// handle to resurrect an object reference to the
// account entity object.
//
ObjectInputStream stream = ...;
Handle handle = (Handle) stream.readObject(handle);
Account account = (Account)javax.rmi.PortableRemoteObject.narrow(
      handle.getEJBObject(), Account.class);
account.debit(100.00);

A handle is not a capability, in the security sense, that would automatically grant its holder the right to invoke methods on the object. When a reference to an object is obtained from a handle, and then a method on the object is invoked, the container performs the usual access checks based on the caller's principal.


EJB.8.8 Entity Home Handles

The EJB specification allows the client to obtain a handle for the home interface. The client can use the home handle to store a reference to an entity bean's home interface in stable storage, and recreate the reference later. This handle functionality may be useful to a client that needs to use the home interface in the future, but does not know the JNDI API name of the home interface.

A handle to a home interface must implement the javax.ejb.HomeHandle interface.

The client code must use the javax.rmi.PortableRemoteObject.narrow(...)method to convert the result of the getEJBHome() method invoked on a handle to the home interface type.

The lifetime and scope of a handle are specific to the handle implementation. At the minimum, a program running in one JVM must be able to serialize the handle, and another program running in a different JVM must be able to deserialize it and recreate an object reference. An entity handle is typically implemented to be usable over a long period of time—it must be usable at least across a server restart.


EJB.8.9 Type Narrowing of Object References

A client program that is intended to be interoperable with all compliant EJB container implementations must use the javax.rmi.PortableRemoteObject.narrow(...) method to perform type-narrowing of the client-side representations of the home and remote interface.

Note

Programs that use the cast operator to narrow the remote and home interfaces are likely to fail if the container implementation uses RMI-IIOP as the underlying communication transport.


Chapter EJB.9. Entity Bean Component Contract

Note

Container support for entity beans is a mandatory feature in the EJB 1.1 release.

The entity bean component contract is the contract between an entity bean and its container. It defines the life cycle of the entity bean instances and the model for method delegation of the client-invoked business methods. The main goal of this contract is to ensure that a component is portable across all compliant EJB containers.

This chapter defines the enterprise bean provider's view of this contract and the container provider's responsibility for managing the life cycle of the enterprise bean instances.


EJB.9.1 Concepts

EJB.9.1.1 Runtime Execution Model

This section describes the runtime model and the classes used in the description of the contract between an entity bean and its container. (See Figure EJB.9-1.)

Figure EJB.9-1. Overview of the Entity Bean Runtime Execution Model

An enterprise bean instance is an object whose class was provided by the bean provider.

An entity EJBObject is an object whose class was generated at deployment time by the container provider's tools. The entity EJBObject class implements the entity bean's remote interface. A client never references an entity bean instance directly—a client always references an entity EJBObject whose class is generated by the container provider's tools.

An entity EJBHome object provides the life cycle operations (create, remove, find) for its entity objects. The class for the entity EJBHome object is generated by the container provider's tools at deployment time. The entity EJBHome object implements the entity bean's home interface that was defined by the bean provider.

EJB.9.1.2 Granularity of Entity Beans

This section provides guidelines to the bean providers for modeling of business objects as entity beans.

In general, an entity bean should represent an independent business object that has an independent identity and life cycle, and is referenced by multiple enterprise beans and/or clients.

A dependent object should not be implemented as an entity bean. Instead, a dependent object is better implemented as a Java class (or several classes) and included as part of the entity bean on which it depends.

A dependent object can be characterized as follows. An object B is a dependent object of an object A, if B is created by A, accessed only by A, and removed by A. This implies, for example, that if B exists when A is being removed, B is automatically removed as well. It also implies that other programs can access the object B only indirectly through object A. In other words, the object A fully manages the life cycle of the object B.

For example, a purchase order might be implemented as an entity bean, but the individual line items on the purchase order should be implemented as helper classes, not as entity beans. An employee record might be implemented as an entity bean, but the employee address and phone number should be implemented as helper classes, not as entity beans.

The state of an entity object that has dependent objects is often stored in multiple records in multiple database tables.

In addition, the bean provider must take into consideration the following factors when making a decision on the granularity of an entity object:

  • Every method call to an entity object via the remote and home interface is potentially a remote call. Even if the calling and called entity beans are collocated in the same Java virtual machine, the call must go through the container, which must create copies of all the parameters that are passed through the interface by value (i.e., all parameters that do not extend the java.rmi.Remote interface). The container is also required to check security and apply the declarative transaction attribute on the inter-component calls. The over-head of an inter-component call will likely be prohibitive for object interactions that are too fine-grained.

  • The EJB deployment descriptor does not provide a mechanism for describing object schemas (the relationships among the fine-grained objects, and how fine-grained objects are mapped to the underlying database). If these relationships need to be visible at deployment time, the information describing the relationships must be passed from the bean provider to the deployer through some means outside of the EJB specification.

EJB.9.1.3 Entity Persistence (Data Access Protocol)

An entity bean implements an object view of an entity stored in an underlying database, or an entity implemented by an existing enterprise application (for example, by a mainframe program or by an ERP application). The data access protocol for transferring the state of the entity between the entity bean instances and the underlying database is referred to as object persistence.

The entity bean component protocol allows the entity bean provider either to implement the entity bean's persistence directly in the entity bean class or in one or more helper classes provided with the entity bean class (bean-managed persistence), or to delegate the entity bean's persistence to the container provider tools used at deployment time (container-managed persistence).

In many cases, the underlying data source may be an existing application rather than a database. (See Figure EJB.9-2.)

Figure EJB.9-2. Client View of Underlying Data Sources Accessed Through Entity Bean

EJB.9.1.3.1 Bean-Managed Persistence

In the bean-managed persistence case, the entity bean provider writes database access calls (e.g., using JDBC API technology or SQLJ) directly in the entity bean component. The data access calls are performed in the ejbCreate(...), ejbRemove(), ejbFind<METHOD>(), ejbLoad(), and ejbStore() methods and/or in the business methods.

The data access calls can be coded directly into the entity bean class, or they can be encapsulated in a data access component that is part of the entity bean.

We expect that most enterprise beans will be created by application development tools which will encapsulate data access in components. These data access components will probably not be the same for all tools. This EJB specification does not define the architecture for data access objects or strategies.

Directly coding data access calls in the entity bean class may make it more difficult to adapt the entity bean to work with a database that has a different schema, or with a different type of database.

If the data access calls are encapsulated in data access components, the data access components may optionally provide deployment interfaces to allow adapting data access to different schemas or even to a different database type. These data access component strategies are beyond the scope of the EJB specification.

EJB.9.1.3.2 Container-Managed Persistence

In the container-managed persistence case, the bean provider does not write the database access calls in the entity bean. Instead, the container provider's tools generate the database access calls at the entity bean's deployment time (i.e., when the entity bean is installed into a container). The entity bean provider must specify in the deployment descriptor the list of the instance fields for which the container provider tools must generate access calls.

The advantage of using container-managed persistence is that the entity bean can be largely independent from the data source in which the entity is stored. The container tools can generate classes that use JDBC API or SQLJ to access the entity state in a relational database, or classes that implement access to a non-relational data source, such as an IMS database, or classes that implement function calls to existing enterprise applications.

The disadvantage is that sophisticated tools must be used at deployment time to map the entity bean's fields to a data source. These tools and containers are typically specific to each data source.

The essential difference between an entity with bean-managed persistence and one with container-managed persistence is that in the bean-managed case, the data access components are provided as part of the entity bean, whereas in the container-managed case, the data access components are generated at deployment time by the container tools.

EJB.9.1.4 Instance Life Cycle

An entity bean instance is in one of the following three states:

  • It does not exist.

  • Pooled state. An instance in the pooled state is not associated with any particular entity object identity.

  • Ready state. An instance in the ready state is assigned an entity object identity. (See Figure EJB.9-3.)

    Figure EJB.9-3. Life Cycle of an Entity Bean Instance

The following steps describe the life cycle of an entity bean instance:

  • An entity bean instance's life starts when the container creates the instance using newInstance(). The container then invokes the setEntityContext() method to pass the instance a reference to the EntityContext interface. The EntityContext interface allows the instance to invoke services provided by the container and to obtain the information about the caller of a client-invoked method.

  • The instance enters the pool of available instances. Each entity bean has its own pool. While the instance is in the available pool, the instance is not associated with any particular entity object identity. All instances in the pool are considered equivalent, and therefore any instance can be assigned by the container to any entity object identity at the transition to the ready state. While the instance is in the pooled state, the container may use the instance to execute any of the entity bean's finder methods (shown as ejbFind<METHOD>(...) in the diagram). The instance does not move to the ready state during the execution of a finder method.

  • An instance transitions from the pooled state to the ready state when the container selects that instance to service a client call to an entity object. There are two possible transitions from the pooled to the ready state: through the ejbCreate(...) and ejbPostCreate(...) methods, or through the ejbActivate() method. The container invokes the ejbCreate(...) and ejbPostCreate(...) methods when the instance is assigned to an entity object during entity object creation (i.e., when the client invokes a create method on the entity bean's home object). The container invokes the ejbActivate() method on an instance when an instance needs to be activated to service an invocation on an existing entity object—this occurs because there is no suitable instance in the ready state to service the client's call.

  • When an entity bean instance is in the ready state, the instance is associated with a specific entity object identity. While the instance is in the ready state, the container can invoke the ejbLoad() and ejbStore() methods zero or more times. A business method can be invoked on the instance zero or more times. Invocations of the ejbLoad() and ejbStore() methods can be arbitrarily mixed with invocations of business methods. The purpose of the ejbLoad and ejbStore methods is to synchronize the state of the instance with the state of the entity in the underlying data source—the container can invoke these methods whenever it determines a need to synchronize the instance's state.

  • The container can choose to passivate an entity bean instance within a transaction. To passivate an instance, the container first invokes the ejbStore method to allow the instance to synchronize the database state with the instance's state, and then the container invokes the ejbPassivate method to return the instance to the pooled state.

  • Eventually, the container will transition the instance to the pooled state. There are two possible transitions from the ready to the pooled state: through the ejbPassivate() method and through the ejbRemove() method. The container invokes the ejbPassivate() method when the container wants to disassociate the instance from the entity object identity without removing the entity object. The container invokes the ejbRemove() method when the container is removing the entity object (i.e., when the client invoked the remove() method on the entity object's remote interface, or one of the remove() methods on the entity bean's home interface).

  • When the instance is put back into the pool, it is no longer associated with an entity object identity. The container can assign the instance to any entity object within the same entity bean home.

  • An instance in the pool can be removed by calling the unsetEntityContext() method on the instance.

Notes:

  1. The EntityContext interface passed by the container to the instance in the setEntityContext method is an interface, not a class that contains static information. For example, the result of the EntityContext.getPrimaryKey() method might be different each time an instance moves from the pooled state to the ready state, and the result of the getCallerPrincipal() and isCallerInRole(...) methods may be different in each business method.

  2. A RuntimeException thrown from any method of the entity bean class (including the business methods and the callbacks invoked by the container) results in the transition to the "does not exist" state. The container must not invoke any method on the instance after a RuntimeException has been caught. From the client perspective, the corresponding entity object continues to exist. The client can continue accessing the entity object through its remote interface because the container can use a different entity bean instance to delegate the client's requests. Exception handling is described further in Chapter EJB.12.

  3. The container is not required to maintain a pool of instances in the pooled state. The pooling approach is an example of a possible implementation, but it is not the required implementation. Whether the container uses a pool or not has no bearing on the entity bean coding style.

EJB.9.1.5 The Entity Bean Component Contract

This section specifies the contract between an entity bean and its container. The contract specified here assumes the use of bean-managed persistence. The differences in the contract for container-managed persistence are defined in Section EJB.9.4.

EJB.9.1.5.1 Entity Bean Instance's View

The following describes the entity bean instance's view of the contract: The entity bean provider is responsible for implementing the following methods in the entity bean class:

  • A public constructor that takes no arguments. The container uses this constructor to create instances of the entity bean class.

  • public void setEntityContext(EntityContext ic);

    A container uses this method to pass a reference to the EntityContext interface to the entity bean instance. If the entity bean instance needs to use the EntityContext interface during its lifetime, it must remember the EntityContext interface in an instance variable.

    This method executes with an unspecified transaction context (refer to Section EJB.11.6.3 for how the container executes methods with an unspecified transaction context). An identity of an entity object is not available during this method.

    The instance can take advantage of the setEntityContext() method to allocate any resources that are to be held by the instance for its lifetime. Such resources cannot be specific to an entity object identity because the instance might be reused during its lifetime to serve multiple entity object identities.

  • public void unsetEntityContext();

    A container invokes this method before terminating the life of the instance.

    This method executes with an unspecified transaction context. An identity of an entity object is not available during this method.

    The instance can take advantage of the unsetEntityContext() method to free any resources that are held by the instance. (These resources typically had been allocated by the setEntityContext() method.)

  • public PrimaryKeyClass ejbCreate(...);

    There are zero[1] or more ejbCreate(...) methods, whose signatures match the signatures of the create(...) methods of the entity bean home interface. The container invokes an ejbCreate(...) method on an entity bean instance when a client invokes a matching create(...) method to create an entity object.

    [1] An entity enterprise bean has no ejbCreate(...) and ejbPostCreate(...) methods if it does not define any create methods in its home interface. Such an entity enterprise bean does not allow the clients to create new EJB objects. The enterprise bean restricts the clients to accessing entities that were created through direct database inserts.

    The implementation of the ejbCreate(...) method typically validates the client-supplied arguments, and inserts a record representing the entity object into the database. The method also initializes the instance's variables. The ejbCreate(...) method must return the primary key for the created entity object.

    An ejbCreate(...) method executes in the transaction context determined by the transaction attribute of the matching create(...) method, as described in Section EJB.11.6.2.

  • public void ejbPostCreate(...);

    For each ejbCreate(...) method, there is a matching ejbPostCreate(...) method that has the same input parameters but the return value is void. The container invokes the matching ejbPostCreate(...) method on an instance after it invokes the ejbCreate(...) method with the same arguments. The entity object identity is available during the ejbPostCreate(...) method. The instance may, for example, obtain the remote interface of the associated entity object and pass it to another enterprise bean as a method argument.

    An ejbPostCreate(...) method executes in the same transaction context as the previous ejbCreate(...) method.

  • public void ejbActivate();

    The container invokes this method on the instance when the container picks the instance from the pool and assigns it to a specific entity object identity. The ejbActivate() method gives the entity bean instance the chance to acquire additional resources that it needs while it is in the ready state.

    This method executes with an unspecified transaction context. The instance can obtain the identity of the entity object via the getPrimaryKey() or getEJBObject() method on the entity context. The instance can rely on the fact that the primary key and entity object identity will remain associated with the instance until the completion of ejbPassivate() or ejbRemove().

    Note that the instance should not use the ejbActivate() method to read the state of the entity from the database; the instance should load its state only in the ejbLoad() method.

  • public void ejbPassivate();

    The container invokes this method on an instance when the container decides to disassociate the instance from an entity object identity, and to put the instance back into the pool of available instances. The ejbPassivate() method gives the instance the chance to release any resources that should not be held while the instance is in the pool. (These resources typically had been allocated during the ejbActivate() method.)

    This method executes with an unspecified transaction context. The instance can still obtain the identity of the entity object via the getPrimaryKey() or getEJBObject() method of the EntityContext interface.

    Note that an instance should not use the ejbPassivate() method to write its state to the database; an instance should store its state only in the ejbStore() method.

  • public void ejbRemove();

    The container invokes this method on an instance as a result of a client's invoking a remove method. The instance is in the ready state when ejbRemove() is invoked and it will be entered into the pool when the method completes.

    This method executes in the transaction context determined by the transaction attribute of the remove method that triggered the ejbRemove method. The instance can still obtain the identity of the entity object via the getPrimaryKey() or getEJBObject() method of the EntityContext interface.

    The container synchronizes the instance's state before it invokes the ejbRemove method. This means that the state of the instance variables at the beginning of the ejbRemove method is the same as it would be at the beginning of a business method.

    An entity bean instance should use this method to remove the entity object's representation in the database.

    Since the instance will be entered into the pool, the state of the instance at the end of this method must be equivalent to the state of a passivated instance. This means that the instance must release any resource that it would normally release in the ejbPassivate() method.

  • public void ejbLoad();

    The container invokes this method on an instance in the ready state to inform the instance that it must synchronize the entity state cached in its instance variables from the entity state in the database. The instance must be prepared for the container to invoke this method at any time that the instance is in the ready state.

    If the instance is caching the entity state (or parts of the entity state), the instance must not use the previously cached state in the subsequent business method. The instance may take advantage of the ejbLoad method, for example, to refresh the cached state by reading it from the database.

    This method executes in the transaction context determined by the transaction attribute of the business method that triggered the ejbLoad method.

  • public void ejbStore();

    The container invokes this method on an instance to inform the instance that the instance must synchronize the entity state in the database with the entity state cached in its instance variables. The instance must be prepared for the container to invoke this method at any time that the instance is in the ready state.

    An instance must write any updates cached in the instance variables to the database in the ejbStore() method.

    This method executes in the same transaction context as the previous ejbLoad or ejbCreate method invoked on the instance. All business methods invoked between the previous ejbLoad or ejbCreate method and this ejbStore method are also invoked in the same transaction context.

  • public PrimaryKeyClass or collection ejbFind<METHOD>(...);

    The container invokes this method on the instance when the container selects the instance to execute a matching client-invoked find<METHOD>(...) method. The instance is in the pooled state (i.e., it is not assigned to any particular entity object identity) when the container selects the instance to execute the ejbFind<METHOD> method on it, and it is returned to the pooled state when the execution of the ejbFind<METHOD> method completes.

    The ejbFind<METHOD> method executes in the transaction context determined by the transaction attribute of the matching find(...) method, as described in Section EJB.11.6.2.

    The implementation of an ejbFind<METHOD> method typically uses the method's arguments to locate the requested entity object or a collection of entity objects in the database. The method must return a primary key or a collection of primary keys to the container (see Section EJB.9.1.8).

EJB.9.1.5.2 Container's View

This subsection describes the container's view of the state management contract. The container must call the following methods:

  • public void setEntityContext(ec);

    The container invokes this method to pass a reference to the EntityContext interface to the entity bean instance. The container must invoke this method after it creates the instance, and before it puts the instance into the pool of available instances.

    The container invokes this method with an unspecified transaction context. At this point, the EntityContext is not associated with any entity object identity.

  • public void unsetEntityContext();

    The container invokes this method when the container wants to reduce the number of instances in the pool. After this method completes, the container must not reuse this instance.

    The container invokes this method with an unspecified transaction context.

  • public PrimaryKeyClass ejbCreate(...);

    public void ejbPostCreate(...);

    The container invokes these two methods during the creation of an entity object as a result of a client invoking a create(...) method on the entity bean's home interface.

    The container first invokes the ejbCreate(...) method whose signature matches the create(...) method invoked by the client. The ejbCreate(...) method returns a primary key for the created entity object. The container creates an entity EJBObject reference for the primary key. The container then invokes a matching ejbPostCreate(...) method to allow the instance to fully initialize itself. Finally, the container returns the entity object's remote interface (i.e., a reference to the entity EJBObject) to the client.

    The container must invoke the ejbCreate(...) and ejbPostCreate(...) methods in the transaction context determined by the transaction attribute of the matching create(...) method, as described in Section EJB.11.6.2.

  • public void ejbActivate();

    The container invokes this method on an entity bean instance at activation time (i.e., when the instance is taken from the pool and assigned to an entity object identity). The container must ensure that the primary key of the associated entity object is available to the instance if the instance invokes the getPrimaryKey() or getEJBObject() method on its EntityContext interface.

    The container invokes this method with an unspecified transaction context.

    Note that instance is not yet ready for the delivery of a business method. The container must still invoke the ejbLoad() method prior to a business method.

  • public void ejbPassivate();

    The container invokes this method on an entity bean instance at passivation time (i.e., when the instance is being disassociated from an entity object identity and moved into the pool). The container must ensure that the identity of the associated entity object is still available to the instance if the instance invokes the getPrimaryKey() or getEJBObject() method on its entity context.

    The container invokes this method with an unspecified transaction context.

    Note that if the instance state has been updated by a transaction, the container must first invoke the ejbStore() method on the instance before it invokes ejbPassivate() on it.

  • public void ejbRemove();

    The container invokes this method before it ends the life of an entity object as a result of a client invoking a remove operation.

    The container invokes this method in the transaction context determined by the transaction attribute of the invoked remove method.

    The container must ensure that the identity of the associated entity object is still available to the instance in the ejbRemove() method (i.e., the instance can invoke the getPrimaryKey() or getEJBObject() method on its EntityContext in the ejbRemove() method).

    The container must ensure that the instance's state is synchronized from the state in the database before invoking the ejbRemove() method (i.e., if the instance is not already synchronized from the state in the database, the container must invoke ejbLoad before it invokes ejbRemove).

  • public void ejbLoad();

    The container must invoke this method on the instance whenever it becomes necessary for the instance to synchronize its instance state from its state in the database. The exact times that the container invokes ejbLoad depend on the configuration of the component and the container, and are not defined by the EJB architecture. Typically, the container will call ejbLoad before the first business method within a transaction to ensure that the instance can refresh its cached state of the entity object from the database. After the first ejbLoad within a transaction, the container is not required to recognize that the state of the entity object in the database has been changed by another transaction, and it is not required to notify the instance of this change via another ejbLoad call.

    The container must invoke this method in the transaction context determined by the transaction attribute of the business method that triggered the ejbLoad method.

  • public void ejbStore();

    The container must invoke this method on the instance whenever it becomes necessary for the instance to synchronize its state in the database with the state of the instance's fields. This synchronization always happens at the end of a transaction. However, the container may also invoke this method when it passivates the instance in the middle of a transaction, or when it needs to transfer the most recent state of the entity object to another instance for the same entity object in the same transaction (see Section EJB.11.7).

    The container must invoke this method in the same transaction context as the previously invoked ejbLoad or ejbCreate method.

  • public primary key type or collection ejbFind<METHOD>(...);

    The container invokes the ejbFind<METHOD>(...) method on an instance when a client invokes a matching find<METHOD>(...) method on the entity bean's home interface. The container must pick an instance that is in the pooled state (i.e., the instance is not associated with any entity object identity) for the execution of the ejbFind<METHOD>(...) method. If there is no instance in the pooled state, the container creates one and calls the setEntityContext(...) method on the instance before dispatching the finder method.

    After the ejbFind<METHOD>(...) method completes, the instance remains in the pooled state. The container may, but is not required to, activate the objects that were located by the finder using the transition through the ejbActivate() method.

    The container must invoke the ejbFind<METHOD>(...) method in the transaction context determined by the transaction attribute of the matching find(...) method, as described in Section EJB.11.6.2.

    If the ejbFind<METHOD> method is declared to return a single primary key, the container creates an entity EJBObject reference for the primary key and returns it to the client. If the ejbFind<METHOD> method is declared to return a collection of primary keys, the container creates a collection of entity EJBObject references for the primary keys returned from ejbFind<METHOD>, and returns the collection to the client. (See Section EJB.9.1.8 for information on collections.)

EJB.9.1.6 Operations Allowed in the Methods of the Entity Bean Class

Table EJB.9-1 defines the methods of an entity bean class in which the enterprise bean instances can access the methods of the javax.ejb.EntityContext interface, the java:comp/env environment naming context, resource managers, and other enterprise beans.

If an entity bean instance attempts to invoke a method of the EntityContext interface, and the access is not allowed in Table EJB.9-1, the container must throw the java.lang.IllegalStateException.

If an entity bean instance attempts to access a resource manager or an enterprise bean, and the access is not allowed in Table EJB.9-1, the behavior is undefined by the EJB architecture.

Table EJB.9-1. Operations Allowed in the Methods of an Entity Bean

Bean Method

Bean Method Can Perform the Following Operations

constructor

—

setEntityContext

unsetEntityContext

EntityContext methods: getEJBHome

JNDI access to java:comp/env

ejbCreate

EntityContext methods: getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly

JNDI access to java:comp/env

Resource manager access

Enterprise bean access

ejbPostCreate

EntityContext methods: getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject, getPrimaryKey

JNDI access to java:comp/env

Resource manager access

Enterprise bean access

ejbRemove

EntityContext methods: getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject, getPrimaryKey

JNDI access to java:comp/env

Resource manager access

Enterprise bean access

ejbFind

EntityContext methods: getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly

JNDI access to java:comp/env

Resource manager access

Enterprise bean access

ejbActivate

ejbPassivate

EntityContext methods: getEJBHome, getEJBObject, getPrimaryKey

JNDI access to java:comp/env

ejbLoad

ejbStore

EntityContext methods: getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject, getPrimaryKey

JNDI access to java:comp/env

Resource manager access

Enterprise bean access

business method from remote interface

EntityContext methods: getEJBHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject, getPrimaryKey

JNDI access to java:comp/env

Resource manager access

Enterprise bean access

Additional restrictions:

  • The getRollbackOnly and setRollbackOnly methods of the EntityContext interface should be used only in the enterprise bean methods that execute in the context of a transaction. The container must throw the java.lang.IllegalStateException if the methods are invoked while the instance is not associated with a transaction.

Reasons for disallowing operations:

  • Invoking the getEJBObject and getPrimaryKey methods is disallowed in the entity bean methods in which there is no entity object identity associated with the instance.

  • Invoking the getCallerPrincipal and isCallerInRole methods is disallowed in the entity bean methods for which the container does not have a client security context.

  • Invoking the getRollbackOnly and setRollbackOnly methods is disallowed in the entity bean methods for which the container does not have a meaningful transaction context. These are the methods that have the NotSupported, Never, or Supports transaction attribute.

  • Accessing resource managers and enterprise beans is disallowed in the entity bean methods for which the container does not have a meaningful transaction context or client security context.

EJB.9.1.7 Caching of Entity State and the ejbLoad and ejbStore Methods

An instance of an entity bean with bean-managed persistence can cache the entity object's state between business method invocations. An instance may choose to cache the entire entity object's state, part of the state, or no state at all.

The container-invoked ejbLoad and ejbStore methods assist the instance with the management of the cached entity object's state. The instance must handle the ejbLoad and ejbStore methods as follows:

  • When the container invokes the ejbStore method on the instance, the instance must push all cached updates of the entity object's state to the underlying database. The container invokes the ejbStore method at the end of a transaction, and may also invoke it at other times when the instance is in the ready state. (For example, the container may invoke ejbStore when passivating an instance in the middle of a transaction, or when transferring the instance's state to another instance to support distributed transactions in a multi-process server.)

  • When the container invokes the ejbLoad method on the instance, the instance must discard any cached entity object's state. The instance may, but is not required to, refresh the cached state by reloading it from the underlying database.

The following examples, which are illustrative but not prescriptive, show how an instance may cache the entity object's state:

  • An instance loads the entire entity object's state in the ejbLoad method and caches it until the container invokes the ejbStore method. The business methods read and write the cached entity state. The ejbStore method writes the updated parts of the entity object's state to the database.

  • An instance loads the most frequently used part of the entity object's state in the ejbLoad method and caches it until the container invokes the ejbStore method. Additional parts of the entity object's state are loaded as needed by the business methods. The ejbStore method writes the updated parts of the entity object's state to the database.

  • An instance does not cache any entity object's state between business methods. The business methods access and modify the entity object's state directly in the database. The ejbLoad and ejbStore methods have an empty implementation.

We expect that most entity developers will not manually code the cache management and data access calls in the entity bean class. We expect that they will rely on application development tools to provide various data access components that encapsulate data access and provide state caching.

EJB.9.1.7.1 ejbLoad and ejbStore with the NotSupported Transaction Attribute

The use of the ejbLoad and ejbStore methods for caching an entity object's state in the instance works well only if the container can use transaction boundaries to drive the ejbLoad and ejbStore methods. When the NotSupported [2] transaction attribute is assigned to a remote interface method, the corresponding enterprise bean class method executes with an unspecified transaction context (see Section EJB.11.6.3). This means that the container does not have any well-defined transaction boundaries to drive the ejbLoad and ejbStore methods on the instance.

[2] This applies also to the Never and Supports attributes.

Therefore, the ejbLoad and ejbStore methods are "unreliable" for the instances that the container uses to dispatch the methods with an unspecified transaction context. The following are the only guarantees that the container provides for the instances that execute the methods with an unspecified transaction context:

  • The container invokes at least one ejbLoad between ejbActivate and the first business method in the instance.

  • The container invokes at least one ejbStore between the last business method on the instance and the ejbPassivate method.

Because the entity object's state accessed between the ejbLoad and ejbStore method pair is not protected by a transaction boundary for the methods that execute with an unspecified transaction context, the bean provider should not attempt to use the ejbLoad and ejbStore methods to control caching of the entity object's state in the instance. Typically, the implementation of the ejbLoad and ejbStore methods should be a no-op (i.e., an empty method), and each business method should access the entity object's state directly in the database.

EJB.9.1.8 Finder Method Return Type

EJB.9.1.8.1 Single-Object Finder

Some finder methods (such as ejbFindByPrimaryKey) are designed to return at most one entity object. For these single-object finders, the result type of the find<METHOD>(...)method defined in the entity bean's home interface is the entity bean's remote interface. The result type of the corresponding ejbFind<METHOD>(...) method defined in the entity's implementation class is the entity bean's primary key type.

The following code illustrates the definition of a single-object finder.

// Entity's home interface
public AccountHome extends javax.ejb.EJBHome {
   ...
   Account findByPrimaryKey(AccountPrimaryKey primkey)
      throws FinderException, RemoteException;
   ...
}

// Entity's implementation class
public AccountBean implements javax.ejb.EntityBean {
   ...
   public AccountPrimaryKey ejbFindByPrimaryKey(
            AccountPrimaryKey primkey)
      throws FinderException
   {
      ...
   }
   ...
}
EJB.9.1.8.2 Multi-Object Finders

Some finder methods are designed to return multiple entity objects. For these multi-object finders, the result type of the find<METHOD>(...)method defined in the entity bean's home interface is a collection of objects implementing the entity bean's remote interface. The result type of the corresponding ejbFind<METHOD>(...) implementation method defined in the entity bean's implementation class is a collection of objects of the entity bean's primary key type.

The bean provider can choose two types to define a collection type for a finder:

  • The JDK™ 1.1 java.util.Enumeration interface

  • The Java™ 2 java.util.Collection interface

A bean provider that wants to ensure that the entity bean is compatible with containers and clients based on JDK™ 1.1 software must use the java.util.Enumeration interface for the finder's result type. [3]

[3] The finder will be also compatible with Java 2 platform-based containers and clients.

A bean provider targeting only containers and clients based on the Java 2 platform can use the java.util.Collection interface for the finder's result type.

The bean provider must ensure that the objects in the java.util.Enumeration or java.util.Collection returned from the ejbFind<METHOD>(...) method are instances of the entity bean's primary key class.

The following is an example of a multi-object finder method definition compatible with containers and clients that are based on both JDK 1.1 and the Java 2 platform:

// Entity's home interface
public AccountHome extends javax.ejb.EJBHome {
   ...
   java.util.Enumeration findLargeAccounts(double limit)
       throws FinderException, RemoteException;
   ...
}

// Entity's implementation class
public AccountBean implements javax.ejb.EntityBean {
   ...
   public java.util.Enumeration ejbFindLargeAccounts(
          double limit) throws FinderException
   {
      ...
   }
   ...
}

The following is an example of a multi-object finder method definition that is compatible only with containers and clients based on Java 2:

// Entity's home interface
public AccountHome extends javax.ejb.EJBHome {
   ...
   java.util.Collection findLargeAccounts(double limit)
      throws FinderException, RemoteException;
   ...
}

// Entity's implementation class
public AccountBean implements javax.ejb.EntityBean {
   ...
   public java.util.Collection ejbFindLargeAccounts(
          double limit) throws FinderException
   {
      ...
   }
   ...
}

EJB.9.1.9 Standard Application Exceptions for Entities

The EJB specification defines the following standard application exceptions:

  • javax.ejb.CreateException

  • javax.ejb.DuplicateKeyException

  • javax.ejb.FinderException

  • javax.ejb.ObjectNotFoundException

  • javax.ejb.RemoveException

This section describes the use of these exceptions by entity beans with bean-managed persistence. The use of the exceptions by entity beans with container-managed persistence is the same, with one additional element: The responsibilities for throwing the exceptions apply to the data access methods generated by the container provider's tools.

EJB.9.1.9.1 CreateException

From the client's perspective, a CreateException (or a subclass of CreateException) indicates that an application level error occurred during the create(...) operation. If a client receives this exception, the client does not know, in general, whether the entity object was created but not fully initialized, or not created at all. Also, the client does not know whether or not the transaction has been marked for rollback. (However, the client may determine the transaction status using the UserTransaction interface.)

The bean provider throws the CreateException (or subclass of CreateException) from the ejbCreate(...) and ejbPostCreate(...) methods to indicate an application-level error from the create or initialization operation. Optionally, the bean provider may mark the transaction for rollback before throwing this exception.

The bean provider is encouraged to mark the transaction for rollback only if data integrity would be lost if the transaction were committed by the client. Typically, when a CreateException is thrown, it leaves the database in a consistent state, allowing the client to recover. For example, ejbCreate may throw the CreateException to indicate that the some of the arguments to the create(...) methods are invalid.

The container treats the CreateException as any other application exception. See Section EJB.12.3.

EJB.9.1.9.2 DuplicateKeyException

The DuplicateKeyException is a subclass of CreateException. It is thrown by the ejbCreate(...) methods to indicate to the client that the entity object cannot be created because an entity object with the same key already exists. The unique key causing the violation may be the primary key, or another key defined in the underlying database.

Normally, the bean provider should not mark the transaction for rollback before throwing the exception.

When the client receives the DuplicateKeyException, the client knows that the entity was not created, and that the client's transaction has not typically been marked for rollback.

EJB.9.1.9.3 FinderException

From the client's perspective, a FinderException (or a subclass of FinderException) indicates that an application level error occurred during the find(...) operation. Typically, the client's transaction has not been marked for rollback because of the FinderException.

The bean provider throws the FinderException (or subclass of FinderException) from the ejbFind<METHOD>(...) methods to indicate an application-level error in the finder method. The bean provider should not, typically, mark the transaction for rollback before throwing the FinderException.

The container treats the FinderException as any other application exception. See Section EJB.12.3.

EJB.9.1.9.4 ObjectNotFoundException

The ObjectNotFoundException is a subclass of FinderException. It is thrown by the ejbFind<METHOD>(...) methods to indicate that the requested entity object does not exist.

Only single-object finders (see Section EJB.9.1.8) should throw this exception. Multi-object finders must not throw this exception. Multi-object finders should return an empty collection as an indication that no matching objects were found.

EJB.9.1.9.5 RemoveException

From the client's perspective, a RemoveException (or a subclass of RemoveException) indicates that an application level error occurred during a remove(...) operation. If a client receives this exception, the client does not know, in general, whether the entity object was removed or not. The client also does not know if the transaction has been marked for rollback. (However, the client may determine the transaction status using the UserTransaction interface.)

The bean provider throws the RemoveException (or subclass of RemoveException) from the ejbRemove() method to indicate an application-level error from the entity object removal operation. Optionally, the bean provider may mark the transaction for rollback before throwing this exception.

The bean provider is encouraged to mark the transaction for rollback only if data integrity would be lost if the transaction were committed by the client. Typically, when a RemoveException is thrown, it leaves the database in a consistent state, allowing the client to recover.

The container treats the RemoveException as any other application exception. See Section EJB.12.3.

EJB.9.1.10 Commit Options

The entity bean protocol is designed to give the container the flexibility to select the disposition of the instance state at transaction commit time. This flexibility allows the container to optimally manage the caching of an entity object's state and the association of an entity object identity with the enterprise bean instances.

The container can select from the following commit-time options:

  • Option A: The container caches a "ready" instance between transactions. The container ensures that the instance has exclusive access to the state of the object in the persistent storage. Therefore, the container does not have to synchronize the instance's state from the persistent storage at the beginning of the next transaction.

  • Option B: The container caches a "ready" instance between transactions. In contrast to Option A, in this option the container does not ensure that the instance has exclusive access to the state of the object in the persistent storage. Therefore, the container must synchronize the instance's state from the persistent storage at the beginning of the next transaction.

  • Option C: The container does not cache a "ready" instance between transactions. The container returns the instance to the pool of available instances after a transaction has completed.

Table EJB.9-2 provides a summary of the commit-time options.

Table EJB.9-2. Summary of Commit-Time Options

Write Instance State to Database

Instance Stays Ready

Instance State Remains Valid

Option A

Yes

Yes

Yes

Option B

Yes

Yes

No

Option C

Yes

No

No

Note that the container synchronizes the instance's state with the persistent storage at transaction commit for all three options.

The selection of the commit option is transparent to the entity bean implementation—the entity bean will work correctly regardless of the commit-time option chosen by the container. The bean provider writes the entity bean in the same way.

The object interaction diagrams in Section EJB.9.5.4 illustrate the three alternative commit options in detail.

EJB.9.1.11 Concurrent Access from Multiple Transactions

When writing the entity bean business methods, the bean provider does not have to worry about concurrent access from multiple transactions. The bean provider may assume that the container will ensure appropriate synchronization for entity objects that are accessed concurrently from multiple transactions.

The container typically uses one of the following implementation strategies to achieve proper synchronization. (These strategies are illustrative, not prescriptive.)

  • The container activates multiple instances of the entity bean, one for each transaction in which the entity object is being accessed (Figure EJB.9-4). The transaction synchronization is performed automatically by the underlying database during the database access calls performed by the business methods; and by the ejbLoad, ejbCreate, ejbStore, and ejbRemove methods. The database system provides all the necessary transaction synchronization; the container does not have to perform any synchronization logic. The commit-time options B and C in Section EJB.9.5.4 apply to this type of container.

    Figure EJB.9-4. Multiple Clients Can Access the Same Entity Object Using Multiple Instances

With this strategy, the type of lock acquired by ejbLoad leads to a trade-off. If ejbLoad acquires an exclusive lock on the instance's state in the database, then throughput of read-only transactions could be impacted. If ejbLoad acquires a shared lock and the instance is updated, then ejbStore will need to promote the lock to an exclusive lock. This may cause a deadlock if it happens concurrently under multiple transactions.

  • The container acquires exclusive access to the entity object's state in the database. The container activates a single instance (Figure EJB.9-5) and serializes the access from multiple transactions to this instance. The commit-time option A in Section EJB.9.5.4 applies to this type of container.

    Figure EJB.9-5. Multiple Clients Can Access the Same Entity Object Using a Single Instance

EJB.9.1.12 Non-Reentrant and Reentrant Instances

An entity bean provider entity can specify that an entity bean is non-reentrant. If an instance of a non-reentrant entity bean executes a client request in a given transaction context, and another request with the same transaction context arrives for the same entity object, the container will throw the java.rmi.RemoteException to the second request. This rule allows the bean provider to program the entity bean as single-threaded, non-reentrant code.

The functionality of some entity beans may require loopbacks in the same transaction context. An example of a loopback is when the client calls entity object A, A calls entity object B, and B calls back A in the same transaction context. The entity bean's method invoked by the loopback shares the current execution context (which includes the transaction and security contexts) with the bean's method invoked by the client.

If the entity bean is specified as non-reentrant in the deployment descriptor, the container must reject an attempt to reenter the instance via the entity bean's remote interface while the instance is executing a business method. (This can happen, for example, if the instance has invoked another enterprise bean, and the other enterprise bean tries to make a loopback call.) The container must reject the loopback call and throw the java.rmi.RemoteException to the caller. The container must allow the call if the bean's deployment descriptor specifies that the entity bean is reentrant.

Reentrant entity beans must be programmed and used with great caution. First, the bean provider must code the entity bean with the anticipation of a loopback call. Second, since the container cannot, in general, tell a loopback from a concurrent call from a different client, the client programmer must be careful to avoid code that could lead to a concurrent call in the same transaction context.

Concurrent calls in the same transaction context targeted at the same entity object are illegal and may lead to unpredictable results. Since the container cannot, in general, distinguish between an illegal concurrent call and a legal loopback, application programmers are encouraged to avoid using loopbacks. Entity beans that do not need callbacks should be marked as non-reentrant in the deployment descriptor, allowing the container to detect and prevent illegal concurrent calls from clients.


EJB.9.2 Responsibilities of the Enterprise Bean Provider

This section describes the responsibilities of an entity bean provider to ensure that the entity bean can be deployed in any EJB container.

The requirements are stated for the provider of an entity bean with bean-managed persistence. The differences for entities with container-managed persistence are defined in Section EJB.9.4.

EJB.9.2.1 Classes and Interfaces

The entity bean provider is responsible for providing the following class files:

  • Entity bean class and any dependent classes

  • Entity bean's remote interface

  • Entity bean's home interface

  • Primary key class

EJB.9.2.2 Enterprise Bean Class

The following are the requirements for an entity bean class:

  • The class must implement, directly or indirectly, the javax.ejb.EntityBean interface.

  • The class must be defined as public and must not be abstract.

  • The class must not be defined as final.

  • The class must define a public constructor that takes no arguments.

  • The class must not define the finalize() method.

  • The class may, but is not required to, implement the entity bean's remote interface. [4] If the class implements the entity bean's remote interface, the class must provide no-op implementations of the methods defined in the javax.ejb.EJBObject interface. The container will never invoke these methods on the bean instances at runtime.

    [4] If the entity bean class does implement the remote interface, care must be taken to avoid passing of this as a method argument or result. This potential error can be avoided by choosing not to implement the remote interface in the entity bean class.

  • A no-op implementation of these methods is required to avoid defining the entity bean class as abstract.

  • The entity bean class must implement the business methods, and the ejbCreate, ejbPostCreate, and ejbFind<METHOD> methods as described later in this section.

  • The entity bean class may have superclasses and/or superinterfaces. If the entity bean has superclasses, the business methods, the ejbCreate and ejbPostCreate methods, the finder methods, and the methods of the EntityBean interface may be implemented in the enterprise bean class or in any of its superclasses.

  • The entity bean class is allowed to implement other methods (for example, helper methods invoked internally by the business methods) in addition to the methods required by the EJB specification.

EJB.9.2.3 ejbCreate Methods

The entity bean class may define zero or more ejbCreate(...) methods whose signatures must follow these rules:

  • The method name must be ejbCreate.

  • The method must be declared as public.

  • The method must not be declared as final or static.

  • The return type must be the entity bean's primary key type.

  • The method argument and return value types must be legal types for RMI-IIOP.

  • The throws clause may define arbitrary application specific exceptions, including the javax.ejb.CreateException.

Compatibility Note

EJB 1.0 allowed the ejbCreate method to throw the java.rmi.RemoteException to indicate a non-application exception. This practice is deprecated in EJB 1.1—an EJB 1.1 compliant enterprise bean should throw the javax.ejb.EJBException or another java.lang.RuntimeException to indicate non-application exceptions to the container (see Section EJB.12.2.2).

The entity object created by the ejbCreate method must have a unique primary key. This means that the primary key must be different from the primary keys of all the existing entity objects within the same home. The ejbCreate method should throw the DuplicateKeyException on an attempt to create an entity object with a duplicate primary key. However, it is legal to reuse the primary key of a previously removed entity object.

EJB.9.2.4 ejbPostCreate Methods

For each ejbCreate(...) method, the entity bean class must define a matching ejbPostCreate(...) method, using the following rules:

  • The method name must be ejbPostCreate.

  • The method must be declared as public.

  • The method must not be declared as final or static.

  • The return type must be void.

  • The method arguments must be the same as the arguments of the matching ejbCreate(...) method.

  • The throws clause may define arbitrary application specific exceptions, including the javax.ejb.CreateException.

Compatibility Note

EJB 1.0 allowed the ejbPostCreate method to throw the java.rmi.RemoteException to indicate a non-application exception. This practice is deprecated in EJB 1.1—an EJB 1.1 compliant enterprise bean should throw the javax.ejb.EJBException or another java.lang.RuntimeException to indicate non-application exceptions to the container (see Section EJB.12.2.2).

EJB.9.2.5 ejbFind Methods

The entity bean class may also define additional ejbFind<METHOD>(...) finder methods.

The signatures of the finder methods must follow the following rules:

  • A finder method name must start with the prefix ejbFind (e.g., ejbFindByPrimaryKey, ejbFindLargeAccounts, ejbFindLateShipments).

  • A finder method must be declared as public.

  • The method must not be declared as final or static.

  • The method argument types must be legal types for RMI-IIOP.

  • The return type of a finder method must be the entity bean's primary key type, or a collection of primary keys (see Section EJB.9.1.8).

  • The throws clause may define arbitrary application specific exceptions, including the javax.ejb.FinderException.

  • Every entity bean must define the ejbFindByPrimaryKey method. The result type for this method must be the primary key type (i.e., the ejbFindByPrimaryKey method must be a single-object finder).

Compatibility Note

EJB 1.0 allowed the finder methods to throw the java.rmi.RemoteException to indicate a non-application exception. This practice is deprecated in EJB 1.1—an EJB 1.1 compliant enterprise bean should throw the javax.ejb.EJBException or another java.lang.RuntimeException to indicate non-application exceptions to the container (see Section EJB.12.2.2).

EJB.9.2.6 Business Methods

The entity bean class may define zero or more business methods whose signatures must follow these rules:

  • The method names can be arbitrary, but they must not start with ejb to avoid conflicts with the callback methods used by the EJB architecture.

  • The business method must be declared as public.

  • The method must not be declared as final or static.

  • The method argument and return value types must be legal types for RMI-IIOP.

  • The throws clause may define arbitrary application specific exceptions.

Compatibility Note

EJB 1.0 allowed the business methods to throw the java.rmi.RemoteException to indicate a non-application exception. This practice is deprecated in EJB 1.1—an EJB 1.1 compliant enterprise bean should throw the javax.ejb.EJBException or another java.lang.RuntimeException to indicate non-application exceptions to the container (see Section EJB.12.2.2).

EJB.9.2.7 Entity Bean's Remote Interface

The following are the requirements for the entity bean's remote interface:

  • The interface must extend the javax.ejb.EJBObject interface.

  • The methods defined in the remote interface must follow the rules for RMI-IIOP. This means that their argument and return value types must be valid types for RMI-IIOP, and their throws clauses must include the java.rmi.RemoteException.

  • The remote interface is allowed to have superinterfaces. Use of interface inheritance is subject to the RMI-IIOP rules for the definition of remote interfaces.

  • For each method defined in the remote interface, there must be a matching method in the entity bean's class. The matching method must have:

    - The same name.

    - The same number and types of its arguments, and the same return type.

    - All the exceptions defined in the throws clause of the matching method of the enterprise bean class must be defined in the throws clause of the method of the remote interface.

EJB.9.2.8 Entity Bean's Home Interface

The following are the requirements for the entity bean's home interface:

The interface must extend the javax.ejb.EJBHome interface.

  • The methods defined in this interface must follow the rules for RMI-IIOP. This means that their argument and return types must be of valid types for RMI-IIOP, and that their throws clause must include the java.rmi.RemoteException.

  • The home interface is allowed to have superinterfaces. Use of interface inheritance is subject to the RMI-IIOP rules for the definition of remote interfaces.

  • Each method defined in the home interface must be one of the following:

    - A create method

    - A finder method

  • Each create method must be named create, and it must match one of the ejbCreate methods defined in the enterprise bean class. The matching ejbCreate method must have the same number and types of its arguments. (Note that the return type is different.)

  • The return type for a create method must be the entity bean's remote interface type.

  • All the exceptions defined in the throws clause of the matching ejbCreate and ejbPostCreate methods of the enterprise bean class must be included in the throws clause of the matching create method of the home interface (i.e., the set of exceptions defined for the create method must be a superset of the union of exceptions defined for the ejbCreate and ejbPostCreate methods).

  • The throws clause of a create method must include the javax.ejb.CreateException.

  • Each finder method must be named find<METHOD> (e.g., findLargeAccounts), and it must match one of the ejbFind<METHOD> methods defined in the entity bean class (e.g., ejbFindLargeAccounts). The matching ejbFind<METHOD> method must have the same number and types of arguments. (Note that the return type may be different.)

  • The return type for a find<METHOD> method must be the entity bean's remote interface type (for a single-object finder), or a collection thereof (for a multi-object finder).

  • The home interface must always include the findByPrimaryKey method, which is always a single-object finder. The method must declare the primary key class as the method argument.

  • All the exceptions defined in the throws clause of an ejbFind method of the entity bean class must be included in the throws clause of the matching find method of the home interface.

  • The throws clause of a finder method must include the javax.ejb.FinderException.

EJB.9.2.9 Entity Bean's Primary Key Class

The bean provider must specify a primary key class in the deployment descriptor.

The primary key type must be a legal value type in RMI-IIOP.

The class must provide suitable implementation of the hashCode() and equals(Object other) methods to simplify the management of the primary keys by client code.


EJB.9.3 The Responsibilities of the Container Provider

This section describes the responsibilities of the container provider to support entity beans. The container provider is responsible for providing the deployment tools, and for managing entity bean instances at runtime.

Because the EJB specification does not define the API between deployment tools and the container, we assume that the deployment tools are provided by the container provider. Alternatively, the deployment tools may be provided by a different vendor who uses the container vendor's specific API.

EJB.9.3.1 Generation of Implementation Classes

The deployment tools provided by the container provider are responsible for the generation of additional classes when the entity bean is deployed. The tools obtain the information that they need for generation of the additional classes by intro-specting the classes and interfaces provided by the entity bean provider and by examining the entity bean's deployment descriptor.

The deployment tools must generate the following classes:

  • A class that implements the entity bean's home interface (i.e., the entity EJBHome class)

  • A class that implements the entity bean's remote interface (i.e., the entity EJBObject class)

The deployment tools may also generate a class that mixes some container-specific code with the entity bean class. The code may, for example, help the container to manage the entity bean instances at runtime. Tools can use subclassing, delegation, and code generation.

The deployment tools may also allow generation of additional code that wraps the business methods and that is used to customize the business logic for an existing operational environment. For example, a wrapper for a debit function on the Account bean may check that the debited amount does not exceed a certain limit, or perform security checking that is specific to the operational environment.

EJB.9.3.2 Entity EJBHome Class

The entity EJBHome class, which is generated by deployment tools, implements the entity bean's home interface. This class implements the methods of the javax.ejb.EJBHome interface, and the type-specific create and finder methods specific to the entity bean.

The implementation of each create(...) method invokes a matching ejbCreate(...) method, followed by the matching ejbPostCreate(...) method, passing the create(...) parameters to these matching methods.

The implementation of the remove(...) methods defined in the javax.ejb.EJBHome interface must activate an instance (if an instance is not already in the ready state) and invoke the ejbRemove method on the instance.

The implementation of each find<METHOD>(...) method invokes a matching ejbFind<METHOD>(...) method. The implementation of the find<METHOD>(...) method must create an entity object reference for the primary key returned from the ejbFind<METHOD> and return the entity object reference to the client. If the ejbFind<METHOD> method returns a collection of primary keys, the implementation of the find<METHOD>(...) method must create a collection of entity object references for the primary keys and return the collection to the client.

EJB.9.3.3 Entity EJBObject Class

The entity EJBObject class, which is generated by deployment tools, implements the entity bean's remote interface. It implements the methods of the javax.ejb.EJBObject interface and the business methods specific to the entity bean.

The implementation of the remove(...) method (defined in the javax.ejb.EJBObject interface) must activate an instance (if an instance is not already in the ready state) and invoke the ejbRemove method on the instance.

The implementation of each business method must activate an instance (if an instance is not already in the ready state) and invoke the matching business method on the instance.

EJB.9.3.4 Handle Class

The deployment tools are responsible for implementing the handle class for the entity bean. The handle class must be serializable by the Java programming language Serialization protocol.

As the handle class is not entity bean specific, the container may, but is not required to, use a single class for all deployed entity beans.

EJB.9.3.5 Home Handle Class

The deployment tools are responsible for implementing the home handle class for the entity bean. The handle class must be serializable by the Java programming language Serialization protocol.

Because the home handle class is not entity bean specific, the container may, but is not required to, use a single class for the home handles of all deployed entity beans.

EJB.9.3.6 Meta-Data Class

The deployment tools are responsible for implementing the class that provides meta-data information to the client view contract. The class must be a valid RMI-IIOP value type, and must implement the javax.ejb.EJBMetaData interface.

Because the meta-data class is not entity bean specific, the container may, but is not required to, use a single class for all deployed enterprise beans.

EJB.9.3.7 Instance's Reentrance

The container runtime must enforce the rules defined in Section EJB.9.1.12.

EJB.9.3.8 Transaction Scoping, Security, Exceptions

The container runtime must follow the rules on transaction scoping, security checking, and exception handling described in Chapters EJB.11, EJB.15, and EJB.12.

EJB.9.3.9 Implementation of Object References

The container should implement the distribution protocol between the client and the container such that the object references of the home and remote interfaces used by entity bean clients are usable for a long period of time. Ideally, a client should be able to use an object reference across a server crash and restart. An object reference should become invalid only when the entity object has been removed, or after a reconfiguration of the server environment (for example, when the entity bean is moved to a different EJB server or container).

The motivation for this is to simplify the programming model for the entity bean client. While the client code needs to have a recovery handler for the system exceptions thrown from the individual method invocations on the home and remote interface, the client should not be forced to reobtain the object references.


EJB.9.4 Entity Beans with Container-Managed Persistence

The previous sections described the component contract for entity beans with bean-managed persistence. The contract for an entity bean with container-managed persistence is the same as the contract for an entity bean with bean-managed persistence (as described in the previous sections), except for the differences described in this section.

The deployment descriptor for an entity bean indicates whether the entity bean uses bean-managed persistence or container-managed persistence.

EJB.9.4.1 Container-Managed Fields

An entity bean with container-managed persistence relies on the container provider's tools to generate methods that perform data access on behalf of the entity bean instances. The generated methods transfer data between the entity bean instance's variables and the underlying resource manager at the times defined by the EJB specification. The generated methods also implement the creation, removal, and lookup of the entity object in the underlying database.

An entity bean with container-manager persistence must not code explicit data access—all data access must be deferred to the container.

The bean provider is responsible for using the cmp-field elements of the deployment descriptor to declare the instance's fields that the container must load and store at the defined times. The fields must be defined in the entity bean class as public, and must not be defined as transient.

The container is responsible for transferring data between the entity bean's instance variables and the underlying data source before or after the execution of the ejbCreate, ejbRemove, ejbLoad, and ejbStore methods, as described in the following subsections. The container is also responsible for the implementation of the finder methods.

The following requirements ensure that an entity bean can be deployed in any compliant container.

  • The bean provider must ensure that the Java programming language types assigned to the container-managed fields are restricted to the following: Java programming language primitive types, Java programming language serializable types, and references of enterprise beans' remote or home interfaces.

  • The container provider may, but is not required to, use Java programming language serialization to store the container-managed fields in the database. If the container chooses a different approach, the effect should be equivalent to that of Java programming language serialization. The container must also be capable of persisting references to enterprise beans' remote and home interfaces (for example, by storing their handle or primary key).

Although the above requirements allow the bean provider to specify almost any arbitrary type for the container-managed fields, we expect that in practice the bean provider will use relatively simple Java programming language types, and that most containers will be able to map these simple Java programming language types to columns in a database schema to externalize the entity state in the database, rather than use Java programming language serialization.

If the bean provider expects that the container-managed fields will be mapped to database fields, he should provide mapping instructions to the deployer. The mapping between the instance's container-managed fields and the schema of the underlying database manager will be then realized by the data access classes generated by the container provider's tools. Because entity beans are typically coarse-grained objects, the content of the container-managed fields may be stored in multiple rows, possibly spread across multiple database tables. These mapping techniques are beyond the scope of the EJB specification, and do not have to be supported by an EJB compliant container. (The container may simply use the Java serialization protocol in all cases.)

Because a compliant EJB container is not required to provide any support for mapping the container-managed fields to a database schema, a bean provider of entity beans that need a particular mapping to an underlying database schema instead should use bean-managed persistence.

The provider of entity beans with container-managed persistence must take into account the following limitations of the container-managed persistence protocol:

  • Data aliasing problems. If container-managed fields of multiple entity beans map to the same data item in the underlying database, the entity beans may see an inconsistent view of the data item if the multiple entity beans are invoked in the same transaction. (That is, an update of the data item done through a container-managed field of one entity bean may not be visible to another entity bean in the same transaction if the other entity bean maps to the same data item.)

  • Eager loading of state. The container loads the entire entity object state into the container-managed fields before invoking the ejbLoad method. This approach may not be optimal for entity objects with large states if most business methods require access to only parts of the state.

An entity bean designer who runs into the limitations of the container-managed persistence should use bean-managed persistence instead.

EJB.9.4.2 ejbCreate, ejbPostCreate

With bean-managed persistence, the entity bean provider is responsible for writing the code that inserts a record into the database in the ejbCreate(...) methods. However, with container-managed persistence, the container performs the database insert after the ejbCreate(...) method completes.

The container must ensure that the values of the container-managed fields are set to the Java language defaults (e.g., 0 for integer, null for pointers) prior to invoking an ejbCreate(...) method on an instance.

The entity bean provider's responsibility is to initialize the container-managed fields in the ejbCreate(...) methods from the input arguments such that when an ejbCreate(...) method returns, the container can extract the container-managed fields from the instance and insert them into the database.

The ejbCreate(...) methods must be defined to return the primary key class type. The implementation of the ejbCreate(...) methods should be coded to return a null. The returned value is ignored by the container.

Note

The above requirement is to allow the creation of an entity bean with bean-managed persistence by subclassing an entity bean with container-managed persistence. The Java programming language rules for overriding methods in subclasses require the signatures of the ejbCreate(...) methods in the subclass and the superclass to be the same.

The container is responsible for creating the entity object's representation in the underlying database, extracting the primary key fields of the newly created entity object representation in the database, and for creating an entity EJBObject reference for the newly created entity object. The container must establish the primary key before it invokes the ejbPostCreate(...) method. The container may cre-ate the representation of the entity in the database immediately after ejbCreate(...) returns, or it can defer it to a later time (for example, to the time after the matching ejbPostCreate(...) has been called, or to the end of the transaction).

Then container invokes the matching ejbPostCreate(...) method on the instance. The instance can discover the primary key by calling getPrimaryKey() on its entity context object.

The container must invoke ejbCreate, perform the database insert operation, and invoke ejbPostCreate in the transaction context determined by the transaction attribute of the matching create(...) method, as described in Section EJB.11.6.2.

The container throws the DuplicateKeyException if the newly created entity object would have the same primary key as one of the existing entity objects within the same home.

EJB.9.4.3 ejbRemove

The container invokes the ejbRemove() method on an entity bean instance with container-managed persistence in response to a client-invoked remove operation on the entity bean's home or remote interface.

The entity bean provider can use the ejbRemove method to implement any actions that must be done before the entity object's representation is removed from the database.

The container synchronizes the instance's state before it invokes the ejbRemove method. This means that the state of the instance variables at the beginning of the ejbRemove method is the same as it would be at the beginning of a business method.

After ejbRemove returns, the container removes the entity object's representation from the database.

The container must perform ejbRemove and the database delete operation in the transaction context determined by the transaction attribute of the invoked remove method, as described in Section EJB.11.6.2.

EJB.9.4.4 ejbLoad

When the container needs to synchronize the state of an enterprise bean instance with the entity object's state in the database, the container reads the entity object's state from the database into the container-managed fields and then it invokes the ejbLoad() method on the instance.

The entity bean provider can rely on the container's having loaded the container-managed fields from the database just before the container invokes the ejbLoad() method. The entity bean can use the ejbLoad() method, for instance, to perform some computation on the values of the fields that were read by the container (for example, uncompressing text fields).

EJB.9.4.5 ejbStore

When the container needs to synchronize the state of the entity object in the database with the state of the enterprise bean instance, the container first calls the ejbStore() method on the instance, and then it extracts the container-managed fields and writes them to the database.

The entity bean provider should use the ejbStore() method to set up the values of the container-managed fields just before the container writes them to the database. For example, the ejbStore() method may perform compression of text before the text is stored in the database.

EJB.9.4.6 Finder Methods

The entity bean provider does not write the finder (ejbFind<METHOD>(...)) methods.

The finder methods are generated at the entity bean deployment time using the container provider's tools. The tools can, for example, create a subclass of the entity bean class that implements the ejbFind<METHOD>() methods, or the tools can generate the implementation of the finder methods directly in the class that implements the entity bean's home interface.

Note that the ejbFind<METHOD> names and parameter signatures do not provide the container tools with sufficient information for automatically generating the implementation of the finder methods for methods other than ejbFindByPrimaryKey. Therefore, the bean provider is responsible for providing a description of each finder method. The entity bean deployer uses container tools to generate the implementation of the finder methods based in the description supplied by the bean provider. The Enterprise JavaBeans architecture does not specify the format of the finder method description.

EJB.9.4.7 Primary Key Type

The container must be able to manipulate the primary key type. Therefore, the primary key type for an entity bean with container-managed persistence must follow the rules in this subsection, in addition to those specified in Section EJB.9.2.9.

There are two ways to specify a primary key class for an entity bean with container-managed persistence:

  • Primary key that maps to a single field in the entity bean class.

  • Primary key that maps to multiple fields in the entity bean class.

The second method is necessary for implementing compound keys, and the first method is convenient for single-field keys. Without the first method, simple types such as string would have to be wrapped in a user-defined class.

EJB.9.4.7.1 Primary Key that Maps to a Single Field in the Entity Bean Class

The bean provider uses the primkey-field element of the deployment descriptor to specify the container-managed field of the entity bean class that contains the primary key. The field's type must be the primary key type.

EJB.9.4.7.2 Primary Key that Maps to Multiple Fields in the Entity Bean Class

The primary key class must be public, and must have a public constructor with no parameters.

All fields in the primary key class must be declared as public.

The names of the fields in the primary key class must be a subset of the names of the container-managed fields. (This allows the container to extract the primary key fields from an instance's container-managed fields, and vice versa.)

EJB.9.4.7.3 Special Case: Unknown Primary Key Class

In special situations, the entity bean provider may choose not to specify the primary key class for an entity bean with container-managed persistence. This case usually happens when the entity bean does not have a natural primary key, and the bean provider wants to allow the deployer to select the primary key fields at deployment time. The entity bean's primary key type will usually be derived from the primary key type used by the underlying database system that stores the entity objects. The primary key used by the database system may not be known to the bean provider.

When defining the primary key for the enterprise bean, the deployer may sometimes need to subclass the entity bean class to add additional container-managed fields (this typically happens for entity beans that do not have a natural primary key, and the primary keys are system-generated by the underlying database system that stores the entity objects).

In this special case, the type of the argument of the findByPrimaryKey method must be declared as java.lang.Object, and the return value of ejbCreate() must be declared as java.lang.Object. The bean provider must specify the primary key class in the deployment descriptor as of the type java.lang.Object.

The primary key class is specified at deployment time in the situations when the bean provider develops an entity bean that is intended to be used with multiple back-ends that provide persistence, and when these multiple back-ends require different primary key structures.

Use of entity beans with a deferred primary key type specification limits the client application programming model, because the clients written prior to deployment of the entity bean may not use, in general, the methods that rely on the knowledge of the primary key type.

The implementation of the enterprise bean class methods must be done carefully. For example, the methods should not depend on the type of the object returned from EntityContext.getPrimaryKey(), because the return type is determined by the deployer after the EJB class has been written.


EJB.9.5 Object Interaction Diagrams

This section uses object interaction diagrams to illustrate the interactions between an entity bean instance and its container.

EJB.9.5.1 Notes

The object interaction diagrams illustrate a box labeled "container-provided classes." These classes are either part of the container or are generated by the container tools. These classes communicate with each other through protocols that are container implementation specific. Therefore, the communication between these classes is not shown in the diagrams.

The classes shown in the diagrams should be considered as an illustrative implementation rather than as a prescriptive one.

EJB.9.5.2 Creating an Entity Object

See Figures EJB.9-6 and EJB.9-7 for the creation of an entity object with bean-managed and container-managed persistence.

Figure EJB.9-6. OID of Creation of an Entity Object with Bean-Managed Persistence

Figure EJB.9-7. OID of Creation of an Entity Object with Container-Managed Persistence

EJB.9.5.3 Passivating and Activating an Instance in a Transaction

See Figures EBJ.9-8 and EBJ.9-9 for the passivation and reactivation of unity bean instance with bean-managed persistence and CMP.

Figure EJB.9-8. OID of Passivation and Reactivation of an Entity Bean Instance with Bean-Managed Persistence

Figure EJB.9-9. OID of Passivation and Reactivation of an Entity Bean Instance with CMP

EJB.9.5.4 Committing a Transaction

See Figures EJB.9-10 and EJB.9-11 for the OID of transaction commit protocol for an entity bean instance with bean-managed persistence and container-managed persistence.

Figure EJB.9-10. OID of Transaction Commit Protocol for an Entity Bean Instance with Bean-Managed Persistence

Figure EJB.9-11. OID of Transaction Commit Protocol for an Entity Bean Instance with Container-Managed Persistence

EJB.9.5.5 Starting the Next Transaction

Figure EJB.9-12 illustrates the protocol performed for an entity bean instance with bean-managed persistence at the beginning of a new transaction. The three options illustrated in the diagram correspond to the three commit options in the previous subsection. Figure EJB.9-13 illustrates the same with container-managed persistence.

Figure EJB.9-12. OID of Start of Transaction for an Entity Bean Instance with Bean-Managed Persistence

Figure EJB.9-13. OID of Start of Transaction for an Entity Bean Instance with Container-Managed Persistence

EJB.9.5.6 Removing an Entity Object

See Figures EJB.9-14 and EJB.9-15 for the OID removal of an entity bean object with bean-managed and container-managed persistence.

Figure EJB.9-14. OID of Removal of an Entity Bean Object with Bean-Managed Persistence

Figure EJB.9-15. OID of Removal of an Entity Bean Object with Container-Managed Persistence

EJB.9.5.7 Finding an Entity Object

See Figures EJB.9-16 and EJB.9-17 for the OID of execution of a finder method on an entity bean instance with bean-managed and container-managed persistence.

Figure EJB.9-16. OID of Execution of a Finder Method on an Entity Bean Instance with Bean-Managed Persistence

Figure EJB.9-17. OID of Execution of a Finder Method on an Entity Bean Instance with Container-Managed Persistence

EJB.9.5.8 Adding and Removing an Instance from the Pool

The diagrams in Sections EJB.9.5.2 through EJB.9.5.7 did not show the sequences between the "does not exist" and "pooled" state (see the diagram in Section EJB.9.1.4). See Figures EJB.9-18 and EJB.9-19 for the OID of a container adding and removing an instance to the pool.

Figure EJB.9-18. OID of a Container Adding an Instance to the Pool

Figure EJB.9-19. OID of a Container Removing an Instance from the Pool


Chapter EJB.10. Example Entity Scenario

This chapter describes an example development and deployment scenario for an entity bean. We use the scenario to explain the responsibilities of the entity bean provider and those of the container provider.

The classes generated by the container provider's tools in this scenario should be considered illustrative rather than prescriptive. Container providers are free to implement the contract between an entity bean and its container in a different way that achieves an equivalent effect (from the perspectives of the entity bean provider and the client-side programmer).


EJB.10.1 Overview

Wombat Inc. has developed the AccountBean entity bean. The AccountBean entity bean is deployed in a container provided by the Acme Corporation.


EJB.10.2 Inheritance Relationship

Figure EJB.10-1 shows an example of the inheritance relationship.

Figure EJB.10-1. Example of the Inheritance Relationship Between the Interfaces and Classes

EJB.10.2.1 What the Entity Bean Provider Is Responsible For

Wombat Inc. is responsible for providing the following:

  • Define the entity bean's remote interface (Account). The remote interface defines the business methods callable by a client. The remote interface must extend the javax.ejb.EJBObject interface, and follow the standard rules for a RMI-IIOP remote interface. The remote interface must be defined as public.

  • Write the business logic in the entity bean class (AccountBean). The entity bean class may, but is not required to, implement the entity bean's remote interface (Account). The entity bean must implement the methods of the javax.ejb.EntityBean interface, the ejbCreate(...) and ejbPostCreate(...) methods invoked at an entity object creation, and the finder methods (the finders should not have to be implemented if the entity bean uses container-managed persistence).

  • Define a home interface (AccountHome) for the entity bean. The home interface defines the entity bean's specific create and finder methods. The home interface must be defined as public, extend the javax.ejb.EJBHome interface, and follow the standard rules for RMI-IIOP remote interfaces.

  • Define a deployment descriptor that specifies any declarative information that the entity bean provider wishes to pass with the entity bean to the next stage of the development/deployment workflow.

EJB.10.2.2 Classes Supplied by Container Provider

The following classes are supplied by the container provider, Acme Corporation:

  • The AcmeHome class provides the Acme implementation of the javax.ejb.EJBHome methods.

  • The AcmeRemote class provides the Acme implementation of the javax.ejb.EJBObject methods.

  • The AcmeBean class provides additional state and methods to allow Acme's container to manage its entity bean instances. For example, if Acme's container uses an LRU algorithm, then AcmeBean may include the clock count and methods to use it.

  • The AcmeMetaData class provides the Acme implementation of the javax.ejb.EJBMetaData methods.

EJB.10.2.3 What the Container Provider Is Responsible For

The tools provided by Acme Corporation are responsible for the following:

  • Generate the entity EJBOBject class (AcmeRemoteAccount) that implements the entity bean's remote interface. The tools also generate the classes that implement the communication protocol specific artifacts for the remote interface.

  • Generate the implementation of the entity bean class suitable for the Acme container (AcmeAccountBean). AcmeAccountBean includes the business logic from the AccountBean class mixed with the services defined in the AcmeBean class. Acme tools can use inheritance, delegation, and code generation to achieve mix-in of the two classes.

  • Generate the entity EJBHome class (AcmeAccountHome) for the entity bean that implements the entity bean's home interface (AccountHome). The tools also generate the classes that implement the communication protocol specific artifacts for the home interface.

  • Generate a class (AcmeAccountMetaData) that implements the javax.ejb.EJBMetaData interface for the Account Bean.

The above classes and tools are container-specific (i.e., they reflect the way Acme Corporation implemented them). Other container providers may use different mechanisms to produce their runtime classes, and the generated classes most likely will be different from those generated by Acme's tools.


Chapter EJB.11. Support for Transactions

One of the key features of the Enterprise JavaBeans architecture is support for distributed transactions. The Enterprise JavaBeans architecture allows an application developer to write an application that atomically updates data in multiple databases which may be distributed across multiple sites. The sites may use EJB servers from different vendors.


EJB.11.1 Overview

This section provides a brief overview of transactions and illustrates a number of transaction scenarios in EJB.

EJB.11.1.1 Transactions

Transactions are a proven technique for simplifying application programming. Transactions free the application programmer from dealing with the complex issues of failure recovery and multi-user programming. If the application programmer uses transactions, the programmer divides the application's work into units called transactions. The transactional system ensures that a unit of work either fully completes, or the work is fully rolled back. Furthermore, transactions make it possible for the programmer to design the application as if it ran in an environment that executes units of work serially.

Support for transactions is an essential component of the Enterprise JavaBeans architecture. The enterprise bean provider and the client application programmer are not exposed to the complexity of distributed transactions. The bean provider can choose between using programmatic transaction demarcation in the enterprise bean code (this style is called bean-managed transaction demarcation) or declarative transaction demarcation performed automatically by the EJB container (this style is called container-managed transaction demarcation).

With bean-managed transaction demarcation, the enterprise bean code demarcates transactions using the javax.transaction.UserTransaction interface. All resource manager [1] accesses between the UserTransaction.begin and UserTransaction.commit calls are part of a transaction.

[1] The terms resource and resource manager used in this chapter refer to the resources declared in the enterprise bean's deployment descriptor using the resource-ref element. These resources are considered to be "managed" by the container.

With container-managed transaction demarcation, the container demarcates transactions per instructions provided by the application assembler in the deployment descriptor. These instructions, called transaction attributes, tell the container whether it should include the work performed by an enterprise bean method in a client's transaction, run the enterprise bean method in a new transaction started by the container, or run the method with "no transaction" (refer to Section EJB.11.6.3 for the description of the "no transaction" case).

Regardless of whether an enterprise bean uses bean-managed or container-managed transaction demarcation, the burden of implementing transaction management is on the EJB container and server provider. The EJB container and server implement the necessary low-level transaction protocols, such as the two-phase commit protocol between a transaction manager and a database system, transaction context propagation, and distributed two-phase commit.

EJB.11.1.2 Transaction Model

The Enterprise JavaBeans architecture supports flat transactions. A flat transaction cannot have any child (nested) transactions.

Note

The decision not to support nested transactions allows vendors of existing transaction processing and database management systems to incorporate support for Enterprise JavaBeans. If these vendors provide support for nested transactions in the future, Enterprise JavaBeans may be enhanced to take advantage of nested transactions.

EJB.11.1.3 Relationship to JTA and JTS

The Java™ Transaction API (JTA) [EJB.5] is a specification of the interfaces between a transaction manager and the other parties involved in a distributed transaction processing system: the application programs, the resource managers, and the application server.

The Java Transaction Service (JTS) [EJB.6] API is a Java programming language binding of the CORBA Object Transaction Service (OTS) 1.1 specification. JTS provides transaction interoperability using the standard IIOP protocol for transaction propagation between servers. The JTS API is intended for vendors who implement transaction processing infrastructure for enterprise middleware. For example, an EJB server vendor may use a JTS implementation as the underlying transaction manager.

The EJB architecture does not require the EJB container to support the JTS interfaces. The EJB architecture requires that the EJB container support the javax.transaction.UserTransaction interface defined in JTA, but it does not require the support for the JTA resource and application server interfaces.


EJB.11.2 Sample Scenarios

This section describes several scenarios that illustrate the distributed transaction capabilities of the Enterprise JavaBeans architecture.

EJB.11.2.1 Update of Multiple Databases

The Enterprise JavaBeans architecture makes it possible for an application program to update data in multiple databases in a single transaction.

In Figure EJB.11-1, a client invokes the enterprise Bean X. X updates data using two database connections that the deployer configured to connect with two different databases, A and B. Then X calls another enterprise Bean Y. Y updates data in database C. The EJB server ensures that the updates to databases A, B, and C are either all committed or all rolled back.

Figure EJB.11-1. Updates to Simultaneous Databases

The application programmer does not have to do anything to ensure transactional semantics. The enterprise Beans X and Y perform the database updates using the standard JDBC API. Behind the scenes, the EJB server enlists the database connections as part of the transaction. When the transaction commits, the EJB server and the database systems perform a two-phase commit protocol to ensure atomic updates across all three databases.

EJB.11.2.2 Update of Databases via Multiple EJB Servers

The Enterprise JavaBeans architecture allows updates of data at multiple sites to be performed in a single transaction.

In Figure EJB.11-2, a client invokes the enterprise Bean X. X updates data in database A, and then calls another enterprise Bean Y that is installed in a remote EJB server. Y updates data in database B. The Enterprise JavaBeans architecture makes it possible to perform the updates to databases A and B in a single transaction.

Figure EJB.11-2. Updates to Multiple Databases in the Same Transaction

When X invokes Y, the two EJB servers cooperate to propagate the transaction context from X to Y. This transaction context propagation is transparent to the application-level code.

At transaction commit time, the two EJB servers use a distributed two-phase commit protocol (if the capability exists) to ensure the atomicity of the database updates.

EJB.11.2.3 Client-Managed Demarcation

A Java client can use the javax.transaction.UserTransaction interface to explicitly demarcate transaction boundaries. The client program obtains the javax.transaction.UserTransaction interface using JNDI API as defined in the Java 2 Platform, Enterprise Edition specification [EJB.10].

The EJB specification does not imply that the javax.transaction.UserTransaction is available to all Java clients. The Java 2 Platform, Enterprise Edition specification specifies the client environments in which the javax.transaction.UserTransaction interface is available.

A client program using explicit transaction demarcation may perform, via enterprise beans, atomic updates across multiple databases residing at multiple EJB servers, as illustrated in Figure EJB.11-3.

Figure EJB.11-3. Updates on Multiple Databases on Multiple Servers

The application programmer demarcates the transaction with begin and commit calls. If the enterprise beans X and Y are configured to use a client transaction (i.e., their methods have either the Required, Mandatory, or Supports transaction attribute), the EJB server ensures that the updates to databases A and B are made as part of the client's transaction.

EJB.11.2.4 Container-Managed Demarcation

Whenever a client invokes an enterprise bean, the container interposes on the method invocation. The interposition allows the container to control transaction demarcation declaratively through the transaction attribute set by the application assembler. (See Section EJB.11.4.1 for a description of transaction attributes.)

For example, if an enterprise bean method is configured with the Required transaction attribute, the container behaves as follows: If the client request is not associated with a transaction context, the container automatically initiates a transaction whenever a client invokes an enterprise bean method that requires a transaction context. If the client request contains a transaction context, the container includes the enterprise bean method in the client transaction.

Figure EJB.11-4 illustrates such a scenario. A non-transactional client invokes the enterprise bean X, and the invoked method has the Required transaction attribute. Because the message from the client does not include a transaction context, the container starts a new transaction before dispatching the remote method on X. X's work is performed in the context of the transaction. When X calls other enterprise beans (Y in our example), the work performed by the other enterprise beans is also automatically included in the transaction (subject to the transaction attribute of the other enterprise bean).

Figure EJB.11-4. Update of Multiple Databases from Non-Transactional Client

The container automatically commits the transaction at the time X returns a reply to the client.

EJB.11.2.5 Bean-Managed Demarcation

A session bean can use the javax.transaction.UserTransaction interface to programmatically demarcate transactions.

EJB.11.2.6 Interoperability with Non-Java Clients and Servers

Although the Enterprise JavaBeans architecture focuses on the Java API (and Java programming language) for writing distributed enterprise applications, it is desirable that such applications are also interoperable with non-Java clients and servers (Figure EJB.11-5).

Figure EJB.11-5. Interoperating with Non-Java Clients and/or Servers

A container can make it possible for an enterprise bean to be invoked from a non-Java client. For example, the CORBA mapping of the Enterprise JavaBeans architecture [EJB.8] allows any CORBA client to invoke any enterprise bean object on a CORBA-enabled server using the standard CORBA API.

Providing connectivity to existing server applications is also important. An EJB server may choose to provide access to existing enterprise applications, such as applications running under CICS on a mainframe. For example, an EJB server may provide a bridge that makes existing CICS programs accessible to enterprise beans. The bridge can make the CICS programs visible to the Java programming language–based developer as if the CICS programs were other enterprise beans installed in some container on the EJB server.

Note

It is beyond the scope of the Enterprise JavaBeans specification to define the bridging protocols that would enable such interoperability.


EJB.11.3 Bean Provider's Responsibilities

This section describes the bean provider's view of transactions and defines his responsibilities.

EJB.11.3.1 Bean-Managed Versus Container-Managed Transaction Demarcation

When designing an enterprise bean, the bean provider must decide whether the enterprise bean will demarcate transactions programmatically in the business methods (bean-managed transaction demarcation), or whether the transaction demarcation is to be performed by the container based on the transaction attributes in the deployment descriptor (container-managed transaction demarcation).

A session bean can be designed with bean-managed transaction demarcation or with container-managed transaction demarcation. (But it cannot be both at the same time.)

An entity bean must always be designed with container-managed transaction demarcation.

An enterprise bean instance can access resource managers in a transaction only in the enterprise bean's methods in which there is a transaction context available. Refer to Table EJB.6-1 on page 406, Table EJB.6-2 on page 417, and Table EJB.9-1 on page 459.

EJB.11.3.1.1 Non-Transactional Execution

Some enterprise beans may need to access resource managers that do not support an external transaction coordinator. The container cannot manage the transactions for such enterprise beans in the same way that it can for the enterprise beans that access resource managers that support an external transaction coordinator.

If an enterprise bean needs to access a resource manager that does not support an external transaction coordinator, the bean provider should design the enterprise bean with container-managed transaction demarcation and assign the NotSupported transaction attribute to all the bean's methods. The EJB architecture does not specify the transactional semantics of the enterprise bean methods. See Section EJB.11.6.3 for how the container implements this case.

EJB.11.3.2 Isolation Levels

Transactions not only make completion of a unit of work atomic, they also isolate the units of work from each other, provided that the system allows concurrent execution of multiple units of work.

The isolation level describes the degree to which the access to a resource manager by a transaction is isolated from the access to the resource manager by other concurrently executing transactions.

The following are guidelines for managing isolation levels in enterprise beans.

  • The API for managing an isolation level is resource-manager specific. (Therefore, the EJB architecture does not define an API for managing isolation level.)

  • If an enterprise bean uses multiple resource managers, the bean provider may specify the same or different isolation level for each resource manager. This means, for example, that if an enterprise bean accesses multiple resource managers in a transaction, access to each resource manager may be associated with a different isolation level.

  • The bean provider must take care when setting an isolation level. Most resource managers require that all accesses to the resource manager within a transaction are done with the same isolation levels. An attempt to change the isolation level in the middle of a transaction may cause undesirable behavior, such as an implicit sync point (a commit of the changes done so far).

  • For session beans with bean-managed transaction demarcation, the bean provider can specify the desirable isolation level programmatically in the enterprise bean's methods, using the resource-manager specific API. For example, the bean provider can use the java.sql.Connection.setTransactionIsolation(...) method to set the appropriate isolation level for database access.

  • For entity beans using container-managed persistence, transaction isolation is managed by the data access classes that are generated by the container provider's tools. The tools must ensure that the management of the isolation levels performed by the data access classes will not result in conflicting isolation level requests for a resource manager within a transaction.

  • Additional care must be taken if multiple enterprise beans access the same resource manager in the same transaction. Conflicts in the requested isolation levels must be avoided.

EJB.11.3.3 Enterprise Beans Using Bean-Managed Transaction Demarcation

This subsection describes the requirements for the bean provider of an enterprise bean with bean-managed transaction demarcation.

The enterprise bean with bean-managed transaction demarcation must be a session bean.

An instance that starts a transaction must complete the transaction before it starts a new transaction.

The bean provider uses the UserTransaction interface to demarcate transactions. All updates to the resource managers between the UserTransaction.begin() and UserTransaction.commit() methods are performed in a transaction. While an instance is in a transaction, the instance must not attempt to use the resource-manager specific transaction demarcation API (e.g., it must not invoke the commit() or rollback() method on the java.sql.Connection interface).

A stateful session bean instance may, but is not required to, commit a started transaction before a business method returns. If a transaction has not been completed by the end of a business method, the container retains the association between the transaction and the instance across multiple client calls until the instance eventually completes the transaction.

The bean-managed transaction demarcation programming model presented to the programmer of a stateful session bean is natural because it is the same as that used by a stand-alone Java application.

A stateless session bean instance must commit a transaction before a business method returns.

The following example illustrates a business method that performs a transaction involving two database connections.

public class MySessionEJB implements SessionBean {
   EJBContext ejbContext;

   public void someMethod(...) {
      javax.transaction.UserTransaction ut;
      javax.sql.DataSource ds1;
      javax.sql.DataSource ds2;
      java.sql.Connection con1;
      java.sql.Connection con2;
      java.sql.Statement stmt1;
      java.sql.Statement stmt2;

      InitialContext initCtx = new InitialContext();

      // obtain con1 object and set it up for transactions

      ds1 = (javax.sql.DataSource)
             initCtx.lookup("java:comp/env/jdbcDatabase1");
      con1 = ds1.getConnection();

      stmt1 = con1.createStatement();

      // obtain con2 object and set it up for transactions
      ds2 = (javax.sql.DataSource)
             initCtx.lookup("java:comp/env/jdbcDatabase2");
      con2 = ds2.getConnection();

      stmt2 = con2.createStatement();

      //
      // Now do a transaction that involves con1 and con2.
      //
      ut = ejbContext.getUserTransaction();

      // start the transaction
      ut.begin();

      // Do some updates to both con1 and con2. The Container
      // automatically enlists con1 and con2 with the transaction.
      stmt1.executeQuery(...);
      stmt1.executeUpdate(...);
      stmt2.executeQuery(...);
      stmt2.executeUpdate(...);
      stmt1.executeUpdate(...);
      stmt2.executeUpdate(...);

      // commit the transaction
      ut.commit();

      // release connections
      stmt1.close();
      stmt2.close();
      con1.close();
      con2.close();
   }
   ...
}

The following example illustrates a stateful session bean that retains a transaction across three client calls, invoked in the following order: method1, method2, and method3.

public class MySessionEJB implements SessionBean {
   EJBContext ejbContext;
   javax.sql.DataSource ds1;
   javax.sql.DataSource ds2;
   java.sql.Connection con1;
   java.sql.Connection con2;

   public void method1(...) {
      java.sql.Statement stmt;

      InitialContext initCtx = new InitialContext();

      // obtain user transaction interface
      ut = ejbContext.getUserTransaction();

      // start a transaction
      ut.begin();

      // make some updates on con1
      ds1 = (javax.sql.DataSource)
             initCtx.lookup("java:comp/env/jdbcDatabase1");
      con1 = ds1.getConnection();
      stmt = con1.createStatement();
      stmt.executeUpdate(...);
      stmt.executeUpdate(...);

      //
      // The container retains the transaction associated with the
      // instance to the next client call (which is method2(...)).
   }

   public void method2(...) {
      java.sql.Statement stmt;

      InitialContext initCtx = new InitialContext();

      // make some updates on con2
      ds2 = (javax.sql.DataSource)
             initCtx.lookup("java:comp/env/jdbcDatabase2");
      con2 = ds2.getConnection();
      stmt = con2.createStatement();
      stmt.executeUpdate(...);
      stmt.executeUpdate(...);

      // The container retains the transaction associated with the
      // instance to the next client call (which is method3(...)).
   }

   public void method3(...) {
      java.sql.Statement stmt;

      // obtain user transaction interface
      ut = ejbContext.getUserTransaction();

      // make some more updates on con1 and con2
      stmt = con1.createStatement();
      stmt.executeUpdate(...);
      stmt = con2.createStatement();
      stmt.executeUpdate(...);

      // commit the transaction
      ut.commit();

      // release connections
      stmt.close();
      con1.close();
      con2.close();
   }
   ...
}

It is possible for an enterprise bean to open and close a database connection in each business method (rather than hold the connection open until the end of transaction). In the following example, if the client executes the sequence of methods (method1, method2, method2, method2, and method3), all the database updates done by the multiple invocations of method2 are performed in the scope of the same transaction, which is the transaction started in method1 and committed in method3.

public class MySessionEJB implements SessionBean {
   EJBContext ejbContext;
   InitialContext initCtx;

   public void method1(...) {
      java.sql.Statement stmt;

      // obtain user transaction interface
      ut = ejbContext.getUserTransaction();

      // start a transaction
      ut.begin();
   }

   public void method2(...) {
      javax.sql.DataSource ds;
      java.sql.Connection con;
      java.sql.Statement stmt;

      // open connection
      ds = (javax.sql.DataSource)
            initCtx.lookup("java:comp/env/jdbcDatabase");
      con = ds.getConnection();

      // make some updates on con
      stmt = con.createStatement();
      stmt.executeUpdate(...);
      stmt.executeUpdate(...);

      // close the connection
      stmt.close();
      con.close();
   }

   public void method3(...) {
      // obtain user transaction interface
      ut = ejbContext.getUserTransaction();
      // commit the transaction
      ut.commit();
   }
   ...
}
EJB.11.3.3.1 getRollbackOnly() and setRollbackOnly() Methods

An enterprise bean with bean-managed transaction demarcation must not use the getRollbackOnly() and setRollbackOnly() methods of the EJBContext interface.

An enterprise bean with bean-managed transaction demarcation has no need to use these methods, because of the following reasons:

  • An enterprise bean with bean-managed transaction demarcation can obtain the status of a transaction by using the getStatus() method of the javax.transaction.UserTransaction interface.

  • An enterprise bean with bean-managed transaction demarcation can roll back a transaction using the rollback() method of the javax.transaction.UserTrasaction interface.

EJB.11.3.4 Enterprise Beans Using Container-Managed Transaction Demarcation

This subsection describes the requirements for the bean provider of an enterprise bean using container-managed transaction demarcation.

The enterprise bean's business methods must not use any resource-manager specific transaction management methods that would interfere with the container's demarcation of transaction boundaries. For example, the enterprise bean methods must not use the following methods of the java.sql.Connection interface: commit(), setAutoCommit(...), and rollback().

The enterprise bean's business methods must not attempt to obtain or use the javax.transaction.UserTransaction interface.

The following is an example of a business method in an enterprise bean with container-managed transaction demarcation. The business method updates two databases using JDBC API connections. The container provides transaction demarcation per the application assembler's instructions.

public class MySessionEJB implements SessionBean {
   EJBContext ejbContext;

   public void someMethod(...) {
      java.sql.Connection con1;
      java.sql.Connection con2;
      java.sql.Statement stmt1;
      java.sql.Statement stmt2;

      // obtain con1 and con2 connection objects
      con1 = ...;
      con2 = ...;

      stmt1 = con1.createStatement();
      stmt2 = con2.createStatement();

      //
      // Perform some updates on con1 and con2. The container
      // automatically enlists con1 and con2 with the container-
      // managed transaction.
      //
      stmt1.executeQuery(...);
      stmt1.executeUpdate(...);

      stmt2.executeQuery(...);
      stmt2.executeUpdate(...);

      stmt1.executeUpdate(...);
      stmt2.executeUpdate(...);

      // release connections
      con1.close();
      con2.close();
   }
   ...
}
EJB.11.3.4.1 javax.ejb.SessionSynchronization Interface

A stateful session bean with container-managed transaction demarcation can optionally implement the javax.ejb.SessionSynchronization interface. The use of the SessionSynchronization interface is described in Section EJB.6.5.2.

EJB.11.3.4.2 javax.ejb.EJBContext.setRollbackOnly() Method

An enterprise bean with container-managed transaction demarcation can use the setRollbackOnly() method of its EJBContext object to mark the transaction such that the transaction can never commit. Typically, an enterprise bean marks a transaction for rollback to protect data integrity before throwing an application exception, because application exceptions do not automatically cause the container to roll back the transaction.

For example, an AccountTransfer bean which debits one account and credits another account could mark a transaction for rollback if it successfully performs the debit operation, but encounters a failure during the credit operation.

EJB.11.3.4.3 javax.ejb.EJBContext.getRollbackOnly() Method

An enterprise bean with container-managed transaction demarcation can use the getRollbackOnly() method of its EJBContext object to test if the current transaction has been marked for rollback. The transaction might have been marked for rollback by the enterprise bean itself, by other enterprise beans, or by other components (outside the EJB specification scope) of the transaction processing infrastructure.

EJB.11.3.5 Declaration in Deployment Descriptor

The bean provider of a session bean must use the transaction-type element to declare whether the session bean is of the bean-managed or container-managed transaction demarcation type. (See Chapter EJB.16 for information about the deployment descriptor.)

The transaction-type element is not supported for entity beans because all entity beans must use container-managed transaction demarcation.

The bean provider of an enterprise bean with container-managed transaction demarcation may optionally specify the transaction attributes for the enterprise bean's methods. See Section EJB.11.4.1.


EJB.11.4 Application Assembler's Responsibilities

This section describes the view and responsibilities of the application assembler.

There is no mechanism for an application assembler to affect enterprise beans with bean-managed transaction demarcation. The application assembler must not define transaction attributes for an enterprise bean with bean-managed transaction demarcation.

The application assembler can use the transaction attribute mechanism described below to manage transaction demarcation for enterprise beans using container-managed transaction demarcation.

EJB.11.4.1 Transaction Attributes

Note

The transaction attributes may be specified either by the bean provider or by the application assembler.

A transaction attribute is a value associated with a method of an enterprise bean's remote or home interface. The transaction attribute specifies how the container must manage transactions for a method when a client invokes the business method via the enterprise bean home or remote interface.

The transaction attribute must be specified for the following remote and home interface methods:

  • For a session bean, the transaction attributes must be specified for the methods defined in the bean's remote interface and all the direct and indirect superinterfaces of the remote interface, excluding the methods of the javax.ejb.EJBObject interface. Transaction attributes must not be specified for the methods of a session bean's home interface.

  • For an entity bean, the transaction attributes must be specified for the methods defined in the bean's remote interface and all the direct and indirect superinterfaces of the remote interface, excluding the getEJBHome, getHandle, getPrimaryKey, and isIdentical methods; and for the methods defined in the bean's home interface and all the direct and indirect superinterfaces of the home interface, excluding the getEJBMetaData and getHomeHandle methods.

Providing the transaction attributes for an enterprise bean is an optional requirement for the application assembler, because, for a given enterprise bean, the application assembler must either specify a value of the transaction attribute for all the methods of the remote and home interfaces for which a transaction attribute must be specified, or the assembler must specify none. If the transaction attributes are not specified for the methods of an enterprise bean, the deployer will have to specify them.

Enterprise JavaBeans defines the following values for the transaction attribute:

  • NotSupported

  • Required

  • Supports

  • RequiresNew

  • Mandatory

  • Never

Refer to Section EJB.11.6.2 for the specification of how the value of the transaction attribute affects the transaction management performed by the container.

If an enterprise bean implements the javax.ejb.SessionSynchronization interface, the application assembler can specify only the following values for the transaction attributes of the bean's methods: Required, RequiresNew, or Mandatory.

The above restriction is necessary to ensure that the enterprise bean is invoked only in a transaction. If the bean were invoked without a transaction, the container would not be able to send the transaction synchronization calls.

The tools used by the application assembler can determine if the bean implements the javax.ejb.SessionSynchronization interface, for example, by using the Java programming language reflection API on the enterprise bean's class.

The following is the description of the deployment descriptor rules that the application assembler uses to specify transaction attributes for the methods of the enterprise beans' remote and home interfaces. (See Section EJB.16.5 for the complete syntax of the deployment descriptor.)

The application assembler uses the container-transaction elements to define the transaction attributes for the methods of the enterprise beans' remote and home interfaces. Each container-transaction element consists of a list of one or more method elements and the trans-attribute element. The container-transaction element specifies that all the listed methods are assigned the specified transaction attribute value. It is required that all the methods specified in a single container-transaction element be methods of the same enterprise bean.

The method element uses the ejb-name, method-name, and method-params elements to denote one or more methods of an enterprise bean's home and remote interfaces. There are three legal styles of composing the method element:

Style 1:
<method>
     <ejb-name>EJBNAME</ejb-name>
     <method-name>*</method-name>
</method>

This style is used to specify a default value of the transaction attribute for the methods for which there is no Style 2 or Style 3 element specified. There must be at most one container-transaction element that uses the Style 1 method element for a given enterprise bean.

Style 2:
<method>
     <ejb-name>EJBNAME</ejb-name>
     <method-name>METHOD</method-name>
</method>

This style is used for referring to a specified method of the remote or home interface of the specified enterprise bean. If there are multiple methods with the same overloaded name, this style refers to all the methods with the same name. There must be at most one container-transaction element that uses the Style 2 method element for a given method name. If there is also a container-transaction element that uses the Style 1 element for the same bean, the value specified by the Style 2 element takes precedence.

Style 3:
<method>
     <ejb-name>EJBNAME</ejb-name>
     <method-name>METHOD</method-name>
     <method-params>
          <method-param>PARAMETER_1</method-param>
          ...
          <method-param>PARAMETER_N</method-param>
     </method-params>
</method>

This style is used to refer to a single method within a set of methods with an overloaded name. The method must be one defined in the remote or home interface of the specified enterprise bean. If there is also a container-transaction ele-ment that uses the Style 2 element for the method name, or the Style 1 element for the bean, the value specified by the Style 3 element takes precedence.

The optional method-intf element can be used to differentiate between methods with the same name and signature that are defined in both the remote and home interfaces.

The following is an example of the specification of the transaction attributes in the deployment descriptor. The updatePhoneNumber method of the EmployeeRecord enterprise bean is assigned the transaction attribute Mandatory; all other methods of the EmployeeRecord bean are assigned the attribute Required. All the methods of the enterprise bean AardvarkPayroll are assigned the attribute RequiresNew.

<ejb-jar>
   ...
   <assembly-descriptor>
      ...
      <container-transaction>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Required</trans-attribute>
      </container-transaction>

      <container-transaction>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>updatePhoneNumber</method-name>
         </method>
         <trans-attribute>Mandatory</trans-attribute>
      </container-transaction>

      <container-transaction>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>RequiresNew</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>


EJB.11.5 Deployer's Responsibilities

The deployer is responsible for ensuring that the methods of the deployed enterprise beans with container-managed transaction demarcation have been assigned a transaction attribute. If the transaction attributes have not been assigned previously by the assembler, they must be assigned by the deployer.


EJB.11.6 Container Provider Responsibilities

This section defines the responsibilities of the container provider.

Every client method invocation on an enterprise bean object via the bean's remote and home interface is interposed by the container, and every connection to a resource manager used by an enterprise bean is obtained via the container. This managed execution environment allows the container to affect the enterprise bean's transaction management.

This does not imply that the container must interpose on every resource manager access performed by the enterprise bean. Typically, the container interposes only the resource manager connection factory (e.g., a JDBC API data source) JNDI API lookup by registering the container-specific implementation of the resource manager connection factory object. The resource manager connection factory object allows the container to obtain the XAResource interface as described in the JTA specification and pass it to the transaction manager. After the setup is done, the enterprise bean communicates with the resource manager without going through the container.

EJB.11.6.1 Bean-Managed Transaction Demarcation

This subsection defines the container's responsibilities for the transaction management of enterprise beans with bean-managed transaction demarcation.

Note that only session beans can be used with bean-managed transaction demarcation. A bean provider is not allowed to provide an entity bean with bean-managed transaction demarcation.

The container must manage client invocations to an enterprise bean instance with bean-managed transaction demarcation as follows. When a client invokes a business method via the enterprise bean's remote or home interface, the container suspends any transaction that may be associated with the client request. If there is a transaction associated with the instance (this would happen if the instance started the transaction in some previous business method), the container associates the method execution with this transaction.

The container must make the javax.transaction.UserTransaction interface available to the enterprise bean's business method via the javax.ejb.EJBContext interface and under the environment entry java:comp/UserTransaction. When an instance uses the javax.transaction.UserTransaction interface to demarcate a transaction, the container must enlist all the resource managers used by the instance between the begin() and commit()—or rollback()—methods with the transaction. When the instance attempts to commit the transaction, the container is responsible for the global coordination of the transaction commit. [2]

[2] The container typically relies on a transaction manager that is part of the EJB server to perform the two-phase commit across all the enlisted resource managers.

In the case of a stateful session bean, it is possible that the business method that started a transaction completes without committing or rolling back the transaction. In such a case, the container must retain the association between the transaction and the instance across multiple client calls until the instance commits or rolls back the transaction. When the client invokes the next business method, the container must invoke the business method in this transaction context.

If a stateless session bean instance starts a transaction in a business method, it must commit the transaction before the business method returns. The container must detect the case in which a transaction was started, but not completed, in the business method, and handle it as follows:

  • Log this as an application error to alert the system administrator.

  • Roll back the started transaction.

  • Discard the instance of the session bean.

  • Throw the java.rmi.RemoteException to the client.

The actions performed by the container for an instance with bean-managed transaction are summarized by Table EJB.11-1. T1 is a transaction associated with a client request, T2 is a transaction that is currently associated with the instance (i.e., a transaction that was started but not completed by a previous business method).

Table EJB.11-1. Container's Actions for Methods of Beans with Bean-Managed Transaction

Client's Transaction

Transaction Currently Associated with Instance

Transaction Associated with the Method

none

none

none

T1

none

none

none

T2

T2

T1

T2

T2

The following items describe each entry in the table:

  • If the client request is not associated with a transaction and the instance is not associated with a transaction, the container invokes the instance with an unspecified transaction context.

  • If the client is associated with a transaction T1, and the instance is not associated with a transaction, the container suspends the client's transaction association and invokes the method with an unspecified transaction context. The container resumes the client's transaction association (T1) when the method completes.

  • If the client request is not associated with a transaction and the instance is already associated with a transaction T2, the container invokes the instance with the transaction that is associated with the instance (T2). This case can never happen for a stateless session bean.

  • If the client is associated with a transaction T1, and the instance is already associated with a transaction T2, the container suspends the client's transaction association and invokes the method with the transaction context that is associated with the instance (T2). The container resumes the client's transaction association (T1) when the method completes. This case can never happen for a stateless session bean.

The container must allow the enterprise bean instance to serially perform several transactions in a method.

When an instance attempts to start a transaction using the begin() method of the javax.transaction.UserTransaction interface while the instance has not com-mitted the previous transaction, the container must throw the javax.transaction.NotSupportedException in the begin() method.

The container must throw the java.lang.IllegalStateException if an instance of a bean with bean-managed transaction demarcation attempts to invoke the setRollbackOnly() or getRollbackOnly() method of the javax.ejb.EJBContext interface.

EJB.11.6.2 Container-Managed Transaction Demarcation

The container is responsible for providing the transaction demarcation for the enterprise beans that the bean provider declared with container-managed transaction demarcation. For these enterprise beans, the container must demarcate transactions as specified in the deployment descriptor by the application assembler. (See Chapter EJB.16 for more information about the deployment descriptor.)

The following subsections define the responsibilities of the container for managing the invocation of an enterprise bean business method when the method is invoked via the enterprise bean's home or remote interface. The container's responsibilities depend on the value of the transaction attribute.

EJB.11.6.2.1 NotSupported

The container invokes an enterprise bean method whose transaction attribute is set to NotSupported with an unspecified transaction context.

If a client calls with a transaction context, the container suspends the association of the transaction context with the current thread before invoking the enterprise bean's business method. The container resumes the suspended association when the business method has completed. The suspended transaction context of the client is not passed to the resource managers or other enterprise Bean objects that are invoked from the business method.

If the business method invokes other enterprise beans, the container passes no transaction context with the invocation.

Refer to Section EJB.11.6.3 for more details of how the container can implement this case.

EJB.11.6.2.2 Required

The container must invoke an enterprise bean method whose transaction attribute is set to Required with a valid transaction context.

If a client invokes the enterprise bean's method while the client is associated with a transaction context, the container invokes the enterprise bean's method in the client's transaction context.

If the client invokes the enterprise bean's method while the client is not associated with a transaction context, the container automatically starts a new transaction before delegating a method call to the enterprise bean business method. The container automatically enlists all the resource managers accessed by the business method with the transaction. If the business method invokes other enterprise beans, the container passes the transaction context with the invocation. The container attempts to commit the transaction when the business method has completed. The container performs the commit protocol before the method result is sent to the client.

EJB.11.6.2.3 Supports

The container invokes an enterprise bean method whose transaction attribute is set to Supports as follows.

  • If the client calls with a transaction context, the container performs the same steps as described in the Required case.

  • If the client calls without a transaction context, the container performs the same steps as described in the NotSupported case.

The Supports transaction attribute must be used with caution. This is because of the different transactional semantics provided by the two possible modes of execution. Only the enterprise beans that will execute correctly in both modes should use the Supports transaction attribute.

EJB.11.6.2.4 RequiresNew

The container must invoke an enterprise bean method whose transaction attribute is set to RequiresNew with a new transaction context.

If the client invokes the enterprise bean's method while the client is not associated with a transaction context, the container automatically starts a new transaction before delegating a method call to the enterprise bean business method. The container automatically enlists all the resource managers accessed by the business method with the transaction. If the business method invokes other enterprise beans, the container passes the transaction context with the invocation. The container attempts to commit the transaction when the business method has completed. The container performs the commit protocol before the method result is sent to the client.

If a client calls with a transaction context, the container suspends the association of the transaction context with the current thread before starting the new transaction and invoking the business method. The container resumes the suspended transaction association after the business method and the new transaction have been completed.

EJB.11.6.2.5 Mandatory

The container must invoke an enterprise bean method whose transaction attribute is set to Mandatory in a client's transaction context. The client is required to call with a transaction context.

  • If the client calls with a transaction context, the container performs the same steps as described in the Required case.

  • If the client calls without a transaction context, the container throws the javax.transaction.TransactionRequiredException exception.

EJB.11.6.2.6 Never

The container invokes an enterprise bean method whose transaction attribute is set to Never without a transaction context defined by the EJB specification. The client is required to call without a transaction context.

  • If the client calls with a transaction context, the container throws the java.rmi.RemoteException exception.

  • If the client calls without a transaction context, the container performs the same steps as described in the NotSupported case.

EJB.11.6.2.7 Transaction Attribute Summary

Table EJB.11-2 provides a summary of the transaction context that the container passes to the business method and resource managers used by the business method, as a function of the transaction attribute and the client's transaction context. T1 is a transaction passed with the client request, while T2 is a transaction initiated by the container.

Table EJB.11-2. Transaction Attribute Summary

Transaction Attribute

Client's Transaction

Transaction Associated with Business Method

Transaction Associatedwith Resource Managers

NotSupported

none

T1

none

none

none

none

Required

none

T1

T2

T1

T2

T1

Supports

none

T1

none

T1

none

T1

RequiresNew

none

T1

T2

T2

T2

T2

Mandatory

none

T1

error

T1

N/A

T1

Never

none

T1

none

error

none

N/A

If the enterprise bean's business method invokes other enterprise beans via their home and remote interfaces, the transaction indicated in the column "Transaction Associated with Business Method" will be passed as part of the client context to the target enterprise bean.

See Section EJB.11.6.3 for how the container handles the "none" case in Table EJB.11-2.

EJB.11.6.2.8 Handling of setRollbackOnly() Method

The container must handle the EJBContext.setRollbackOnly() method invoked from a business method executing with the Required, RequiresNew, or Mandatory transaction attribute as follows:

  • The container must ensure that the transaction will never commit. Typically, the container instructs the transaction manager to mark the transaction for rollback.

  • If the container initiated the transaction immediately before dispatching the business method to the instance (as opposed to the transaction being inherited from the caller), the container must note that the instance has invoked the setRollbackOnly() method. When the business method invocation completes, the container must roll back rather than commit the transaction. If the business method has returned normally or with an application exception, the container must pass the method result or the application exception to the client after the container performed the rollback.

The container must throw the java.lang.IllegalStateException if the EJBContext.setRollbackOnly() method is invoked from a business method executing with the Supports, NotSupported, or Never transaction attribute.

EJB.11.6.2.9 Handling of getRollbackOnly() Method

The container must handle the EJBContext.getRollbackOnly() method invoked from a business method executing with the Required, RequiresNew, or Mandatory transaction attribute.

The container must throw the java.lang.IllegalStateException if the EJBContext.getRollbackOnly() method is invoked from a business method executing with the Supports, NotSupported, or Never transaction attribute.

EJB.11.6.2.10 Handling of getUserTransaction() Method

If an instance of an enterprise bean with container-managed transaction demarcation attempts to invoke the getUserTransaction() method of the EJBContext interface, the container must throw the java.lang.IllegalStateException.

EJB.11.6.2.11 javax.ejb.SessionSynchronization Callbacks

If a session bean class implements the javax.ejb.SessionSynchronization interface, the container must invoke the afterBegin(), beforeCompletion(), and afterCompletion(...) callbacks on the instance as part of the transaction commit protocol.

The container invokes the afterBegin() method on an instance before it invokes the first business method in a transaction.

The container invokes the beforeCompletion() method to give the enterprise bean instance the last chance to cause the transaction to roll back. The instance may cause the transaction to roll back by invoking the EJBContext.setRollbackOnly() method.

The container invokes the afterCompletion(Boolean committed) method after the completion of the transaction commit protocol to notify the enterprise bean instance of the transaction outcome.

EJB.11.6.3 Handling of Methods that Run with "an Unspecified Transaction Context"

The term "an unspecified transaction context" is used in the EJB specification to refer to the cases in which the EJB architecture does not fully define the transaction semantics of an enterprise bean method execution. This includes the following cases:

  • The execution of a method of an enterprise bean with container-managed transaction demarcation for which the value of the transaction attribute is NotSupported, Never, or Supports. [3]

    [3] For the Supports attribute, the handling described in this section applies only to the case when the client calls without a transaction context.

  • The execution of the ejbCreate, ejbRemove, ejbPassivate, and ejbActivate methods of a session bean with container-managed transaction demarcation.

The EJB specification does not prescribe how the container should manage the execution of a method with an unspecified transaction context—the transaction semantics are left to the container implementation. Some techniques for how the container may choose to implement the execution of a method with an unspecified transaction context are as follows (the list is not inclusive of all possible strategies):

  • The container may execute the method and access the underlying resource managers without a transaction context.

  • The container may treat each call of an instance to a resource manager as a single transaction (e.g., the container may set the auto-commit option on a JDBC API connection).

  • The container may merge multiple calls of an instance to a resource manager into a single transaction.

  • The container may merge multiple calls of an instance to multiple resource managers into a single transaction.

  • If an instance invokes methods on other enterprise beans, and the invoked methods are also designated to run with an unspecified transaction context, the container may merge the resource manager calls from the multiple instances into a single transaction.

  • Any combination of the above.

Since the enterprise bean does not know which technique the container implements, the enterprise bean must be written conservatively not to rely on any particular container behavior.

A failure that occurs in the middle of the execution of a method that runs with an unspecified transaction context may leave the resource managers accessed from the method in an unpredictable state. The EJB architecture does not define how the application should recover the resource managers' state after such a failure.


EJB.11.7 Access from Multiple Clients in the Same Transaction Context

This section describes a more complex distributed transaction scenario, and specifies the container's behavior required for this scenario.

EJB.11.7.1 Transaction "Diamond" Scenario with an Entity Object

An entity object may be accessed by multiple clients in the same transaction. For example, program A may start a transaction, call program B and program C in the transaction context, and then commit the transaction. If programs B and C access the same entity object, the topology of the transaction creates a diamond (Figure EJB.11-6).

Figure EJB.11-6. Transaction Diamond Scenario with Entity Object

An example (not realistic in practice) is a client program that tries to perform two purchases at two different stores within the same transaction. At each store, the program that is processing the client's purchase request debits the client's bank account.

It is difficult to implement an EJB server that handles the case in which programs B and C access an entity object through different network paths. This case is challenging because many EJB servers implement the EJB container as a collection of multiple processes, running on the same or multiple machines. Each client is typically connected to a single process. If clients B and C connect to different EJB container processes, and both B and C need to access the same entity object in the same transaction, the issue is how the container can make it possible for B and C to see a consistent state of the entity object within the same transaction. [4]

[4] This diamond problem applies only to the case when B and C are in the same transaction.

The above example illustrates a simple diamond. We use the term diamond to refer to any distributed transaction scenario in which an entity object is accessed in the same transaction through multiple network paths.

Note that in the diamond scenario the clients B and C access the entity object serially. Concurrent access to an entity object in the same transaction context would be considered an application programming error, and it would be handled in a container-specific way.

Note that the issue of handling diamonds is not unique to the EJB architecture. This issue exists in all distributed transaction processing systems.

The following subsections define the responsibilities of the EJB roles when handling distributed transaction topologies that may lead to a diamond involving an entity object.

EJB.11.7.2 Container Provider's Responsibilities

This subsection specifies the EJB container's responsibilities with respect to the diamond case involving an entity object.

The EJB specification requires that the container provide support for local diamonds. In a local diamond, components A, B, C, and D are deployed in the same EJB container.

The EJB specification does not require an EJB container to support distributed diamonds. In a distributed diamond, a target entity object is accessed from multiple clients in the same transaction through multiple network paths, and the clients (programs B and C) are not enterprise beans deployed in the same EJB container as the target entity object.

If the container provider chooses not to support distributed diamonds, and if the container can detect that a client invocation would lead to a diamond, the container should throw the java.rmi.RemoteException to the client.

If the container provider chooses to support distributed diamonds, it should provide a consistent view of the entity state within a transaction. The container provider can implement the support in several ways. (The options that follow are illustrative, not prescriptive.)

  • Always instantiate the entity bean instance for a given entity object in the same process, and route all clients' requests to this process. Within the process, the container routes all the requests within the same transaction to the same enterprise bean instance.

  • Instantiate the entity bean instance for a given entity object in multiple processes, and use the ejbStore and ejbLoad methods to synchronize the state of the instances within the same transaction. For example, the container can issue ejbStore after each business method, and issue ejbLoad before the start of the next business method. This technique ensures that the instance used by a one client sees the updates done by other clients within the same transaction.

An illustration of the second approach is shown in Figure EJB.11-7. The illustration is illustrative, not prescriptive for the container implementors.

Figure EJB.11-7. Handling of Diamonds by a Multi-Process Container

Program B makes a call to an entity object representing Account 100. The request is routed to an instance in process 1. The container invokes ejbLoad on the instance. The instance loads the state from the database in the ejbLoad method. The instance updates the state in the business method. When the method completes, the container invokes ejbStore. The instance writes the updated state to the database in the ejbStore method.

Now program C makes a call to the same entity object in the same transaction. The request is routed to a different process (2). The container invokes ejbLoad on the instance. The instance loads the state from the database in the ejbLoad method. The loaded state was written by the instance in process 1. The instance updates the state in the business method. When the method completes, the container invokes ejbStore. The instance writes the updated state to the database in the ejbStore method.

In the above scenario, the container presents the business methods operating on the entity object Account 100 with a consistent view of the entity object's state within the transaction.

Another implementation of the EJB container might avoid calling ejbLoad and ejbStore on each business method by using a distributed lock manager.

EJB.11.7.3 Bean Provider's Responsibilities

This subsection specifies the bean provider's responsibilities with respect to the diamond case involving an entity object.

The diamond case is transparent to the bean provider—the bean provider does not have to code the enterprise bean differently for the bean to participate in a diamond. Any solution to the diamond problem implemented by the container is transparent to the bean and does not change the semantics of the bean.

EJB.11.7.4 Application Assembler and Deployer's Responsibilities

This subsection specifies the application assembler and deployer's responsibilities with respect to the diamond case involving an entity object.

The application assembler and deployer should be aware that distributed diamonds might occur. In general, the application assembler should try to avoid creating unnecessary distributed diamonds.

If a distributed diamond is necessary, the deployer should advise the container (using a container-specific API) that an entity object of the entity bean may be involved in distributed diamond scenarios.

EJB.11.7.5 Transaction Diamonds Involving Session Objects

While it is illegal for two clients to access the same session object, it is possible for applications that use session beans to encounter the diamond case. For example, program A starts a transaction and then invokes two different session objects (Figure EJB.11-8).

Figure EJB.11-8. Transaction Diamond Scenario with a Session Bean

If the session bean instances cache the same data item (e.g., the current balance of Account 100) across method invocations in the same transaction, most likely the program is going to produce incorrect results.

The problem may exist regardless of whether the two session objects are the same or different session beans. The problem may exist (and may be harder to discover) if there are intermediate objects between the transaction initiator and the session objects that cache the data.

There are no requirements for the container provider because it is impossible for the container to detect this problem.

The bean provider and application assembler must avoid creating applications that would result in inconsistent caching of data in the same transaction by multiple session objects.


Chapter EJB.12. Exception Handling

    Section EJB.12.1. Overview and Concepts

    Section EJB.12.2. Bean Provider's Responsibilities

    Section EJB.12.3. Container Provider Responsibilities

    Section EJB.12.4. Client's View of Exceptions

    Section EJB.12.5. System Administrator's Responsibilities

    Section EJB.12.6. Differences from EJB 1.0


EJB.12.1 Overview and Concepts

EJB.12.1.1 Application Exceptions

An application exception is an exception defined in the throws clause of a method of the enterprise bean's home and remote interfaces, other than the java.rmi.RemoteException.

Enterprise bean business methods use application exceptions to inform the client of abnormal application-level conditions, such as unacceptable values of the input arguments to a business method. A client can typically recover from an application exception. Application exceptions are not intended for reporting system-level problems.

For example, the Account enterprise bean may throw an application exception to report that a debit operation cannot be performed because of an insufficient balance. The Account bean should not use an application exception to report, for example, the failure to obtain a database connection.

The javax.ejb.CreateException, javax.ejb.RemoveException, javax.ejb.FinderException, and subclasses thereof are considered to be application exceptions. These exceptions are used as standard application exceptions to report errors to the client from the create, remove, and finder methods (see Section EJB.9.1.9). These exceptions are covered by the rules on application exceptions that are defined in this chapter.

EJB.12.1.2 Goals for Exception Handling

The EJB specification for exception handling is designed to meet these high-level goals:

  • An application exception thrown by an enterprise bean instance should be reported to the client precisely (i.e., the client gets the same exception).

  • An application exception thrown by an enterprise bean instance should not automatically roll back a client's transaction. The client should typically be given a chance to recover a transaction from an application exception.

  • An unexpected exception that may have left the instance's state variables and/or underlying persistent data in an inconsistent state can be handled safely.


EJB.12.2 Bean Provider's Responsibilities

This section describes the view and responsibilities of the bean provider with respect to exception handling.

EJB.12.2.1 Application Exceptions

The bean provider defines the application exceptions in the throws clauses of the methods of the remote and home interfaces. Because application exceptions are intended to be handled by the client, and not by the system administrator, they should be used only for reporting business logic exceptions, not for reporting system level problems.

The bean provider is responsible for throwing the appropriate application exception from the business method to report a business logic exception to the client. Because the application exception does not automatically result in marking the transaction for rollback, the bean provider must do one of the following to ensure data integrity before throwing an application exception from an enterprise bean instance:

  • Ensure that the instance is in a state such that a client's attempt to continue and/or commit the transaction does not result in loss of data integrity. For example, the instance throws an application exception indicating that the value of an input parameter was invalid before the instance performed any database updates.

  • Mark the transaction for rollback using the EJBContext.setRollbackOnly() method before throwing an application exception. Marking the transaction for rollback will ensure that the transaction can never commit.

An application exception must not be defined as a subclass of the java.lang.RuntimeException, or of the java.rmi.RemoteException. These are reserved for system exceptions (see next subsection).

The bean provider is also responsible for using the standard EJB application exceptions (javax.ejb.CreateException, javax.ejb.RemoveException, javax.ejb.FinderException, and subclasses thereof) as described in Section EJB.9.1.9.

Bean providers may define subclasses of the standard EJB application exceptions and throw instances of the subclasses in the entity bean methods. A subclass will typically provide more information to the client that catches the exception.

EJB.12.2.2 System Exceptions

This subsection describes how the bean provider should handle various system-level exceptions and errors that an enterprise bean instance may encounter during the execution of a business method or a container callback method (e.g., ejbLoad).

The enterprise bean business method and container callback methods may encounter various exceptions or errors that prevent the method from successfully completing. Typically, this happens because the exception or error is unexpected, or the exception is expected but the EJB provider does not know how to recover from it. Examples of such exceptions and errors are failure to obtain a database connection, JNDI API exceptions, unexpected RemoteException from invocation of other enterprise beans, [1] unexpected RuntimeException, Java Virtual Machine errors, and so on.

[1] Note that the enterprise bean business method may attempt to recover from a RemoteException. The text in this subsection applies only to the case when the business method does not wish to recover from the RemoteException.

If the enterprise bean method encounters a system-level exception or error that does not allow the method to complete successfully, the method should throw a suitable non-application exception that is compatible with the method's throws clause. While the EJB specification does not prescribe the exact usage of the exception, it encourages the bean provider to follow these guidelines:

  • If the bean method encounters a RuntimeException or error, it should simply propagate the error from the bean method to the container (i.e., the bean method does not have to catch the exception).

  • If the bean method performs an operation that results in a checked exception [2] that the bean method cannot recover, the bean method should throw the javax.ejb.EJBException that wraps the original exception.

    [2] A checked exception is one that is not a subclass of java.lang.RuntimeException.

  • Any other unexpected error conditions should be reported using the javax.ejb.EJBException.

Note that the javax.ejb.EJBException is a subclass of the java.lang.RuntimeException, and therefore it does not have to be listed in the throws clauses of the business methods.

The container catches a non-application exception, logs it (which can result in alerting the system administrator), and throws the java.rmi.RemoteException (or subclass thereof) to the client. The bean provider can rely on the container to perform the following tasks when catching a non-application exception:

  • The transaction in which the bean method participated will be rolled back.

  • No other method will be invoked on an instance that threw a non-application exception.

This means that the bean provider does not have to perform any cleanup actions before throwing a non-application exception. It is the container that is responsible for the cleanup.

EJB.12.2.2.1 javax.ejb.NoSuchEntityException

The NoSuchEntityException is a subclass of EJBException. It should be thrown by the entity bean class methods to indicate that the underlying entity has been removed from the database.

An entity bean class typically throws this exception from the ejbLoad and ejbStore methods, and from the methods that implement the business methods defined in the remote interface.


EJB.12.3 Container Provider Responsibilities

This section describes the responsibilities of the container provider for handling exceptions. The EJB architecture specifies the container's behavior for the following exceptions:

  • Exceptions from enterprise bean's business methods

  • Exceptions from container-invoked callbacks on the enterprise bean

  • Exceptions from management of container-managed transaction demarcation

EJB.12.3.1 Exceptions from an Enterprise Bean's Business Methods

Business methods are considered to be the methods defined in the enterprise bean's remote and home interface (including all their superinterfaces) and the following methods: ejbCreate(...), ejbPostCreate(...), ejbRemove(), and the ejbFind<METHOD> methods.

Table EJB.12-1 specifies how the container must handle the exceptions thrown by the business methods for beans with container-managed transaction demarcation. The table specifies the container's action as a function of the condition under which the business method executes and the exception thrown by the business method. The table also illustrates the exception that the client will receive and how the client can recover from the exception. (Section EJB.12.4 describes the client's view of exceptions in detail.)

Table EJB.12-2 specifies how the container must handle the exceptions thrown by the business methods for beans with bean-managed transaction demarcation. [3] The table specifies the container's action as a function of the condition under which the business method executes and the exception thrown by the business method. The table also illustrates the exception that the client will receive and how the client can recover from the exception. (Section EJB.12.4 describes the client's view of exceptions in detail.)

[3] Note that the EJB specification allows only session beans to use bean-managed transaction demarcation.

Table EJB.12-1. Handling of Exceptions Thrown by a Business Method of a Bean with Container-Managed Transaction Demarcation

Method Condition

Method Exception

Container's Action

Client's View

Bean method runs in the context of the caller's transaction. [a] This case may happen with Required, Mandatory, and Supports attributes.

AppException

Re-throw AppException

Receives AppException.

Can attempt to continue computation in the transaction, and eventually commit the transaction (the commit would fail if the instance called setRollbackOnly()).

All other exceptions and errors

Log the exception or error.[b]

Mark the transaction for rollback.

Discard instance.[c]

Throw TransactionRolledBackException to the client.

Receives TransactionRolled BackException.

Continuing transaction is fruitless.

Bean method runs in the context of a transaction that the container started immediately before dispatching the business method. This case may happen with Required and RequiresNew attributes.

AppException

If the instance called setRollbackOnly(), then rollback the transaction, and re-throw AppException.

Otherwise, attempt to commit the transaction, and then re-throw AppException.

Receives AppException.

If the client executes in a transaction, the client's transaction is not marked for rollback, and client can continue its work.

All other exceptions

Log the exception or error.

Rollback the container-started transaction.

Discard instance.

Throw RemoteException.

Receives RemoteException.

If the client executes in a transaction, the client's transaction is not marked for rollback, and client can continue its work.

Bean method runs with an unspecified transaction context. This case may happen with the NotSupported, Never, and Supports attributes.

AppException

Re-throw AppException.

Receives AppException.

If the client executes in a transaction, the client's transaction is not marked for rollback, and client can continue its work.

All other exceptions

Log the exception or error.

Discard instance.

Throw RemoteException.

Receives RemoteException.

If the client executes in a transaction, the client's transaction is not marked for rollback, and client can continue its work.

[a] The caller can be another enterprise bean or an arbitrary client program.

[b] Log the exception or error means that the container logs the exception or error so that the system administrator is alerted of the problem.

[c] Discard instance means that the container must not invoke any business methods or container callbacks on the instance.

Table EJB.12-2. Handling of Exceptions Thrown by a Business Method of a Session with Bean-Managed Transaction Demarcation

Bean Method Condition

Bean Method Exception

Container Action

Client Receives

Bean is stateful or stateless session.

AppException

Re-throw AppException

Receives AppException.

All other exceptions

Log the exception or error.

Mark for rollback a transaction that has been started, but not yet completed, by the instance.

Discard instance.

Throw RemoteException.

Receives RemoteException.

EJB.12.3.2 Exceptions from Container-Invoked Callbacks

This subsection specifies the container's handling of exceptions thrown from the container-invoked callbacks on the enterprise bean. It applies to the following callback methods:

  • The ejbActivate(), ejbLoad(), ejbPassivate(), ejbStore(), setEntityContext(EntityContext), and unsetEntityContext() methods of the EntityBean interface.

  • The ejbActivate(), ejbPassivate(), and setSessionContext(SessionContext) methods of the SessionBean interface.

  • The afterBegin(), beforeCompletion() and afterCompletion(boolean) methods of the SessionSynchronization interface.

The container must handle all exceptions or errors from these methods as follows:

  • Log the exception or error to bring the problem to the attention of the system administrator.

  • If the instance is in a transaction, mark the transaction for rollback.

  • Discard the instance (i.e., the container must not invoke any business methods or container callbacks on the instance).

  • If the exception or error happened during the processing of a client invoked method, throw the java.rmi.RemoteException to the client. If the instance executed in the client's transaction, the container should throw the javax.transaction.TransactionRolledBackException because it provides more information to the client. (The client knows that it is fruitless to continue the transaction.)

EJB.12.3.3 javax.ejb.NoSuchEntityException

The NoSuchEntityException is a subclass of EJBException. If it is thrown by a method of an entity bean class, the container must handle the exception using the rules for EJBException described in Sections EJB.12.3.1 and EJB.12.3.2.

To give the client a better indication of the cause of the error, the container should throw the java.rmi.NoSuchObjectException to the client (which is a subclass of java.rmi.RemoteException).

EJB.12.3.4 Non-Existing Session Object

If a client makes a call to a session object that has been removed, the container should throw the java.rmi.NoSuchObjectException to the client (which is a subclass of java.rmi.RemoteException).

EJB.12.3.5 Exceptions from the Management of Container-Managed Transactions

The container is responsible for starting and committing the container-managed transactions, as described in Section EJB.11.6.2. This subsection specifies how the container must deal with the exceptions that may be thrown by the transaction start and commit operations.

If the container fails to start or commit a container-managed transaction, the container must throw the java.rmi.RemoteException to the client.

However, the container should not throw the java.rmi.RemoteException if the container performs a transaction roll back because the instance has invoked the setRollbackOnly() method on its EJBContext object. In this case, the container must roll back the transaction and pass the business method result or the application exception thrown by the business method to the client.

Note that some implementations of the container may retry a failed transaction transparently to the client and enterprise bean code. Such a container would throw the java.rmi.RemoteException after a number of unsuccessful tries.

EJB.12.3.6 Release of Resources

When the container discards an instance because of a system exception, the container should release all the resources held by the instance that were acquired through the resource factories declared in the enterprise bean environment (See Section EJB.14.4).

Note

While the container should release the connections to the resource managers that the instance acquired through the resource factories declared in the enterprise bean environment, the container cannot, in general, release "unmanaged" resources that the instance may have acquired through the JDK APIs. For example, if the instance has opened a TCP/IP connection, most container implementations will not be able to release the connection. The connection will be eventually released by the JVM garbage collector mechanism.

EJB.12.3.7 Support for Deprecated Use of java.rmi.RemoteException

The EJB 1.0 specification allowed the business methods, ejbCreate, ejbPostCreate, ejbFind<METHOD>, ejbRemove, and the container-invoked callbacks (i.e., the methods defined in the EntityBean, SessionBean, and SessionSynchronization inter-faces) implemented in the enterprise bean class to use the java.rmi.RemoteException to report non-application exceptions to the container.

This use of the java.rmi.RemoteException is deprecated in EJB 1.1—enterprise beans written for the EJB 1.1 specification should use the javax.ejb.EJBException instead.

The EJB 1.1 specification requires that a container support the deprecated use of the java.rmi.RemoteException. The container should treat the java.rmi.RemoteException thrown by an enterprise bean method in the same way as it is specified for the javax.ejb.EJBException.

Note

The use of the java.rmi.RemoteException is deprecated only in the above-mentioned methods. The methods of the remote and home interface still must use the java.rmi.RemoteException as required by the EJB specification.


EJB.12.4 Client's View of Exceptions

This section describes the client's view of exceptions received from an enterprise bean invocation.

A client accesses an enterprise bean through the enterprise bean's remote and home interfaces. Both of these interfaces are Java RMI interfaces, and therefore the throws clauses of all their methods (including those inherited from superinterfaces) include the mandatory java.rmi.RemoteException.The throws clauses may include an arbitrary number of application exceptions.

EJB.12.4.1 Application Exception

If a client program receives an application exception from an enterprise bean invocation, the client can continue calling the enterprise bean. An application exception does not result in the removal of the EJB object.

If a client program receives an application exception from an enterprise bean invocation while the client is associated with a transaction, the client can typically continue the transaction because an application exception does not automatically cause the container to mark the transaction for rollback.

For example, if a client receives the ExceedLimitException application exception from the debit method of an Account bean, the client may invoke the debit method again, possibly with a lower debit amount parameter. If the client exe-cuted in a transaction context, throwing the ExceedLimitException exception would not automatically result in rolling back, or marking for rollback, the client's transaction.

Although the container does not automatically mark for rollback a transaction because of a thrown application exception, the transaction might have been marked for rollback by the enterprise bean instance before it threw the application exception. There are two ways to learn if a particular application exception results in transaction rollback or not:

  • Statically. Programmers can check the documentation of the enterprise bean's remote or home interface. The bean provider may have specified (although he is not required to) the application exceptions for which the enterprise bean marks the transaction for rollback before throwing the exception.

  • Dynamically. Clients that are enterprise beans with container-managed transaction demarcation can use the getRollbackOnly() method of the javax.ejb.EJBContext object to learn if the current transaction has been marked for rollback; other clients may use the getStatus() method of the javax.transaction.UserTransaction interface to obtain the transaction status.

EJB.12.4.2 java.rmi.RemoteException

The client receives the java.rmi.RemoteException as an indication of a failure to invoke an enterprise bean method or to properly complete its invocation. The exception can be thrown by the container or by the communication subsystem between the client and the container.

If the client receives the java.rmi.RemoteException exception from a method invocation, the client, in general, does not know if the enterprise bean's method has been completed or not.

If the client executes in the context of a transaction, the client's transaction may, or may not, have been marked for rollback by the communication subsystem or target bean's container.

For example, the transaction would be marked for rollback if the underlying transaction service or the target bean's container doubted the integrity of the data because the business method may have been partially completed. Partial completion could happen, for example, when the target bean's method returned with a RuntimeException exception, or if the remote server crashed in the middle of executing the business method.

The transaction may not necessarily be marked for rollback. This might occur, for example, when the communication subsystem on the client side has not been able to send the request to the server.

When a client executing in a transaction context receives a RemoteException from an enterprise bean invocation, the client may use either of the following strategies to deal with the exception:

  • Discontinue the transaction. If the client is the transaction originator, it may simply roll back its transaction. If the client is not the transaction originator, it can mark the transaction for rollback or perform an action that will cause a rollback. For example, if the client is an enterprise bean, the enterprise bean may throw a RuntimeException which will cause the container to roll back the transaction.

  • Continue the transaction. The client may perform additional operations on the same or other enterprise beans, and eventually attempt to commit the transaction. If the transaction was marked for rollback at the time the RemoteException was thrown to the client, the commit will fail.

If the client chooses to continue the transaction, the client can first inquire about the transaction status to avoid fruitless computation on a transaction that has been marked for rollback. A client that is an enterprise bean with container-managed transaction demarcation can use the EJBContext.getRollbackOnly() method to test if the transaction has been marked for rollback; a client that is an enterprise bean with bean-managed transaction demarcation, and other client types, can use the UserTransaction.getStatus() method to obtain the status of the transaction.

Some implementations of EJB servers and containers may provide more detailed exception reporting by throwing an appropriate subclass of the java.rmi.RemoteException to the client. The following subsections describe the several subclasses of the java.rmi.RemoteException that may be thrown by the container to give the client more information.

EJB.12.4.2.1 javax.transaction.TransactionRolledbackException

The javax.transaction.TransactionRolledbackException is a subclass of the java.rmi.RemoteException. It is defined in the JTA standard extension.

If a client receives the javax.transaction.TransactionRolledbackException, the client knows for certain that the transaction has been marked for rollback. It would be fruitless for the client to continue the transaction because the transaction can never commit.

EJB.12.4.2.2 javax.transaction.TransactionRequiredException

The javax.transaction.TransactionRequiredException is a subclass of the java.rmi.RemoteException. It is defined in the JTA standard extension.

The javax.transaction.TransactionRequiredException informs the client that the target enterprise bean must be invoked in a client's transaction, and that the client invoked the enterprise bean without a transaction context.

This error usually indicates that the application was not properly formed.

EJB.12.4.2.3 java.rmi.NoSuchObjectException

The java.rmi.NoSuchObjectException is a subclass of the java.rmi.RemoteException. It is thrown to the client if a remote business method cannot complete because the EJB object no longer exists.


EJB.12.5 System Administrator's Responsibilities

The system administrator is responsible for monitoring the log of the non-application exceptions and errors logged by the container, and for taking actions to correct the problems that caused these exceptions and errors.


EJB.12.6 Differences from EJB 1.0

The EJB 1.1 specification of exception handling preserved the rules defined in the EJB 1.0 specification, with the following exceptions:

  • EJB 1.0 specified that the enterprise bean business methods and container-invoked callbacks use the java.rmi.RemoteException to report non-application exceptions. This practice is deprecated in EJB 1.1—the enterprise bean methods should use the javax.ejb.EJBException or other suitable RuntimeException to report non-application exceptions.

  • In EJB 1.1, all non-application exceptions thrown by the instance result in the rollback of the transaction in which the instance executed and in discarding the instance. In EJB 1.0, the container would not roll back a transaction and discard the instance if the instance threw the java.rmi.RemoteException.

  • In EJB 1.1, an application exception does not cause the container to automatically roll back a transaction. In EJB 1.0, the container was required to roll back a transaction when an application exception was passed through a transaction boundary started by the container. In EJB 1.1, the container performs the roll back only if the instance has invoked the setRollbackOnly() method on its EJBContext object.


Chapter EJB.13. Support for Distribution

    Section EJB.13.1. Overview

    Section EJB.13.2. Client-Side Objects in Distributed Environment

    Section EJB.13.3. Standard Distribution Protocol


EJB.13.1 Overview

The home and remote interfaces of the enterprise bean's client view are defined as Java™ RMI [EJB.3] interfaces. This allows the container to implement the home and remote interfaces as distributed objects. A client using the home and remote interfaces can reside on a different machine than the enterprise bean (location transparency), and the object references of the home and remote interfaces can be passed over the network to other applications.

The EJB specification further constrains the Java RMI types that can be used by enterprise beans to the legal RMI-IIOP types [EJB.7]. This makes it possible for the EJB container implementors to use RMI-IIOP as the object distribution protocol.

Note

The EJB 1.1 specification does not require container vendors to use RMI-IIOP. A later release of the J2EE platform is likely to require a J2EE platform implementor to implement the RMI-IIOP protocol for EJB interoperability in heterogeneous server environments.


EJB.13.2 Client-Side Objects in Distributed Environment

When the RMI-IIOP protocol or similar distribution protocols are used, the client communicates with the enterprise bean using stubs for the server-side objects (Figure EJB.13-1). The stubs implement the home and remote interfaces.

Figure EJB.13-1. Location of EJB Client Stubs

The communication stubs used on the client side are artifacts generated at enterprise bean's deployment time by the EJB container provider tools. The stubs used on the client are standard if the container uses RMI-IIOP as the distribution protocol; the stubs are container-specific otherwise.


EJB.13.3 Standard Distribution Protocol

The standard mapping of the Enterprise JavaBeans architecture to CORBA is defined in a separate document.

The mapping enables the following interoperability:

  • A client using an ORB from one vendor can access enterprise beans residing on an EJB server provided by another vendor.

  • Enterprise beans in one EJB server can access enterprise beans in another EJB server.

  • A non-Java platform CORBA client can access any enterprise bean object.


Chapter EJB.14. Enterprise Bean Environment

This chapter specifies the interfaces for accessing the enterprise bean environment.


EJB.14.1 Overview

The application assembler and deployer should be able to customize an enterprise bean's business logic without accessing the enterprise bean's source code.

In addition, ISVs typically develop enterprise beans that are, to a large degree, independent from the operational environment in which the application will be deployed. Most enterprise beans must access resource managers and external information. The key issue is how enterprise beans can locate external information without prior knowledge of how the external information is named and organized in the target operational environment.

The enterprise bean environment mechanism attempts to address both of the above issues.

This chapter is organized as follows:

  • Section EJB.14.2 defines the interfaces that specify and access the enterprise bean's environment. The section illustrates the use of the enterprise bean's environment for generic customization of the enterprise bean's business logic.

  • Section EJB.14.3 defines the interfaces for obtaining the home interface of another enterprise bean using an EJB specification reference. An EJB specification reference is a special entry in the enterprise bean's environment.

  • Section EJB.14.4 defines the interfaces for obtaining a resource manager connection factory using a resource manager connection factory reference. A resource manager connection factory reference is a special entry in the enterprise bean's environment.


EJB.14.2 Bean Environment as JNDI Naming Context

The enterprise bean's environment is a mechanism that allows customization of the enterprise bean's business logic during deployment or assembly. The enterprise bean's environment allows the enterprise bean to be customized without the need to access or change the enterprise bean's source code.

The container implements the enterprise bean's environment, and provides it to the enterprise bean instance through the JNDI interfaces. The enterprise bean's environment is used as follows:

  1. The enterprise bean's business methods access the environment using the JNDI interfaces. The bean provider declares in the deployment descriptor all the environment entries that the enterprise bean expects to be provided in its environment at runtime.

  2. The container provides an implementation of the JNDI API naming context that stores the enterprise bean environment. The container also provides the tools that allow the deployer to create and manage the environment of each enterprise bean.

  3. The deployer uses the tools provided by the container to create the environment entries that are declared in the enterprise bean's deployment descriptor. The deployer can set and modify the values of the environment entries.

  4. The container makes the environment naming context available to the enterprise bean instances at runtime. The enterprise bean's instances use the JNDI interfaces to obtain the values of the environment entries.

Each enterprise bean defines its own set of environment entries. All instances of an enterprise bean within the same home share the same environment entries; the environment entries are not shared with other enterprise beans. Enterprise bean instances are not allowed to modify the bean's environment at runtime.

If an enterprise bean is deployed multiple times in the same container, each deployment results in the creation of a distinct home. The deployer may set different values for the enterprise bean environment entries for each home.

Note

Terminology warning—The enterprise bean's "environment" should not be confused with the "environment properties" defined in the JNDI API documentation.

The following subsections describe the responsibilities of each EJB role.

EJB.14.2.1 Bean Provider's Responsibilities

This section describes the bean provider's view of the enterprise bean's environment, and defines his or her responsibilities.

EJB.14.2.1.1 Access to Enterprise Bean's Environment

An enterprise bean instance locates the environment naming context using the JNDI interfaces. An instance creates a javax.naming.InitialContext object by using the constructor with no arguments, and looks up the environment naming via the InitialContext under the name java:comp/env. The enterprise bean's environment entries are stored directly in the environment naming context, or in any of its direct or indirect subcontexts.

The value of an environment entry is of the type in the Java programming language declared by the bean provider in the deployment descriptor.

The following code example illustrates how an enterprise bean accesses its environment entries.

public class EmployeeServiceBean implements SessionBean {

   ...
   public void setTaxInfo(int numberOfExemptions, ...)
          throws InvalidNumberOfExemptionsException {
      ...

      // Obtain the enterprise bean's environment naming context.
      Context initCtx = new InitialContext();
      Context myEnv = (Context)initCtx.lookup("java:comp/env");

      // Obtain the maximum number of tax exemptions
      // configured by the Deployer.
      Integer max = (Integer)myEnv.lookup("maxExemptions");

      // Obtain the minimum number of tax exemptions
      // configured by the Deployer.
      Integer min = (Integer)myEnv.lookup("minExemptions");

      // Use the environment entries to customize business logic.
      if (numberOfExeptions > maxExemptions ||
         numberOfExemptions < minExemptions)
            throw new InvalidNumberOfExemptionsException();

      // Get some more environment entries. These environment
      // entries are stored in subcontexts.
      String val1 = (String)myEnv.lookup("foo/name1");
      Boolean val2 = (Boolean)myEnv.lookup("foo/bar/name2");

      // The enterprise bean can also lookup using full
         pathnames.
      Integer val3 = (Integer)
          initCtx.lookup("java:comp/env/name3");
      Integer val4 = (Integer)
          initCtx.lookup("java:comp/env/foo/name4");
      ...
   }
}
EJB.14.2.1.2 Declaration of Environment Entries

The bean provider must declare all the environment entries accessed from the enterprise bean's code. The environment entries are declared using the env-entry elements in the deployment descriptor.

Each env-entry element describes a single environment entry. The env-entry element consists of an optional description of the environment entry, the environment entry name relative to the java:comp/env context, the expected Java type of the environment entry value (i.e., the type of the object returned from the JNDI lookup method), and an optional environment entry value.

An environment entry is scoped to the session or entity bean whose declaration contains the env-entry element. This means that the environment entry is inaccessible from other enterprise beans at runtime, and that other enterprise beans may define env-entry elements with the same env-entry-name without causing a name conflict.

The environment entry values may be one of the following Java programming language types: String, Integer, Boolean, Double, Byte, Short, Long, and Float.

If the bean provider provides a value for an environment entry using the env-entry-value element, the value can be changed later by the application assembler or deployer. The value must be a string that is valid for the constructor of the specified type that takes a single String parameter.

The following example is the declaration of environment entries used by the EmployeeServiceBean whose code was illustrated in the previous subsection.

<enterprise-beans>
   <session>
           ...
      <ejb-name>EmployeeService</ejb-name>
      <ejb-class>
         com.wombat.empl.EmployeeServiceBean
      </ejb-class>
      ...
      <env-entry>
         <description>
            The maximum number of tax exemptions
            allowed to be set.
         </description>
         <env-entry-name>maxExemptions</env-entry-name>
         <env-entry-type>java.lang.Integer</env-entry-type>
         <env-entry-value>15</env-entry-value>
      </env-entry>
      <env-entry>
         <description>
            The minimum number of tax exemptions
            allowed to be set.
         </description>
         <env-entry-name>minExemptions</env-entry-name>
         <env-entry-type>java.lang.Integer</env-entry-type>
         <env-entry-value>1</env-entry-value>
      </env-entry>
      <env-entry>
         <env-entry-name>foo/name1</env-entry-name>
         <env-entry-type>java.lang.String</env-entry-type>
         <env-entry-value>value1</env-entry-value>
      </env-entry>
      <env-entry>
         <env-entry-name>foo/bar/name2</env-entry-name>
         <env-entry-type>java.lang.Boolean</env-entry-type>
         <env-entry-value>true</env-entry-value>
      </env-entry>
      <env-entry>
         <description>Some description.</description>
         <env-entry-name>name3</env-entry-name>
         <env-entry-type>java.lang.Integer</env-entry-type>
      </env-entry>
      <env-entry>
         <env-entry-name>foo/name4</env-entry-name>
         <env-entry-type>java.lang.Integer</env-entry-type>
         <env-entry-value>10</env-entry-value>
      </env-entry>
      ...
   </session>
</enterprise-beans>
...

EJB.14.2.2 Application Assembler's Responsibility

The application assembler is allowed to modify the values of the environment entries set by the bean provider, and is allowed to set the values of those environment entries for which the bean provider has not specified any initial values.

EJB.14.2.3 Deployer's Responsibility

The deployer must ensure that the values of all the environment entries declared by an enterprise bean are set to meaningful values.

The deployer can modify the values of the environment entries that have been previously set by the bean provider and/or application assembler, and must set the values of those environment entries for which no value has been specified.

The description elements provided by the bean provider or application assembler help the deployer with this task.

EJB.14.2.4 Container Provider Responsibility

The container provider has the following responsibilities:

  • Provide a deployment tool that allows the deployer to set and modify the values of the enterprise bean's environment entries.

  • Implement the java:comp/env environment naming context, and provide it to the enterprise bean instances at runtime. The naming context must include all the environment entries declared by the bean provider, with their values supplied in the deployment descriptor or set by the deployer. The environment naming context must allow the deployer to create subcontexts if they are needed by an enterprise bean.

  • The container must ensure that the enterprise bean instances have only read access to their environment variables. The container must throw the javax.naming.OperationNotSupportedException from all the methods of the javax.naming.Context interface that modify the environment naming context and its subcontexts.


EJB.14.3 EJB References

This section describes the programming and deployment descriptor interfaces that allow the bean provider to refer to the homes of other enterprise beans using "logical" names called EJB references. The EJB references are special entries in the enterprise bean's environment. The deployer binds the EJB references to the enterprise bean's homes in the target operational environment.

The deployment descriptor also allows the application assembler to link an EJB reference declared in one enterprise bean to another enterprise bean contained in the same EJB JAR file, or in another EJB JAR file in the same J2EE application unit. The link is an instruction to the tools used by the deployer that the EJB reference must be bound to the home of the specified target enterprise bean.

EJB.14.3.1 Bean Provider's Responsibilities

This subsection describes the bean provider's view and responsibilities with respect to EJB references.

EJB.14.3.1.1 EJB Reference Programming Interfaces

The bean provider must use EJB references to locate the home interfaces of other enterprise beans as follows.

  • Assign an entry in the enterprise bean's environment to the reference. (See Section EJB.14.3.1.2 for information on how EJB references are declared in the deployment descriptor.)

  • The EJB specification recommends, but does not require, that all references to other enterprise beans be organized in the ejb subcontext of the bean's environment (i.e., in the java:comp/env/ejb JNDI context).

  • Look up the home interface of the referenced enterprise bean in the enterprise bean's environment using JNDI.

The following example illustrates how an enterprise bean uses an EJB reference to locate the home interface of another enterprise bean.

public class EmployeeServiceBean implements SessionBean {

   public void changePhoneNumber(...) {
      ...

      // Obtain the default initial JNDI context.
      Context initCtx = new InitialContext();

      // Look up the home interface of the EmployeeRecord
      // enterprise bean in the environment.
      Object result = initCtx.lookup(
         "java:comp/env/ejb/EmplRecord");

      // Convert the result to the proper type.
      EmployeeRecordHome emplRecordHome = (EmployeeRecordHome)
         javax.rmi.PortableRemoteObject.narrow(result,
                EmployeeRecordHome.class);
      ...
   }
}

In the example, the bean provider of the EmployeeServiceBean enterprise bean assigned the environment entry ejb/EmplRecord as the EJB reference name to refer to the home of another enterprise bean.

EJB.14.3.1.2 Declaration of EJB References in Deployment Descriptor

Although the EJB reference is an entry in the enterprise bean's environment, the bean provider must not use a env-entry element to declare it. Instead, the bean provider must declare all the EJB references using the ejb-ref elements of the deployment descriptor. This allows the EJB JAR consumer (i.e., application assembler or deployer) to discover all the EJB references used by the enterprise bean.

Each ejb-ref element describes the interface requirements that the referencing enterprise bean has for the referenced enterprise bean. The ejb-ref element contains an optional description element and the mandatory ejb-ref-name, ejb-ref-type, home, and remote elements.

The ejb-ref-name element specifies the EJB reference name; its value is the environment entry name used in the enterprise bean code. The ejb-ref-type element specifies the expected type of the enterprise bean; its value must be either Entity or Session. The home and remote elements specify the expected types in the Java programming language of the referenced enterprise bean's home and remote interfaces.

An EJB reference is scoped to the session or entity bean whose declaration contains the ejb-ref element. This means that the EJB reference is not accessible to other enterprise beans at runtime, and that other enterprise beans may define ejb-ref elements with the same ejb-ref-name without causing a name conflict.

The following example illustrates the declaration of EJB references in the deployment descriptor.

...
<enterprise-beans>
   <session>
      ...
      <ejb-name>EmployeeService</ejb-name>
      <ejb-class>
         com.wombat.empl.EmployeeServiceBean
      </ejb-class>
      ...
      <ejb-ref>
         <description>
            This is a reference to the entity bean that
            encapsulates access to employee records.
         </description>
         <ejb-ref-name>ejb/EmplRecord</ejb-ref-name>
         <ejb-ref-type>Entity</ejb-ref-type>
         <home>com.wombat.empl.EmployeeRecordHome</home>
         <remote>com.wombat.empl.EmployeeRecord</remote>
      </ejb-ref>

      <ejb-ref>
         <ejb-ref-name>ejb/Payroll</ejb-ref-name>
         <ejb-ref-type>Entity</ejb-ref-type>
         <home>com.aardvark.payroll.PayrollHome</home>
         <remote>com.aardvark.payroll.Payroll</remote>
      </ejb-ref>

      <ejb-ref>
         <ejb-ref-name>ejb/PensionPlan</ejb-ref-name>
         <ejb-ref-type>Session</ejb-ref-type>
         <home>com.wombat.empl.PensionPlanHome</home>
         <remote>com.wombat.empl.PensionPlan</remote>
         </ejb-ref>
         ...
   </session>
   ...
</enterprise-beans>
...

EJB.14.3.2 Application Assembler's Responsibilities

The application assembler can use the ejb-link element in the deployment descriptor to link an EJB reference to a target enterprise bean. The link will be observed by the deployment tools.

The application assembler specifies the link between two enterprise beans as follows:

  • The application assembler uses the optional ejb-link element of the ejb-ref element of the referencing enterprise bean. The value of the ejb-link element is the name of the target enterprise bean. (It is the name defined in the ejb-name element of the target enterprise bean.) The target enterprise bean can be in the same EJB JAR file, or in another EJB JAR in the same J2EE application unit as the referencing enterprise bean.

  • The application assembler must ensure that the target enterprise bean is type-compatible with the declared EJB reference. This means that the target enterprise bean must be of the type indicated in the ejb-ref-type element, and that the home and remote interfaces of the target enterprise bean must be type-compatible with the interfaces declared in the EJB reference.

The following illustrates an ejb-link in the deployment descriptor.

...
<enterprise-beans>
   <session>
         ...
      <ejb-name>EmployeeService</ejb-name>
      <ejb-class>
         com.wombat.empl.EmployeeServiceBean
      </ejb-class>
      ...
      <ejb-ref>
         <ejb-ref-name>ejb/EmplRecord</ejb-ref-name>
         <ejb-ref-type>Entity</ejb-ref-type>
         <home>com.wombat.empl.EmployeeRecordHome</home>
         <remote>com.wombat.empl.EmployeeRecord</remote>
         <ejb-link>EmployeeRecord</ejb-link>
      </ejb-ref>
      ...
   </session>
   ...

   <entity>
      <ejb-name>EmployeeRecord</ejb-name>
      <home>com.wombat.empl.EmployeeRecordHome</home>
      <remote>com.wombat.empl.EmployeeRecord</remote>
      ...
   </entity>
   ...
</enterprise-beans>
...

The application assembler uses the ejb-link element to indicate that the EJB reference "EmplRecord" declared in the EmployeeService enterprise bean has been linked to the EmployeeRecord enterprise bean.

EJB.14.3.3 Deployer's Responsibility

The deployer is responsible for the following:

  • The deployer must ensure that all the declared EJB references are bound to the homes of enterprise beans that exist in the operational environment. The deployer may use, for example, the JNDI LinkRef mechanism to create a symbolic link to the actual JNDI name of the target enterprise bean's home.

  • The deployer must ensure that the target enterprise bean is type-compatible with the types declared for the EJB reference. This means that the target enterprise bean must of the type indicated in the ejb-ref-type element, and that the home and remote interfaces of the target enterprise bean must be Java type-compatible with the home and remote interfaces declared in the EJB reference.

  • If an EJB reference declaration includes the ejb-link element, the deployer must bind the enterprise bean reference to the home of the enterprise bean specified as the link's target.

EJB.14.3.4 Container Provider's Responsibility

The container provider must provide the deployment tools that allow the Deployer to perform the tasks described in the previous subsection. The deployment tools provided by the EJB container provider must be able to process the information supplied in the ejb-ref elements in the deployment descriptor.

At the minimum, the tools must be able to:

  • Preserve the application assembly information in the ejb-link elements by binding an EJB reference to the home interface of the specified target enterprise bean.

  • Inform the deployer of any unresolved EJB references, and allow him or her to resolve an EJB reference by binding it to a specified compatible target enterprise bean.


EJB.14.4 Resource Manager Connection Factory References

A resource manager connection factory is an object that is used to create connections to a resource manager. For example, an object that implements the javax.sql.DataSource interface is a resource manager connection factory for java.sql.Connection objects which implement connections to a database management system.

This section describes the enterprise bean programming and deployment descriptor interfaces that allow the enterprise bean code to refer to resource factories using logical names called resource manager connection factory references. The resource manager connection factory references are special entries in the enterprise bean's environment. The deployer binds the resource manager connection factory references to the actual resource factories that are configured in the container. Because these resource factories allow the container to affect resource management, the connections acquired through the resource manager connection factory references are called managed resources (e.g., these resource factories allow the container to implement connection pooling and automatic enlistment of the connection with a transaction).

EJB.14.4.1 Bean Provider's Responsibilities

This subsection describes the bean provider's view of locating resource factories and defines his responsibilities.

EJB.14.4.1.1 Programming Interfaces for Resource Manager Connection Factory References

The bean provider must use resource manager connection factory references to obtain connections to resources as follows.

  • Assign an entry in the enterprise bean's environment to the resource manager connection factory reference. (See Section EJB.14.4.1.2 for information on how resource manager connection factory references are declared in the deployment descriptor.)

  • The EJB specification recommends, but does not require, that all resource manager connection factory references be organized in the subcontexts of the bean's environment, using a different subcontext for each resource manager type. For example, all JDBC™ DataSource references might be declared in the java:comp/env/jdbc subcontext, and all JMS connection factories in the java:comp/env/jms subcontext. Also, all JavaMail connection factories might be declared in the java:comp/env/mail subcontext and all URL connection factories in the java:comp/env/url subcontext.

  • Look up the resource manager connection factory object in the enterprise bean's environment using the JNDI interface.

  • Invoke the appropriate method on the resource manager connection factory method to obtain a connection to the resource. The factory method is specific to the resource type. It is possible to obtain multiple connections by calling the factory object multiple times.

The bean provider has two choices with respect to dealing with associating a principal with the resource manager access:

  • Allow the deployer to set up principal mapping or resource manager sign-on information. In this case, the enterprise bean code invokes a resource manager connection factory method that has no security-related parameters.

  • Sign on to the resource manager from the bean code. In this case, the enterprise bean invokes the appropriate resource manager connection factory method that takes the sign-on information as method parameters.

The bean provider uses the res-auth deployment descriptor element to indicate which of the two resource manager authentication approaches is used.

We expect that the first form (i.e., letting the deployer set up the resource manager sign-on information) will be the approach used by most enterprise beans.

The following code sample illustrates obtaining a JDBC connection.

public class EmployeeServiceBean implements SessionBean {
   EJBContext ejbContext;

   public void changePhoneNumber(...) {
      ...

      // obtain the initial JNDI context
      Context initCtx = new InitialContext();

      // perform JNDI lookup to obtain resource manager
      // connection factory
      javax.sql.DataSource ds = (javax.sql.DataSource)
         initCtx.lookup("java:comp/env/jdbc/EmployeeAppDB");

      // Invoke factory to obtain a connection. The security
      // principal is not given, and therefore
      // it will be configured by the Deployer.
      java.sql.Connection con = ds.getConnection();
      ...
   }
}
EJB.14.4.1.2 Declaration of Resource Manager Connection Factory References in Deployment Descriptor

Although a resource manager connection factory reference is an entry in the enterprise bean's environment, the bean provider must not use an env-entry element to declare it.

Instead, the bean provider must declare all the resource manager connection factory references in the deployment descriptor using the resource-ref elements. This allows the EJB JAR consumer (i.e., application assembler or deployer) to discover all the resource manager connection factory references used by an enterprise bean.

Each resource-ref element describes a single resource manager connection factory reference. The resource-ref element consists of the description element and the mandatory res-ref-name, res-type, and res-auth elements. The res-ref-name element contains the name of the environment entry used in the enterprise bean's code. The res-type element contains the Java type of the resource manager connection factory that the enterprise bean code expects. The res-auth element indicates whether the enterprise bean code performs resource manager sign-on programmatically, or whether the container signs on to the resource manager using the principal mapping information supplied by the deployer. The bean provider indicates the sign-on responsibility by setting the value of the res-auth element to Application or container.

A resource manager connection factory reference is scoped to the session or entity bean whose declaration contains the resource-ref element. This means that the resource manager connection factory reference is not accessible from other enterprise beans at runtime, and that other enterprise beans may define resource-ref elements with the same res-ref-name without causing a name conflict.

The type declaration allows the deployer to identify the type of the resource manager connection factory.

Note that the indicated type is the Java type of the resource manager connection factory, not the Java type of the resource.

The following example is the declaration of resource manager connection factory references used by the EmployeeService enterprise bean illustrated in the previous subsection.

...
<enterprise-beans>
   <session>
          ...
      <ejb-name>EmployeeService</ejb-name>
      <ejb-class>
         com.wombat.empl.EmployeeServiceBean
      </ejb-class>
      ...
      <resource-ref>
         <description>
            A data source for the database in which
            the EmployeeService enterprise bean will
            record a log of all transactions.
         </description>
         <res-ref-name>jdbc/EmployeeAppDB</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Container</res-auth>
      </resource-ref>
      ...
   </session>
</enterprise-beans>
...
EJB.14.4.1.3 Standard Resource Manager Connection Factory Types

The bean provider must use the javax.sql.DataSource resource manager connection factory type for obtaining JDBC API connections, and the javax.jms.QueueConnectionFactory or the javax.jms.TopicConnectionFactory for obtaining JMS connections.

The bean provider must use the javax.mail.Session resource manager connection factory type for obtaining JavaMail™ API connections, and the java.net.URL resource manager connection factory type for obtaining URL connections.

It is recommended that the bean provider names JDBC API data sources in the java:comp/env/jdbc subcontext, and JMS connection factories in the java:comp/env/jms subcontext. It is also recommended that the bean provider names all JavaMail API connection factories in the java:comp/env/mail subcontext, and all URL connection factories in the java:comp/env/url subcontext.

Note

A future EJB specification will add the "connector" mechanism that will allow an enterprise bean to use the API described in this section to obtain resource objects that provide access to additional back-end systems.

EJB.14.4.2 Deployer's Responsibility

The deployer uses deployment tools to bind the resource manager connection factory references to the actual resource factories configured in the target operational environment.

The deployer must perform the following tasks for each resource manager connection factory reference declared in the deployment descriptor:

  • Bind the resource manager connection factory reference to a resource manager connection factory that exists in the operational environment. The deployer may use, for example, the JNDI LinkRef mechanism to create a symbolic link to the actual JNDI API name of the resource manager connection factory. The resource manager connection factory type must be compatible with the type declared in the res-type element.

  • Provide any additional configuration information that the resource manager needs for opening and managing the resource. The configuration mechanism is resource-manager specific, and is beyond the scope of this specification.

  • If the value of the res-auth element is container, the deployer is responsible for configuring the sign-on information for the resource manager. This is performed in a manner specific to the EJB container and resource manager; it is beyond the scope of this specification.

For example, if principals must be mapped from the security domain and principal realm used at the enterprise beans application level to the security domain and principal realm of the resource manager, the deployer or system administrator must define the mapping. The mapping is performed in a manner specific to the EJB container and resource manager; it is beyond the scope of the current EJB specification.

EJB.14.4.3 Container Provider Responsibility

The EJB container provider is responsible for the following:

  • Provide the deployment tools that allow the deployer to perform the tasks described in the previous subsection.

  • Provide the implementation of the resource manager connection factory classes for the resource managers that are configured with the EJB container.

  • If the bean provider set the res-auth of a resource manager connection factory reference to Application, the container must allow the bean to perform explicit programmatic signon using the resource manager's API.

  • The container must provide tools that allow the deployer to set up resource manager sign-on information for the resource manager references whose res-auth element is set to container. The minimum requirement is that the deployer must be able to specify the user/password information for each resource manager connection factory reference declared by the enterprise bean, and the container must be able to use the user/password combination for user authentication when obtaining a connection to the resource by invoking the resource manager connection factory.

Although not required by the EJB specification, we expect that containers will support some form of a single sign-on mechanism that spans the application server and the resource managers. The container will allow the deployer to set up the resource managers such that the EJB caller principal can be propagated (directly or through principal mapping) to a resource manager, if required by the application.

While not required by the EJB specification, most EJB container providers also provide the following features:

  • A tool to allow the system administrator to add, remove, and configure a resource manager for the EJB Server.

  • A mechanism to pool connections to the resources for the enterprise beans and otherwise manage the use of resources by the container. The pooling must be transparent to the enterprise beans.

EJB.14.4.4 System Administrator's Responsibility

The system administrator is typically responsible for the following:

  • Add, remove, and configure resource managers in the EJB server environment.

In some scenarios, these tasks can be performed by the deployer.


EJB.14.5 Deprecated EJBContext.getEnvironment() Method

The environment naming context introduced in EJB 1.1 replaces the EJB 1.0 concept of environment properties.

An EJB 1.1 compliant container is not required to implement support for the EJB 1.0 style environment properties. If the container does not implement the functionality, it should throw a RuntimeException (or subclass thereof) from the EJBContext.getEnvironment() method.

If an EJB 1.1 compliant container chooses to provide support for the EJB 1.0 style environment properties (so that it can support enterprise beans written to the EJB 1.0 specification), it should implement the support as described below.

When the tools convert the EJB 1.0 deployment descriptor to the EJB 1.1 XML format, they should place the definitions of the environment properties into the ejb10-properties subcontext of the environment naming context. The env-entry elements should be defined as follows: the env-entry-name element contains the name of the environment property, the env-entry-type must be java.lang.String, and the optional env-entry-value contains the environment property value.

For example, an EJB 1.0 enterprise bean with two environment properties foo and bar should declare the following env-entry elements in its EJB 1.1 format deployment descriptor.

...
<env-entry>
   env-entry-name>ejb10-properties/foo</env-entry-name>
   <env-entry-type>java.lang.String</env-entry-type>
</env-entry>
<env-entry>
   <description>bar's description</description>
   <env-entry-name>ejb10-properties/bar</env-entry-name>
   <env-entry-type>java.lang.String</env-entry-type>
   <env-entry-value>bar value</env-entry-value>
</env-entry>
...

The container should provide the entries declared in the ejb10-properties subcontext to the instances as a java.util.Properties object that the instances obtain by invoking the EJBContext.getEnvironment() method.

The enterprise bean uses the EJB 1.0 API to access the properties, as shown by the following example.

public class SomeBean implements SessionBean {
   SessionContext ctx;
   java.util.Properties env;

   public void setSessionContext(SessionContext sc) {
      ctx = sc;
      env = ctx.getEnvironment();
   }

   public someBusinessMethod(...) ... {
      String fooValue = env.getProperty("foo");
      String barValue = env.getProperty("bar");
   }
   ...

}


EJB.14.6 UserTransaction Interface

Note

The requirement for the container to publish the UserTransaction interface in the enterprise bean's JNDI API context was added to make the requirements on UserTransaction uniform with the other Java 2 Platform, Enterprise Edition application component types.

The container must make the UserTransaction interface available to the enterprise beans that are allowed to use this interface (only session beans with bean-managed transaction demarcation are allowed to use this interface) in JNDI API under the name java:comp/UserTransaction.

The container must not make the UserTransaction interface available to the enterprise beans that are not allowed to use this interface. The container should throw javax.naming.NameNotFoundException if an instance of an enterprise bean that is not allowed to use the UserTransaction interface attempts to look up the interface in JNDI API.

The following two code examples are functionally equivalent public MySessionBean implements SessionBean {

Example 1.
   ...
   public someMethod()
   {
      Context initCtx = new InitialContext();
      UserTransaction utx = (UserTransaction)initCtx.lookup(
         "java:comp/UserTransaction");
      utx.begin();
      ...
      utx.commit();
   }
   ...
}
Example 2.
public MySessionBean implements SessionBean {
   SessionContext ctx;
   ...
   public someMethod()
   {
      UserTransaction utx = ctx.getUserTransaction();
      utx.begin();
      ...
      utx.commit();
   }
   ...
}


Chapter EJB.15. Security Management

This chapter defines the EJB architecture support for security management.

The deployment aspect of security management has changed significantly since EJB 1.0. These changes were made primarily to support ISV enterprise beans, which are usually written without the knowledge of the target security domain.


EJB.15.1 Overview

We set the following goals for the security management in the EJB architecture:

  • Lessen the burden of the application developer (i.e., the bean provider) for securing the application by allowing greater coverage from more qualified EJB architecture roles. The EJB container provider provides the implementation of the security infrastructure; the deployer and system administrator define the security policies.

  • Allow the security policies to be set by the application assembler or deployer rather than being hard-coded by the bean provider at development time.

  • Allow the enterprise bean applications to be portable across multiple EJB servers that use different security mechanisms.

The EJB architecture encourages the bean provider to implement the enterprise bean class without hard-coding the security policies and mechanisms into the business methods. In most cases, the enterprise bean's business method should not contain any security-related logic. This allows the deployer to configure the security policies for the application in a way that is most appropriate for the operational environment of the enterprise.

To make the deployer's task easier, the application assembler (which could be the same party as the bean provider) may define security roles for an application composed of one or more enterprise beans. A security role is a semantic grouping of permissions that a given type of users of the application must have in order to use the application successfully. The applications assembler can define (declaratively in the deployment descriptor) method permissions for each security role. A method permission is a permission to invoke a specified group of methods of the enterprise beans' home and remote interfaces. The security roles defined by the application assembler present a simplified security view of the enterprise beans application to the deployer—the deployer's view of the application's security requirements is the small set of security roles rather than a large number of individual methods.

The deployer is responsible for assigning principals, or groups of principals, which are defined in the target operational environment, to the security roles defined by the application assembler for the enterprise beans in the deployment descriptor. The deployer is also responsible for configuring other aspects of the security management of the enterprise beans, such as principal mapping for inter-enterprise bean calls and principal mapping for resource manager access.

At runtime, a client will be allowed to invoke a business method only if the principal associated with the client call has been assigned by the deployer to have at least one security role that is allowed to invoke the business method.

The container provider is responsible for enforcing the security policies at runtime, providing the tools for managing security at runtime, and providing the tools used by the deployer to manage security during deployment.

Because not all security policies can be expressed declaratively, the EJB architecture provides a simple programmatic interface that the bean provider may use to access the security context from the business methods.

The following sections define the responsibilities of the individual EJB roles with respect to security management.


EJB.15.2 Bean Provider's Responsibilities

This section defines the bean provider's perspective of the EJB architecture support for security, and defines his responsibilities.

EJB.15.2.1 Invocation of Other Enterprise Beans

An enterprise bean business method can invoke another enterprise bean via the other bean's remote or home interface. The EJB architecture provides neither pro-grammatic nor deployment descriptor interfaces for the invoking enterprise bean to control the principal passed to the invoked enterprise bean.

The management of caller principals passed on enterprise bean invocations (i.e., principal delegation) is set up by the deployer and system administrator in a container-specific way. The bean provider and application assembler should describe all the requirements for the caller's principal management of inter-enterprise bean invocations as part of the description. The default principal management (in the absence of other deployment instructions) is to propagate the caller principal from the caller to the callee. (That is, the called enterprise bean will see the same returned value of the EJBContext.getCallerPrincipal() as the calling enterprise bean.)

EJB.15.2.2 Resource Access

Section EJB.14.4 defines the protocol for accessing resource managers, including the requirements for security management.

EJB.15.2.3 Access of Underlying OS Resources

The EJB architecture does not define the operating system principal under which enterprise bean methods execute. Therefore, the bean provider cannot rely on a specific principal for accessing the underlying OS resources, such as files. (See Section EJB.15.6.8 for the reasons behind this rule.)

We believe that most enterprise business applications store information in resource managers such as relational databases rather than in resources at the operating system levels. Therefore, this rule should not affect the portability of most enterprise beans.

EJB.15.2.4 Programming Style Recommendations

The bean provider should neither implement security mechanisms nor hard-code security policies in the enterprise beans' business methods. Rather, the bean provider should rely on the security mechanisms provided by the EJB container, and should let the application assembler and deployer define the appropriate security policies for the application.

The bean provider and application assembler may use the deployment descriptor to convey security-related information to the deployer. The information helps the deployer to set up the appropriate security policy for the enterprise bean application.

EJB.15.2.5 Programmatic Access to Caller's Security Context

Note

In general, security management should be enforced by the container in a manner that is transparent to the enterprise beans' business methods. The security API described in this section should be used only in the less frequent situations in which the enterprise bean business methods need to access the security context information.

The javax.ejb.EJBContext interface provides two methods (plus two deprecated methods that were defined in EJB 1.0) that allow the bean provider to access security information about the enterprise bean's caller.

public interface javax.ejb.EJBContext {

   ...

   //
   // The following two methods allow the EJB class
   // to access security information.
   //
   java.security.Principal getCallerPrincipal();
   boolean isCallerInRole(String roleName);

   //
   // The following two EJB 1.0 methods are deprecated.
   //
   java.security.Identity getCallerIdentity();
   boolean isCallerInRole(java.security.Identity role);

   ...

}

The bean provider can invoke the getCallerPrincipal and isCallerInRole methods only in the enterprise bean's business methods for which the container has a client security context, as specified in Table EJB.6-1 on page 406, Table EJB.6-2 on page 417, and Table EJB.9-1 on page 459. If they are invoked when no security context exists, they should throw the java.lang.IllegalStateException runtime exception.

The getCallerIdentity() and isCallerInRole(Identity role) methods are deprecated in EJB 1.1. The bean provider must use the getCallerPrincipal() and isCallerInRole(String roleName) methods for new enterprise beans.

An EJB 1.1 compliant container may choose to implement the two deprecated methods as follows.

  • A container that does not want to provide support for this deprecated method should throw a RuntimeException (or subclass of RuntimeException) from the getCallerIdentity() method.

  • A container that wants to provide support for the getCallerIdentity() method should return an instance of a subclass of the java.security.Identity abstract class from the method. The getName() method invoked on the returned object must return the same value that getCallerPrincipal().getName() would return.

  • A container that does not want to provide support for this deprecated method should throw a RuntimeException (or subclass of RuntimeException) from the isCallerInRole(Identity identity) method.

  • A container that wants to implement the isCallerInRole(Identity identity) method should implement it as follows:

    public isCallerInRole(Identity identity) {
   return isCallerInRole(identity.getName());
}

EJB.15.2.5.1 Use of getCallerPrincipal()

The purpose of the getCallerPrincipal() method is to allow the enterprise bean methods to obtain the current caller principal's name. The methods might, for example, use the name as a key to information in a database.

An enterprise bean can invoke the getCallerPrincipal() method to obtain a java.security.Principal interface representing the current caller. The enterprise bean can then obtain the distinguished name of the caller principal using the getName() method of the java.security.Principal interface.

The meaning of the current caller, the Java class that implements the java.security.Principal interface, and the realm of the principals returned by the getCallerPrincipal() method depend on the operational environment and the configuration of the application.

An enterprise may have a complex security infrastructure that includes multiple security domains. The security infrastructure may perform one or more mappings of principals on the path from an EJB caller to the EJB object. For example, an employee accessing his company over the Internet may be identified by a user id and password (basic authentication), and the security infrastructure may authenticate the principal and then map the principal to a Kerberos principal that is used on the enterprise's intranet before delivering the method invocation to the EJB object. If the security infrastructure performs principal mapping, the getCallerPrincipal() method returns the principal that is the result of the mapping, not the original caller principal. (In the previous example, getCallerPrincipal() would return the Kerberos principal.) The management of the security infrastructure, such as principal mapping, is performed by the system administrator role; it is beyond the scope of the EJB specification.

The following code sample illustrates the use of the getCallerPrincipal() method.

public class EmployeeServiceBean implements SessionBean {
   EJBContext ejbContext;

   public void changePhoneNumber(...) {
      ...

      // Obtain the default initial JNDI context.
      Context initCtx = new InitialContext();

      // Look up the home interface of the EmployeeRecord
      // enterprise bean in the environment.
      Object result = initCtx.lookup(
         "java:comp/env/ejb/EmplRecord");

      // Convert the result to the proper type.
      EmployeeRecordHome emplRecordHome = (EmployeeRecordHome)
         javax.rmi.PortableRemoteObject.narrow(result,
                EmployeeRecordHome.class);

      // obtain the caller principal.
      callerPrincipal = ejbContext.getCallerPrincipal();

      // obtain the caller principal's name.
      callerKey = callerPrincipal.getName();

      // use callerKey as primary key to EmployeeRecord finder
      EmployeeRecord myEmployeeRecord =
         emplRecordHome.findByPrimaryKey(callerKey);

      // update phone number
      myEmployeeRecord.changePhoneNumber(...);

      ...
   }
}

In the previous example, the enterprise bean obtains the principal name of the current caller and uses it as the primary key to locate an EmployeeRecord entity object. This example assumes that application has been deployed such that the current caller principal contains the primary key used for the identification of employees (e.g., employee number).

EJB.15.2.5.2 Use of isCallerInRole(String roleName)

The main purpose of the isCallerInRole(String roleName) method is to allow the bean provider to code the security checks that cannot be easily defined declaratively in the deployment descriptor using method permissions. Such a check might impose a role-based limit on a request, or it might depend on information stored in the database.

The enterprise bean code uses the isCallerInRole(String roleName) method to test whether the current caller has been assigned to a given security role. Security roles are defined by the application assembler in the deployment descriptor (see Section EJB.15.3.1) and are assigned to principals or principal groups that exist in the operational environment by the deployer.

The following code sample illustrates the use of the isCallerInRole(String roleName) method.

public class PayrollBean ... {
   EntityContext ejbContext;

   public void updateEmployeeInfo(EmplInfo info) {

      oldInfo = ... read from database;

      // The salary field can be changed only by caller's
      // who have the security role "payroll"
      if (info.salary != oldInfo.salary &&
         !ejbContext.isCallerInRole("payroll")) {
            throw new SecurityException(...);
      }
      ...
   }
   ...
}
EJB.15.2.5.3 Declaration of Security Roles Referenced from the Bean's Code

The bean provider is responsible for declaring in the security-role-ref elements of the deployment descriptor all the security role names used in the enterprise bean code. Declaring the security roles references in the code allows the application assembler or deployer to link the names of the security roles used in the code to the security roles defined for an assembled application through the security-role elements.

The bean provider must declare each security role referenced in the code using the security-role-ref element as follows:

  • Declare the name of the security role using the role-name element. The name must be the security role name that is used as a parameter to the isCallerInRole(String roleName) method.

  • Optional: Provide a description of the security role in the description element.

A security role reference, including the name defined by the role-name element, is scoped to the session or entity bean element whose declaration contains the security-role-ref element.

The following example illustrates how an enterprise bean's references to security roles are declared in the deployment descriptor.

...
<enterprise-beans>
   ...
   <entity>
      <ejb-name>AardvarkPayroll</ejb-name>
      <ejb-class>com.aardvark.payroll.PayrollBean</ejb-class>
      ...
      <security-role-ref>
         <description>
            This security role should be assigned to the
            employees of the payroll department who are
            allowed to update employees' salaries.
         </description>
         <role-name>payroll</role-name>
      </security-role-ref>
      ...
   </entity>
   ...
</enterprise-beans>
...

The deployment descriptor above indicates that the enterprise bean AardvarkPayroll makes the security check using isCallerInRole("payroll") in its business method.


EJB.15.3 Application Assembler's Responsibilities

The application assembler (which could be the same party as the bean provider) may define a security view of the enterprise beans contained in the EJB JAR file. Providing the security view in the deployment descriptor is optional for the bean provider and application assembler.

The main reason for the application assembler's providing the security view of the enterprise beans is to simplify the deployer's job. In the absence of a security view of an application, the deployer needs detailed knowledge of the application in order to deploy the application securely. For example, the deployer would have to know what each business method does to determine which users can call it. The security view defined by the application assembler presents a more consolidated view to the deployer, allowing the deployer to be less familiar with the application.

The security view consists of a set of security roles. A security role is a semantic grouping of permissions that a given type of users of an application must have in order to use the application successfully.

The applications assembler defines method permissions for each security role. A method permission is a permission to invoke a specified group of methods of the enterprise beans' home and remote interfaces.

It is important to keep in mind that the security roles are used to define the logical security view of an application. They should not be confused with the user groups, users, principals, and other concepts that exist in the target enterprise's operational environment.

In special cases, a qualified deployer may change the definition of the security roles for an application, or completely ignore them and secure the application using a different mechanism that is specific to the operational environment.

If the bean provider has declared any security role references using the security-role-ref elements, the application assembler must link all the security role references listed in the security-role-ref elements to the security roles defined in the security-role elements. This is described in more detail in Section EJB.15.3.3.

EJB.15.3.1 Security Roles

The application assembler can define one or more security roles in the deployment descriptor. The application assembler then assigns groups of methods of the enterprise beans' home and remote interfaces to the security roles to define the security view of the application.

Because the application assembler does not, in general, know the security environment of the operational environment, the security roles are meant to be logical roles (or actors), each representing a type of user that should have the same access rights to the application.

The deployer then assigns user groups and/or user accounts defined in the operational environment to the security roles defined by the application assembler.

Defining the security roles in the deployment descriptor is optional [1] for the application assembler. Their omission in the deployment descriptor means that the application assembler chose not to pass any security deployment related instructions to the deployer in the deployment descriptor.

[1] If the application assembler does not define security roles in the deployment descriptor, the deployer will have to define security roles at deployment time.

The application assembler is responsible for the following:

  • Define each security role using a security-role element.

  • Use the role-name element to define the name of the security role.

  • Optionally, use the description element to provide a description of a security role.

The security roles defined by the security-role elements are scoped to the EJB JAR file level, and apply to all the enterprise beans in the EJB JAR file.

The following example illustrates a security role definition in a deployment descriptor.

   ...
<assembly-descriptor>
   <security-role>
      <description>
         This role includes the employees of the
         enterprise who are allowed to access the
         employee self-service application. This role
         is allowed only to access his/her own
         information.
      </description>
      <role-name>employee</role-name>
   </security-role>

   <security-role>
      <description>
         This role includes the employees of the human
         resources department. The role is allowed to
         view and update all employee records.
      </description>
      <role-name>hr-department</role-name>
   </security-role>

   <security-role>
      <description>
         This role includes the employees of the payroll
         department. The role is allowed to view and
         update the payroll entry for any employee.
      </description>
      <role-name>payroll-department</role-name>
   </security-role>

   <security-role>
      <description>
         This role should be assigned to the personnel
         authorized to perform administrative functions
         for the employee self-service application.
         This role does not have direct access to
         sensitive employee and payroll information.
      </description>
      <role-name>admin</role-name>
   </security-role>
   ...
</assembly-descriptor>

EJB.15.3.2 Method Permissions

If the application assembler has defined security roles for the enterprise beans in the EJB JAR file, he or she can also specify the methods of the remote and home interface that each security role is allowed to invoke.

Method permissions are defined in the deployment descriptor as a binary relation from the set of security roles to the set of methods of the home and remote interfaces of the enterprise beans, including all their superinterfaces (including the methods of the EJBHome and EJBObject interfaces). The method permissions relation includes the pair (R, M) if and only if the security role R is allowed to invoke the method M.

The application assembler defines the method permissions relation in the deployment descriptor using the method-permission elements as follows.

  • Each method-permission element includes a list of one or more security roles and a list of one or more methods. All the listed security roles are allowed to invoke all the listed methods. Each security role in the list is identified by the role-name element, and each method (or a set of methods, as described below) is identified by the method element. An optional description can be associated with a method-permission element using the description element.

  • The method permissions relation is defined as the union of all the method permissions defined in the individual method-permission elements.

  • A security role or a method may appear in multiple method-permission elements.

It is possible that some methods are not assigned to any security roles. This means that none of the security roles defined by the application assembler needs access to the methods.

The method element uses the ejb-name, method-name, and method-params elements to denote one or more methods of an enterprise bean's home and remote interfaces. There are three legal styles for composing the method element:

Style 1:
<method>
     <ejb-name>EJBNAME</ejb-name>
     <method-name>*</method-name>
</method>

This style is used for referring to all of the remote and home interface methods of a specified enterprise bean.

Style 2:
<method>
     <ejb-name>EJBNAME</ejb-name>
     <method-name>METHOD</method-name>
</method>

This style is used for referring to a specified method of the remote or home interface of the specified enterprise bean. If there are multiple methods with the same overloaded name, this style refers to all of the overloaded methods.

Style 3:
<method>
     <ejb-name>EJBNAME</ejb-name>
     <method-name>METHOD</method-name>
     <method-params>
          <method-param>PARAMETER_1</method-param>
          ...
          <method-param>PARAMETER_N</method-param>
     </method-params>
</method>

This style is used to refer to a specified method within a set of methods with an overloaded name. The method must be defined in the specified enterprise bean's remote or home interface.

The optional method-intf element can be used to differentiate methods with the same name and signature that are defined in both the remote and home interfaces.

The following example illustrates how security roles are assigned method permissions in the deployment descriptor:

...
<method-permission>
   <role-name>employee</role-name>
   <method>
      <ejb-name>EmployeeService</ejb-name>
      <method-name>*</method-name>
   </method>
</method-permission>
<method-permission>
   <role-name>employee</role-name>
   <method>
      <ejb-name>AardvarkPayroll</ejb-name>
      <method-name>findByPrimaryKey</method-name>
   </method>
   <method>
      <ejb-name>AardvarkPayroll</ejb-name>
      <method-name>getEmployeeInfo</method-name>
   </method>
   <method>
      <ejb-name>AardvarkPayroll</ejb-name>
      <method-name>updateEmployeeInfo</method-name>
   </method>
</method-permission>

<method-permission>
   <role-name>payroll-department</role-name>
   <method>
      <ejb-name>AardvarkPayroll</ejb-name>
      <method-name>findByPrimaryKey</method-name>
   </method>
   <method>
      <ejb-name>AardvarkPayroll</ejb-name>
      <method-name>getEmployeeInfo</method-name>
   </method>
   <method>
      <ejb-name>AardvarkPayroll</ejb-name>
      <method-name>updateEmployeeInfo</method-name>
   </method>
   <method>
      <ejb-name>AardvarkPayroll</ejb-name>
      <method-name>updateSalary</method-name>
   </method>
</method-permission>

<method-permission>
   <role-name>admin</role-name>
   <method>
      <ejb-name>EmployeeServiceAdmin</ejb-name>
      <method-name>*</method-name>
   </method>
</method-permission>
...

EJB.15.3.3 Linking Security Role References to Security Roles

If the application assembler defines the security-role elements in the deployment descriptor, he or she is also responsible for linking all the security role references declared in the security-role-ref elements to the security roles defined in the security-role elements.

The application assembler links each security role reference to a security role using the role-link element. The value of the role-link element must be the name of one of the security roles defined in a security-role element.

A role-link element must be used even if the value of role-name is the same as the value of the role-link reference.

The following deployment descriptor example shows how to link the security role reference named payroll to the security role named payroll-department.

...
<enterprise-beans>
   ...
   <entity>
      <ejb-name>AardvarkPayroll</ejb-name>
      <ejb-class>com.aardvark.payroll.PayrollBean</ejb-class>
      ...
      <security-role-ref>
         <description>
            This role should be assigned to the
            employees of the payroll department.
            Members of this role have access to
            anyone's payroll record.

            The role has been linked to the
            payroll-department role.
         </description>
         <role-name>payroll</role-name>
         <role-link>payroll-department</role-link>
      </security-role-ref>
      ...
   </entity>
   ...
</enterprise-beans>
...


EJB.15.4 Deployer's Responsibilities

The deployer is responsible for ensuring that an assembled application is secure after it has been deployed in the target operational environment. This section defines the deployer's responsibility with respect to EJB architecture security management.

The deployer uses deployment tools provided by the EJB container provider to read the security view of the application supplied by the application assembler in the deployment descriptor. The deployer's job is to map the security view that was specified by the application assembler to the mechanisms and policies used by the security domain in the target operational environment. The output of the deployer's work includes an application security policy descriptor that is specific to the operational environment. The format of this descriptor and the information stored in the descriptor are specific to the EJB container.

The following subsections describe the security related tasks performed by the deployer.

EJB.15.4.1 Security Domain and Principal Realm Assignment

The deployer is responsible for assigning the security domain and principal realm to an enterprise bean application.

Multiple principal realms within the same security domain may exist, for example, to separate the realms of employees, trading partners, and customers. Multiple security domains may exist, for example, in application hosting scenarios.

EJB.15.4.2 Assignment of Security Roles

The deployer assigns principals and/or groups of principals (such as individual users or user groups) used for managing security in the operational environment to the security roles defined in the security-role elements of the deployment descriptor.

Typically, the deployer does not need to change the method permissions assigned to each security role in the deployment descriptor.

The application assembler linked all the security role references used in the bean's code to the security roles defined in the security-role elements. The deployer does not assign principals and/or principal groups to the security role references—the principals and/or principal groups assigned to a security role apply also to all the linked security role references. For example, the deployer of the AardvarkPayroll enterprise bean in Section EJB.15.3.3 would assign principals and/or principal groups to the security-role payroll-department, and the assigned principals and/or principal groups would be implicitly assigned also to the linked security role payroll.

The EJB architecture does not specify how an enterprise should implement its security architecture. Therefore, the process of assigning the logical security roles defined in the application's deployment descriptor to the operational environment's security concepts is specific to that operational environment. Typically, the deployment process consists of assigning to each security role one or more user groups (or individual users) defined in the operational environment. This assignment is done on a per-application basis. (That is, if multiple independent EJB JAR files use the same security role name, each may be assigned differently.)

EJB.15.4.3 Principal Delegation

The deployer is responsible for configuring the principal delegation for inter-component calls. The deployer must follow any instructions supplied by the application assembler (for example, provided in the description elements of the deployment descriptor, or in a deployment manual).

The default mode is to propagate the caller principal from one component to another (i.e., the caller principal of the first enterprise bean in a call-chain is passed to the enterprise beans down the chain). In the absence of instructions from the application assembler, the deployer should configure the enterprise beans such that this "caller propagation" mode is used when one enterprise bean calls another. This ensures that the returned value of getCallerPrincipal() will be the same for all the enterprise beans involved in a call chain.

EJB.15.4.4 Security Management of Resource Access

The deployer's responsibilities with respect to securing resource managers access are defined in Section EJB.14.4.2.

EJB.15.4.5 General Notes on Deployment Descriptor Processing

The deployer can use the security view defined in the deployment descriptor by the bean provider and application assembler merely as "hints" and may change the information whenever necessary to adapt the security policy to the operational environment.

Since providing the security information in the deployment descriptor is optional for the application assembler, the deployer is responsible for performing any tasks that have not been done by the application assembler. (For example, if the definition of security roles and method permissions is missing in the deployment descriptor, the deployer must define the security roles and method permissions for the application.) It is not required that the deployer store the output of this activity in the standard EJB JAR file format.


EJB.15.5 EJB Architecture Client Responsibilities

This section defines the rules that the EJB architecture client program must follow to ensure that the security context passed on the client calls, and possibly imported by the enterprise bean, does not conflict with the EJB server's capabilities for association between a security context and transactions.

These rules are:

  • A transactional client cannot change its principal association within a transaction. This rule ensures that all calls from the client within a transaction are performed with the same security context.

  • A session bean's client must not change its principal association for the duration of the communication with the session object. This rule ensures that the server can associate a security identity with the session instance at instance creation time, and never have to change the security association during the session instance lifetime.

  • If transactional requests within a single transaction arrive from multiple clients (this could happen if there are intermediary objects or programs in the transaction call-chain), all requests within the same transaction must be associated with the same security context.


EJB.15.6 EJB Container Provider's Responsibilities

This section describes the responsibilities of the EJB container and server provider.

EJB.15.6.1 Deployment Tools

The EJB container provider is responsible for providing the deployment tools that the deployer can use to perform the tasks defined in Section EJB.15.4.

The deployment tools read the information from the deployment descriptor and present the information to the deployer. The tools guide the deployer through the deployment process, and present him or her with choices for mapping the security information in the deployment descriptor to the security management mechanisms and policies used in the target operational environment.

The deployment tools' output is stored in an EJB container specific manner, and is available at runtime to the EJB container.

EJB.15.6.2 Security Domain(s)

The EJB container provides a security domain and one or more principal realms to the enterprise beans. The EJB architecture does not specify how an EJB server should implement a security domain, and does not define the scope of a security domain.

A security domain can be implemented, managed, and administered by the EJB server. For example, the EJB server may store X509 certificates or it might use an external security provider such as Kerberos.

The EJB specification does not define the scope of the security domain. For example, the scope may be defined by the boundaries of the application, EJB server, operating system, network, or enterprise.

The EJB server can, but is not required to, provide support for multiple security domains and/or multiple principal realms.

The case of multiple domains on the same EJB server can happen when a large server is used for application hosting. Each hosted application can have its own security domain to ensure security and management isolation between applications owned by multiple organizations.

EJB.15.6.3 Security Mechanisms

The EJB container provider must provide the security mechanisms necessary to enforce the security policies set by the deployer. The EJB specification does not specify the exact mechanisms that must be implemented and supported by the EJB server.

The typical security functions provided by the EJB server include:

  • Authentication of principals.

  • Access authorization for EJB calls and resource manager access.

  • Secure communication with remote clients (privacy, integrity, etc.).

EJB.15.6.4 Passing Principals on EJB Architecture Calls

The EJB container provider is responsible for providing the deployment tools that allow the deployer to configure the principal delegation for calls from one enterprise bean to another. The EJB container is responsible for performing the principal delegation as specified by the deployer.

The minimal requirement is that the EJB container must be capable of allowing the deployer to specify that the caller principal is propagated on calls from one enterprise bean to another (i.e., the multiple beans in the call chain will see the same return value from getCallerPrincipal()).

This requirement is necessary for applications that need a consistent return value of getCallerPrincipal() across a chain of calls between enterprise beans.

EJB.15.6.5 Security Methods in javax.ejbEJBContext

The EJB container must provide access to the caller's security context information from the enterprise beans' instances via the getCallerPrincipal() and isCallerInRole(String roleName) methods. The EJB container must provide this context information during the execution of a business method invoked via the enterprise bean's remote or home interface, as defined in Table EJB.6-1 on page 406, Table EJB.6-2 on page 417, and Table EJB.9-1 on page 459.

The container must ensure that all enterprise bean method invocations received through the home and remote interfaces are associated with some principal. The container must never return a null from the getCallerPrincipal() method.

EJB.15.6.6 Secure Access to Resource Managers

The EJB container provider is responsible for providing secure access to resource managers as described in Section EJB.14.4.3.

EJB.15.6.7 Principal Mapping

If the application requires that its clients are deployed in a different security domain, or if multiple applications deployed across multiple security domains need to interoperate, the EJB container provider is responsible for the mechanism and tools that allow mapping of principals. The tools are used by the system administrator to configure the security for the application's environment.

EJB.15.6.8 System Principal

The EJB 1.1 specification does not define the "system" principal under which the JVM running an enterprise bean's method executes.

Leaving the principal undefined makes it easier for the EJB container vendors to provide the runtime support for EJB architecture on top of their existing server infrastructures. For example, while one EJB container implementation can execute all instances of all enterprise beans in a single JVM, another implementation can use a separate JVM per EJB JAR per client. Some EJB containers may make the system principal the same as the application-level principal; others may use different principals, potentially from different principal realms and even security domains.

EJB.15.6.9 Runtime Security Enforcement

The EJB container is responsible for enforcing the security policies defined by the deployer. The implementation of the enforcement mechanism is EJB container implementation specific. The EJB container may, but does not have to, use the Java programming language security as the enforcement mechanism.

For example, to isolate multiple executing enterprise bean instances, the EJB container can load the multiple instances into the same Java virtual machine and isolate them via using multiple class-loaders, or it can load each instance into its own Java virtual machine and rely on the address space protection provided by the operation system.

The general security enforcement requirements for the EJB container follow:

  • The EJB container must provide enforcement of the client access control per the policy defined by the deployer. A caller is allowed to invoke a method if, and only if, the caller principal is assigned at least one of the security roles that includes the method in its method permissions definition. (That is, it is not meant that the caller must be assigned all the roles associated with the method.) If the container denies a client access to a business method, the container must throw the java.rmi.RemoteExcetion to the client.

  • The EJB container must isolate an enterprise bean instance from other instances and other application components running on the server. The EJB container must ensure that other enterprise bean instances and other application components are allowed to access an enterprise bean only via the enterprise bean's remote and home interfaces.

  • The EJB container must isolate an enterprise bean instance at runtime such that the instance does not gain unauthorized access to privileged system information. Such information includes the internal implementation classes of the container, the various runtime state and context maintained by the container, object references of other enterprise bean instances, or resource managers used by other enterprise bean instances. The EJB container must ensure that the interactions between the enterprise beans and the container are only through the EJB architected interfaces.

  • The EJB container must ensure the security of the persistent state of the enterprise beans.

  • The EJB container must manage the mapping of principals on calls to other enterprise beans or on access to resource managers according to the security policy defined by the deployer.

  • The container must allow the same enterprise bean to be deployed independently multiple times, each time with a different security policy. [2] The container must allow multiple-deployed enterprise beans to coexist at runtime.

    [2] The enterprise bean is installed each time using a different JNDI name.

EJB.15.6.10 Audit Trail

The EJB container may provide a security audit trail mechanism. A security audit trail mechanism typically logs all java.security.Exceptions. It also logs all denials of access to EJB servers, EJB container, EJB remote interfaces, and EJB home interfaces.


EJB.15.7 System Administrator's Responsibilities

This section defines the security-related responsibilities of the system administrator. Note that some responsibilities may be carried out by the deployer instead, or may require cooperation of the deployer and the system administrator.

EJB.15.7.1 Security Domain Administration

The system administrator is responsible for the administration of principals. Security domain administration is beyond the scope of the EJB specification.

Typically, the system administrator is responsible for creating a new user account, adding a user to a user group, removing a user from a user group, and removing or freezing a user account.

EJB.15.7.2 Principal Mapping

If the client is in a different security domain than the target enterprise bean, the system administrator is responsible for mapping the principals used by the client to the principals defined for the enterprise bean. The result of the mapping is available to the deployer. The specification of principal mapping techniques is beyond the scope of the EJB architecture.

EJB.15.7.3 Audit Trail Review

If the EJB container provides an audit trail facility, the system administrator is responsible for its management.


Chapter EJB.16. Deployment Descriptor

This chapter defines the deployment descriptor that is part of the EJB JAR file. Section EJB.16.1 provides an overview of the deployment descriptor. Sections EJB.16.2 through EJB.16.4 describe the information in the deployment descriptor from the perspective of the EJB roles responsible for providing the information. Section EJB.16.5 defines the deployment descriptor's XML DTD. Section EJB.16.7 provides a complete example of a deployment descriptor of an assembled application.


EJB.16.1 Overview

The deployment descriptor is part of the contract between the EJB JAR file producer and consumer. This contract covers the passing of enterprise beans from the bean provider to the application assembler and from the application assembler to the deployer.

An EJB JAR file produced by the bean provider contains one or more enterprise beans and typically does not contain application assembly instructions. An EJB JAR file produced by an application assembler contains one or more enterprise beans, plus application assembly information describing how the enterprise beans are combined into a single application deployment unit.

The J2EE specification defines how enterprise beans and other application components contained in multiple EJB JAR files can be assembled into an application.

The role of the deployment descriptor is to capture the declarative information (i.e., information that is not included directly in the enterprise beans' code) that is intended for the consumer of the EJB JAR file.

There are two basic kinds of information in the deployment descriptor:

  • Enterprise beans' structural information. Structural information describes the structure of an enterprise bean and declares an enterprise bean's external dependencies. Providing structural information in the deployment descriptor is mandatory for the EJB JAR file producer. The structural information cannot, in general, be changed because doing so could break the enterprise bean's function.

  • Application assembly information. Application assembly information describes how the enterprise bean (or beans) in the EJB JAR file is composed into a larger application deployment unit. Providing assembly information in the deployment descriptor is optional for the EJB JAR file producer. Assembly level information can be changed without breaking the enterprise bean's function, although doing so may alter the behavior of an assembled application.


EJB.16.2 Bean Provider's Responsibilities

The bean provider is responsible for providing the structural information for each enterprise bean in the deployment descriptor.

The bean provider must use the enterprise-beans element to list all the enterprise beans in the EJB JAR file.

The bean provider must provide the following information for each enterprise bean:

  • Enterprise bean's name. The bean provider must assign a logical name to each enterprise bean in the EJB JAR file. There is no architected relationship between this name and the JNDI API name that the deployer will assign to the enterprise bean. The bean provider specifies the enterprise bean's name in the ejb-name element.

  • Enterprise bean's class. The bean provider must specify the fully-qualified name of the class in the Java programming language that implements the enterprise bean's business methods. The bean provider specifies the enterprise bean's class name in the ejb-class element.

  • Enterprise bean's home interfaces. The bean provider must specify the fully-qualified name of the enterprise bean's home interface in the home element.

  • Enterprise bean's remote interfaces. The bean provider must specify the fully-qualified name of the enterprise bean's remote interface in the remote element.

  • Enterprise bean's type. The enterprise bean's types are session and entity. The bean provider must use the appropriate session or entity element to declare the enterprise bean's structural information.

  • Reentrancy indication. The bean provider must specify whether an entity bean is reentrant or not. Session beans are never reentrant.

  • Session bean's state management type. If the enterprise bean is a session bean, the bean provider must use the session-type element to declare whether the session bean is stateful or stateless.

  • Session bean's transaction demarcation type. If the enterprise bean is a session bean, the bean provider must use the transaction-type element to declare whether transaction demarcation is performed by the enterprise bean or by the container.

  • Entity bean's persistence management. If the enterprise bean is an entity bean, the bean provider must use the persistence-type element to declare whether persistence management is performed by the enterprise bean or by the container.

  • Entity bean's primary key class. If the enterprise bean is an entity bean, the bean provider specifies the fully-qualified name of the entity bean's primary key class in the prim-key-class element. The bean provider must specify the primary key class for an entity with bean-managed persistence, and may (but is not required to) specify the primary key class for an entity with container-managed persistence.

  • Container-managed fields. If the enterprise bean is an entity bean with container-managed persistence, the bean provider must specify the container-managed fields using the cmp-fields elements.

  • Environment entries. The bean provider must declare all the enterprise bean's environment entries as specified in Section EJB.14.2.1.

  • Resource manager connection factory references. The bean provider must declare all the enterprise bean's resource manager connection factory references as specified in Section EJB.14.4.1.

  • EJB references. The bean provider must declare all the enterprise bean's references to the homes of other enterprise beans as specified in Section EJB.14.3.1.

  • Security role references. The bean provider must declare all the enterprise bean's references to security roles as specified in Section EJB.15.2.5.3.

The deployment descriptor produced by the bean provider must be well formed in the XML sense, and valid with respect to the DTD in Section EJB.16.5.

The content of the deployment descriptor must conform to the semantics rules specified in the DTD comments and elsewhere in this specification. The deployment descriptor must refer to the DTD using the following statement:

<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.
//DTD Enterprise JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-
jar_1_1.dtd">


EJB.16.3 Application Assembler's Responsibility

The application assembler assembles enterprise beans into a single deployment unit. The application assembler's input is one or more EJB JAR files provided by one or more bean providers, and the output is also one or more EJB JAR files. The application assembler can combine multiple input EJB JAR files into a single output EJB JAR file, or split an input EJB JAR file into multiple output EJB JAR files. Each output EJB JAR file is either a deployment unit intended for the deployer or a partially assembled application that is intended for another application assembler.

The bean provider and application assembler may be the same person or organization. In such a case, the person or organization performs the responsibilities described in both this and the previous sections.

The application assembler may modify the following information that was specified by the bean provider:

  • Enterprise bean's name. The application assembler may change the enterprise bean's name defined in the ejb-name element.

  • Values of environment entries. The application assembler may change existing and/or define new values of environment properties.

  • Description fields. The application assembler may change existing or create new description elements.

The application assembler must not, in general, modify any other information listed in Section EJB.16.2 that was provided in the input EJB JAR file.

In addition, the application assembler may, but is not required to, specify any of the following application assembly information:

  • Binding of enterprise bean references. The application assembler may link an enterprise bean reference to another enterprise bean in the EJB JAR file. The application assembler creates the link by adding the ejb-link element to the referencing bean.

  • Security roles. The application assembler may define one or more security roles. The security roles define the recommended security roles for the clients of the enterprise beans. The application assembler defines the security roles using the security-role elements.

  • Method permissions. The application assembler may define method permissions. Method permission is a binary relation between the security roles and the methods of the remote and home interfaces of the enterprise beans. The application assembler defines method permissions using the method-permission elements.

  • Linking of security role references. If the application assembler defines security roles in the deployment descriptor, the application assembler must link the security role references declared by the bean provider to the security roles. The application assembler defines these links using the role-link element.

  • Transaction attributes. The application assembler may define the value of the transaction attributes for the methods of the remote and home interfaces of the enterprise beans that require container-managed transaction demarcation. All entity beans and the session beans declared by the bean provider as transaction-type Container require container-managed transaction demarcation. The application assembler uses the container-transaction elements to declare the transaction attributes.

If an input EJB JAR file contains application assembly information, the application assembler is allowed to change the application assembly information supplied in the input EJB JAR file. (This could happen when the input EJB JAR file was produced by another application assembler.)

The deployment descriptor produced by the bean provider must be well formed in the XML sense, and valid with respect to the DTD in Section EJB.16.5. The content of the deployment descriptor must conform to the semantic rules specified in the DTD comments and elsewhere in this specification. The deployment descriptor must refer to the DTD using the following statement:

<!DOCTYPE EJB JAR PUBLIC "-//Sun Microsystems, Inc.
//DTD Enterprise JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-
jar_1_1.dtd">


EJB.16.4 Container Provider's Responsibilities

The container provider provides tools that read and import the information contained in the XML deployment descriptor.


EJB.16.5 Deployment Descriptor DTD

This section defines the XML DTD for the EJB EJB.1.1 deployment descriptor. The comments in the DTD specify additional requirements for the syntax and semantics that cannot be easily expressed by the DTD mechanism.

The content of the XML elements is in general case sensitive. This means, for example, that

<reentrant>True</reentrant>

must be used, rather than

<reentrant>true</reentrant>.

All valid EJB JAR deployment descriptors must contain the following DOCTYPE declaration:

<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.
//DTD Enterprise JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-
jar_1_1.dtd">

We plan to provide an EJB JAR file verifier that can be used by the bean provider and application assembler roles to ensure that an EJB JAR is valid. The verifier would check all the requirements for the EJB JAR file and the deployment descriptor stated by this specification.

<!--
This is the XML DTD for the EJB 1.1 deployment descriptor.
-->

<!--
The assembly-descriptor element contains application-assembly
information.

The application-assembly information consists of the following
parts: the definition of security roles, the definition of method
permissions, and the definition of transaction attributes for
enterprise beans with container-managed transaction demarcation.

All the parts are optional in the sense that they are omitted if
the lists represented by them are empty.

Providing an assembly-descriptor in the deployment descriptor is
optional for the ejb-jar file producer.

Used in: ejb-jar
-->
<!ELEMENT assembly-descriptor (security-role*, method-permission*,
      container-transaction*)>

<!--
The cmp-field element describes a container-managed field. The
field element includes an optional description of the field, and
the name of the field.

Used in: entity
-->
<!ELEMENT cmp-field (description?, field-name)>

<!--
The container-transaction element specifies how the container must
manage transaction scopes for the enterprise bean's method
invocations. The element consists of an optional description, a list
of method elements, and a transaction attribute.The transaction
attribute is to be applied to all the specified methods.

Used in: assembly-descriptor
-->
<!ELEMENT container-transaction (description?, method+,
      trans-attribute)>

<!--
The description element is used by the ejb-jar file producer to
provide text describing the parent element.

The description element should include any information that the
ejb-jar file producer wants to provide to the consumer of the ejb-
jar file (i.e., to the Deployer). Typically, the tools used by the
ejb-jar file consumer will display the description when processing
the parent element.

Used in: cmp-field, container-transaction, ejb-jar, entity, env-
entry, ejb-ref, method, method-permission, resource-ref, security-
role, security-role-ref, and session.
-->
<!ELEMENT description (#PCDATA)>

<!--
The display-name element contains a short name that is intended to
be display by tools.

Used in: ejb-jar, session, and entity

Example:
   <display-name>Employee Self Service</display-name>
-->
<!ELEMENT display-name (#PCDATA)>

<!--
The ejb-class element contains the fully-qualified name of the enterprise bean's
class.

Used in: entity and session

Example:
      <ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
-->
<!ELEMENT ejb-class (#PCDATA)>

<!--
The optional ejb-client-jar element specifies a JAR file that
contains the class files necessary for a client program to access
the enterprise beans in the ejb-jar file. The deployer should make
the ejb-client JAR file accessible to the client's class-loader.

Used in: ejb-jar

Example:
   <ejb-client-jar>employee_service_client.jar</ejb-client-jar>
-->
<!ELEMENT ejb-client-jar (#PCDATA)>

<!--
The ejb-jar element is the root element of the EJB deployment
descriptor. It contains an optional description of the ejb-jar
file, optional display name, optional small icon file name,
optional large icon file name, mandatory structural information
about all included enterprise beans, optional application-assembly
descriptor, and an optional name of an ejb-client-jar file for the
ejb-jar.
-->
<!ELEMENT ejb-jar (description?, display-name?, small-icon?,
      large-icon?, enterprise-beans, assembly-descriptor?,
      ejb-client-jar?)>

<!--
The ejb-link element is used in the ejb-ref element to specify
that an EJB reference is linked to another enterprise bean in the
ejb-jar file.

The value of the ejb-link element must be the ejb-name of an
enterprise bean in the same ejb-jar file, or in another ejb-jar
file in the same J2EE application unit.

Used in: ejb-ref

Example:
      <ejb-link>EmployeeRecord</ejb-link>
-->
<!ELEMENT ejb-link (#PCDATA)>

<!--
The ejb-name element specifies an enterprise bean's name. This
name is assigned by the ejb-jar file producer to name the
enterprise bean in the ejb-jar file's deployment descriptor. The
name must be unique among the names of the enterprise beans in the
same ejb-jar file.

The enterprise bean code does not depend on the name; therefore
the name can be changed during the application-assembly process
without breaking the enterprise bean's function.

There is no architected relationship between the ejb-name in the
deployment descriptor and the JNDI name that the deployer will
assign to the enterprise bean's home.

The name must conform to the lexical rules for an NMTOKEN.

Used in: entity, method, and session
Example:
      <ejb-name>EmployeeService</ejb-name>
-->
<!ELEMENT ejb-name (#PCDATA)>

<!--
The ejb-ref element is used for the declaration of a reference to
another enterprise bean's home. The declaration consists of an
optional description; the EJB reference name used in the code of
the referencing enterprise bean; the expected type of the
referenced enterprise bean; the expected home and remote
interfaces of the referenced enterprise bean; and an optional ejb-
link information.

The optional ejb-link element is used to specify the referenced
enterprise bean. It is used typically in ejb-jar files that
contain an assembled application.

Used in: entity and session
-->
<!ELEMENT ejb-ref (description?, ejb-ref-name, ejb-ref-type, home,
      remote, ejb-link?)>

<!--
The ejb-ref-name element contains the name of an EJB reference.
The EJB reference is an entry in the enterprise bean's
environment.

It is recommended that name is prefixed with "ejb/".

Used in: ejb-ref

Example:
      <ejb-ref-name>ejb/Payroll</ejb-ref-name>
-->
<!ELEMENT ejb-ref-name (#PCDATA)>

<!--
The ejb-ref-type element contains the expected type of the
referenced enterprise bean.

The ejb-ref-type element must be one of the following:
       <ejb-ref-type>Entity</ejb-ref-type>
       <ejb-ref-type>Session</ejb-ref-type>

Used in: ejb-ref
-->
<!ELEMENT ejb-ref-type (#PCDATA)>

<!--
The enterprise-beans element contains the declarations of one or
more enterprise beans.
-->
<!ELEMENT enterprise-beans (session | entity)+>

<!--
The entity element declares an entity bean. The declaration
consists of: an optional description; optional display name;
optional small icon file name; optional large icon file name; a
name assigned to the enterprise bean in the deployment descriptor;
the names of the entity bean's home and remote interfaces; the
entity bean's implementation class; the entity bean's persistence
management type; the entity bean's primary key class name; an
indication of the entity bean's reentrancy; an optional list of
container-managed fields; an optional specification of the primary
key field; an optional declaration of the bean's environment
entries; an optional declaration of the bean's EJB references; an
optional declaration of the security role references; and an
optional declaration of the bean's resource manager connection
factory references.

The optional primkey-field may be present in the descriptor if the
entity's persistency-type is container.

The other elements that are optional are "optional" in the sense
that they are omitted if the lists represented by them are empty.

At least one cmp-field element must be present in the descriptor
if the entity's persistency-type is container, and none must not
be present if the entity's persistence-type is Bean.

Used in: enterprise-beans
-->
<!ELEMENT entity (description?, display-name?, small-icon?,
      large-icon?, ejb-name, home, remote, ejb-class,
      persistence-type, prim-key-class, reentrant,
      cmp-field*, primkey-field?, env-entry*,
      ejb-ref*, security-role-ref*, resource-ref*)>

<!--
The env-entry element contains the declaration of an enterprise
bean's environment entries. The declaration consists of an
optional description, the name of the environment entry, and an
optional value.

Used in: entity and session
-->
<!ELEMENT env-entry (description?, env-entry-name, env-entry-type,
      env-entry-value?)>

<!--
The env-entry-name element contains the name of an enterprise
bean's environment entry.

Used in: env-entry

Example:
      <env-entry-name>minAmount</env-entry-name>
-->
<!ELEMENT env-entry-name (#PCDATA)>

<!--
The env-entry-type element contains the fully-qualified Java type
of the environment entry value that is expected by the enterprise
bean's code.

The following are the legal values of env-entry-type:
java.lang.Boolean, java.lang.String, java.lang.Integer,
java.lang.Double, java.lang.Byte, java.lang.Short, java.lang.Long,
and java.lang.Float.

Used in: env-entry

Example:
      <env-entry-type>java.lang.Boolean</env-entry-type>
-->
<!ELEMENT env-entry-type (#PCDATA)>

<!--
The env-entry-value element contains the value of an enterprise
bean's environment entry.

Used in: env-entry

Example:
      <env-entry-value>100.00</env-entry-value>
-->
<!ELEMENT env-entry-value (#PCDATA)>

<!--
The field-name element specifies the name of a container managed
field. The name must be a public field of the enterprise bean
class or one of its superclasses.

Used in: cmp-field

Example:
      <field-name>firstName</field-Name>
-->
<!ELEMENT field-name (#PCDATA)>

<!--
The home element contains the fully-qualified name of the
enterprise bean's home interface.

Used in: ejb-ref, entity, and session

Example:
      <home>com.aardvark.payroll.PayrollHome</home>
-->
<!ELEMENT home (#PCDATA)>

<!--
The large-icon element contains the name of a file containing a
large (32 x 32) icon image. The file name is relative path within
the ejb-jar file.

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.

Example:
   <large-icon>employee-service-icon32x32.jpg</large-icon>
-->
<!ELEMENT large-icon (#PCDATA)>

<!--
The method element is used to denote a method of an enterprise
bean's home or remote interface, or a set of methods. The ejb-name
element must be the name of one of the enterprise beans declared
in the deployment descriptor; the optional method-intf element
allows to distinguish between a method with the same signature
that is defined in both the home and remote interface; the method-
name element specifies the method name; and the optional method-
params elements identify a single method among multiple methods
with an overloaded method name.

There are three possible styles of the method element syntax:

1. <method>
      <ejb-name>EJBNAME</ejb-name>
      <method-name>*</method-name>
   </method>

   This style is used to refer to all the methods of the specified
   enterprise bean's home and remote interfaces.

2. <method>
      <ejb-name>EJBNAME</ejb-name>
      <method-name>METHOD</method-name>
   </method>>

   This style is used to refer to the specified method of the
   specified enterprise bean. If there are multiple methods with
   the same overloaded name, the element of this style refers to
   all the methods with the overloaded name.

3. <method>
      <ejb-name>EJBNAME</ejb-name>
      <method-name>METHOD</method-name>
      <method-params>
         <method-param>PARAM-1</method-param>
         <method-param>PARAM-2</method-param>
         ...
         <method-param>PARAM-n</method-param>
      </method-params>
   <method>

   This style is used to refer to a single method within a set of
   methods with an overloaded name. PARAM-1 through PARAM-n are
   the fully-qualified Java types of the method's input parameters
   (if the method has no input arguments, the method-params
   element contains no method-param elements). Arrays are
   specified by the array element's type, followed by one or more
   pair of square brackets (e.g., int[][]).

Used in: method-permission and container-transaction

Examples:

   Style 1: The following method element refers to all the methods
       of the EmployeeService bean's home and remote interfaces:

       <method>
          <ejb-name>EmployeeService</ejb-name>
          <method-name>*</method-name>
       </method>

   Style 2: The following method element refers to all the create
       methods of the EmployeeService bean's home interface:

       <method>
          <ejb-name>EmployeeService</ejb-name>
          <method-name>create</method-name>
       </method>

   Style 3: The following method element refers to the
       create(String firstName, String LastName) method of the
       EmployeeService bean's home interface.

       <method>
          <ejb-name>EmployeeService</ejb-name>
          <method-name>create</method-name>
          <method-params>
             <method-param>java.lang.String</method-param>
             <method-param>java.lang.String</method-param>
          </method-params>
       </method>

   The following example illustrates a Style 3 element with
   more complex parameter types. The method
          foobar(char s, int i, int[] iar, mypackage.MyClass mycl,
            mypackage.MyClass[][] myclaar)
       would be specified as:

       <method>
          <ejb-name>EmployeeService</ejb-name>
          <method-name>foobar</method-name>
          <method-params>
             <method-param>char</method-param>
             <method-param>int</method-param>
             <method-param>int[]</method-param>
             <method-param>mypackage.MyClass</method-param>
             <method-param>mypackage.MyClass[][]</method-param>
          </method-params>
       </method>

   The optional method-intf element can be used when it becomes
   necessary to differentiate between a method defined in the home
   interface and a method with the same name and signature that is
   defined in the remote interface.

   For example, the method element

       <method>
          <ejb-name>EmployeeService</ejb-name>
          <method-intf>Remote</method-intf>
          <method-name>create</method-name>
          <method-params>
             <method-param>java.lang.String</method-param>
             <method-param>java.lang.String</method-param>
          </method-params>
       </method>

   can be used to differentiate the create(String, String) method
   defined in the remote interface from the create(String, String)
   method defined in the home interface, which would be defined as

       <method>
          <ejb-name>EmployeeService</ejb-name>
          <method-intf>Home</method-intf>
          <method-name>create</method-name>
          <method-params>
             <method-param>java.lang.String</method-param>
             <method-param>java.lang.String</method-param>
          </method-params>
       </method>

   The method-intf element can be used with all three Styles of
   the method element usage. For example, the following method
   element example could be used to refer to all the methods of
   the EmployeeService bean's home interface.

       <method>
          <ejb-name>EmployeeService</ejb-name>
          <method-intf>Home</method-intf>
          <method-name>*</method-name>
       </method>

-->
<!ELEMENT method (description?, ejb-name, method-intf?, method-
          name, method-params?)>

<!--
The method-intf element allows a method element to differentiate
between the methods with the same name and signature that are
defined in both the remote and home interfaces.

The method-intf element must be one of the following:
      <method-intf>Home</method-intf>
      <method-intf>Remote</method-intf>

Used in: method
-->
<!ELEMENT method-intf (#PCDATA)>

<!--
The method-name element contains a name of an enterprise bean
method, or the asterisk (*) character. The asterisk is used when
the element denotes all the methods of an enterprise bean's remote
and home interfaces.

Used in: method
-->
<!ELEMENT method-name (#PCDATA)>

<!--
The method-param element contains the fully-qualified Java type
name of a method parameter.

Used in: method-params
-->
<!ELEMENT method-param (#PCDATA)>

<!--
The method-params element contains a list of the fully-qualified
Java type names of the method parameters.

Used in: method
-->
<!ELEMENT method-params (method-param*)>

<!--
The method-permission element specifies that one or more security
roles are allowed to invoke one or more enterprise bean methods.
The method-permission element consists of an optional description,
a list of security role names, and a list of method elements.

The security roles used in the method-permission element must be
defined in the security-role element of the deployment descriptor,
and the methods must be methods defined in the enterprise bean's
remote and/or home interfaces.

Used in: assembly-descriptor
-->
<!ELEMENT method-permission (description?, role-name+, method+)>

<!--
The persistence-type element specifies an entity bean's
persistence management type.

The persistence-type element must be one of the two following:
       <persistence-type>Bean</persistence-type>
       <persistence-type>Container</persistence-type>

Used in: entity
-->
<!ELEMENT persistence-type (#PCDATA)>

<!--
The prim-key-class element contains the fully-qualified name of an
entity bean's primary key class.

If the definition of the primary key class is deferred to
deployment time, the prim-key-class element should specify
java.lang.Object.

Used in: entity

Examples:
   <prim-key-class>java.lang.String</prim-key-class>
   <prim-key-class>com.wombat.empl.EmployeeID</prim-key-class>
   <prim-key-class>java.lang.Object</prim-key-class>

-->
<!ELEMENT prim-key-class (#PCDATA)>

<!--
The primkey-field element is used to specify the name of the
primary key field for an entity with container-managed
persistence.

The primkey-field must be one of the fields declared in the cmp-
field element, and the type of the field must be the same as the
primary key type.

The primkey-field element is not used if the primary key maps
to multiple container-managed fields (i.e., the key is a compound
key). In this case, the fields of the primary key class must be
public, and their names must correspond to the field names of the
entity bean class that comprise the key.

Used in: entity

Example:
   <primkey-field>EmployeeId</primkey-field>
-->
<!ELEMENT primkey-field (#PCDATA)>

<!--
The reentrant element specifies whether an entity bean is
reentrant or not.

The reentrant element must be one of the two following:
      <reentrant>True</reentrant>
      <reentrant>False</reentrant>

Used in: entity
-->
<!ELEMENT reentrant (#PCDATA)>

<!--
The remote element contains the fully-qualified name of the
enterprise bean's remote interface.

Used in: ejb-ref, entity, and session

Example:
      <remote>com.wombat.empl.EmployeeService</remote>
-->
<!ELEMENT remote (#PCDATA)>

<!--
The res-auth element specifies whether the enterprise bean code
signs on programmatically to the resource manager, or whether the
Container will sign on to the resource manager on behalf of the
bean. In the latter case, the Container uses information that is
supplied by the Deployer.

The value of this element must be one of the two following:
       <res-auth>Application</res-auth>
       <res-auth>Container</res-auth>
-->
<!ELEMENT res-auth (#PCDATA)>

<!--
The res-ref-name element specifies the name of a resource manager
connection factory reference.

Used in: resource-ref
-->
<!ELEMENT res-ref-name (#PCDATA)>

<!--
The res-type element specifies the type of the data source. The
type is specified by the Java interface (or class) expected to be
implemented by the data source.

Used in: resource-ref
-->
<!ELEMENT res-type (#PCDATA)>

<!--
The resource-ref element contains a declaration of enterprise
bean's reference to an external resource. It consists of an
optional description, the resource manager connection factory
reference name, the indication of the resource manager connection
factory type expected by the enterprise bean code, and the type of
authentication (bean or container).

Used in: entity and session

Example:
      <resource-ref>
         <res-ref-name>EmployeeAppDB</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Container</res-auth>
      </resource-ref>
-->
<!ELEMENT resource-ref (description?, res-ref-name, res-type,
          res-auth)>

<!--
The role-link element is used to link a security role reference to
a defined security role. The role-link element must contain the
name of one of the security roles defined in the security-role
elements.

Used in: security-role-ref
-->
<!ELEMENT role-link (#PCDATA)>

<!--
The role-name element contains the name of a security role.

The name must conform to the lexical rules for an NMTOKEN.

Used in: method-permission, security-role, and security-role-ref
-->
<!ELEMENT role-name (#PCDATA)>

<!--
The security-role element contains the definition of a security
role. The definition consists of an optional description of the
security role, and the security role name.

Used in: assembly-descriptor

Example:
      <security-role>
         <description>
            This role includes all employees who are authorized
            to access the employee service application.
         </description>
         <role-name>employee</role-name>
      </security-role>
-->
<!ELEMENT security-role (description?, role-name)>

<!--
The security-role-ref element contains the declaration of a
security role reference in the enterprise bean's code. The
declaration consists of an optional description, the security role
name used in the code, and an optional link to a defined security
role.

The value of the role-name element must be the String used as the
parameter to the EJBContext.isCallerInRole(String roleName)
method.

The value of the role-link element must be the name of one of the
security roles defined in the security-role elements.

Used in: entity and session

-->
<!ELEMENT security-role-ref (description?, role-name, role-link?)>

<!--
The session-type element describes whether the session bean is a
stateful session, or stateless session.

The session-type element must be one of the two following:
       <session-type>Stateful</session-type>
       <session-type>Stateless</session-type>
-->
<!ELEMENT session-type (#PCDATA)>

<!--
The session element declares an session bean. The declaration
consists of: an optional description; optional display name;
optional small icon file name; optional large icon file name; a
name assigned to the enterprise bean in the deployment
description; the names of the session bean's home and remote
interfaces; the session bean's implementation class; the session
bean's state management type; the session bean's transaction
management type; an optional declaration of the bean's environment
entries; an optional declaration of the bean's EJB references; an
optional declaration of the security role references; and an
optional declaration of the bean's resource manager connection
factory references.

The elements that are optional are "optional" in the sense that
they are omitted when if lists represented by them are empty.

Used in: enterprise-beans
-->
<!ELEMENT session (description?, display-name?, small-icon?,
      large-icon?, ejb-name, home, remote, ejb-class,
      session-type, transaction-type, env-entry*,
      ejb-ref*, security-role-ref*, resource-ref*)>

<!--
The small-icon element contains the name of a file containing a
small (16 x 16) icon image. The file name is relative path within
the ejb-jar file.

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.

Example:
   <small-icon>employee-service-icon16x16.jpg</small-icon>
-->
<!ELEMENT small-icon (#PCDATA)>

<!--
The transaction-type element specifies an enterprise bean's
transaction management type.

The transaction-type element must be one of the two following:
      <transaction-type>Bean</transaction-type>
      <transaction-type>Container</transaction-type>

Used in: session
-->
<!ELEMENT transaction-type (#PCDATA)>

<!--
The trans-attribute element specifies how the container must
manage the transaction boundaries when delegating a method
invocation to an enterprise bean's business method.

The value of trans-attribute must be one of the following:
      <trans-attribute>NotSupported</trans-attribute>
      <trans-attribute>Supports</trans-attribute>
      <trans-attribute>Required</trans-attribute>
      <trans-attribute>RequiresNew</trans-attribute>
      <trans-attribute>Mandatory</trans-attribute>
      <trans-attribute>Never</trans-attribute>

Used in: container-transaction
-->
<!ELEMENT trans-attribute (#PCDATA)>

<!--
The ID mechanism is to allow tools that produce additional
deployment information (i.e information beyond the standard EJB
deployment descriptor information) to store the non-standard
information in a separate file, and easily refer from these tools-
specific files to the information in the standard deployment
descriptor.

The EJB architecture does not allow the tools to add the non-
standard information into the EJB deployment descriptor.
-->
<!ATTLIST assembly-descriptor id ID #IMPLIED>
<!ATTLIST cmp-field id ID #IMPLIED>
<!ATTLIST container-transaction id ID #IMPLIED>
<!ATTLIST description id ID #IMPLIED>
<!ATTLIST display-name id ID #IMPLIED>
<!ATTLIST ejb-class id ID #IMPLIED>
<!ATTLIST ejb-client-jar id ID #IMPLIED>
<!ATTLIST ejb-jar id ID #IMPLIED>
<!ATTLIST ejb-link id ID #IMPLIED>
<!ATTLIST ejb-name id ID #IMPLIED>
<!ATTLIST ejb-ref id ID #IMPLIED>
<!ATTLIST ejb-ref-name id ID #IMPLIED>
<!ATTLIST ejb-ref-type id ID #IMPLIED>
<!ATTLIST enterprise-beans id ID #IMPLIED>
<!ATTLIST entity id ID #IMPLIED>
<!ATTLIST env-entry id ID #IMPLIED>
<!ATTLIST env-entry-name id ID #IMPLIED>
<!ATTLIST env-entry-type id ID #IMPLIED>
<!ATTLIST env-entry-value id ID #IMPLIED>
<!ATTLIST field-name id ID #IMPLIED>
<!ATTLIST home id ID #IMPLIED>
<!ATTLIST large-icon id ID #IMPLIED>
<!ATTLIST method id ID #IMPLIED>
<!ATTLIST method-intf id ID #IMPLIED>
<!ATTLIST method-name id ID #IMPLIED>
<!ATTLIST method-param id ID #IMPLIED>
<!ATTLIST method-params id ID #IMPLIED>
<!ATTLIST method-permission id ID #IMPLIED>
<!ATTLIST persistence-type id ID #IMPLIED>
<!ATTLIST prim-key-class id ID #IMPLIED>
<!ATTLIST primkey-field id ID #IMPLIED>
<!ATTLIST reentrant id ID #IMPLIED>
<!ATTLIST remote id ID #IMPLIED>
<!ATTLIST res-auth id ID #IMPLIED>
<!ATTLIST res-ref-name id ID #IMPLIED>
<!ATTLIST res-type id ID #IMPLIED>
<!ATTLIST resource-ref id ID #IMPLIED>
<!ATTLIST role-link id ID #IMPLIED>
<!ATTLIST role-name id ID #IMPLIED>
<!ATTLIST security-role id ID #IMPLIED>
<!ATTLIST security-role-ref id ID #IMPLIED>
<!ATTLIST session-type id ID #IMPLIED>
<!ATTLIST session id ID #IMPLIED>
<!ATTLIST small-icon id ID #IMPLIED>
<!ATTLIST transaction-type id ID #IMPLIED>
<!ATTLIST trans-attribute id ID #IMPLIED>


EJB.16.6 Deployment Descriptor Example

The following example illustrates a sample deployment descriptor for the EJB JAR containing the Wombat's assembled application described in Section EJB.3.2.

Note

The text in the <description> elements has been formatted by adding white space to appear properly indented in this document. In a real deployment descriptor document, the <description> elements would likely contain no extra white space characters.

<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.
//DTD Enterprise JavaBeans 1.1//EN"
"http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd"><ejb-jar>
   <description>
      This ejb-jar file contains assembled enterprise beans that
      are part of employee self-service application.
   </description>

   <enterprise-beans>
      <session>
         <description>
            The EmployeeService session bean implements a session
            between an employee and the employee self-service
            application.
         </description>
         <ejb-name>EmployeeService</ejb-name>
         <home>com.wombat.empl.EmployeeServiceHome</home>
         <remote>com.wombat.empl.EmployeeService</remote>
         <ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Bean</transaction-type>

         <env-entry>
            <env-entry-name>envvar1</env-entry-name>
            <env-entry-type>String</env-entry-type>
            <env-entry-value>some value</env-entry-value>

         </env-entry>

         <ejb-ref>
            <ejb-ref-name>ejb/EmplRecords</ejb-ref-name>
            <ejb-ref-type>Entity</ejb-ref-type>
            <home>com.wombat.empl.EmployeeRecordHome</home>
            <remote>com.wombat.empl.EmployeeRecord</remote>
            <ejb-link>EmployeeRecord</ejb-link>
         </ejb-ref>

         <ejb-ref>
            <ejb-ref-name>ejb/Payroll</ejb-ref-name>
            <ejb-ref-type>Entity</ejb-ref-type>
            <home>com.aardvark.payroll.PayrollHome</home>
            <remote>com.aardvark.payroll.Payroll</remote>
            <ejb-link>AardvarkPayroll</ejb-link>
         </ejb-ref>

         <ejb-ref>
            <ejb-ref-name>ejb/PensionPlan</ejb-ref-name>
            <ejb-ref-type>Session</ejb-ref-type>
            <home>com.wombat.empl.PensionPlanHome</home>
            <remote>com.wombat.empl.PensionPlan</remote>
         </ejb-ref>

         <resource-ref>
            <description>
               This is a reference to a JDBC database.
               EmployeeService keeps a log of all transactions
               performed through the EmployeeService bean for
               auditing purposes.
            </description>
            <res-ref-name>jdbc/EmployeeAppDB</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
         </resource-ref>
      </session>

      <session>
         <description>
            The EmployeeServiceAdmin session bean implements
            the session used by the application's administrator.
         </description>

         <ejb-name>EmployeeServiceAdmin</ejb-name>
         <home>com.wombat.empl.EmployeeServiceAdminHome</home>
         <remote>com.wombat.empl.EmployeeServiceAdmin</remote>
         <ejb-class>
            com.wombat.empl.EmployeeServiceAdminBean</ejb-class>
         <session-type>Stateful</session-type>
         <transaction-type>Bean</transaction-type>

         <resource-ref>
            <description>
               This is a reference to a JDBC database.
               EmployeeService keeps a log of all transactions
               performed through the EmployeeService bean for
               auditing purposes.
            </description>
            <res-ref-name>jdbc/EmployeeAppDB</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
         </resource-ref>
      </session>

      <entity>
         <description>
            The EmployeeRecord entity bean encapsulates access
            to the employee records.The deployer will use
            container-managed persistence to integrate the
            entity bean with the back-end system managing
            the employee records.
         </description>

         <ejb-name>EmployeeRecord</ejb-name>
         <home>com.wombat.empl.EmployeeRecordHome</home>
         <remote>com.wombat.empl.EmployeeRecord</remote>
         <ejb-class>com.wombat.empl.EmployeeRecordBean</ejb-class>
         <persistence-type>Container</persistence-type>
         <prim-key-class>com.wombat.empl.EmployeeID
            </prim-key-class>
         <reentrant>True</reentrant>

         <cmp-field><field-name>employeeID</field-name>
            </cmp-field>
         <cmp-field><field-name>firstName</field-name></cmp-field>
         <cmp-field><field-name>lastName</field-name></cmp-field>
         <cmp-field><field-name>address1</field-name></cmp-field>
         <cmp-field><field-name>address2</field-name></cmp-field>
         <cmp-field><field-name>city</field-name></cmp-field>
         <cmp-field><field-name>state</field-name></cmp-field>
         <cmp-field><field-name>zip</field-name></cmp-field>
         <cmp-field><field-name>homePhone</field-name></cmp-field>
         <cmp-field><field-name>jobTitle</field-name></cmp-field>
         <cmp-field><field-name>managerID</field-name></cmp-field>
         <cmp-field><field-name>jobTitleHistory
            </field-name></cmp-field>
      </entity>

      <entity>
         <description>
            The Payroll entity bean encapsulates access
            to the payroll system.The deployer will use
            container-managed persistence to integrate the
            entity bean with the back-end system managing
            payroll information.
         </description>

         <ejb-name>AardvarkPayroll</ejb-name>
         <home>com.aardvark.payroll.PayrollHome</home>
         <remote>com.aardvark.payroll.Payroll</remote>
         <ejb-class>com.aardvark.payroll.PayrollBean</ejb-class>
         <persistence-type>Bean</persistence-type>
         <prim-key-class>com.aardvark.payroll.AccountID
            </prim-key-class>
         <reentrant>False</reentrant>

         <security-role-ref>
            <role-name>payroll-org</role-name>
            <role-link>payroll-department</role-link>
         </security-role-ref>
      </entity>
   </enterprise-beans>

   <assembly-descriptor>
      <security-role>
         <description>
            This role includes the employees of the
            enterprise who are allowed to access the
            employee self-service application. This role
            is allowed only to access his/her own
            information.
         </description>
         <role-name>employee</role-name>
      </security-role>

      <security-role>
         <description>
            This role includes the employees of the human
            resources department. The role is allowed to
            view and update all employee records.
         </description>
         <role-name>hr-department</role-name>
      </security-role>

      <security-role>
         <description>
            This role includes the employees of the payroll
            department. The role is allowed to view and
            update the payroll entry for any employee.
         </description>
         <role-name>payroll-department</role-name>
      </security-role>

      <security-role>
         <description>
            This role should be assigned to the personnel
            authorized to perform administrative functions
            for the employee self-service application.
            This role does not have direct access to
            sensitive employee and payroll information.
         </description>
         <role-name>admin</role-name>
      </security-role>

      <method-permission>
         <role-name>employee</role-name>
         <method>
            <ejb-name>EmployeeService</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>

      <method-permission>
         <role-name>employee</role-name>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>findByPrimaryKey</method-name>
         </method>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>getDetail</method-name>
         </method>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>updateDetail</method-name>
         </method>
      </method-permission>

      <method-permission>
         <role-name>employee</role-name>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>findByPrimaryKey</method-name>
         </method>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>getEmployeeInfo</method-name>
         </method>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>updateEmployeeInfo</method-name>
         </method>
      </method-permission>

      <method-permission>
         <role-name>admin</role-name>
         <method>
            <ejb-name>EmployeeServiceAdmin</ejb-name>
            <method-name>*</method-name>
         </method>
      </method-permission>

      <method-permission>
         <role-name>hr-department</role-name>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>create</method-name>
         </method>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>remove</method-name>
         </method>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>changeManager</method-name>
         </method>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>changeJobTitle</method-name>
         </method>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>findByPrimaryKey</method-name>
         </method>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>getDetail</method-name>
         </method>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>updateDetail</method-name>
         </method>
      </method-permission>

      <method-permission>
         <role-name>payroll-department</role-name>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>findByPrimaryKey</method-name>
         </method>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>getEmployeeInfo</method-name>
         </method>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>updateEmployeeInfo</method-name>
         </method>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>updateSalary</method-name>
         </method>
      </method-permission>

      <container-transaction>
         <method>
            <ejb-name>EmployeeRecord</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Required</trans-attribute>
      </container-transaction>

      <container-transaction>
         <method>
            <ejb-name>AardvarkPayroll</ejb-name>
            <method-name>*</method-name>
         </method>
         <trans-attribute>Required</trans-attribute>
      </container-transaction>
   </assembly-descriptor>
</ejb-jar>


Chapter EJB.17. EJB JAR File

The EJB JAR file is the standard format for packaging of enterprise beans. The EJB JAR file format is used to package un-assembled enterprise beans (the bean provider's output), and to package assembled applications (the application assembler's output).


EJB.17.1 Overview

The EJB JAR file format is the contract between the bean provider and application assembler and between the application assembler and the deployer.

An EJB JAR file produced by the bean provider contains one or more enterprise beans that typically do not contain application assembly instructions. An EJB JAR file produced by an application assembler (which can be the same person or organization as the bean provider) contains one or more enterprise beans, plus application assembly information describing how the enterprise beans are combined into a single application deployment unit.


EJB.17.2 Deployment Descriptor

The EJB JAR file must contain the deployment descriptor in the format defined in Chapter EJB.16. The deployment descriptor must be stored with the name META-INF/EJB JAR.xml in the EJB JAR file.


EJB.17.3 Class Files

For each enterprise bean, the EJB JAR file must include the class files of the following:

  • The enterprise bean class

  • The enterprise bean home and remote interface

  • The primary key class if the bean is an entity bean

The EJB JAR file must also contain the class files for all the classes and interfaces that the enterprise bean class and the remote and home interfaces depend on. This includes their superclasses and superinterfaces, and the classes and interfaces used as method parameters, results, and exceptions.

An EJB JAR file does not have to include the class files of the home and remote interfaces of an enterprise bean that is referenced by an enterprise bean in the EJB JAR, or other classes needed by the referenced enterprise bean, if the referenced enterprise bean or needed classes are defined in another jar file that is named in the Class-Path attribute in the Manifest file of the referencing EJB JAR file, or the transitive closure of such Class-Path references. Note that this Class-Path mechanism works only with JDK 1.2 and later.


EJB.17.4 ejb-client JAR File

The EJB JAR file producer can create an ejb-client JAR file for the EJB JAR file. The ejb-client JAR file contains all the class files that a client program needs to use the client view of the enterprise beans that are contained in the EJB JAR file.

The ejb-client JAR file is specified in the deployment descriptor of the EJB JAR file using the optional ejb-client-jar element. The deployer should ensure that the specified ejb-client JAR file is accessible to the client program's class-loader. If no ejb-client-jar element is specified, the deployer should make the entire EJB JAR file accessible to the client's class-loader.

The EJB specification does not specify whether the EJB JAR file should include by copy or by reference the classes that are in the ejb-client JAR. If the by-copy approach is used, the producer simply includes all the class files in the ejb-client JAR file also in the EJB JAR file. If the by-reference approach is used, the EJB JAR file producer does not duplicate the content of the ejb-client JAR file in the EJB JAR file, but instead uses a Manifest Class-Path entry in the EJB JAR file to specify that the EJB JAR file depends on the ejb-client JAR at runtime.

The use of the Class-Path entries in the JAR files is explained in the Java 2 Platform, Enterprise Edition Specification.


EJB.17.5 Deprecated in EJB 1.1

This section describes the deployment information that was defined in EJB 1.0, and is deprecated in EJB 1.1.

EJB.17.5.1 EJB JAR Manifest

The JAR manifest file is no longer used by the EJB architecture to identify the enterprise beans contained in an EJB JAR file.

EJB 1.0 used the Manifest file to identify the individual enterprise beans that were included in the EJB JAR file. In EJB 1.1, the enterprise beans are identified in the deployment descriptor, so the information in the manifest is no longer needed.

EJB.17.5.2 Serialized Deployment Descriptor JavaBeans™ Components

The mechanism of using serialized JavaBeans components as deployment descriptors has been replaced by the XML-based deployment descriptor.


Chapter EJB.18. Runtime Environment

This chapter defines the application programming interfaces (APIs) that a compliant EJB container must make available to the enterprise bean instances at runtime. These APIs can be used by portable enterprise beans because the APIs are guaranteed to be available in all EJB containers.

The chapter also defines the restrictions that the EJB container provider can impose on the functionality that it provides to the enterprise beans. These restrictions are necessary to enforce security and to allow the container to properly manage the runtime environment.


EJB.18.1 Bean Provider's Responsibilities

This section describes the view and responsibilities of the bean provider.

EJB.18.1.1 APIs Provided by Container

The EJB provider can rely on the EJB container provider to provide the following APIs:

  • JDK 1.1.x or Java 2

  • EJB 1.1 Standard Extension

  • JDBC 2.0 Standard Extension (support for row sets only)

  • JNDI 1.2 Standard Extension

  • JTA 1.0.1 Standard Extension (the UserTransaction interface only)

  • JavaMail 1.1 Standard Extension (for sending mail only)

The bean provider must take into consideration that while some containers will provide JDK 1.1.x APIs, other containers may provide the Java 2 (i.e., JDK 1.2) APIs. This means that the bean providers that want to deploy their enterprise beans in all containers must restrict the APIs used by the enterprise beans to those that are available in JDK 1.1 and the previously listed standard extensions.

EJB.18.1.2 Programming Restrictions

This section describes the programming restrictions that a bean provider must follow to ensure that the enterprise bean is portable and can be deployed in any compliant EJB container. The restrictions apply to the implementation of the business methods. Section EJB.18.2, which describes the container's view of these restrictions, defines the programming environment that all EJB containers must provide.

  • An enterprise bean must not use read/write static fields. Using read-only static fields is allowed. Therefore, it is recommended that all static fields in the enterprise bean class be declared as final.

This rule is required to ensure consistent runtime semantics because while some EJB containers may use a single JVM to execute all enterprise bean's instances, others may distribute the instances across multiple JVMs.

  • An enterprise bean must not use thread synchronization primitives to synchronize execution of multiple instances.

Same reason as above. Synchronization would not work if the EJB container distributed to enterprise bean's instances across multiple JVMs.

  • An enterprise bean must not use the AWT functionality to attempt to output information to a display, or to input information from a keyboard.

Most servers do not allow direct interaction between an application program and a keyboard/display attached to the server system.

  • An enterprise bean must not use the java.io package to attempt to access files and directories in the file system.

The file system APIs are not well suited for business components to access data. Business components should use a resource manager API, such as JDBC API, to store data.

  • An enterprise bean must not attempt to listen on a socket, accept connections on a socket, or use a socket for multicast.

The EJB architecture allows an enterprise bean instance to be a network socket client, but it does not allow it to be a network server. Allowing the instance to become a network server would conflict with the basic function of the enterprise bean—to serve the EJB clients.

  • The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. The enterprise bean must not attempt to use the Reflection API to access information that the security rules of the Java programming language make unavailable.

Allowing the enterprise bean to access information about other classes and to access the classes in a manner that is normally disallowed by the Java programming language could compromise security.

  • The enterprise bean must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the Java virtual machine; or change the input, output, and error streams.

These functions are reserved for the EJB container. Allowing the enterprise bean to use these functions could compromise security and decrease the container's ability to properly manage the runtime environment.

  • The enterprise bean must not attempt to set the socket factory used by ServerSocket, Socket, or the stream handler factory used by URL.

These networking functions are reserved for the EJB container. Allowing the enterprise bean to use these functions could compromise security and decrease the container's ability to properly manage the runtime environment.

  • The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread or to change a thread's priority or name. The enterprise bean must not attempt to manage thread groups.

These functions are reserved for the EJB container. Allowing the enterprise bean to manage threads would decrease the container's ability to properly manage the runtime environment.

  • The enterprise bean must not attempt to directly read or write a file descriptor.

Allowing the enterprise bean to read and write file descriptors directly could compromise security.

  • The enterprise bean must not attempt to obtain the security policy information for a particular code source.

Allowing the enterprise bean to access the security policy information would create a security hole.

  • The enterprise bean must not attempt to load a native library.

This function is reserved for the EJB container. Allowing the enterprise bean to load native code would create a security hole.

  • The enterprise bean must not attempt to gain access to packages and classes that the usual rules of the Java programming language make unavailable to the enterprise bean.

This function is reserved for the EJB container. Allowing the enterprise bean to perform this function would create a security hole.

  • The enterprise bean must not attempt to define a class in a package.

This function is reserved for the EJB container. Allowing the enterprise bean to perform this function would create a security hole.

  • The enterprise bean must not attempt to access or modify the security configuration objects (Policy, Security, Provider, Signer, and Identity).

These functions are reserved for the EJB container. Allowing the enterprise bean to use these functions could compromise security.

  • The enterprise bean must not attempt to use the subclass and object substitution features of the Java Serialization Protocol.

Allowing the enterprise bean to use these functions could compromise security.

  • The enterprise bean must not attempt to pass this as an argument or method result. The enterprise bean must pass the result of SessionContext.getEJBObject() or EntityContext.getEJBObject() instead.

To guarantee portability of the enterprise bean's implementation across all compliant EJB containers, the bean provider should test the enterprise bean using a container with the security settings defined in Tables EJB.18-1 and EJB.18-2. The tables define the minimal functionality that a compliant EJB container must provide to the enterprise bean instances at runtime.


EJB.18.2 Container Provider's Responsibility

This section defines the container's responsibilities for providing the runtime environment to the enterprise bean instances. The requirements described here are considered to be the minimal requirements; a container may choose to provide additional functionality that is not required by the EJB specification.

EJB.18.2.1 Java 2 Platform-Based Container

A Java 2 platform-based EJB container must make the following APIs available to the enterprise bean instances at runtime:

  • Java 2 APIs

  • EJB 1.1 APIs

  • JNDI 1.2

  • JTA 1.0.1, the UserTransaction interface only

  • JDBC™ 2.0 extension

  • JavaMail 1.1, sending mail only

The following subsections describe the requirements in more detail.

EJB.18.2.1.1 Java 2 APIs Requirements

The container must provide the full set of Java 2 platform APIs. The container is not allowed to subset the Java 2 platform APIs.

The EJB container is allowed to make certain Java 2 platform functionality unavailable to the enterprise bean instances by using the Java 2 platform security policy mechanism. The primary reason for the container to make certain functions unavailable to enterprise bean instances is to protect the security and integrity of the EJB container environment, and to prevent the enterprise bean instances from interfering with the container's functions.

Table EJB.18-1 defines the Java 2 platform security permissions that the EJB container must be able to grant to the enterprise bean instances at runtime. The term "grant" means that the container must be able to grant the permission; the term "deny" means that the container should deny the permission.

Table EJB.18-1. Java 2 Platform Security Policy for a Standard EJB Container

Permission Name

EJB Container Policy

java.security.AllPermission

deny

java.awt.AWTPermission

deny

java.io.FilePermission

deny

java.net.NetPermission

deny

java.util.PropertyPermission

grant "read", "*"

deny all other

java.lang.reflect.ReflectPermission

deny

java.lang.RuntimePermission

grant "queuePrintJob",

deny all other

java.lang.SecurityPermission

deny

java.io.SerializablePermission

deny

java.net.SocketPermission

grant "connect", "*" [a],

deny all other

[a] This permission is necessary, for example, to allow enterprise beans to use the client functionality of the Java IDL API and RMI-IIOP packages that are part of Java 2 platform.

Some containers may allow the deployer to grant more, or fewer, permissions to the enterprise bean instances than specified in Table EJB.18-1. Support for this is not required by the EJB specification. Enterprise beans that rely on more or fewer permissions will not be portable across all EJB containers.

EJB.18.2.1.2 EJB 1.1 Requirements

The container must implement the EJB 1.1 interfaces as defined in this documentation.

EJB.18.2.1.3 JNDI 1.2 Requirements

At the minimum, the EJB container must provide a JNDI API name space to the enterprise bean instances. The EJB container must make the name space available to an instance when the instance invokes the javax.naming.InitialContext default (no-arg) constructor.

The EJB container must make available at least the following objects in the name space:

  • The home interfaces of other enterprise beans

  • The resource factories used by the enterprise beans

The EJB specification does not require that all the enterprise beans deployed in a container be presented with the same JNDI API name space. However, all the instances of the same enterprise bean must be presented with the same JNDI API name space.

EJB.18.2.1.4 JTA 1.0.1 Requirements

The EJB container must include the JTA 1.0.1 extension, and it must provide the javax.transaction.UserTransaction interface to enterprise beans with bean-managed transaction demarcation through the javax.ejb.EJBContext interface, and also in JNDI under the name java:comp/UserTransaction, in the cases required by the EJB specification.

The EJB container is not required to implement the other interfaces defined in the JTA specification. The other JTA interfaces are low-level transaction manager and resource manager integration interfaces, and are not intended for direct use by enterprise beans.

EJB.18.2.1.5 JDBC™ 2.0 Extension Requirements

The EJB container must include the JDBC 2.0 extension and provide its functionality to the enterprise bean instances, with the exception of the low-level XA and connection pooling interfaces. These low-level interfaces are intended for integration of a JDBC driver with an application server, not for direct use by enterprise beans.

EJB.18.2.2 JDK™ 1.1 Based Container

A JDK 1.1 based EJB container must make the following APIs available to the enterprise bean instances at runtime:

  • JDK 1.1 or higher

  • EJB 1.1 APIs

  • JNDI 1.2

  • JTA 1.0.1, the UserTransaction interface only

  • JDBC™ 2.0 extension

  • JavaMail 1.1, sending mail only

The following subsections describes the requirements in more detail.

EJB.18.2.2.1 JDK 1.1 APIs Requirements

The container must provide the full set of JDK 1.1 APIs. The container is not allowed to subset the JDK 1.1 APIs.

The EJB container is allowed to make certain JDK 1.1 functionality unavailable to the enterprise bean instances by using the JDK security manager mechanism. The primary reason for the container to make certain functions unavailable to enterprise bean instances is to protect the security and integrity of the EJB container environment, and to prevent the enterprise bean instances from interfering with the container's functions.

Table EJB.18-2 defines the JDK 1.1 security manager checks that the EJB container must allow to succeed when the check is invoked from an enterprise bean instance.

Table EJB.18-2. JDK 1.1 Security Manager Checks for a Standard EJB Container

Security Manager Check

EJB Container's Security Manager Policy

checkAccept(String, int)

throw SecurityException

checkAccess(Thread)

throw SecurityException

checkAccess(ThreadGroup)

throw SecurityException

checkAwtEventQueueAccess()

throw SecurityException

checkConnect(String, int)

allow

checkConnect(String, int, Object)

allow

checkCreateClassLoader()

throw SecurityException

checkDelete(String)

throw SecurityException

checkExec(String)

throw SecurityException

checkExit(int)

throw SecurityException

checkLink(int)

throw SecurityException

checkListen(int)

throw SecurityException

checkMemberAccess(Class, int)

throw SecurityException

checkMulticast(InetAddress)

throw SecurityException

checkMulticast(InetAddress, byte)

throw SecurityException

checkPackageAccess(String)

throw SecurityException

checkPackageDefinition(String)

throw SecurityException

checkPrintJobAccess()

allow

checkPropertiesAccess()

throw SecurityException

checkPropertyAccess(String)

allow read of all properties

checkRead(FileDescriptor)

throw SecurityException

checkRead(String)

throw SecurityException

checkRead(String, Object)

throw SecurityException

checkSecurityAccess(String)

throw SecurityException

checkSetFactory()

throw SecurityException

checkSystemClipboardAccess()

throw SecurityException

checkTopLevelWindow(Object)

throw SecurityException

checkWrite(FileDescriptor)

throw SecurityException

checkWrite(String)

throw SecurityException

Some containers may allow the deployer to grant more, or fewer, permissions to the enterprise bean instances than specified in Table EJB.18-1. Support for this is not required by the EJB specification. Enterprise beans that rely on more or fewer permissions will not be portable across all EJB containers.

EJB.18.2.2.2 EJB 1.1 Requirements

The container must implement the EJB 1.1 interfaces as defined in this documentation.

EJB.18.2.2.3 JNDI 1.2 Requirements

Same as defined in Section EJB.18.2.1.3.

EJB.18.2.2.4 JTA 1.0.1 Requirements

Same as defined in Section EJB.18.2.1.4.

EJB.18.2.2.5 JDBC 2.0 Extension Requirements

Same as defined in Section EJB.18.2.1.5, with the following exception: The EJB container is not required to provide the support for the RowSet functionality.

This exception was made because the RowSet functionality requires the Java 2 Collections.

EJB.18.2.3 Argument Passing Semantics

The enterprise bean's home and remote interfaces are remote interfaces for Java RMI. The container must ensure the semantics for passing arguments conform to Java RMI. Non-remote objects must be passed by value.

Specifically, the EJB container is not allowed to pass non-remote objects by reference on inter-EJB invocations when the calling and called enterprise beans are collocated in the same Java virtual machine. Doing so could result in the multiple beans sharing the state of an object in the Java progarmming language, which would break the enterprise bean's semantics.


Chapter EJB.19. Responsibilities of EJB Architecture Roles

This chapter provides the summary of the responsibilities of each EJB architecture role.


EJB.19.1 Bean Provider's Responsibilities

This section highlights the requirements for the bean provider. Meeting these requirements is necessary to ensure that the enterprise beans developed by the bean provider can be deployed in all compliant EJB containers.

EJB.19.1.1 API Requirements

The enterprise beans must meet all the API requirements defined in the individual chapters of this document.

EJB.19.1.2 Packaging Requirements

The bean provider is responsible for packaging the enterprise beans in an EJB JAR file in the format described in Chapter EJB.17.

The deployment descriptor must include the structural information described in Section EJB.16.2.

The deployment descriptor may optionally include any of the application assembly information as described in Section EJB.16.3.


EJB.19.2 Application Assembler's Responsibilities

The requirements for the application assembler are in defined in Section EJB.16.3.


EJB.19.3 EJB Container Provider's Responsibilities

The EJB container provider is responsible for providing the deployment tools used by the deployer to deploy enterprise beans packaged in the EJB JAR file. The requirements for the deployment tools are defined in the individual chapters of this document.

The EJB container provider is responsible for implementing its part of the EJB contracts, and for providing all the runtime services described in the individual chapters of this document.


EJB.19.4 Deployer's Responsibilities

The deployer uses the deployment tools provided by the EJB container provider to deploy EJB JAR files produced by the bean providers and application assemblers.

The individual chapters of this document describe the responsibilities of the deployer in more detail.


EJB.19.5 System Administrator's Responsibilities

The system administrator is responsible for configuring the EJB container and server, setting up security management, integrating resource managers with the EJB container, and runtime monitoring of deployed enterprise beans applications.

The individual chapters of this document describe the responsibilities of the system administrator in more detail.


EJB.19.6 Client Programmer's Responsibilities

The EJB client programmer writes applications that access enterprise beans via their home and remote interfaces.


Chapter EJB.20. Enterprise JavaBeans™ API Reference

The following interfaces and classes comprise the Enterprise JavaBeans API:


EJB.20.1 Package javax.ejb

Interfaces:

public interface EJBContext
public interface EJBHome
public interface EJBMetaData
public interface EJBObject
public interface EnterpriseBean
public interface EntityBean
public interface EntityContext
public interface Handle
public interface HomeHandle
public interface SessionBean
public interface SessionContext
public interface SessionSynchronization

Classes:

public class CreateException
public class DuplicateKeyException
public class EJBException
public class FinderException
public class ObjectNotFoundException
public class RemoveException


EJB.20.2 Package javax.ejb.deployment

The javax.ejb.deployment package that was defined in the EJB 1.0 specification is deprecated in EJB 1.1. The EJB 1.0 deployment descriptor format should not be used by EJB JAR file producer, and the support for it is not required by EJB 1.1 compliant containers.

We intend to provide a tool which will help convert an EJB 1.0 deployment descriptor to the EJB 1.1 XML-based format. The javax.ejb.deployment package will be provided only as part of this tool.

The Javadoc specification of the EJB interface is included in a ZIP file distributed with this document.


Chapter EJB.21. Related Documents

  1. [1] JavaBeans. http://java.sun.com/beans.

  2. [2] Java Naming and Directory Interface (JNDI). http://java.sun.com/products/jndi.

  3. [3] Java Remote Method Invocation (RMI). http://java.sun.com/products/rmi .

  4. [4] Java Security. http://java.sun.com/security .

  5. [5] Java Transaction API (JTA). http://java.sun.com/products/jta.

  6. [6] Java Transaction Service (JTS). http://java.sun.com/products/jts .

  7. [7] Java to IDL Mapping. OMG TC Document. http://www.omg.org/cgi-bin/doc?formal/99-07-59.

  8. [8] Enterprise JavaBeans to CORBA Mapping. http://java.sun.com/products/ejb/docs.html .

  9. [9] OMG Object Transaction Service. http://www.omg.org/corba/sectrans.htm#trans.

  10. [10] Java 2 Platform, Enterprise Edition, v1.2 (J2EE). http://java.sun.com/j2ee .


Appendix EJB.A. Features Deferred to Future Releases

We plan to provide an SPI-level interface for attaching a resource manager (such as a JDBC driver) to the EJB container as a separate Connector API.

We plan to enhance the support for entities in the next major release (EJB 2.0). We are looking into the area of use of the UML for the design and analysis of enterprise beans applications.

We plan to provide integration of EJB with JMS as part of EJB 2.0.


Appendix EJB.B. Frequently Asked Questions

This appendix provides the answers to a number of frequently asked questions.


EJB.B.1 Client-Demarcated Transactions

The EJB 1.0 specification did not explain how a client other than another enterprise bean can obtain the javax.transaction.UserTransaction interface.

The Java2, Enterprise Edition specification [EJB.10] defines how a client can obtain the javax.transaction.UserTransaction interface using JNDI.

The following is an example of how a Java application can obtain the javax.transaction.UserTransaction interface.

...
Context ctx = new InitialContext();
UserTransaction utx =
   (UserTransaction)ctx.lookup("java:comp/UserTransaction");

//
// Perform calls to enterprise beans in a transaction.
//
utx.begin();
... call one or more enterprise beans
utx.commit();
...


EJB.B.2 Inheritance

The current EJB specification does not specify the concept of component inheritance. There are complex issues that would have to be addressed in order to define component inheritance (for example, the issue of how the primary key of the derived class relates to the primary key of the parent class, and how component inheritance affects the parent component's persistence).

However, the bean provider can take advantage of the Java programming language support for inheritance as follows:

  • Interface inheritance. It is possible to use the Java programming language interface inheritance mechanism for inheritance of the home and remote interfaces. A component may derive its home and remote interfaces from some "parent" home and remote interfaces; the component then can be used anywhere where a component with the parent interfaces is expected. This is a Java language feature, and its use is transparent to the EJB container.

  • Implementation class inheritance. It is possible to take advantage of the Java class implementation inheritance mechanism for the enterprise bean class. For example, the class CheckingAccountBean class can extend the AccountBean class to inherit the implementation of the business methods.


EJB.B.3 Entities and Relationships

The current EJB architecture does not specify how one entity bean should store an object reference of another entity bean. The desirable strategy is application-dependent. The enterprise bean (if the bean uses bean-managed persistence) or the container (if the bean uses container-managed persistence) can use any of the following strategies for maintaining persistently a relationship between entities (the list is not inclusive of all possible strategies):

  • Object's primary key. This is applicable if the target object's home is known and fixed.

  • Home name and object's primary key.

  • Home object reference and object's primary key.

  • Object's handle.


EJB.B.4 Finder Methods for Entities with Container-Managed Persistence

The EJB specification does not provide a formal mechanism for the bean provider of a bean with container-managed persistence to specify the criteria for the finder methods.

The current mechanism is that bean provider describes the finders in a description of the entity bean. The current EJB specification does not provide any syntax for describing the finders.

We plan to address this issue in a future release of the specification.


EJB.B.5 JDK 1.1 or Java 2

Chapter EJB.18 describes the issue of using JDK 1.1 versus Java 2 in detail.

In summary, the bean provider can produce enterprise beans that will run in both JDK 1.1 and Java 2 platform based containers. The container provider can use either JDK 1.1 or Java 2 platform as the basis for the implementation of the container.


EJB.B.6 javax.transaction.UserTransaction Versus javax.jts.UserTransaction

The correct spelling is javax.transaction.UserTransaction.

The use of javax.jts.UserTransaction is deprecated in EJB 1.1.


EJB.B.7 How to Obtain Database Connections

Section EJB.14.4 specifies how an enterprise bean should obtain connections to resources such as JDBC API connections. The connection acquisition protocol uses resource manager connection factory references that are part of the enterprise bean's environment.

The following is an example of how an enterprise bean obtains a JDBC connection:

public class EmployeeServiceBean implements SessionBean {
   EJBContext ejbContext;

   public void changePhoneNumber(...) {
      ...

      // obtain the initial JNDI context
      Context initCtx = new InitialContext();

      // perform JNDI lookup to obtain resource manager connection
         // factory
      javax.sql.DataSource ds = (javax.sql.DataSource)
         initCtx.lookup("java:comp/env/jdbc/EmployeeAppDB");

      // Invoke factory to obtain a connection. The security
      // principal is not given, and therefore
      // it will be configured by the Deployer.
      java.sql.Connection con = ds.getConnection();
      ...
   }
}


EJB.B.8 Session Beans and Primary Key

The EJB 1.1 specification specifies the container's behavior for the cases when a client attempts to access the primary key of a session object. In summary, the container must throw an exception on a client's attempt to access the primary key of a session object.


EJB.B.9 Copying of Parameters Required for EJB Calls Within the Same JVM

The enterprise bean's home and remote interfaces are remote interface in the Java RMI sense. The container must ensure the Java RMI argument passing semantics. Non-remote objects must be passed by value.

Specifically, the EJB container is not allowed to pass local objects by reference on inter-enterprise bean invocations when the calling and called enterprise beans are collocated in the same JVM. Doing so could result in the multiple beans sharing the state of a Java object, which would break the enterprise bean's semantics.


Appendix EJB.C. Revision History

    Section EJB.C.1. Changes Since Release 0.8

    Section EJB.C.2. Changes Since Release 0.9

    Section EJB.C.3. Changes Since Release 0.95

    Section EJB.C.4. Changes Since 1.0

    Section EJB.C.5. Changes Since EBJ.1.1 Draft 1

    Section EJB.C.6. Changes Since EJB.1.1 Draft 2

    Section EJB.C.7. Changes Since EJB 1.1 Draft 3

    Section EJB.C.8. Changes Since EJB 1.1 Public Draft

    Section EJB.C.9. Changes Since EJB 1.1 Public Draft 2

    Section EJB.C.10. Changes Since EJB 1.1 Public Draft 3

    Section EJB.C.11. Changes Since EJB 1.1 Public Release

    Section EJB.C.12. Changes Since EJB 1.1 Public Release


EJB.C.1 Changes Since Release 0.8

Removed java.ejb.BeanPermission from the API. This file was incorrectly included in the 0.8 specification.

Renamed packages to java.ejb and javax.ejb.deployment. The Enterprise JavaBeans API is packaged as a standard extension, and standard extensions should be prefixed with javax. Also renamed java.jts to javax.jts.

Made clear that a container can support multiple EJB classes. We renamed the javax.ejb.Container to javax.ejb.EJBHome. Some reviewers pointed out that the use of the term "container" for the interface that describes the life cycle operations of an EJB class as seen by a client was confusing.

Folded the factory and finder methods into the enterprise bean's home interface. This reduces the number of Java classes per EJB class and the number of round-trips between a client and the container required to create or find an EJB object. It also simplifies the client-view API.

Removed the PINNED mode of a session bean. Many reviewers considered this mode to be "dangerous" since it could prevent the container from efficiently managing its memory resources.

Clarified the life cycle of a stateless session bean.

Added a chapter with the specification for exception handling.

We have renamed the contract between a component and its container to component contract. The previously used term container contract confused several reviewers.

Added description of finder methods.

Modified the entity create protocol by breaking the ejbCreate method into two: ejbCreate and ejbPostCreate. This provides a cleaner separation of the discrete steps involved in creating an entity in a database and its associated middle-tier object.

Added more clarification to the description of the entity component protocol.

Added more information about the responsibilities of the enterprise bean provider and container provider.

Renamed SessionSynchronization.beginTransaction() to SessionSynchronization.afterBegin() to avoid confusion with UserTransaction.begin().

Added the specification of isolation levels for container-managed entity beans.


EJB.C.2 Changes Since Release 0.9

Renamed javax.ejb.InstanceContext to javax.ejb.EJBContext.

Fixed bugs in the javadoc of the javax.ejb.EntityContext interface.

Combined the state diagrams for non-transactional and transactional session beans into a single diagram.

Added the definition of the restrictions on using transaction scopes with a session bean (a session bean can be only in a single transaction at a time).

Allowed the enterprise bean's class to implement the enterprise bean's remote interface. This change was requested by reviewers to facilitate migration of existing code written in the Java programming language to Enterprise JavaBeans.

Removed the javax.ejb.EJBException from the specification, and replaced its use by the standard java.rmi.RemoteException. This change was necessary because of the previous change that allows the enterprise bean class to implement its remote interface.

Changed some rules regarding exception handling.

Renamed to the javax.jts.CurrentTransaction interface to javax.jts.UserTransaction to avoid confusion with the org.omg.CosTransactions.Current interface. Thejavax.jts.UserTransaction interface defines the subset of operations that are "safe" to use at the application level, and can be supported by the majority of the transaction managers used by existing platforms.

Added specification for TX_BEAN_MANAGED transactions.

Made the isolation levels supplied in the deployment descriptor applicable also to session beans and entities with bean-managed persistence.

Renamed the destroy() methods to remove(). This change was requested by several reviewers who pointed out the potential for name space collisions in their implementations.

Added the create arguments to the ejbPostCreate method. This simplifies the programming of an entity bean that needs the create arguments in the ejbPostCreate method (previously, the bean would have to save these arguments in the ejbCreate method).

Added restrictions on the use of per-method deployment attributes.

Added javax.ejb.EJBMetaData to the examples, and added the generation of the class that implements this interface as a requirement for the container tools.

Added the getRollbackOnly method to the javax.ejb.EJBContext interface. This method allows an instance to test if the current transaction has been marked for rollback. The test may help the enterprise bean to avoid fruitless computation after it caught an exception.

We removed the placeholder Appendix for examples. We will provide examples on the Enterprise JavaBeans architecture web site rather than in this document.


EJB.C.3 Changes Since Release 0.95

Allowed a container-managed field to be of any Java programming language Serializable type.

Clarified the bean provider responsibilities for the ejbFind<METHOD> methods entity beans with container-managed persistence.

Added two rules on exception handling and transaction management. The new rules are for the TX_BEAN_MANAGED beans.

Use the javax.rmi.PortableRemoteObject.narrow(...) method to perform the narrow operations after a JNDI lookup in the code samples used in the specification. While some JNDI providers may return from the lookup(...) method the exact stub for the home interface making it possible for the client application to use a cast operation, other providers may return a wider type that requires an explicit narrow to the home interface type. The javax.rmi.PortableRemoteObject.narrow(...) method is the standard Java RMI way to perform the explicit narrow operation.

Changed several deployment descriptor method names.


EJB.C.4 Changes Since 1.0

This sections lists the changes since EJB 1.0.

Specified the behavior of EJBObject.getPrimaryKey(), EJBMetaData.getPrimaryKeyClass(), EJBHome.remove(Object primaryKey), and isIdentical(Object other) for session beans. As session beans do not have client-accessible primary keys, these operations result in exceptions.

Disallowed TX_BEAN_MANAGED for entity beans.

Disallowed use of SessionSynchronization for TX_BEAN_MANAGED sessions.

Allowed using java.lang.String as a primary key type.

Allowed deferring the specification of the primary key class for entities with container-managed persistence to the deployment time.

Clarified that a matching ejbPostCreate is required for each ejbCreate.

Added requirement for hashCode and equals for the primary key class.

Deprecated the package javax.ejb.deployment by replacing the JavaBeans-based deployment descriptor with an XML-based deployment descriptor.

Improved the information in the deployment descriptor by clearly separating structural information from application assembly information, and by removing support for information that should be supplied by the deployer rather than by the EJB JAR producer (i.e., ISV). The EJB 1.0 deployment descriptor mixed all this information together, making it hard for people to understand the division of responsibility for setting the various values, and it was not clear what values can be changed at application assembly and/or deployment.

Added the requirement for the bean provider to specify whether the enterprise bean uses a bean-managed or container-managed transaction.

Added Never the list of possible values of the transaction attributes to allow specification of the case in which an enterprise bean must never be called from a transactional client.

Removed the Appendix describing the javax.transaction package. Inclusion of this package in the EJB document is no longer needed because the JTA documentation is publicly available.

Tightened the specification of the responsibilities for transaction management.

Tighten the rules for the runtime environment that the bean provider can expect and the EJB container provider must provide. See Chapter EJB.18.


EJB.C.5 Changes Since EBJ.1.1 Draft 1

This sections lists the changes since EJB 1.1 Draft 1.

Allow use of the Java 2 java.util.Collection interfaces for the result of entity finder methods.

Defining the FinderException in the finder methods of the home interface is mandatory now.

Cleanup of the exception specification, including minor changes from EJB 1.0 summarized in Section EJB.12.6.

The scope of the EJB specification for managing transaction isolation levels was reduced to sessions with bean-managed transaction demarcation. The current EJB specification does not have any API for managing transaction isolation for beans with container-managed transaction demarcation (note that all entity beans fall into this category).

Eliminated the stateless-session element in the XML DTD. Now the session element is used to describe both the stateful and stateless session beans.

Added an optional description element to the method element. The intention is to allow tools to display the description of the method.

Clarified that the enterprise bean class may have superclasses, and that the business methods and the various container callbacks can be implemented in the enterprise bean class, or in any of its superclasses.

Fixed the example that illustrates the use of handles for session objects. Serialized handles are not guaranteed to be deserializable in a different system, and therefore they cannot be e-mailed.

Updated the Overview chapter.

Allowed deferring the specification of the primary key class for all entities (not only for those with container-managed persistence as it was the case in Draft 1).

Allow enterprise beans to print. The container must grant the permission to the enterprise beans to queue printer job.

The setRollbackOnly() and getRollbackOnly() methods of the EJBContext object must not be used by enterprise beans with bean-managed transaction demarcation. There is no need for these beans to use these methods.


EJB.C.6 Changes Since EJB.1.1 Draft 2

Fix an error in the requirement for how a container must deal with inter-EJB invocations when both the calling and called beans are in the same JVM. The correct requirement is that the RMI semantics must be ensured, and therefore the container must not pass non-remote objects by reference.

Clarified the requirements for serialization of the session objects.

Specified that an EJB compliant container may always return a null from the deprecated getCallerIdentity() method.

Added a section on distributed transaction scenarios involving access to the same entity from multiple clients in the same transaction.

Changed the specification of the return value type of the ejbCreate(...) methods for entities with container-managed persistence. The previous specification required that the ejbCreate methods are defined as returning void. The new requirement is that the ejbCreate methods be defined as returning the primary key class type. The implementation of the ejbCreate method should return null. This change is to allow tools, if they wish, to create an entity bean with bean-managed persistence by subclassing an original entity bean with container-managed persistence.

For compatibility with EJB 1.0, added the support for the java.rmi.RemoteException to be thrown from the enterprise bean class methods. This is needed to allow an EJB 1.1 container to support enterprise beans written to the EJB 1.0 specification. The use of the java.rmi.RemoteException in the enterprise bean class methods is deprecated, and new applications should throw the javax.ejb.EJBException instead.

Removed the deprecated package javax.ejb.deployment from the EJB interfaces. The deprecated package javax.ejb.deployment will be distributed only with the deployment descriptor conversion tool.

Updated the examples in the transaction chapter by removing the setAutoCommit and setTransactionIsolation calls. These calls are not typically done by the enterprise bean.

Added the <method-intf> element to allow a method element to differentiate between methods with same signature when defined in both the remote and home interfaces.

Specified the behavior of the getUserTransaction(), setRollbackOnly(), and getRollbackOnly() methods for the cases when the methods are invoked by beans that are not allowed to use these methods. The container will throw the java.lang.IllegalException in these situations.

Specified that PortableRemoteObject.narrow(...) must be used by a client to convert the result of Handle.getEJBObject() to the remote interface type.

Required portable enterprise bean clients to use the PortableRemoteObject.narrow(...).

Clarified the minimal lifetime for handles.

Clarified that the caller must have at least one security role (not all) associated with the method permission in order to be allowed to invoke the method.

Support for entities has been made mandatory for the container provider.

Added a section to the Exception chapter dealing with the release of resources held by the instance when the instance is being discarded because of a system exception.

Added the res-auth element to the deployment descriptor for the bean provider to indicate whether the bean code performs an explicit signon to a resource manager, or whether the bean relies on the container to perform signon based on the information supplied by deployer.

Added java.io.Serializable as a superinterface of javax.ejb.Handle. The EJB 1.0 spec required that the implementation class implements the java.io.Serializable interface; this change expresses the requirement syntactically.

Added the interface javax.ejb.HomeHandle to provide support for handles for home objects.

Allowed a session bean instance to be removed upon a timeout while the instance is in the passivated state.

Add the javax.ejb.NoSuchEntityException exception to the API. Added requirements for throwing the java.rmi.NoSuchObjectExcetion to the chapter on exceptions.


EJB.C.7 Changes Since EJB 1.1 Draft 3

Replaced the support for environment properties with the JNDI API-based environment entries. The EJB 1.0 style of environment properties access is deprecated in EJB 1.1.

Removed the finalize() method from the state diagrams. Specified that an enterprise bean must not define the finalize() method in the enterprise bean class. This is because it cannot be guaranteed that the method is called at all in some container implementations.

Made clear that the result of comparing two object references using the Java "==" operator or the equals() method is undefined.

Added Tables EJB.6-1, EJB.6-2, and EJB.9-1 that specify which operations are allowed in the enterprise bean methods.

Clarified what "proper transaction context" means in the chapter on entities.

Flattened the DTD hierarchy by removing the elements that grouped entries of the same type.

Relaxed the rules for the primary key class. An entity with bean-managed persistence can use any RMI-IIOP Value Type as its primary key type; the primary key type of an entity with container-managed persistence is more constrained.

Added the isStatelessSession() method to the EJBMetaData interface.

Updated the chapter in distribution to simply reference RMI-IIOP. The original chapter had been written before RMI-IIOP was completed.


EJB.C.8 Changes Since EJB 1.1 Public Draft

Added the ejb-client-jar element to the deployment descriptor to allow the EJB JAR file producer to specify a JAR file that contains the classes necessary to access the enterprise beans in the EJB JAR file.

The value of the res-auth element was changed to Application (it was Bean) to be consistent with the Java 2 Platform, Enterprise Edition Specification.

Changed the lexical rules for the env-entry-value element so that values of the type String need not be double-quoted in the deployment descriptor. See Section EJB.14.2.1.2.

Added the requirement for the container to provide the UserTransaction interface to the enterprise bean instances in the environment JNDI API context under the name java:comp/UserTransaction. See Section EJB.14.6.

Clarified that the container must never return a null from the getCallerPrincipal() method.

Allow the stateful session bean's ejbCreate, ejbRemove, ejbActivate, and ejbPassivate methods to access resource managers without transaction context. This was allowed in EJB 1.0.

Cleaned up the description of transactions. Removed the confusing term local transaction, and created the description of how a container may deal with the resource manager updates from a method that runs with an unspecified transaction context into Section EJB.11.6.3 (the term local transaction was used to refer to the cases that are now covered by this section).

Added an explanation of how ejbLoad and ejbStore work for entity bean instances that execute with an unspecified transaction context. See Section EJB.9.1.7.1.

Fixed the argument type of the isIdentical(EJBObject) method. The spec showed it incorrectly as java.lang.Object. The EJB class files and javadoc have always been correct.

Disallowed the use of UserTransaction in the setSessionContext method, as specified in Tables EJB.6-1 and EJB.6-2.

Specified which methods can be assigned a transaction attribute, and which methods can be included in method-permission elements.

Clarified in Section EJB.12.3.6 which "resources" the container is responsible for releasing when an instance is being discarded.

Augmented the restrictions on client's security context in Section EJB.15.5 to cover the case in which requests in the same transaction are received from multiple intermediate objects.

Moved the description of the "transaction diamond" scenario from Section EJB.9.1.13 to Section EJB.11.7. Described also the transaction diamond scenario for session beans.

Clarified the scope of the env-entry-name, ejb-ref-name, res-ref-name, security-role-ref, and role-name elements.

Specified that application exceptions must not be defined as a subclass of RuntimeException or RemoteException.

Clarified that the container-managed persistence fields must not be defined as transient.

Clarified in Section EJB.9.2.3 that the entity object created by the ejbCreate(...) method must have a unique primary key.

Clarified in Section EJB.6.8 how the container delegates requests to instances of a stateless session bean.

Added to Section EJB.18.1.2 the restriction that an enterprise bean must not pass this as a method argument or result.

In Section EJB.6.4.1 specified that the container must be able to preserve to an object reference of the UserTransaction interface across passivation. Same for the object references of enterprise beans' home interfaces.

Noted in Chapter EJB.11 that the transaction attributes may be specified by either the bean provider or the application assembler. The previous text suggested that only the application assembler was allowed to specify the transaction attributes.

Made the terminology more consistent throughout the specification. Used the terms session bean, session object, session bean instance, home interface, remote interface, session EJBObject, and session EJBHome consistently. Used similar terminology for the entity bean related terms. Note that we turned off the change bars while making this editorial cleanup.

Disallowed the use of the setRollbackOnly and getRollbackOnly method, the use of the UserTransaction interface, resource manager access, and enterprise bean access in the ejbCreate and ejbRemove methods of the stateless session bean (see Table EJB.6-2 on page 417). The container does not have a transaction context and client security context during the execution of these two operations of a stateless session bean.

Added support for referencing the deployment descriptor elements through XML IDs. The main reason for this is to make it easier for tools that want to pass additional non-standard deployment information for the enterprise beans. The tools should put the non-standard information into a separate file, and optionally make use of the ID mechanism to reference the information in the standard EJB deployment descriptor. Tools are not allowed to extend the format of the EJB deployment descriptor.

Made a minor change to the language in Section EJB.15.3.2 for the case that a method is not assigned to any security role.

Added a paragraph stating that the container should implement the object references of the home and remote interfaces of entity objects such that a client can use the references over a long period of time (Section EJB.9.3.9).


EJB.C.9 Changes Since EJB 1.1 Public Draft 2

We changed the JTA requirements to refer to version JTA 1.0.1.

Added clarifications to Sections EJB.9.1.5.1, EJB.9.1.5.2, and EJB.9.4.3 stating that the container must ensure that the instance's state is synchronized before it invokes ejbRemove.

Renamed the primkey-class element to prim-key-class to be consistent with the rest of the element names.

Clarified in Section EJB.12.1.1 that a bean provider is allowed to define subclasses of the standard EJB application exceptions.

Added the requirement (in Section EJB.9.4.2) for the container to reset the container-manager fields to the default Java language values prior to invoking ejbCreate.

Clarified the reason for allowing the primary key type for CMP entities to be specified at deployment time (Section EJB.9.4.7.3).


EJB.C.10 Changes Since EJB 1.1 Public Draft 3

Made clear in Section EJB.11.2.3 that not all EJB client environments are required to support the UserTransaction interface.

Specified the name and URI to be used in the DOCTYPE PUBLIC ID in the EJB XML deployment descriptors.

Corrected Section EJB.5.3.2 to state that a javax.ejb.RemoveException be thrown instead of java.rmi.RemoteException.

Fixed a few errors in Tables EJB.6-1, EJB.6-2, and EJB.9-1.

Changed the format of the Style 3 method element of the EJB deployment descriptor. See Section EJB.16.5. This change was necessary to disambiguate a Style 3 element for a method with no arguments from a Style 2 element.


EJB.C.11 Changes Since EJB 1.1 Public Release

Fixed an error in Section EJB.15.2.5. The getCallerPrincipal and isCallerInRole functions, when called in an inappropriate context, must throw the java.lang.IllegalStateException, not the javax.ejb.EJBException.

Fixed the omission of a requirement in Section EJB.9.4.1. The container-managed fields must be declared as public fields in the enterprise bean class. This requirement was present in the EJB 1.0 specification, and it was inadvertently left out when the sections on container-managed persistence were reorganized during the EJB 1.1 specification process.

Made it clear in Section EJB.6.4.1 that an instance is allowed to retain across passivation references to enterprise beans' remote and home interfaces, references to the SessionContext object, references to the java:comp/env JNDI API context and its subcontexts, and references to the UserTransaction anywhere in the instances conversational state (i.e., not only directly in the fields of the session bean class). For example, it is possible to retain a collection of remote interfaces in the conversational state.

Changed the version numbers in the DOCTYPE specification in the deployment descriptor from 1.2 to 1.1. The correct DOCTYPE specification is:

<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.
//DTD Enterprise JavaBeans 1.1//EN"
"http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">

Clarified in Sections EJB.5.5 and EJB.8.7 that handles are not capabilities in the security sense.

Replaced the term resource factory reference with the term resource manager connection factory reference. This change makes the terminology consistent with other J2EE specs.

Added a missing entry to Table EJB.18-2 for checkLink.

Clarified in Section EJB.16.5 that the DTD XML elements' content is case sensitive.

Fixed a few typos in the text.


EJB.C.12 Changes Since EJB 1.1 Public Release

Clarified in Section EJB.17.3 that the enterprise bean's dependent files could be in other jar files if the jar files are specified in the EJB JAR file's Class-Path.

Clarified in Section EJB.16.5 that the method-intf can be used with all Style elements, specifically with method-name being *.

Clarified in Section EJB.9.1.9.4 that multi-object finders should return an empty collection if no object is found.

Allowed enterprise beans to read system properties.


Previous Section

Glossary

access control

The methods by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.

ACID

The acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation, and durability.

activation

The process of transferring an enterprise bean from secondary storage to memory.

See also [passivation]

applet

A component that typically executes in a web browser but can execute in a variety of other applications or devices that support the applet programming model.

applet container

A container that includes support for the applet programming model.

application assembler

A person that combines components and modules into deployable application units.

application client

A first-tier client component that executes in its own Java virtual machine. Application clients have access to some (JNDI, JDBC, RMI-IIOP, JMS) J2EE platform APIs.

application client container

A container that supports application client components.

application client module

A software unit that consists of one or more classes and an application client deployment descriptor.

application component provider

A vendor that provides the Java classes that implement components' methods, JSP page definitions, and any required deployment descriptors.

authentication

The process by which an entity proves to another entity that it is acting on behalf of a specific identity. The J2EE platform requires four types of authentication: basic, digest, form-based, and mutual.

authorization
See [access control]
authorization constraint

A set of security roles that are allowed access to the resources in a web resource collection.

basic authentication

An authentication mechanism in which a web server authenticates an entity with a user name and password obtained using the web client's built-in authentication mechanism.

bean-managed persistence

When the transfer of data between an entity bean instance's variables and the underlying resource manager is managed by the entity bean.

bean-managed transaction

When an enterprise bean defines the boundaries of the transaction.

business logic

The code that implements the functionality of an application. In the Enterprise JavaBeans model, this logic is implemented by the methods of an enterprise bean.

business method

A method of an enterprise bean that implements the business logic or rules of an application.

callback methods

Methods in a component called by the container to notify the component of important events in its life cycle.

caller

Same as caller principal.

caller principal

The principal that identifies the invoker of the enterprise bean method.

commit

The point in a transaction when all updates to any resources involved in the transaction are made permanent.

component

An application-level software unit supported by a container. Components are configurable at deployment time. The J2EE platform defines four types of components: enterprise beans, web components, applets, and application clients.

component contract

The contract between a component and its container. The contract includes: life cycle management of the component, a context interface that the instance uses to obtain various information and services from its container, and a list of services that every container must provide for its components.

component environment

A set of requirements defined by the application component provider required to be available to a J2EE component in its naming environment. The environment entries are declaratively specified in the component's deployment descriptor. Each component names and accesses its environment configuration values using the java:comp/env JNDI context. These values can be objects a component is dependent on, such as a JDBC DataSource, or a simple value such as a tax rate.

connection
See [resource manager connection]
connection factory
See [resource manager connection factory]
connector

A standard extension mechanism for containers to provide connectivity to enterprise information systems. A connector is specific to an enterprise information system and consists of a resource adapter and application development tools for enterprise information system connectivity. The resource adapter is plugged in to a container through its support for system-level contracts defined in the connector architecture.

connector architecture

An architecture for integration of J2EE products with enterprise information systems. There are two parts to this architecture: a resource adapter provided by an enterprise information system vendor and the J2EE product that allows this resource adapter to plug in. This architecture defines a set of contracts that a resource adapter has to support to plug in to a J2EE product, for example, transactions, security, and resource management.

container

An entity that provides life cycle management, security, deployment, and runtime services to components. Each type of container (EJB, web, JSP, servlet, applet, and application client) also provides component-specific services.

container-managed persistence

When transfer of data between an entity bean's variables and the underlying resource manager is managed by the enterprise bean's container.

container-managed transaction

When an EJB container defines the boundaries of a transaction. An entity bean must use container-managed transactions.

context attribute

An object bound into the context associated with a servlet.

conversational state

The field values of a session bean plus the transitive closure of the objects reachable from the bean's fields. The transitive closure of a bean is defined in terms of the serialization protocol for the Java programming language, that is, the fields that would be stored by serializing the bean instance.

CORBA

Common Object Request Broker Architecture. A language-independent, distributed object model specified by the Object Management Group (OMG).

create method

A method defined in the home interface and invoked by a client to create an enterprise bean.

credentials

The information describing the security attributes of a principal. Credentials can be acquired only through authentication or delegation.

CTS

Compatibility test suite. A suite of compatibility tests for verifying that a J2EE product complies with the J2EE platform specification.

delegation

An act whereby one principal authorizes another principal to use its identity or privileges with some restrictions.

deployer

A person who installs modules and J2EE applications into an operational environment.

deployment

The process whereby software is installed into an operational environment.

deployment descriptor

An XML file provided with each module and application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.

digest authentication

An authentication mechanism in which a web server authenticates an entity with a user name and password obtained using the web client's built-in authentication mechanism. The authentication is performed by transmitting the password in an encrypted form which is much more secure than the base64 encoding used by basic authentication.

distributed application

An application made up of distinct components running in separate runtime environments, usually on different platforms connected via a network. Typical distributed applications are two-tier (client-server), three-tier (client-middleware-server), and multitier (client-multiple middleware-multiple servers).

DOM

Document object model. A tree of objects with interfaces for traversing the tree and writing an XML version of it, as defined by the W3C specification.

DTD

Document Type Definition. A description of the structure and properties of a class of XML files.

EAR file

A JAR archive that contains a J2EE application.

EJB™
See [Enterprise JavaBeans]
EJB container

A container that implements the EJB component contract of the J2EE architecture. This contract specifies a runtime environment for enterprise beans that includes security, concurrency, life cycle management, transaction, deployment, and other services. An EJB container is provided by an EJB or J2EE server.

EJB container provider

A vendor that supplies an EJB container.

EJB context

An object that allows an enterprise bean to invoke services provided by the container and to obtain the information about the caller of a client-invoked method.

EJB home object

An object that provides the life cycle operations (create, remove, find) for an enterprise bean. The class for the EJB home object is generated by the container's deployment tools. The EJB home object implements the enterprise bean's home interface. The client references an EJB home object to perform life cycle operations on an EJB object. The client uses JNDI to locate an EJB home object.

EJB JAR file

A JAR archive that contains an EJB module.

EJB module

A software unit that consists of one or more enterprise beans and an EJB deployment descriptor.

EJB object

An object whose class implements the enterprise bean's remote interface. A client never references an enterprise bean instance directly; a client always references an EJB object. The class of an EJB object is generated by the container's deployment tools.

EJB server

Software that provides services to an EJB container. For example, an EJB container typically relies on a transaction manager that is part of the EJB server to perform the two-phase commit across all the participating resource managers. The J2EE architecture assumes that an EJB container is hosted by an EJB server from the same vendor, so does not specify the contract between these two entities. An EJB server may host one or more EJB containers.

EJB server provider

A vendor that supplies an EJB server.

enterprise bean

A component that implements a business task or business entity and resides in an EJB container; either an entity bean or a session bean.

enterprise bean provider

An application programmer who produces enterprise bean classes, remote and home interfaces, and deployment descriptor files, and packages them in an EJB JAR file.

enterprise information system

The applications that comprise an enterprise's existing system for handling company-wide information. These applications provide an information infrastructure for an enterprise. An enterprise information system offers a well-defined set of services to its clients. These services are exposed to clients as local and/or remote interfaces. Examples of enterprise information systems include: ERP systems, mainframe transaction processing systems, and legacy database systems.

enterprise information system resource

An entity that provides enterprise information system-specific functionality to its clients. Examples are: a record or set of records in a database system, a business object in an ERP system, and a transaction program in a transaction processing system.

Enterprise JavaBeans™ (EJB)

A component architecture for the development and deployment of object-oriented, distributed, enterprise-level applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and secure.

entity bean

An enterprise bean that represents persistent data maintained in a database. An entity bean can manage its own persistence or it can delegate this function to its container. An entity bean is identified by a primary key. If the container in which an entity bean is hosted crashes, the entity bean, its primary key, and any remote references survive the crash.

finder method

A method defined in the home interface and invoked by a client to locate an entity bean.

form-based authentication

An authentication mechanism in which a web container provides an application-specific form for logging in.

group

A collection of principals within a given security policy domain.

handle

An object that identifies an enterprise bean. A client may serialize the handle and then later deserialize it to obtain a reference to the enterprise bean.

home handle

An object that can be used to obtain a reference of the home interface. A home handle can be serialized and written to stable storage and deserialized to obtain the reference.

home interface

One of two interfaces for an enterprise bean. The home interface defines zero or more methods for creating and removing an enterprise bean. For session beans, the home interface defines create and remove methods, while for entity beans, the home interface defines create, finder, and remove methods.

HTML

Hypertext markup language. A markup language for hypertext documents on the Internet. HTML enables the embedding of images, sounds, video streams, form fields, references to other objects with URLs, and basic text formatting.

HTTP

Hypertext transfer protocol. The Internet protocol used to fetch hypertext objects from remote hosts. HTTP messages consist of requests from client to server and responses from server to client.

HTTPS

HTTP layered over the SSL protocol.

IDL

Interface definition language. A language used to define interfaces to remote CORBA objects. The interfaces are independent of operating systems and programming languages.

IIOP

Internet inter-ORB protocol. A protocol used for communication between CORBA object request brokers.

impersonation

An act whereby one entity assumes the identity and privileges of another entity without restrictions and without any indication visible to the recipients of the impersonator's calls that delegation has taken place. Impersonation is a case of simple delegation.

initialization parameter

A parameter that initializes the context associated with a servlet.

ISV

Independent software vendor.

J2EE™

Java 2, Enterprise Edition.

J2ME™

Java 2, Micro Edition.

J2SE™

Java 2, Standard Edition.

J2EE application

Any deployable unit of J2EE functionality. This can be a single module or a group of modules packaged into an .ear file with a J2EE application deployment descriptor. J2EE applications are typically engineered to be distributed across multiple computing tiers.

J2EE product

An implementation that conforms to the J2EE platform specification.

J2EE product provider

A vendor that supplies a J2EE product.

J2EE server

The runtime portion of a J2EE product. A J2EE server provides web and/or EJB containers.

Java™ 2 Platform, Standard Edition (J2SE platform)

The core Java technology platform.

Java™ 2 Platform, Enterprise Edition (J2EE platform)

An environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.

Java™ 2 SDK, Enterprise Edition (J2EE SDK)

Sun's implementation of the J2EE platform. This implementation provides an operational definition of the J2EE platform.

Java™ Message Service (JMS)

An API for using enterprise messaging systems such as IBM MQ Series, TIBCO Rendezvous, and so on.

Java Naming and Directory Interface™ (JNDI)

An API that provides naming and directory functionality.

Java™ Transaction API (JTA)

An API that allows applications and J2EE servers to access transactions.

Java™ Transaction Service (JTS)

Specifies the implementation of a transaction manager which supports JTA and implements the Java mapping of the OMG Object Transaction Service (OTS) 1.1 specification at the level below the API.

JavaBeans™ component

A Java class that can be manipulated in a visual builder tool and composed into applications. A JavaBeans component must adhere to certain property and event interface conventions.

Java IDL

A technology that provides CORBA interoperability and connectivity capabilities for the J2EE platform. These capabilities enable J2EE applications to invoke operations on remote network services using the OMG IDL and IIOP.

JavaMail™

An API for sending and receiving e-mail.

JavaServer Pages™ (JSP)

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.

JDBC™

An API for database-independent connectivity between the J2EE platform and a wide range of data sources.

JSP
See [JavaServer Pages]
JSP action

A JSP element 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.

JSP action, custom

An action described in a portable manner by a tag library descriptor and a collection of Java classes and imported into a JSP page by a taglib directive.

JSP action, standard

An action that is defined in the JSP specification and is always available to a JSP file without being imported.

JSP application

A stand-alone web application, written using the JavaServer Pages technology, that can contain JSP pages, servlets, HTML files, images, applets, and JavaBeans components.

JSP container

A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

JSP container, distributed

A JSP container that can run a web application that is tagged as distributable and is spread across multiple Java virtual machines that might be running on different hosts.

JSP declaration

A JSP scripting element that declares methods, variables, or both in a JSP file.

JSP directive

A JSP element that gives an instruction to the JSP container and is interpreted at translation time.

JSP element

A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.

JSP expression

A scripting element that contains a valid scripting language expression that is evaluated, converted to a string, and placed into the implicit out object.

JSP file

A file that contains a JSP page. In the Servlet 2.2 specification, a JSP file must have a .jsp extension.

JSP page

A text-based document using fixed template data and JSP elements that describes how to process a request to create a response.

JSP scripting element

A JSP 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."

JSP scriptlet

A JSP 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."

JSP tag

A piece of text between a left angle bracket and a right angle bracket that is used in a JSP file as part of a JSP element. The tag is distinguishable as markup, as opposed to data, because it is surrounded by angle brackets.

JSP tag library

A collection of tags identifying custom actions described via a tag library descriptor and Java classes.

method permission

A permission to invoke a specified group of methods of an enterprise bean's home and remote interfaces.

module

A software unit that consists of one or more J2EE components of the same container type and one deployment descriptor of that type. There are three types of modules: EJB, web, and application client. Modules can be deployed as stand-alone units or assembled into an application.

mutual authentication

An authentication mechanism in which a client uses a public key certificate to establish its identity and maintains its own security context.

ORB

Object request broker. A library that enables CORBA objects to locate and communicate with one another.

OS principal

A principal native to the operating system on which the J2EE platform is executing.

OTS

Object transaction service. A definition of the interfaces that permit CORBA objects to participate in transactions.

passivation

The process of transferring an enterprise bean from memory to secondary storage.

See also [activation]

persistence

The protocol for transferring the state of an entity bean between its instance variables and an underlying database.

POA

Portable object adapter. A CORBA standard for building server-side applications that are portable across heterogeneous ORBs.

primary key

An object that uniquely identifies an entity bean within a home.

principal

The identity assigned to an entity as a result of authentication.

privilege

A security attribute that does not have the property of uniqueness and that may be shared by many principals. Privileges to access certain resources may be identified for a particular group.

realm

Also, a string, passed as part of an HTTP request during basic authentication, that defines a protection space. The protected resources on a server can be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database.

See also [security policy domain]

reentrant entity bean

An entity bean that can handle multiple simultaneous, interleaved, or nested invocations which will not interfere with each other.

reference implementation
See [Java 2 SDK, Enterprise Edition]
remote interface

One of two interfaces for an enterprise bean. The remote interface defines the business methods callable by a client.

remove method

Method defined in the home interface and invoked by a client to destroy an enterprise bean.

resource adapter

A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter is typically specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs in to a container. The application components deployed on the container then use the client API (exposed by adapter) or tool generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms—transactions, security, and connection pooling—for connectivity to the enterprise information system.

resource manager

Provides access to a set of shared resources. A resource manager participates in transactions that are externally controlled and coordinated by a transaction manager. A resource manager is typically in different address space or on a different machine from the clients that access it. Note: An enterprise information system is referred to as resource manager when it is mentioned in the context of resource and transaction management.

resource manager connection

An object that represents a session with a resource manager.

resource manager connection factory

An object used for creating a resource manager connection.

RMI

Remote method invocation. A technology that allows an object running in one Java virtual machine to invoke methods on an object running in a different Java virtual machine.

RMI-IIOP

A version of RMI implemented to use the CORBA IIOP protocol. RMI over IIOP provides interoperability with CORBA objects implemented in any language if all the remote interfaces are originally defined as RMI interfaces.

role (development)

The function performed by a party in the development and deployment phases of an application developed using J2EE technology. The roles are: application component provider, application assembler, deployer, J2EE product provider, EJB container provider, EJB server provider, web container provider, web server provider, tool provider, and system administrator.

role (security)

An abstract logical grouping of users that is defined by the application assembler. When an application is deployed, the roles are mapped to security identities, such as principals or groups, in the operational environment.

role mapping

The process of associating the groups and/or principals recognized by the container to security roles specified in the deployment descriptor. Security roles have to be mapped by the deployer before the component is installed in the server.

rollback

The point in a transaction when all updates to any resources involved in the transaction are reversed.

SAX

Simple API for XML. An event-driven, serial-access mechanism for accessing XML documents.

security attributes

A set of properties associated with a principal. Security attributes can be associated with a principal by an authentication protocol and/or by a J2EE product provider.

security constraint

A declarative way to annotate the intended protection of web content. A security constraint consists of a web resource collection, an authorization constraint, and a user data constraint.

security context

An object that encapsulates the shared state information regarding security between two entities.

security permission

A mechanism, defined by J2SE, used by the J2EE platform to express the programming restrictions imposed on application component providers.

security permission set

The minimum set of security permissions that a J2EE product provider must provide for the execution of each component type.

security policy domain

A scope over which security policies are defined and enforced by a security administrator. A security policy domain has a collection of users (or principals), uses a well-defined authentication protocol(s) for authenticating users (or principals), and may have groups to simplify setting of security policies.

security role
See [role (security)]
security technology domain

A scope over which the same security mechanism is used to enforce a security policy. Multiple security policy domains can exist within a single technology domain.

security view

The set of security roles defined by the application assembler.

server principal

The OS principal that the server is executing as.

servlet

A Java program that extends the functionality of a web server, generating dynamic content and interacting with web clients using a request-response paradigm.

servlet container

A container that provides the network services over which requests and responses are sent, decodes requests, and formats responses. All servlet containers must support HTTP as a protocol for requests and responses, but may also support additional request-response protocols such as HTTPS.

servlet container, distributed

A servlet container that can run a web application that is tagged as distributable and that executes across multiple Java virtual machines running on the same host or on different hosts.

servlet context

An object that contains a servlet's view of the web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

servlet mapping

Defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

session

An object used by a servlet to track a user's interaction with a web application across multiple HTTP requests.

session bean

An enterprise bean that is created by a client and that usually exists only for the duration of a single client-server session. A session bean performs operations, such as calculations or accessing a database, for the client. While a session bean may be transactional, it is not recoverable should a system crash occur. Session bean objects can be stateless or they can maintain conversational state across methods and transactions. If a session bean maintains state, then the EJB container manages this state if the object must be removed from memory. However, the session bean object itself must manage its own persistent data.

SQL

Structured query language. The standardized relational database language for defining database objects and manipulating data.

SQL/J

A set of standards that includes specifications for embedding SQL statements in methods in the Java programming language and specifications for calling Java static methods as SQL stored procedures and user-defined functions. An SQL checker can detect errors in static SQL statements at program development time, rather than at execution time as with a JDBC driver.

SSL

Secure socket layer. A security protocol that provides privacy over the Internet. The protocol allows client-server applications to communicate in a way that cannot be eavesdropped or tampered with. Servers are always authenticated and clients are optionally authenticated.

stateful session bean

A session bean with a conversational state.

stateless session bean

A session bean with no conversational state. All instances of a stateless session bean are identical.

system administrator

The person responsible for configuring and administering the enterprise's computers, networks, and software systems.

transaction

An atomic unit of work that modifies data. A transaction encloses one or more program statements, all of which either complete or roll back. Transactions enable multiple users to access the same data concurrently.

transaction attribute

A value specified in an enterprise bean's deployment descriptor that is used by the EJB container to control the transaction scope when the enterprise bean's methods are invoked. A transaction attribute can have the following values: Required, RequiresNew, Supports, NotSupported, Mandatory, Never.

transaction isolation level

The degree to which the intermediate state of the data being modified by a transaction is visible to other concurrent transactions and data being modified by other transactions is visible to it.

transaction manager

Provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation.

tool provider

An organization or software vendor that provides tools used for the development, packaging, and deployment of J2EE applications.

URI

Uniform resource identifier. A compact string of characters for identifying an abstract or physical resource. A URI is either a URL or a URN. URLs and URNs are concrete entities that actually exist; a URI is an abstract superclass.

URL

Uniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the World Wide Web. A URL looks like "protocol: //host/localinfo" where "protocol" specifies a protocol for fetching the object (such as HTTP or FTP), "host" specifies the Internet name of the targeted host, and "localinfo" is a string (often a file name) passed to the protocol handler on the remote host.

URL path

The URL passed by an HTTP request to invoke a servlet. The URL consists of the context path + servlet path + path information, where context path is the path prefix associated with a servlet context that this servlet is a part of. If this context is the default context rooted at the base of the web server's URL namespace, the path prefix will be an empty string. Otherwise, the path prefix starts with a / character but does not end with a / character. Servlet path is the path section that directly corresponds to the mapping which activated this request. This path starts with a / character. Path info is the part of the request path that is not part of the context path or the servlet path.

URN

Uniform resource name. A unique identifier that identifies an entity but doesn't tell where it is located. A system can use a URN to look up an entity locally before trying to find it on the web. It also allows the web location to change, while still allowing the entity to be found.

user data constraint

Indicates how data between a client and a web container should be protected. The protection can be the prevention of tampering with the data or prevention of eavesdropping on the data.

WAR file

A JAR archive that contains a web module.

web application

An application written for the Internet, including those built with Java technologies such as JavaServer Pages and servlets, as well as those built with non-Java technologies such as CGI and Perl.

web application, distributable

A web application that uses J2EE technology written so that it can be deployed in a web container distributed across multiple Java virtual machines running on the same host or different hosts. The deployment descriptor for such an application uses the distributable element.

web component

A component that provides services in response to requests; either a servlet or a JSP page.

web container

An entity that implements the web component contract of the J2EE architecture. This contract specifies a runtime environment for web components that includes security, concurrency, life cycle management, transaction, deployment, and other services. A web container provides the same services as a JSP container and a federated view of the J2EE platform APIs. A web container is provided by a web or J2EE server.

web container, distributed

A web container that can run a web application that is tagged as distributable and that executes across multiple Java virtual machines running on the same host or on different hosts.

web container provider

A vendor that supplies a web container.

web module

A unit that consists of one or more web components and a web deployment descriptor.

web resource collection

A list of URL patterns and HTTP methods that describe a set of resources to be protected.

web server

Software that provides services to access the Internet, an intranet, or an extranet. A web server hosts web sites, provides support for HTTP and other protocols, and executes server-side programs (such as CGI scripts or servlets) that perform certain functions. In the J2EE architecture, a web server provides services to a web container. For example, a web container typically relies on a web server to provide HTTP message handling. The J2EE architecture assumes that a web container is hosted by a web server from the same vendor, so does not specify the contract between these two entities. A web server may host one or more web containers.

web server provider

A vendor that supplies a web server.

XML

Extensible markup language. A markup language that allows you to define the tags (markup) needed to identify the data and text in XML documents. J2EE deployment descriptors are expressed in XML.
    Previous Section