Você está na página 1de 981

SCBCD Study Guide

SCBCD Study Guide Next

SCBCD Study Guide


IBA JV Mikalai Zaikin
<NZaikin[at]iba.by>

Copyright 2004 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. March 2004
Revision History Revision 2.4 Proposed Final Draft 3. Revision 2.3 Proposed Final Draft 2. Revision 2.2 Proposed Final Draft 1. Revision 2.1 Chap 1.4, 13 updates. Revision 2.0 Chap 14 updates. Revision 1.9 Chap 14.2, 14.3 updates. 3 Dec 2003 MZ 4 Dec 2003 MZ 7 Dec 2003 MZ 19 Dec 2003 MZ 22 Dec 2003 MZ 31 Mar 2004 MZ

Abstract The purpose of this document is to help in preparation for exam CX-310-090 (Sun Certified Business Component Developer for the Java 2 Platform, Enterprise Edition 1.3).

http://java.boot.by/bcd-guide/ 1 / 6 2004/6/12 11:55:46

SCBCD Study Guide

This document should not be used as the only study material for SCBDC test. It covers all objective topics, but it is not enough. I tried to make this document as much accurate as possible, but if you find any error, please let me know.

Table of Contents Foreword Preface I. Exam Objectives 1. EJB Overview Identify the use, benefits, and characteristics of Enterprise JavaBeans technology, for version 2.0 of the EJB specification. Identify EJB 2.0 container requirements. Identify correct and incorrect statements or examples about EJB programming restrictions. Match EJB roles with the corresponding description of the role's responsibilities, where the description may include deployment descriptor information. Given a list, identify which are requirements for an EJB-jar file. 2. Client View of a Session Bean Identify correct and incorrect statements or examples about the client view of a session bean's local and remote home interfaces, including the code used by a client to locate a session bean's home interface. Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces. 3. Session Bean Component Contract Identify correct and incorrect statements or examples about session beans, including conversational state, the SessionBean interface, and create methods. Identify the use and the behavior of the ejbPassivate method in a session bean, including the responsibilities of both the container and the bean provider. Identify the interface and method for each of the following: retrieve the session bean's remote home interface, retrieve the session bean's local component interface, determine if the session bean's caller has a particular role, allow the instance to mark the current transaction as a rollback, retrieve the UserTransaction interface, prepare the instance for reuse following passivation, release resources prior to removal, identify the invoker of the bean instance's component interface, be notified that a new transaction has begun, and be notified that the current transaction has completed. Match the correct description about purpose and function to which session bean type they apply: stateless, stateful, or both. Given a list of responsibilities related to session beans, identify those which are the responsibility of the session bean provider and those which are the responsibility of the EJB container provider.
http://java.boot.by/bcd-guide/ 2 / 6 2004/6/12 11:55:46

SCBCD Study Guide

4.

5.

6.

7.

Given a list of requirements, identify those which are the requirements for a session bean class, a remote component interface, a remote home interface, create methods, business methods, a local component interface, and a local home interface. Session Bean Life Cycle Identify correct and incorrect statements or examples about the life cycle of a stateful or stateless session bean instance. Given a list of methods for a stateful or stateless session bean class, define which of the following operations can be performed from each of those methods: SessionContext interface methods, UserTransaction methods, Java Naming and Directory Interface API (JNDI API) access to java:comp/env environment naming context, resource manager access, and other enterprise bean access. Given a list of scenarios, identify which will result in an ejbRemove method not being called on a bean instance. Client View of an Entity Identify correct and incorrect statements or examples about the client of an entity bean's local and remote home interface, including viewing the code used to locate an entity bean's home interface and the home interface methods provided to the client. Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject). Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject). Identify the use, syntax, and behavior of, the following entity bean home method types, for Container-Managed Persistence (CMP); finder methods, create methods, remove methods, and home methods. Component Contract for Container-Managed Persistence (CMP) Identify correct and incorrect statements or examples about the entity bean provider's view and programming contract for CMP, including the requirements for a CMP entity bean. Identify correct and incorrect statements or examples about persistent relationships, remove protocols, and about the abstract schema type of a CMP entity bean. Identify correct and incorrect statements or examples about the rules and semantics for relationship assignment and relationship updating in a CMP bean. Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: ejb-name, abstract-schema-name, ejbrelation, ejb-relationship-role, cmr-field, cmr-field-type, and relationship-rolesource. Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships). Identify the interfaces and methods a CMP entity bean must and must not implement. CMP Entity Bean Life Cycle

http://java.boot.by/bcd-guide/ 3 / 6 2004/6/12 11:55:46

SCBCD Study Guide

Identify correct and incorrect statements or examples about the life cycle of a CMP entity bean. From a list, identify the purpose, behavior, and responsibilities of the bean provider for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect. From a list, identify the responsibility of the container for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect. 8. Entity Beans From a list of behaviors, match them with the appropriate EntityContext method responsible for that behavior. Identify correct and incorrect statements or examples about an entity bean's primary key and object identity. 9. EJB-QL Identify correct and incorrect syntax for an EJB QL query including the SELECT, FROM, and WHERE clauses. Identify correct and incorrect statements or examples about the purpose and use of EJB QL. Identify correct and incorrect conditional expressions, BETWEEN expressions, IN expressions, LIKE expressions, and comparison expressions. 10. Message-Driven Bean Component Contract Identify correct and incorrect statements or examples about the client view of a message-driven bean, and the life cycle of a message-driven bean. Identify the interfaces and methods a JMS message-driven bean must implement. Identify the use and behavior of the MessageDrivenContext interface methods. From a list, identify the responsibility of the bean provider and the responsibility of the container provider for a message-driven bean. 11. Transactions Identify correct and incorrect statements or examples about EJB transactions, including bean-managed transaction demarcation and container-managed transaction demarcation. Identify correct and incorrect statements about the Application Assembler's responsibilities, including the use of deployment descriptor elements related to transactions and the identification of the methods of a particular bean type for which a transaction attribute must be specified. Given a list of transaction behaviors, match them with the appropriate transaction attributes. Given a list of responsibilities, identify whose which are the Container's with respect to transactions, including the handling of getRollbackOnly, setRollbackOnly, getUserTransaction, SessionSynchronzation callbacks, for both container and bean-managed transactions. 12. Exceptions

http://java.boot.by/bcd-guide/ 4 / 6 2004/6/12 11:55:46

SCBCD Study Guide

Identify correct and incorrect statements or examples about exception handling in EJB. Given a list of responsibilities related to exceptions, identify those which are the bean provider's, and those which are the responsibility of the container provider. Be prepared to recognize responsibilities for which neither the bean provider or the container provider are responsible. Identify correct and incorrect statements or examples about application exceptions and system exceptions in entity beans, session beans, and message-driven beans. Given a particular method condition, identify the following: whether an exception will be thrown, the type of exception thrown, the container's action, and the client's view. Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation. 13. Enterprise Bean Environment Identify correct and incorrect statements or examples about an enterprise bean's environment JNDI API naming. Identify correct and incorrect statements about the purpose and use of the deployment descriptor elements for environment entries, EJB references, and resource manager connection factory references; including whether a given code listing is appropriate and correct with respect to a particular deployment descriptor element. Given a list of responsibilities, identify which belong to the deployer, bean provider, application assembler, container provider, system administrator, or any combination. 14. Security Management Identify correct and incorrect statements about the EJB support for security management including security roles, security role references, and method permissions. From a list of responsibilities, identify which belong to the application assembler, bean provider, deployer, container provider, or system administrator. Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context. Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag. II. Appendixes A. First Appendix First Section Second Section Third Section Bibliography

Next Foreword
http://java.boot.by/bcd-guide/ 5 / 6 2004/6/12 11:55:46

SCBCD Study Guide

http://java.boot.by/bcd-guide/ 6 / 6 2004/6/12 11:55:46

Foreword

Foreword Prev Next

Foreword
A preface.

Prev SCBCD Study Guide

Up Home

Next Preface

http://java.boot.by/bcd-guide/pr01.html2004/6/12 11:55:49

SCBCD Study Guide

SCBCD Study Guide Next

SCBCD Study Guide


IBA JV Mikalai Zaikin
<NZaikin[at]iba.by>

Copyright 2004 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. March 2004
Revision History Revision 2.4 Proposed Final Draft 3. Revision 2.3 Proposed Final Draft 2. Revision 2.2 Proposed Final Draft 1. Revision 2.1 Chap 1.4, 13 updates. Revision 2.0 Chap 14 updates. Revision 1.9 Chap 14.2, 14.3 updates. 3 Dec 2003 MZ 4 Dec 2003 MZ 7 Dec 2003 MZ 19 Dec 2003 MZ 22 Dec 2003 MZ 31 Mar 2004 MZ

Abstract The purpose of this document is to help in preparation for exam CX-310-090 (Sun Certified Business Component Developer for the Java 2 Platform, Enterprise Edition 1.3).

http://java.boot.by/bcd-guide/index.html 1 / 6 2004/6/12 11:55:51

SCBCD Study Guide

This document should not be used as the only study material for SCBDC test. It covers all objective topics, but it is not enough. I tried to make this document as much accurate as possible, but if you find any error, please let me know.

Table of Contents Foreword Preface I. Exam Objectives 1. EJB Overview Identify the use, benefits, and characteristics of Enterprise JavaBeans technology, for version 2.0 of the EJB specification. Identify EJB 2.0 container requirements. Identify correct and incorrect statements or examples about EJB programming restrictions. Match EJB roles with the corresponding description of the role's responsibilities, where the description may include deployment descriptor information. Given a list, identify which are requirements for an EJB-jar file. 2. Client View of a Session Bean Identify correct and incorrect statements or examples about the client view of a session bean's local and remote home interfaces, including the code used by a client to locate a session bean's home interface. Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces. 3. Session Bean Component Contract Identify correct and incorrect statements or examples about session beans, including conversational state, the SessionBean interface, and create methods. Identify the use and the behavior of the ejbPassivate method in a session bean, including the responsibilities of both the container and the bean provider. Identify the interface and method for each of the following: retrieve the session bean's remote home interface, retrieve the session bean's local component interface, determine if the session bean's caller has a particular role, allow the instance to mark the current transaction as a rollback, retrieve the UserTransaction interface, prepare the instance for reuse following passivation, release resources prior to removal, identify the invoker of the bean instance's component interface, be notified that a new transaction has begun, and be notified that the current transaction has completed. Match the correct description about purpose and function to which session bean type they apply: stateless, stateful, or both. Given a list of responsibilities related to session beans, identify those which are the responsibility of the session bean provider and those which are the responsibility of the EJB container provider.
http://java.boot.by/bcd-guide/index.html 2 / 6 2004/6/12 11:55:51

SCBCD Study Guide

4.

5.

6.

7.

Given a list of requirements, identify those which are the requirements for a session bean class, a remote component interface, a remote home interface, create methods, business methods, a local component interface, and a local home interface. Session Bean Life Cycle Identify correct and incorrect statements or examples about the life cycle of a stateful or stateless session bean instance. Given a list of methods for a stateful or stateless session bean class, define which of the following operations can be performed from each of those methods: SessionContext interface methods, UserTransaction methods, Java Naming and Directory Interface API (JNDI API) access to java:comp/env environment naming context, resource manager access, and other enterprise bean access. Given a list of scenarios, identify which will result in an ejbRemove method not being called on a bean instance. Client View of an Entity Identify correct and incorrect statements or examples about the client of an entity bean's local and remote home interface, including viewing the code used to locate an entity bean's home interface and the home interface methods provided to the client. Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject). Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject). Identify the use, syntax, and behavior of, the following entity bean home method types, for Container-Managed Persistence (CMP); finder methods, create methods, remove methods, and home methods. Component Contract for Container-Managed Persistence (CMP) Identify correct and incorrect statements or examples about the entity bean provider's view and programming contract for CMP, including the requirements for a CMP entity bean. Identify correct and incorrect statements or examples about persistent relationships, remove protocols, and about the abstract schema type of a CMP entity bean. Identify correct and incorrect statements or examples about the rules and semantics for relationship assignment and relationship updating in a CMP bean. Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: ejb-name, abstract-schema-name, ejbrelation, ejb-relationship-role, cmr-field, cmr-field-type, and relationship-rolesource. Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships). Identify the interfaces and methods a CMP entity bean must and must not implement. CMP Entity Bean Life Cycle

http://java.boot.by/bcd-guide/index.html 3 / 6 2004/6/12 11:55:51

SCBCD Study Guide

Identify correct and incorrect statements or examples about the life cycle of a CMP entity bean. From a list, identify the purpose, behavior, and responsibilities of the bean provider for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect. From a list, identify the responsibility of the container for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect. 8. Entity Beans From a list of behaviors, match them with the appropriate EntityContext method responsible for that behavior. Identify correct and incorrect statements or examples about an entity bean's primary key and object identity. 9. EJB-QL Identify correct and incorrect syntax for an EJB QL query including the SELECT, FROM, and WHERE clauses. Identify correct and incorrect statements or examples about the purpose and use of EJB QL. Identify correct and incorrect conditional expressions, BETWEEN expressions, IN expressions, LIKE expressions, and comparison expressions. 10. Message-Driven Bean Component Contract Identify correct and incorrect statements or examples about the client view of a message-driven bean, and the life cycle of a message-driven bean. Identify the interfaces and methods a JMS message-driven bean must implement. Identify the use and behavior of the MessageDrivenContext interface methods. From a list, identify the responsibility of the bean provider and the responsibility of the container provider for a message-driven bean. 11. Transactions Identify correct and incorrect statements or examples about EJB transactions, including bean-managed transaction demarcation and container-managed transaction demarcation. Identify correct and incorrect statements about the Application Assembler's responsibilities, including the use of deployment descriptor elements related to transactions and the identification of the methods of a particular bean type for which a transaction attribute must be specified. Given a list of transaction behaviors, match them with the appropriate transaction attributes. Given a list of responsibilities, identify whose which are the Container's with respect to transactions, including the handling of getRollbackOnly, setRollbackOnly, getUserTransaction, SessionSynchronzation callbacks, for both container and bean-managed transactions. 12. Exceptions

http://java.boot.by/bcd-guide/index.html 4 / 6 2004/6/12 11:55:51

SCBCD Study Guide

Identify correct and incorrect statements or examples about exception handling in EJB. Given a list of responsibilities related to exceptions, identify those which are the bean provider's, and those which are the responsibility of the container provider. Be prepared to recognize responsibilities for which neither the bean provider or the container provider are responsible. Identify correct and incorrect statements or examples about application exceptions and system exceptions in entity beans, session beans, and message-driven beans. Given a particular method condition, identify the following: whether an exception will be thrown, the type of exception thrown, the container's action, and the client's view. Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation. 13. Enterprise Bean Environment Identify correct and incorrect statements or examples about an enterprise bean's environment JNDI API naming. Identify correct and incorrect statements about the purpose and use of the deployment descriptor elements for environment entries, EJB references, and resource manager connection factory references; including whether a given code listing is appropriate and correct with respect to a particular deployment descriptor element. Given a list of responsibilities, identify which belong to the deployer, bean provider, application assembler, container provider, system administrator, or any combination. 14. Security Management Identify correct and incorrect statements about the EJB support for security management including security roles, security role references, and method permissions. From a list of responsibilities, identify which belong to the application assembler, bean provider, deployer, container provider, or system administrator. Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context. Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag. II. Appendixes A. First Appendix First Section Second Section Third Section Bibliography

Next Foreword
http://java.boot.by/bcd-guide/index.html 5 / 6 2004/6/12 11:55:51

SCBCD Study Guide

http://java.boot.by/bcd-guide/index.html 6 / 6 2004/6/12 11:55:51

Preface

Preface Prev Next

Preface
This document is available in 2 formats: single page and chunked pages If you would like to have PDF (printable eBook for Adobe Acrobat Reader) version or CHM (single file copy of web-site to browse offline) version of SCBCD Study Guide, please, contact me.

Prev Foreword

Up Home

Next Part I. Exam Objectives

http://java.boot.by/bcd-guide/pr02.html2004/6/12 11:55:54

Part I. Exam Objectives

Part I. Exam Objectives Prev Next

Exam Objectives
Prev Preface Up Home Next Chapter 1. EJB Overview

http://java.boot.by/bcd-guide/pt01.html2004/6/12 11:55:56

Chapter 1. EJB Overview

Chapter 1. EJB Overview Prev Part I. Exam Objectives Next

Chapter 1. EJB Overview

Identify the use, benefits, and characteristics of Enterprise JavaBeans technology, for version 2.0 of the EJB specification.
Characteristics Enterprise JavaBeans architecture is the standard component architecture for building distributed object-oriented business applications. Enterprise JavaBeans architecture makes it possible to build distributed applications by combining components developed using tools from different vendors. Application developers do not have to understand low-level transaction and state management details, multi-threading, connection pooling, and other complex low-level APIs. Enterprise JavaBeans applications follow the Write Once, Run Anywhere philosophy of the Java programming language. The Enterprise JavaBeans architecture addresses the development, deployment, and runtime aspects of an enterprise applications life cycle. Enterprise JavaBeans architecture defines the contracts that enable tools from multiple vendors to develop and deploy components Enterprise JavaBeans architecture is compatible with the CORBA protocols. This allows remote invocations on session and entity beans from J2EE components that are deployed in products from different vendors. Benefits Defines the integration of EJB with the Java Message Service. Introduces message-driven beans (MDB) - a stateless components that are invoked by the container as a result of the arrival of a JMS message (MDB does not have home/home-local or remote/local interfaces). Provides a local client view and support for efficient, lightweight access to enterprise beans from local clients. Provides improved support for the persistence of entity beans.
http://java.boot.by/bcd-guide/ch01.html 1 / 2 2004/6/12 11:55:58

Chapter 1. EJB Overview

Provides improved support for the management of relationships among entity beans (Local CMP Beans only). Provides a query syntax (EJB QL) for entity bean finder and select methods (CMP only). Provides support for additional methods in the home interface (business logic methods via ejbHome<MethodName>().

Prev Part I. Exam Objectives

Up Home

Next Identify EJB 2.0 container requirements.

http://java.boot.by/bcd-guide/ch01.html 2 / 2 2004/6/12 11:55:58

Identify EJB 2.0 container requirements.

Identify EJB 2.0 container requirements. Prev Chapter 1. EJB Overview Next

Identify EJB 2.0 container requirements.


The EJB Provider can rely on the EJB 2.0 Container Provider to provide the following APIs:

Java 2 Platform, Standard Edition, v1.3 (J2SE) APIs EJB 2.0 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) JMS 1.0.2 Standard Extension JavaMail 1.1 Standard Extension (for sending mail only) JAXP 1.0

Prev Chapter 1. EJB Overview

Up Home

Next Identify correct and incorrect statements or examples about EJB programming restrictions.

http://java.boot.by/bcd-guide/ch01s02.html2004/6/12 11:56:00

Identify correct and incorrect statements or examples about EJB programming restrictions.

Identify correct and incorrect statements or examples about EJB programming restrictions. Prev Chapter 1. EJB Overview Next

Identify correct and incorrect statements or examples about EJB programming restrictions.
An enterprise Bean must not use read/write static fields. Using read-only ( final) static fields is allowed. An enterprise Bean must not use thread synchronization primitives to synchronize execution of multiple instances. An enterprise Bean must not use the AWT functionality to attempt to output information to a display, or to input information from a keyboard. An enterprise bean must not use the java.io package to attempt to access files and directories in the file system. An enterprise bean must not attempt to listen on a socket, accept connections on a socket, or use a socket for multicast. Enterprise bean instance is allowed be a network socket client. 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. 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 JVM; or change the input, output, and error streams. 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 threads priority or name. The enterprise bean must not attempt to directly read or write a file descriptor. The enterprise bean must not attempt to obtain the security policy information for a particular code source. The enterprise bean must not attempt to load a native library. 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. The enterprise bean must not attempt to define a class in a package.

http://java.boot.by/bcd-guide/ch01s03.html 1 / 2 2004/6/12 11:56:02

Identify correct and incorrect statements or examples about EJB programming restrictions.

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(), SessionContext. getEJBLocalObject(), EntityContext.getEJBObject(), or EntityContext.getEJBLocalObject() instead.

Prev Identify EJB 2.0 container requirements.

Up Home

Next Match EJB roles with the corresponding description of the role's responsibilities, where the description may include deployment descriptor information.

http://java.boot.by/bcd-guide/ch01s03.html 2 / 2 2004/6/12 11:56:02

Match EJB roles with the corresponding description of the role's resp...where the description may include deployment descriptor information.

Match EJB roles with the corresponding description of the role's responsibilities, where the description may include deployment descriptor information. Prev Chapter 1. EJB Overview Next

Match EJB roles with the corresponding description of the role's responsibilities, where the description may include deployment descriptor information.
There are 6 roles defined : Bean Provider The Bean Provider 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 home and component interfaces; and the bean's deployment descriptor. The deployment descriptor (DD) 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 resources that the enterprise bean uses). Bean Provider is responsible for packaging the enterprise beans in an ejb-jar file. The deployment descriptor must include the structural information. Structural information describes the structure of an enterprise bean and declares an enterprise bean's external dependencies. The structural information cannot be changed because doing so could break the enterprise bean's function. MUST USE the enterprise-beans element to list all the enterprise beans in the ejb-jar file. 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. The Application Assembler outputs one or more ejb-jar files that contain the enterprise beans along with their application assembly instructions. The Application Assembler inserts the application assembly instructions into the deployment descriptors. The deployment descriptor must include the 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. Assembly level information can be changed without breaking the enterprise bean's function, although doing so may alter the behavior of an assembled application. Deployer

http://java.boot.by/bcd-guide/ch01s04.html 1 / 3 2004/6/12 11:56:05

Match EJB roles with the corresponding description of the role's resp...where the description may include deployment descriptor information.

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 or her role, the Deployer uses tools provided by the EJB Container Provider. Uses the deployment tools provided by the EJB Container provider to deploy ejb-jar files produced by the Bean Providers and Application Assemblers. EJB Server Provider The EJB server provider is a specialist in the area of distributed transaction management, distributed objects, and other lower-level system services. A typical EJB server provider is an operating system vendor, middleware vendor, or database vendor. The job of the server provider is to provide a runtime EJB server environment that is compliant with the EJB specification. IBM is a server provider of the WebSphere Application Server. EJB Container Provider 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 remote clients, scalable management of resources, and other services that are generally required as part of a manageable server platform. Responsible for providing the DEPLOYMENT TOOLS used by the Deployer to deploy enterprise beans packaged in the ejb-jar file. Responsible for providing all the runtime services for the deployed enterprise bean instances. The focus of a Container Provider is on the development of a scalable, secure, transactionenabled 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. The Container Provider also manages the persistence issues for its entity beans that use container-managed persistence (CMP). The Container Provider's tools generate code that moves data between the enterprise bean's container-managed fields and a database or an existing application. This code generation typically takes place at deployment time (vendor-specific).

http://java.boot.by/bcd-guide/ch01s04.html 2 / 3 2004/6/12 11:56:05

Match EJB roles with the corresponding description of the role's resp...where the description may include deployment descriptor information.

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. Responsible for configuring the EJB Container and server, setting up security management, integrating resource managers with the EJB Container.

Prev Identify correct and incorrect statements or examples about EJB programming restrictions.

Up Home

Next Given a list, identify which are requirements for an EJB-jar file.

http://java.boot.by/bcd-guide/ch01s04.html 3 / 3 2004/6/12 11:56:05

Given a list, identify which are requirements for an EJB-jar file.

Given a list, identify which are requirements for an EJB-jar file. Prev Chapter 1. EJB Overview Next

Given a list, identify which are requirements for an EJB-jar file.


The ejb-jar file MUST CONTAIN, either by inclusion or by reference (Class-Path attribute in the Manifest file), the class files of each enterprise bean as follows:

The enterprise bean class. The enterprise bean home and component interfaces. The primary key class if the bean is an entity bean. All the classes and interfaces that each enterprise bean class and the home and component interfaces depend on, except J2EE and J2SE classes.

The Application Assembler MUST NOT package the stubs of the EJBHome and EJBObject interfaces in the ejb-jar file.

Prev Match EJB roles with the corresponding description of the role's responsibilities, where the description may include deployment descriptor information.

Up Home

Next Chapter 2. Client View of a Session Bean

http://java.boot.by/bcd-guide/ch01s05.html2004/6/12 11:56:12

Chapter 2. Client View of a Session Bean

Chapter 2. Client View of a Session Bean Prev Part I. Exam Objectives Next

Chapter 2. Client View of a Session Bean

Identify correct and incorrect statements or examples about the client view of a session bean's local and remote home interfaces, including the code used by a client to locate a session bean's home interface.
A client locates a session beans home interface using JNDI. For example, the remote 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);

If the Cart session bean provides a local client view instead of a remote client view and CartHome is a local home interface, this lookup might be as follows:

Context initialContext = new InitialContext(); CartHome cartHome = (CartHome) initialContext.lookup(java:comp/env/ejb/cart);

A client can pass a remote home object reference to another application. The receiving application can use the home interface in the same way that it would use a remote home object reference obtained via JNDI. A client can pass a local home object reference to another application through its local interface. A local home object reference cannot be passed as an argument or result of a method on an enterprise beans remote home or remote interface. The REMOTE HOME interface allows a client to do the following:

Create a new session object. Remove a session object (using bean's HANDLE).

http://java.boot.by/bcd-guide/ch02.html 1 / 3 2004/6/12 11:56:14

Chapter 2. Client View of a Session Bean

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 REMOTE 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 remote home interface.

public interface EJBHome extends Remote { EJBMetaData getEJBMetaData() throws RemoteException; HomeHandle getHomeHandle() throws RemoteException; void remove(Handle handle) throws RemoteException, RemoveException; void remove(Object primaryKey) throws RemoteException, RemoveException; // only Entity EJB !!! }

The LOCAL HOME interface allows a local client to do the following:

Create a new session object.

public interface EJBLocalHome { void remove(Object primaryKey) throws RemoveException, EJBException; // only Entity EJB !!! }

EJBMetaData and HomeHandle are ONLY accessible for REMOTE HOME interfaces. EJBHome interface extends Remote (marker) interface. Session bean can be removed ONLY using it's handle (remote view ONLY), since it does not have primary key.

Prev Given a list, identify which are requirements for an EJB-jar file.

Up Home

Next Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces.

http://java.boot.by/bcd-guide/ch02.html 2 / 3 2004/6/12 11:56:14

Chapter 2. Client View of a Session Bean

http://java.boot.by/bcd-guide/ch02.html 3 / 3 2004/6/12 11:56:14

Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces.

Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces. Prev Chapter 2. Client View of a Session Bean Next

Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces.
A client NEVER DIRECTLY accesses instances of the session beans class. A client always uses the session beans COMPONENT interface to access a session beans instance. The class that implements the session beans component interface is provided by the container. 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. Get the session objects remote home interface. Get the session objects handle. Test if the session object is identical with another session object. Remove the session object.

public interface EJBObject extends Remote { EJBHome getEJBHome() throws RemoteException; Handle getHandle() throws RemoteException; Object getPrimaryKey() throws RemoteException; boolean isIdentical(EJBObject obj) throws RemoteException; void remove() throws RemoteException, RemoveException; }

A session EJBLocalObject supports:

The business logic methods of the object. The session EJBLocalObject delegates invocation of a business method to the session bean instance. Get the session objects local home interface. Test if the session object is identical with another session object. Remove the session object.

public interface EJBLocalObject { EJBLocalHome getEJBLocalHome() throws EJBException; Object getPrimaryKey() throws EJBException; boolean isIdentical(EJBLocalObject obj) throws EJBException; void remove() throws RemoveException, EJBException;
http://java.boot.by/bcd-guide/ch02s02.html 1 / 2 2004/6/12 11:56:17

Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces.

Method getPrimaryKey() on session bean will throw EJBException (local SB) or RemoteException (remote SB) because session bean does not have primary key. EJBObject interface extends Remote (marker) interface.

Prev Chapter 2. Client View of a Session Bean

Up Home

Next Chapter 3. Session Bean Component Contract

http://java.boot.by/bcd-guide/ch02s02.html 2 / 2 2004/6/12 11:56:17

Chapter 3. Session Bean Component Contract

Chapter 3. Session Bean Component Contract Prev Part I. Exam Objectives Next

Chapter 3. Session Bean Component Contract

Identify correct and incorrect statements or examples about session beans, including conversational state, the SessionBean interface, and create methods.
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.

The conversational state of a STATEFUL session object is defined as the session bean instances field values. In advanced cases, a session objects 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. All session beans must implement the SessionBean interface.

public interface SessionBean extends EnterpriseBean { void ejbActivate() throws EJBException, RemoteException; void ejbPassivate() throws EJBException, RemoteException; void ejbRemove() throws EJBException, RemoteException; void setSessionContext(SessionContext ctx) throws EJBException, RemoteException; } public interface EnterpriseBean extends Serializable { }

A client creates a session bean instance using one of the create<METHOD> methods defined in the session beans home interface:

public interface CartHome extends javax.ejb.EJBHome {


http://java.boot.by/bcd-guide/ch03.html 1 / 3 2004/6/12 11:56:20

Chapter 3. Session Bean Component Contract

CartRemote create(String customerName, String account) throws RemoteException, BadAccountException, CreateException; CartRemote createLargeCart(String customerName, String account) throws RemoteException, BadAccountException, CreateException; }

..... CartRemote cart = cartHome.create(John, 7506);

or for LOCAL view:

public interface CartHome extends javax.ejb.EJBLocalHome { CartLocal create(String customerName, String account) throws BadAccountException, CreateException; CartLocal createLargeCart(String customerName, String account) throws BadAccountException, CreateException; }

..... CartLocal cart = cartHome.create(John, 7506);

The container creates an instance of a session bean in three steps: 1. The container calls the bean class newInstance() method to create a new session bean instance. 2. The container calls the setSessionContext(context) method to pass the context object to the instance. 3. The container calls the instances ejbCreate<METHOD>() method whose signature matches the signature of the create<METHOD>() method invoked by the client. Each session bean class must have at LEAST one ejbCreate<METHOD>() method (NOTE: for Entity Beans create methods are optional). Invoking create() method by client on home interface of STATELESS session bean will NOT invoke ejbCreate() method on bean object. It only creates new EJB(Local)Object. ejbCreate() on STATELESS session bean is invoked by EJB container when it decides to put object in methodready pool. For STATELESS session beans container handles creating of instances.
http://java.boot.by/bcd-guide/ch03.html 2 / 3 2004/6/12 11:56:20

Chapter 3. Session Bean Component Contract

Invoking remove() method by client on home interface of STATELESS session bean will NOT invoke ejbRemove() method on bean object. It does nothing. ejbRemove() on STATELESS session bean is invoked by EJB container when it decides to remove object from method-ready pool. For STATELESS session beans container handles removing of instances. Invoking create<METHOD>() method by client on home interface of STATEFUL session bean will invoke ejbCreate<METHOD>() method on bean object. More precisely: newInstance(), setSessionContext(context), ejbCreate<METHOD>([ARGS]). Invoking remove() method by client on home interface of STATEFUL session bean will invoke ejbRemove() method on bean object. The home interface of a STATELESS session bean must have one (and ONLY one) create() method that takes NO arguments. The create() method of the remote home interface must return the session beans remote interface. The create method of the local home interface must return the session beans local interface. STATELESS session bean CAN have instance variables, but there is no guarantee, that these variables will be accessed by the same 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. A STATELESS session bean MUST NOT implement the javax.ejb.SessionSynchronization interface.

Prev Identify correct and incorrect statements or examples about the client view of a session bean's local and remote component interfaces.

Up Home

Next Identify the use and the behavior of the ejbPassivate method in a session bean, including the responsibilities of both the container and the bean provider.

http://java.boot.by/bcd-guide/ch03.html 3 / 3 2004/6/12 11:56:20

Identify the use and the behavior of the ejbPassivate method in a sessi...ding the responsibilities of both the container and the bean provider.

Identify the use and the behavior of the ejbPassivate method in a session bean, including the responsibilities of both the container and the bean provider. Prev Chapter 3. Session Bean Component Contract Next

Identify the use and the behavior of the ejbPassivate method in a session bean, including the responsibilities of both the container and the bean provider.
Bean Provider's responsibility Passivation is performed only for STATEFUL session beans. 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 instances non-transient fields after the ejbPassivate method completes must be one of the following:

A serializable object. A null. An enterprise beans remote interface reference. An enterprise beans remote home interface reference. An entity beans local interface reference. An entity beans local home interface reference. A reference to the SessionContext object. A reference to the environment naming context (java:comp/env JNDI) A reference to the UserTransaction interface. A reference to a resource manager connection factory. An object that is not directly serializable, because it contains references on "nonserializable" objects mentioned above.

Bean Provider must close all JDBC connections in ejbPassivate and assign the instances fields storing the connections to null. The Bean Provider must assume that the content of transient fields MAY be lost between the ejbPassivate and ejbActivate notifications. Container's responsibility The container performs the Java programming language Serialization (or its equivalent) of the instances state after it invokes the ejbPassivate method on the instance. The container must be able to properly save and restore the reference to the home and component interfaces of the enterprise beans stored in the instances state even if the classes that implement the object references are not serializable. If the session bean instance stores in its conversational state an object reference to the javax.ejb. SessionContext interface, java:comp/env JNDI context or UserTransaction interface, the container

http://java.boot.by/bcd-guide/ch03s02.html 1 / 2 2004/6/12 11:56:23

Identify the use and the behavior of the ejbPassivate method in a sessi...ding the responsibilities of both the container and the bean provider.

must be able to save and restore the object reference across the instances passivation. 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 (as opposed to pure Serialization, which GUARANTEES that transient variables will come back with default values for that type). Passivation typically happens spontaneously based on the needs of the container. It happens just BEFORE writing state to secondary storage. Activation typically occurs when a client calls a method. It happens just AFTER reading state from secondary storage.

Prev Chapter 3. Session Bean Component Contract

Up

Next Identify the interface and method for each of the following: retrieve the session bean's remote home interface, retrieve the session bean's local component interface, determine if the session bean's caller has a particular role, allow the instance to mark the current transaction as a rollback, retrieve the UserTransaction interface, prepare the instance for reuse following passivation, release resources prior to removal, identify the invoker of the bean instance's component interface, be notified that a new transaction has begun, and be notified that the current transaction has completed.

Home

http://java.boot.by/bcd-guide/ch03s02.html 2 / 2 2004/6/12 11:56:23

Identify the interface and method for each of the following: retrieve t...has begun, and be notified that the current transaction has completed.

Identify the interface and method for each of the following: retrieve the session bean's remote home interface, retrieve the session bean's local component interface, determine if the session bean's caller has a particular role, allow the instance to mark the current transaction as a rollback, retrieve the UserTransaction interface, prepare the instance for reuse following passivation, release resources prior to removal, identify the invoker of the bean instance's component interface, be notified that a new transaction has begun, and be notified that the current transaction has completed. Prev Chapter 3. Session Bean Component Contract Next

Identify the interface and method for each of the following: retrieve the session bean's remote home interface, retrieve the session bean's local component interface, determine if the session bean's caller has a particular role, allow the instance to mark the current transaction as a rollback, retrieve the UserTransaction interface, prepare the instance for reuse following passivation, release resources prior to removal, identify the invoker of the bean instance's component interface, be notified that a new transaction has begun, and be notified that the current transaction has completed.
A container provides the session bean instances with a SessionContext, which gives the session bean instance access to the instances context maintained by the container. The SessionContext interface has the following methods:

The getEJBObject method returns the session beans remote interface. The getEJBHome method returns the session beans remote home interface. The getEJBLocalObject method returns the session beans local interface. The getEJBLocalHome method returns the session beans local home interface. The getCallerPrincipal method returns the java.security.Principal that identifies the invoker of the bean instances EJB object. The isCallerInRole method tests if the session bean instances 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 (CMT) 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 (CMT) 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 (BMT) can use this method.

public interface SessionContext extends EJBContext { EJBLocalObject getEJBLocalObject() throws IllegalStateException; EJBObject getEJBObject() throws IllegalStateException; } public interface EJBContext {
http://java.boot.by/bcd-guide/ch03s03.html 1 / 3 2004/6/12 11:56:25

Identify the interface and method for each of the following: retrieve t...has begun, and be notified that the current transaction has completed.

EJBHome getEJBHome(); EJBLocalHome getEJBLocalHome(); java.security.Principal getCallerPrincipal(); boolean isCallerInRole(String roleName); UserTransaction getUserTransaction() throws IllegalStateException; void setRollbackOnly() throws IllegalStateException; boolean getRollbackOnly() throws IllegalStateException; } /** * This interface represents the abstract notion of a principal, which * can be used to represent any entity, such as an individual, a * corporation, and a login id. */ public interface Principal { public String getName(); }

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 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 instances 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>(...) 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 clean up mechanism to periodically clean up the unreleased resources. 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 instances passivation and then reopened during an instances activation (for example, DB connections). A STATEFUL session bean class (CMT only) can optionally implement the javax.ejb.
http://java.boot.by/bcd-guide/ch03s03.html 2 / 3 2004/6/12 11:56:25

Identify the interface and method for each of the following: retrieve t...has begun, and be notified that the current transaction has completed.

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 instances 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 instances conversational state is not transactional, it may need to manually reset its state if a rollback occurred.

public interface SessionSynchronization { void afterBegin() throws EJBException, RemoteException; void afterCompletion(boolean committed) throws EJBException, RemoteException; void beforeCompletion() throws EJBException, RemoteException; }

ONLY a STATEFUL Session bean with CONTAINER-managed transaction (CMT) demarcation may implement the SessionSynchronization interface. A stateless Session bean MUST NOT implement the SessionSynchronization interface.

Prev Identify the use and the behavior of the ejbPassivate method in a session bean, including the responsibilities of both the container and the bean provider.

Up Home

Next Match the correct description about purpose and function to which session bean type they apply: stateless, stateful, or both.

http://java.boot.by/bcd-guide/ch03s03.html 3 / 3 2004/6/12 11:56:25

Match the correct description about purpose and function to which session bean type they apply: stateless, stateful, or both.

Match the correct description about purpose and function to which session bean type they apply: stateless, stateful, or both. Prev Chapter 3. Session Bean Component Contract Next

Match the correct description about purpose and function to which session bean type they apply: stateless, stateful, or both.
The conversational state of a STATEFUL session object is defined as the session bean instances field values, plus the transitive closure of the objects from the instances fields reached by following Java object references. 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 servicing a clientinvoked method. 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. There is no fixed mapping between clients and STATELESS instances. The container simply delegates a clients work to any available instance that is method-ready. There is "method ready" STATE for STATEFUL session beans. Because they have relationship: one client - one bean. There is "method ready" POOL for STATELESS session beans. Because they have relationship: one client - many beans.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch03s04.html 1 / 2 2004/6/12 11:56:28

Match the correct description about purpose and function to which session bean type they apply: stateless, stateful, or both.

Identify the interface and method for each of the following: retrieve the session bean's remote home interface, retrieve the session bean's local component interface, determine if the session bean's caller has a particular role, allow the instance to mark the current transaction as a rollback, retrieve the UserTransaction interface, prepare the instance for reuse following passivation, release resources prior to removal, identify the invoker of the bean instance's component interface, be notified that a new transaction has begun, and be notified that the current transaction has completed.

Given a list of responsibilities related to session beans, identify those which are the responsibility of the session bean provider and those which are the responsibility of the EJB container provider. Home

http://java.boot.by/bcd-guide/ch03s04.html 2 / 2 2004/6/12 11:56:28

Given a list of responsibilities related to session beans, identify thos...r and those which are the responsibility of the EJB container provider.

Given a list of responsibilities related to session beans, identify those which are the responsibility of the session bean provider and those which are the responsibility of the EJB container provider. Prev Chapter 3. Session Bean Component Contract Next

Given a list of responsibilities related to session beans, identify those which are the responsibility of the session bean provider and those which are the responsibility of the EJB container provider.
Bean Provider's responsibility The session bean provider is responsible for providing the following class files:

Session bean class. Session beans remote interface and remote home interface, if the session bean provides a remote client view. Session beans local interface and local home interface, if the session bean provides a local client view.

Container Provider's responsibility The container provider is responsible for providing the deployment tools and for managing the session bean instances at runtime. 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 beans deployment descriptor. The deployment tools must generate the following classes:

A class class). A class A class class). A class

that implements the session beans remote home interface (session EJBHome that implements the session beans remote interface (session EJBObject class). that implements the session beans local home interface (session EJBLocalHome that implements the session beans local interface (session EJBLocalObject 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 session EJBHome class, which is generated by the deployment tools, implements the session beans remote home interface. This class implements the methods of the javax.ejb.

http://java.boot.by/bcd-guide/ch03s05.html 1 / 2 2004/6/12 11:56:30

Given a list of responsibilities related to session beans, identify thos...r and those which are the responsibility of the EJB container provider.

EJBHome interface and the create<METHOD> methods specific to the session bean. The implementation of each create<METHOD>(...) method invokes a matching ejbCreate<METHOD>(...) method. The session EJBObject class, which is generated by the deployment tools, implements the session beans 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. The session EJBLocalHome class, which is generated by the deployment tools, implements the session beans local home interface. This class implements the methods of the javax.ejb. EJBLocalHome interface and the create<METHOD> methods specific to the session bean. The implementation of each create<METHOD>(...) method invokes a matching ejbCreate<METHOD>(...) method. The session EJBLocalObject class, which is generated by the deployment tools, implements the session beans local interface. It implements the methods of the javax.ejb. EJBLocalObject 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. The deployment tools are responsible for implementing the handle classes for the session beans REMOTE HOME and REMOTE interfaces. The deployment tools are responsible for implementing the class that provides meta-data to the remote client view contract. The class must be a valid RMI Value class and must implement the javax.ejb.EJBMetaData interface. 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 may throw the java.rmi.RemoteException to the second request if the client is a remote client, or the javax.ejb.EJBException if the client is a local client. The container MUST follow the rules with respect to transaction scoping, security checking, and exception handling. The container MUST implement the SessionContext.getEJBObject() method such that the bean instance can use the Java language cast to convert the returned value to the session beans remote interface type. Specifically, the bean instance does not have to use the PortableRemoteObject.narrow(...) method for the type conversion.

Prev Match the correct description about purpose and function to which session bean type they apply: stateless, stateful, or both.

Up

Next Given a list of requirements, identify those which are the requirements for a session bean class, a remote component interface, a remote home interface, create methods, business methods, a local component interface, and a local home interface.

Home

http://java.boot.by/bcd-guide/ch03s05.html 2 / 2 2004/6/12 11:56:30

Given a list of requirements, identify those which are the requirement...ess methods, a local component interface, and a local home interface.

Given a list of requirements, identify those which are the requirements for a session bean class, a remote component interface, a remote home interface, create methods, business methods, a local component interface, and a local home interface. Prev Chapter 3. Session Bean Component Contract Next

Given a list of requirements, identify those which are the requirements for a session bean class, a remote component interface, a remote home interface, create methods, business methods, a local component interface, and a local home interface.
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 (NOTE, CMP ENTITY bean class MUST 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 beans component interface (NOTE: AVOID passing of this). 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<METHOD> 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.

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 if the method corresponds to a business method on the session beans remote interface. The throws clause may define arbitrary application exceptions.

The session BEAN CLASS must define one or more ejbCreate<METHOD>(...) methods whose signatures must follow these rules:

http://java.boot.by/bcd-guide/ch03s06.html 1 / 4 2004/6/12 11:56:33

Given a list of requirements, identify those which are the requirement...ess methods, a local component interface, and a local home interface.

The method name MUST have ejbCreate as its prefix. 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 if there is a create<METHOD>(...) corresponding to the ejbCreate<METHOD>(...) method on the session beans remote home interface. The throws clause may define arbitrary application exceptions, possibly including the javax. ejb.CreateException.

The following are the requirements for the session beans REMOTE [component] 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 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 session beans class. The matching method must have:
r r r

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.

The remote interface methods must not expose local interface types, local home interface types, or the managed collection classes that are used for entity beans with containermanaged persistence as arguments or results.

The following are the requirements for the session beans REMOTE 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 clauses MUST include the java.rmi.RemoteException. The remote 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 beans remote home interface MUST define one or more create<METHOD>(...) methods. (NOTE, Entity Beans may define ZERO create(...) methods). A STATELESS session bean must define exactly ONE create() method with NO arguments. Each create method MUST be named create<METHOD>, and it MUST match one of the ejbCreate<METHOD> methods defined in the session bean class. The matching ejbCreate<METHOD> method MUST have the same number and types of arguments. (Note that the return type is different.) The methods for a STATELESS session bean MUST be named create and ejbCreate. The return type for a create<METHOD> method MUST be the session beans REMOTE

http://java.boot.by/bcd-guide/ch03s06.html 2 / 4 2004/6/12 11:56:33

Given a list of requirements, identify those which are the requirement...ess methods, a local component interface, and a local home interface.

INTERFACE type. All the exceptions defined in the throws clause of an ejbCreate<METHOD> method of the session bean class must be defined in the throws clause of the matching create<METHOD> method of the remote home interface. The throws clause of create<METHOD>(...) MUST include javax.ejb.CreateException.

The following are the requirements for the session beans LOCAL [component] interface:

The interface MUST extend the javax.ejb.EJBLocalObject interface. The throws clause of a method defined in the LOCAL interface MUST NOT include the java. rmi.RemoteException. The local interface is allowed to have superinterfaces. For each method defined in the local interface, there must be a matching method in the session beans class. The matching method must have:
r r r

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 local interface.

The following are the requirements for the session beans LOCAL HOME interface:

The interface MUST extend the javax.ejb.EJBLocalHome interface. The throws clause of a method in the LOCAL home interface MUST NOT include the java.rmi. RemoteException. The local home interface is allowed to have superinterfaces. A session beans local home interface MUST define one or more create<METHOD>(...) methods. A STATELESS session bean MUST define exactly ONE create() method with NO arguments. Each create method MUST be named create<METHOD>, and it MUST match one of the ejbCreate<METHOD> methods defined in the session bean class. The matching ejbCreate<METHOD> method MUST have the same number and types of arguments. (Note that the return type is different.) The methods for a STATELESS session bean MUST be named create and ejbCreate. The return type for a create<METHOD> method MUST be the session beans local interface type. All the exceptions defined in the throws clause of an ejbCreate<METHOD> method of the session bean class MUST be defined in the throws clause of the matching create<METHOD> method of the local home interface. The throws clause of create<METHOD> method MUST include javax.ejb.CreateException.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch03s06.html 3 / 4 2004/6/12 11:56:33

Given a list of requirements, identify those which are the requirement...ess methods, a local component interface, and a local home interface.

Given a list of responsibilities related to session beans, identify those which are the responsibility of the session bean provider and those which are the responsibility of the EJB container provider.

Chapter 4. Session Bean Life Cycle Home

http://java.boot.by/bcd-guide/ch03s06.html 4 / 4 2004/6/12 11:56:33

Chapter 4. Session Bean Life Cycle

Chapter 4. Session Bean Life Cycle Prev Part I. Exam Objectives Next

Chapter 4. Session Bean Life Cycle

Identify correct and incorrect statements or examples about the life cycle of a stateful or stateless session bean instance.
Stateful Session Bean

A session bean instances life starts when a client invokes a create<METHOD>(...) method on the session beans 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<METHOD>(...) on the instance and returns the session object reference to the client. The instance is now in the METHOD READY STATE. The session bean instance is now ready for clients business methods. Based on the transaction attributes in the session beans deployment descriptor and the transaction context associated with the clients invocation, a business method is executed either in a transaction context or with an unspecified transaction context. 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

http://java.boot.by/bcd-guide/ch04.html 1 / 3 2004/6/12 11:56:36

Chapter 4. Session Bean Life Cycle

the beginning of the transaction. The containers 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 instances 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 if the client is a remote client, or the javax.ejb.NoSuchObjectLocalException if the client is a local 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 instances 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 component 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 if the client is a remote client, or the javax.ejb.NoSuchObjectLocalException if the client is a local client. (The java.rmi.NoSuchObjectException is a subclass of the java.rmi. RemoteException; the javax.ejb.NoSuchObjectLocalException is a subclass of the javax.ejb. EJBException). 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.

Stateless Session Bean

A stateless session bean instances 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 timethere is NO relationship to a clients 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.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch04.html 2 / 3 2004/6/12 11:56:36

Chapter 4. Session Bean Life Cycle

Given a list of requirements, identify those which are the requirements for a session bean class, a remote component interface, a remote home interface, create methods, business methods, a local component interface, and a local home interface.

Home

Given a list of methods for a stateful or stateless session bean class, define which of the following operations can be performed from each of those methods: SessionContext interface methods, UserTransaction methods, Java Naming and Directory Interface API (JNDI API) access to java:comp/env environment naming context, resource manager access, and other enterprise bean access.

http://java.boot.by/bcd-guide/ch04.html 3 / 3 2004/6/12 11:56:36

Given a list of methods for a stateful or stateless session bean class,...ing context, resource manager access, and other enterprise bean access.

Given a list of methods for a stateful or stateless session bean class, define which of the following operations can be performed from each of those methods: SessionContext interface methods, UserTransaction methods, Java Naming and Directory Interface API (JNDI API) access to java:comp/env environment naming context, resource manager access, and other enterprise bean access. Prev Chapter 4. Session Bean Life Cycle Next

Given a list of methods for a stateful or stateless session bean class, define which of the following operations can be performed from each of those methods: SessionContext interface methods, UserTransaction methods, Java Naming and Directory Interface API (JNDI API) access to java:comp/env environment naming context, resource manager access, and other enterprise bean access.
Stateful Session Bean Table 4.1. Operations allowed in the methods of a stateful session bean
Bean method can perform the following operations Bean method Container-managed transaction demarcation SessionContext methods: getEJBHome, getEJBLocalHome. JNDI access to java:comp/env SessionContext methods: getEJBHome, getEJBLocalHome, getCallerPrincipal, isCallerInRole, getEJBObject, getEJBLocalObject. JNDI access to java:comp/env Resource manager access Enterprise bean access JNDI access to java:comp/env Resource manager access Enterprise bean access SessionContext methods: getEJBHome, getEJBLocalHome. JNDI access to java:comp/env SessionContext methods: getEJBHome, getEJBLocalHome, getCallerPrincipal, isCallerInRole, getEJBObject, getEJBLocalObject, getUserTransaction. UserTransaction methods Bean-managed transaction demarcation

constructor

setSessionContext

ejbCreate ejbRemove ejbActivate ejbPassivate

http://java.boot.by/bcd-guide/ch04s02.html 1 / 3 2004/6/12 11:56:39

Given a list of methods for a stateful or stateless session bean class,...ing context, resource manager access, and other enterprise bean access.

Business method from component interface

SessionContext methods: getEJBHome, getEJBLocalHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject, getEJBLocalObject. JNDI access to java:comp/env Resource manager access Enterprise bean access SessionContext methods: getEJBHome, getEJBLocalHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject, getEJBLocalObject. JNDI access to java:comp/env Resource manager access Enterprise bean access SessionContext methods: getEJBHome, getEJBLocalHome, getCallerPrincipal, isCallerInRole, getEJBObject, getEJBLocalObject. JNDI access to java:comp/env

SessionContext methods: getEJBHome, getEJBLocalHome, getCallerPrincipal, isCallerInRole, getEJBObject, getEJBLocalObject, getUserTransaction. UserTransaction methods JNDI access to java:comp/env Resource manager access Enterprise bean access

afterBegin beforeCompletion

N/A (a bean with bean-managed transaction (BMT) demarcation cannot implement the SessionSynchronization interface)

afterCompletion

Stateless Session Bean Table 4.2. Operations allowed in the methods of a stateless session bean
Bean method can perform the following operations Bean method

http://java.boot.by/bcd-guide/ch04s02.html 2 / 3 2004/6/12 11:56:39

Given a list of methods for a stateful or stateless session bean class,...ing context, resource manager access, and other enterprise bean access.

Container-managed transaction demarcation constructor SessionContext methods: getEJBHome, getEJBLocalHome. JNDI access to java:comp/env SessionContext methods: getEJBHome, getEJBLocalHome, getEJBObject, getEJBLocalObject. JNDI access to java:comp/env

Bean-managed transaction demarcation SessionContext methods: getEJBHome, getEJBLocalHome. JNDI access to java:comp/env SessionContext methods: getEJBHome, getEJBLocalHome, getEJBObject, getEJBLocalObject, getUserTransaction. JNDI access to java:comp/env

setSessionContext

ejbCreate ejbRemove

SessionContext methods: getEJBHome, getEJBLocalHome, getCallerPrincipal, getRollbackOnly, isCallerInRole, setRollbackOnly, getEJBObject, getEJBLocalObject. Business method from component interface JNDI access to java:comp/env Resource manager access Enterprise bean access

SessionContext methods: getEJBHome, getEJBLocalHome, getCallerPrincipal, isCallerInRole, getEJBObject, getEJBLocalObject, getUserTransaction. UserTransaction methods JNDI access to java:comp/env Resource manager access Enterprise bean access

Prev Chapter 4. Session Bean Life Cycle

Up Home

Next Given a list of scenarios, identify which will result in an ejbRemove method not being called on a bean instance.

http://java.boot.by/bcd-guide/ch04s02.html 3 / 3 2004/6/12 11:56:39

Given a list of scenarios, identify which will result in an ejbRemove method not being called on a bean instance.

Given a list of scenarios, identify which will result in an ejbRemove method not being called on a bean instance. Prev Chapter 4. Session Bean Life Cycle Next

Given a list of scenarios, identify which will result in an ejbRemove method not being called on a bean instance.
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 (java.lang.RuntimeException (or subclass), javax.ejb.EJBException, java.rmi. RemoteException, failure to obtain a database connection, JNDI exceptions) exception thrown from the instances 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>(...) 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 clean up mechanism to periodically clean up the unreleased resources.

Prev Given a list of methods for a stateful or stateless session bean class, define which of the following operations can be performed from each of those methods: SessionContext interface methods, UserTransaction methods, Java Naming and Directory Interface API (JNDI API) access to java:comp/env environment naming context, resource manager access, and other enterprise bean access.

Up

Next Chapter 5. Client View of an Entity

Home

http://java.boot.by/bcd-guide/ch04s03.html2004/6/12 11:56:43

Chapter 5. Client View of an Entity

Chapter 5. Client View of an Entity Prev Part I. Exam Objectives Next

Chapter 5. Client View of an Entity

Identify correct and incorrect statements or examples about the client of an entity bean's local and remote home interface, including viewing the code used to locate an entity bean's home interface and the home interface methods provided to the client.
The client of an entity bean may be a REMOTE client or the client may be a LOCAL client. A REMOTE client accesses an entity bean through the entity beans remote and remote home interfaces. The remote and remote home interfaces of the entity bean provide the remote client view. The remote 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 LOCAL client accesses an entity bean through the entity beans local and local home interfaces. The container provides classes that implement the entity beans local and local home interfaces. The objects that implement the local home and local interfaces are local Java objects. The arguments of the methods of the LOCAL interface and LOCAL HOME interface are passed by REFERENCE. The arguments and results of the methods of the REMOTE interface and REMOTE HOME interface are passed by VALUE. The remote client view can also be mapped to non-Java client environments, such as CORBA clients not written in the Java programming language. Locating an entity beans REMOTE home interface

Context initialContext = new InitialContext(); AccountRemoteHome accountHome = (AccountRemoteHome) javax.rmi.PortableRemoteObject.narrow( initialContext.lookup(java:comp/env/ejb/accounts), AccountRemoteHome.class );

http://java.boot.by/bcd-guide/ch05.html 1 / 3 2004/6/12 11:56:45

Chapter 5. Client View of an Entity

Locating an entity beans LOCAL home interface

Context initialContext = new InitialContext(); AccountLocalHome accountHome = (AccountLocalHome) initialContext.lookup(java:comp/env/ejb/accounts);

The CONTAINER provides the implementation of the remote home interface for each entity bean deployed in the container that defines a remote home interface. The container makes the remote home interface accessible to the clients through JNDI. The entity beans remote 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. Execute a home business method. 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 meta-data 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 beans remote home interface must extend the javax.ejb.EJBHome interface and follow the standard rules for Java programming language remote interfaces. The CONTAINER provides the implementation of the local home interface for each entity bean deployed in the container that defines a local home interface. The container makes the local home interface accessible to local clients through JNDI. The entity beans LOCAL home interface allows a local 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. Execute a home business method.

An entity beans LOCAL HOME interface MUST extend the javax.ejb.EJBLocalHome interface.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch05.html 2 / 3 2004/6/12 11:56:45

Chapter 5. Client View of an Entity

Given a list of scenarios, identify which will result in an ejbRemove method not being called on a bean instance.

Home

Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject).

http://java.boot.by/bcd-guide/ch05.html 3 / 3 2004/6/12 11:56:45

Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject).

Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject). Prev Chapter 5. Client View of an Entity Next

Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject).
A local client can access an entity object through the entity beans local [component] interface. An entity beans local interface MUST extend the javax.ejb.EJBLocalObject interface. A local interface defines the business methods that are callable by local clients.

public interface Account extends javax.ejb.EJBLocalObject { void debit(double amount) throws InsufficientBalanceException; void credit(double amount); double getBalance(); }

Methods of the entity beans local interface MUST NOT throw the java.rmi.RemoteException. The javax.ejb.EJBLocalObject interface defines the methods that allow the local client to perform the following operations on an entity objects local reference:

Obtain the local home interface for the entity object. Remove the entity object. Obtain the entity objects primary key.

The CONTAINER provides the implementation of the methods defined in the javax.ejb. EJBLocalObject interface. Only the business methods are delegated to the instances of the enterprise bean class.

public interface EJBLocalObject { EJBLocalHome getEJBLocalHome() throws EJBException; Object getPrimaryKey() throws EJBException; boolean isIdentical(EJBLocalObject obj) throws EJBException; void remove() throws RemoveException, EJBException; }

Prev

Up

Next

http://java.boot.by/bcd-guide/ch05s02.html 1 / 2 2004/6/12 11:56:49

Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject).

Chapter 5. Client View of an Entity Home

Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject).

http://java.boot.by/bcd-guide/ch05s02.html 2 / 2 2004/6/12 11:56:49

Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject).

Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject). Prev Chapter 5. Client View of an Entity Next

Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject).
A client can access an entity object through the entity beans remote interface. An entity beans remote interface MUST extend the javax.ejb.EJBObject interface. A remote interface defines the business methods that are callable by remote clients.

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 objects reference:

Obtain the remote home interface for the entity object. Remove the entity object. Obtain the entity objects handle (ONLY REMOTE objects have handles, LOCAL objects DO NOT have handles). Obtain the entity objects 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.

public interface EJBObject extends Remote { EJBHome getEJBHome() throws RemoteException; Handle getHandle() throws RemoteException; Object getPrimaryKey() throws RemoteException; boolean isIdentical(EJBObject obj) throws RemoteException; void remove() throws RemoteException, RemoveException; }

http://java.boot.by/bcd-guide/ch05s03.html 1 / 2 2004/6/12 11:56:51

Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject).

Prev Identify correct and incorrect statements or examples about the client view of an entity bean's local component interface (EJBLocalObject).

Up

Next Identify the use, syntax, and behavior of, the following entity bean home method types, for Container-Managed Persistence (CMP); finder methods, create methods, remove methods, and home methods.

Home

http://java.boot.by/bcd-guide/ch05s03.html 2 / 2 2004/6/12 11:56:51

Identify the use, syntax, and behavior of, the following entity bean ...P); finder methods, create methods, remove methods, and home methods.

Identify the use, syntax, and behavior of, the following entity bean home method types, for Container-Managed Persistence (CMP); finder methods, create methods, remove methods, and home methods. Prev Chapter 5. Client View of an Entity Next

Identify the use, syntax, and behavior of, the following entity bean home method types, for Container-Managed Persistence (CMP); finder methods, create methods, remove methods, and home methods.
REMOTE view CMP Entity EJB An entity beans remote home interface defines ONE (AT LEAST findByPrimaryKey(pKey)) or MORE finder methods, 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, The return type of a finder method on the REMOTE HOME interface must be the entity beans REMOTE interface, or a type representing a collection (java.util.Collection or java.util.Set) of objects that implement the entity beans REMOTE interface. The throws clause of EVERY finder method on the remote home interface includes the java.rmi. RemoteException and the javax.ejb.FinderException. The following example shows the findByPrimaryKey method:

public interface AccountHome extends javax.ejb.EJBHome { ... public Account findByPrimaryKey(String AccountNumber) throws RemoteException, FinderException; }

AccountHome = ...; Account account = accountHome.findByPrimaryKey(100-3450-3333);

An entity beans remote home interface can define ZERO or MORE create<METHOD>(...) methods. The arguments of the create methods are typically used to initialize the state of the created entity object. The name of each create method starts with the prefix create. The RETURN type of a create<METHOD> method on the REMOTE HOME interface is the entity beans REMOTE interface.
http://java.boot.by/bcd-guide/ch05s04.html 1 / 5 2004/6/12 11:56:55

Identify the use, syntax, and behavior of, the following entity bean ...P); finder methods, create methods, remove methods, and home methods.

The throws clause of EVERY create<METHOD> method on the REMOTE home interface includes the java.rmi.RemoteException and the javax.ejb.CreateException. It MAY include additional applicationlevel exceptions.

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; public Account createLargeAccount(String firstname, String lastname, double initialBalance) throws RemoteException, CreateException; ... }

AccountHome accountHome = ...; Account account = accountHome.create(John, Smith, 500.00);

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 remote client result in the java.rmi.NoSuchObjectException. An entity beans remote home interface MAY define one or more HOME METHODS. Home methods are methods that the bean provider supplies for business logic that is NOT SPECIFIC to an entity bean instance. They MUST NOT start with create, find, or remove. The method arguments and return value types of a home method on the remote home interface MUST be legal types for RMI-IIOP.
http://java.boot.by/bcd-guide/ch05s04.html 2 / 5 2004/6/12 11:56:55

Identify the use, syntax, and behavior of, the following entity bean ...P); finder methods, create methods, remove methods, and home methods.

The throws clause of EVERY home method on the remote home interface includes the java.rmi. RemoteException. It may also include additional application-level exceptions.

public interface EmployeeHome extends javax.ejb.EJBHome { ... // this method returns a living index depending on // the state and the base salary of an employee: // the method is not specific to an instance public float livingIndex(String state, float Salary) throws RemoteException; // this method adds a bonus to all of the employees // based on a company profit-sharing index public void addBonus(float company_share_index) throws RemoteException, ShareIndexOutOfRangeException; ... }

LOCAL view CMP Entity EJB An entity beans local home interface defines ONE (findByPrimaryKey(primaryKey) method is MANDATORY for all Entity Beans) or MORE finder methods. The name of each finder method starts with the prefix find. The return type of a finder method on the local home interface MUST be the entity beans LOCAL interface, or a type representing a collection (java.util.Collection or java.util.Set) of objects that implement the entity beans LOCAL interface. The throws clause of EVERY finder method on the LOCAL HOME interface includes the javax.ejb. FinderException. The throws clause MUST NOT include the java.rmi.RemoteException. The local home interface includes the findByPrimaryKey(primaryKey) method, which 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 beans primary key type, and its return type is the entity beans LOCAL INTERFACE. There is a unique findByPrimaryKey(primaryKey) method for an entity bean on its local home interface; this method MUST NOT be overloaded.

public interface AccountHome extends javax.ejb.EJBLocalHome { ... public Account findByPrimaryKey(String AccountNumber) throws FinderException; }

http://java.boot.by/bcd-guide/ch05s04.html 3 / 5 2004/6/12 11:56:55

Identify the use, syntax, and behavior of, the following entity bean ...P); finder methods, create methods, remove methods, and home methods.

AccountHome = ...; Account account = accountHome.findByPrimaryKey(100-3450-3333);

An entity beans local home interface can define ZERO or MORE create<METHOD>(...) methods. The name of each create method starts with the prefix create. The return type of a create<METHOD> method on the LOCAL HOME interface is the entity beans LOCAL interface. The throws clause of EVERY create<METHOD> method on the LOCAL HOME interface includes the javax.ejb.CreateException. It MAY include additional application-level exceptions. It MUST NOT include the java.rmi.RemoteException.

public interface AccountHome extends javax.ejb.EJBLocalHome { public Account create(String firstName, String lastName, double initialBalance) throws CreateException; public Account create(String accountNumber, double initialBalance) throws CreateException, LowInitialBalanceException; public Account createLargeAccount(String firstname, String lastname, double initialBalance) throws CreateException; ... }

AccountHome accountHome = ...; Account account = accountHome.create(John, Smith, 500.00);

The javax.ejb.EJBLocalHome interface defines the REMOVE method to allow the client to remove an entity object (NOTE, local objects do NOT have handles).

public interface EJBLocalHome { void remove(Object primaryKey) throws RemoveException, EJBException; }

http://java.boot.by/bcd-guide/ch05s04.html 4 / 5 2004/6/12 11:56:55

Identify the use, syntax, and behavior of, the following entity bean ...P); finder methods, create methods, remove methods, and home methods.

After an entity object has been removed, subsequent attempts to access the local entity object by the local client result in the javax.ejb.NoSuchObjectLocalException. An entity beans local home interface MAY define one or more HOME METHODS. Home methods are methods that the bean provider supplies for business logic that is NOT specific to an entity bean instance. They MUST NOT start with create, find, or remove. The throws clause of a home method on the local home interface MAY include additional application-level exceptions. It MUST NOT include the java.rmi.RemoteException.

public interface EmployeeHome extends javax.ejb.EJBLocalHome { ... // this method returns a living index depending on // the state and the base salary of an employee: // the method is not specific to an instance public float livingIndex(String state, float Salary); // this method adds a bonus to all of the employees // based on a company profit sharing index public void addBonus(float company_share_index) throws ShareIndexOutOfRangeException; ... }

Prev Identify correct and incorrect statements or examples about the client view of a entity bean's remote component interface (EJBObject).

Up Home

Next Chapter 6. Component Contract for Container-Managed Persistence (CMP)

http://java.boot.by/bcd-guide/ch05s04.html 5 / 5 2004/6/12 11:56:55

Chapter 6. Component Contract for Container-Managed Persistence (CMP)

Chapter 6. Component Contract for Container-Managed Persistence (CMP) Prev Part I. Exam Objectives Next

Chapter 6. Component Contract for Container-Managed Persistence (CMP)

Identify correct and incorrect statements or examples about the entity bean provider's view and programming contract for CMP, including the requirements for a CMP entity bean.
An entity bean implements an object view of a business entity or set of business entities stored in an underlying database or implemented by an existing enterprise application An entity bean with container-managed persistence (CMP) typically consists of its entity bean class; a component interface which defines its client view business methods; a home interface which defines the create, remove, home, and finder methods of its client view; and its abstract persistence schema as specified in the deployment descriptor (META-INF/ejb-jar.xml). A client of an entity bean can control the lifecycle of a bean by using the beans HOME interface and can manipulate the bean as a business entity by using the methods defined by its COMPONENT interface. The home and component interfaces of a bean define its CLIENT VIEW. The bean provider MUST observe the following programming contract when defining an entity bean class that uses container-managed persistence (CMP):

The Bean Provider must define the entity bean class as an ABSTRACT class. The container provides the implementation class that is used at RUNTIME. The container-managed persistent fields and container-managed relationship fields MUST NOT be defined in the entity bean class. From the perspective of the Bean Provider, the container-managed persistent (CMP) fields and container-managed relationship (CMR) fields are VIRTUAL fields only, and are accessed through get and set accessor methods. The IMPLEMENTATION of the container-managed persistent fields and container-managed relationship fields is supplied by the Container. The container-managed persistent (CMP) fields and container-managed relationship (CMR) fields MUST be specified in the deployment descriptor (DD) using the cmp-field and cmr-field elements respectively. The names of these fields MUST be valid Java identifiers and must begin with a LOWERCASE letter. The Bean Provider MUST define the accessor methods for the container-managed persistent fields and container-managed relationship fields as get and set methods, using the JavaBeans conventions. The IMPLEMENTATION of the accessor methods is supplied by the Container. The accessor methods MUST be public, MUST be abstract, and MUST bear the name of the container-managed persistent field (cmp-field) or container-managed relationship field (cmr-field) that is specified in the deployment descriptor (DD), and in which the first letter of the name of the cmp-field or cmr-field has been UPPERCASED and prefixed by get or

http://java.boot.by/bcd-guide/ch06.html 1 / 2 2004/6/12 11:56:57

Chapter 6. Component Contract for Container-Managed Persistence (CMP)

set. The accessor methods for a container-managed relationship (CMR) field MUST be defined in terms of the LOCAL interface of the related entity bean. The accessor methods for container-managed relationship fields for one-to-many or manyto-many relationships MUST utilize one of the following Collection interfaces: java.util. Collection or java.util.Set. The Collection interfaces used in relationships are specified in the deployment descriptor. The IMPLEMENTATION of the collection classes used for the container-managed relationship fields is supplied by the Container. An entity bean local interface type (or a collection of such) CAN be the type of a cmr-field. An entity bean local interface type (or a collection of such) CAN NOT be the type of a cmpfield. The accessor methods for the container-managed relationship fields MUST NOT be exposed in the REMOTE interface of an entity bean. The LOCAL interface types of the entity bean and of related entity beans MUST NOT be exposed through the REMOTE interface of the entity bean. The collection classes that are used for container-managed relationships MUST NOT be exposed through the REMOTE interface of the entity bean. Once the primary key for an entity bean has been set, the Bean Provider MUST NOT attempt to change it by use of set accessor methods on the primary key cmp-fields. The Bean Provider SHOULD therefore NOT expose the SET accessor methods for the primary key cmp-fields in the component interface of the entity bean. The Bean Provider MUST ensure that the Java types assigned to the cmp-fields are restricted to the following: Java primitive types and Java serializable types.

Prev Identify the use, syntax, and behavior of, the following entity bean home method types, for Container-Managed Persistence (CMP); finder methods, create methods, remove methods, and home methods.

Up

Next Identify correct and incorrect statements or examples about persistent relationships, remove protocols, and about the abstract schema type of a CMP entity bean.

Home

http://java.boot.by/bcd-guide/ch06.html 2 / 2 2004/6/12 11:56:57

Identify correct and incorrect statements or examples about persistent...e protocols, and about the abstract schema type of a CMP entity bean.

Identify correct and incorrect statements or examples about persistent relationships, remove protocols, and about the abstract schema type of a CMP entity bean. Prev Chapter 6. Component Contract for Container-Managed Persistence (CMP) Next

Identify correct and incorrect statements or examples about persistent relationships, remove protocols, and about the abstract schema type of a CMP entity bean.
An entity bean may have relationships with other entity beans with container-managed persistence (CMP). Relationships may be one-to-one, one-to-many, or many-to-many relationships. Container-managed relationships can exist ONLY among entity beans within the same LOCAL relationship scope, as defined by the relationships element in the deployment descriptor. Container-managed relationships (CMR) are defined in terms of the LOCAL interfaces of the related beans. Relationships may be either bidirectional or unidirectional. If a relationship is bidirectional, it can be navigated in both directions, whereas a unidirectional relationship can be navigated in one direction only. A unidirectional relationship is implemented with a cmr-field on the entity bean instance from which navigation can take place, and no related cmr-field on the entity bean instance that is the target of the relationship. Unidirectional relationships are typically used when the Bean Provider wishes to restrict the visibility of a relationship.

<relationships> <ejb-relation> <ejb-relation-name> Customer-Address </ejb-relation-name> <ejb-relationship-role> <ejb-relationship-role-name> Customer-has-a-Address </ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>CustomerEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>homeAddress</cmr-field-name> </cmr-field>
http://java.boot.by/bcd-guide/ch06s02.html 1 / 6 2004/6/12 11:57:02

Identify correct and incorrect statements or examples about persistent...e protocols, and about the abstract schema type of a CMP entity bean.

</ejb-relationship-role> <ejb-relationship-role> <ejb-relationship-role-name> Address-belongs-to-Customer </ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>AddressEJB</ejb-name> </relationship-role-source> </ejb-relationship-role> </ejb-relation> </relationships>

An entity bean that DOES NOT have a LOCAL interface can have ONLY unidirectional relationships from itself to other entity beans. The lack of a local interface prevents other entity beans from having a relationship to it. The bean developer navigates or manipulates relationships by using the get and set accessor methods for the container-managed relationship (CMR) fields and the java.util.Collection API for collection-valued container-managed relationship fields.

<relationships> ... <ejb-relation> <ejb-relation-name> Customer-Phones </ejb-relation-name> <ejb-relationship-role> <ejb-relationship-role-name> Customer-has-many-Phone-numbers </ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>CustomerEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>phoneNumbers</cmr-field-name> <cmr-field-type>java.util.Collection</cmr-field-type> </cmr-field> </ejb-relationship-role> <ejb-relationship-role> <ejb-relationship-role-name>
http://java.boot.by/bcd-guide/ch06s02.html 2 / 6 2004/6/12 11:57:02

Identify correct and incorrect statements or examples about persistent...e protocols, and about the abstract schema type of a CMP entity bean.

Phone-belongs-to-Customer </ejb-relationship-role-name> <multiplicity>Many</multiplicity> <relationship-role-source> <ejb-name>PhoneEJB</ejb-name> </relationship-role-source> </ejb-relationship-role> </ejb-relation> ... </relationships>

public abstract class CustomerBean implements javax.ejb.EntityBean { ... public void addPhoneNumber(String number, byte type) throws NamingException, CreateException { InitialContext jndiEnc = new InitialContext(); PhoneHomeLocal phoneHome = (PhoneHomeLocal) (jndiEnc.lookup("PhoneHomeLocal")); PhoneLocal phone = phoneHome.create(number,type); Collection phoneNumbers = this.getPhoneNumbers(); phoneNumbers.add(phone); } public void removePhoneNumber(byte typeToRemove) { Collection phoneNumbers = this.getPhoneNumbers(); Iterator iterator = phoneNumbers.iterator(); while(iterator.hasNext()){ PhoneLocal phone = (PhoneLocal)iterator.next(); if (phone.getType() == typeToRemove) { phoneNumbers.remove(phone); break; } } } public abstract java.util.Collection getPhoneNumbers( ); public abstract void setPhoneNumbers(java.util.Collection phones); }

http://java.boot.by/bcd-guide/ch06s02.html 3 / 6 2004/6/12 11:57:02

Identify correct and incorrect statements or examples about persistent...e protocols, and about the abstract schema type of a CMP entity bean.

The bean provider MUST consider the type and cardinality of relationships when the entity bean classes are programmed. The get method for a cmr-field MUST return either the local interface of the entity bean or a collection (either java.util.Collection or java.util.Set) of the same. The set method for the relationship MUST take as an argument the entity beans local interface or a collection of the same.

public abstract class CustomerBean implements javax.ejb.EntityBean { ... // persistent relationships public abstract AddressLocal getHomeAddress(); public abstract void setHomeAddress(AddressLocal address); public abstract AddressLocal getBillingAddress(); public abstract void setBillingAddress(AddressLocal address); public abstract CreditCardLocal getCreditCard(); public abstract void setCreditCard(CreditCardLocal card); public abstract java.util.Collection getPhoneNumbers( ); public abstract void setPhoneNumbers(java.util.Collection phones); ... }

The Bean Provider can specify the removal of an entity object in two ways:

By the use of a remove method on the entity beans COMPONENT interface or HOME interface. By the use of a cascade-delete specification in the deployment descriptor (ONLY when other member of relationship has multiplicity ONE).

When the remove() method is invoked on an entity object, the container MUST invoke the entity Bean Providers ejbRemove() method. After the bean providers ejbRemove() method returns (and prior to returning to the client), the Container MUST remove the entity object from all relationships in which it participates, and THEN remove its persistent representation.

Once an entity has been removed from a relationship, the accessor methods for any relationships to the entity will reflect this removal. An accessor method for a one-to-one or many-to-one relationship to the entity will return null; and an accessor method for a many-to-many relationship to the entity will return a collection from which the entity object has been removed. The Container MUST detect any subsequent attempt to invoke an accessor method on the removed entity object and throw the java.rmi.NoSuchObjectException if the client is a REMOTE client or the javax.ejb.NoSuchObjectLocalException if the client is a LOCAL client. The Container MUST detect an attempt to assign a removed entity object as the value of a cmr-field of another object (whether as an argument to a set accessor method or as an

http://java.boot.by/bcd-guide/ch06s02.html 4 / 6 2004/6/12 11:57:02

Identify correct and incorrect statements or examples about persistent...e protocols, and about the abstract schema type of a CMP entity bean.

argument to a method of the java.util.Collection API) and throw the java.lang. IllegalArgumentException. After removing the entity object from all relationships and removing its persistent representation, the Container MUST then cascade the removal to all entity beans with which the entity had been previously in container-managed relationships for which the cascade-delete option was specified. The remove method, alone, causes only the entity on which it is invoked to be removed. It DOES NOT cause the deletion to be cascaded to other entity objects. In order for the deletion of one entity object to be automatically cascaded to another, the cascade-delete mechanism should be used. The cascade-delete deployment descriptor element is used within a particular relationship to specify that the lifetime of one or more entity objects is dependent upon the lifetime of another entity object.

<ejb-relation> <ejb-relation-name>Customer-HomeAddress</ejb-relation-name> <ejb-relationship-role> <ejb-relationship-role-name> Customer-has-a-Address </ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>CustomerEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>homeAddress</cmr-field-name> </cmr-field> </ejb-relationship-role> <ejb-relationship-role> <ejb-relationship-role-name> Address-belongs-to-Customer </ejb-relationship-role-name> <multiplicity>One</multiplicity> <cascade-delete/> <relationship-role-source> <ejb-name>AddressEJB</ejb-name> </relationship-role-source> </ejb-relationship-role> </ejb-relation>

The cascade-delete deployment descriptor element is contained within the ejb-relationship-role


http://java.boot.by/bcd-guide/ch06s02.html 5 / 6 2004/6/12 11:57:02

Identify correct and incorrect statements or examples about persistent...e protocols, and about the abstract schema type of a CMP entity bean.

element. The cascade-delete element can ONLY be specified for an ejb-relationship-role element contained in an ejb-relation element if the other ejb-relationship-role element in the same ejbrelation element specifies a multiplicity of ONE. The cascade-delete option CANNOT be specified for a many-to-many relationship. The deletion of one entity object can only be cascaded to cause the deletion of other entity objects if the first entity object is in a one-to-one or one-to-many relationship with those other entity objects.

Prev Chapter 6. Component Contract for Container-Managed Persistence (CMP)

Up

Next Identify correct and incorrect statements or examples about the rules and semantics for relationship assignment and relationship updating in a CMP bean.

Home

http://java.boot.by/bcd-guide/ch06s02.html 6 / 6 2004/6/12 11:57:02

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

Identify correct and incorrect statements or examples about the rules and semantics for relationship assignment and relationship updating in a CMP bean. Prev Chapter 6. Component Contract for Container-Managed Persistence (CMP) Next

Identify correct and incorrect statements or examples about the rules and semantics for relationship assignment and relationship updating in a CMP bean.
The assignment operations for container-managed relationships have a special semantics that is determined by the referential integrity semantics for the relationship multiplicity. In the case of a one-to-one relationship, when the Bean Provider uses a set accessor method to assign an object from a cmr-field in one instance to a cmr-field of the SAME relationship type (i. e., as defined by the ejb-relation and ejb-relationship-role deployment descriptor elements) in another instance, the object is effectively MOVED and the value of the source cmr-field is set to null in the same transaction context. If the argument to the set accessor method is NOT of the same type as the cmr-field, the container MUST throw the java.lang.IllegalArgumentException. In the case of a one-to-many or many-to-many relationship, either the java.util.Collection API or a set accessor method may be used to manipulate the contents of a collection-valued cmr-field. These two approaches are discussed below. The methods of the java.util.Collection API for the container-managed collections used for collection-valued cmr-fields have the usual semantics, with the following exception: the add and addAll methods applied to container-managed collections in one-to-many relationships have a special semantics that is determined by the referential integrity of one-to-many relationships. If the argument to the add method is already an element of a collection-valued relationship field of the same relationship type as the target collection (as defined by the ejb-relation and ejbrelationship-role deployment descriptor elements), it is removed from this first relationship and added, in the same transaction context, to the target relationship (i.e., it is effectively moved from one collection of the relationship type to the other). For example, if there is a one-to-many relationship between field "person" and "telephones", adding a "telephone" to a new field "person" will have the effect of removing it from its current field "person".

public abstract class PersonBean implements javax.ejb.EntityBean { ... public void addPhoneNumber(PhoneLocal phone) { Collection phoneNumbers = this.getPhoneNumbers(); phoneNumbers.add(phone); } ... }

http://java.boot.by/bcd-guide/ch06s03.html 1 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

The addAll method, when applied to a target collection in a one-to-many relationship, has similar semantics, applied to the members of its collection argument individually.

public abstract class PersonBean implements javax.ejb.EntityBean { ... public void addPhoneNumbers(Collection numbers) { Collection phoneNumbers = this.getPhoneNumbers(); phoneNumbers.addAll(numbers); } // relationship fields public abstract Set getPhoneNumbers( ); public abstract void setPhoneNumbers(Set numbers); ... }

Bean Provider MUST NOT modify the container-managed COLLECTION while the iteration is in progress in any way that causes elements to be added or removed, other than by the java.util. Iterator.remove() method. If elements are added or removed from the underlying containermanaged collection used by an iterator other than by the java.util.Iterator.remove() method, the container should throw the java.lang.IllegalStateException on the next operation on the iterator.

Collection nySalesreps = nyOffice.getSalesreps(); Collection sfSalesreps = sfOffice.getSalesreps(); Iterator i = nySalesreps.iterator(); Salesrep salesrep; // a WRONG way to transfer the salesrep while (i.hasNext()) { salesrep = (Salesrep)i.next(); sfSalesreps.add(salesrep); // removes salesrep from nyOffice } // this is a CORRECT and safe way to transfer the salesrep while (i.hasNext()) { salesrep = (Salesrep)i.next(); i.remove(); sfSalesreps.add(salesrep); }

The semantics of a set accessor method, when applied to a collection-valued cmr-field, is also determined by the referential integrity semantics associated with the multiplicity of the
http://java.boot.by/bcd-guide/ch06s03.html 2 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

relationship. The identity of the collection object referenced by a cmr-field does not change when a set accessor method is executed. In the case of a one-to-many relationship, if a collection of entity objects is assigned from a cmrfield of in one instance to a cmr-field of the same relationship type in another instance, the objects in the collection are effectively MOVED. The CONTENTS of the collection of the target instance are REPLACED with the contents of the collection of the source instance, but the identity of the collection object containing the instances in the relationship does not change. The source cmr-field references the same collection object as before (i.e., the identity of the collection object is preserved), but the collection is empty. The Bean Provider can thus use the set(...) method to MOVE objects between the collections referenced by cmr-fields of the same relationship type in different instances. The set accessor method, when applied to a cmr-field in a one-to-many relationship thus has the semantics of the java.util.Collection methods clear, followed by addAll, applied to the TARGET collection; and clear, applied to the SOURCE collection. It is the responsibility of the container to transfer the contents of the collection instances in the same transaction context.

public void changeTelephoneNumber() { Address a = getShippingAddress(); Address b = getBillingAddress(); Collection c = b.getTelephoneNumbers(); a.setTelephoneNumbers(b.getTelephoneNumbers()); if (c.isEmpty()) { // MUST be true ... } }

In the case of a many-to-many relationship, if the value of a cmr-field is assigned to a cmr-field of the same relationship type in another instance, the objects in the collection of the first instance are assigned as the contents of the cmr-field of the second instance. The identities of the collection objects referenced by the cmr-fields do not change. The contents of the collections are shared, but not the collections themselves. The set accessor method, when applied to a cmrfield in a many-to-many relationship thus has the semantics of the java.util.Collection methods clear, followed by addAll, applied to the TARGET collection.

public void shareCustomers(SalesRep rep) { setCustomers(rep.getCustomers()); // the customers are shared among the salesreps }

1. One-to-one bidirectional relationships

http://java.boot.by/bcd-guide/ch06s03.html 3 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

EntityBean_B entityBean_B1 = entityBean_A1.getEntityBean_B(); EntityBean_B entityBean_B2 = entityBean_A2.getEntityBean_B();

entityBean_A1.setEntityBean_B(entityBean_A2.getEntityBean_B()); if entityBean_A1.getEntityBean_B().isIdentical(entityBean_B2) { ... } // true if (entityBean_A2.getEntityBean_B() == null) { ... } // true if (entityBean_B1.getEntityBean_A() == null) { ... } // true

2. One-to-one unidirectional relationships

http://java.boot.by/bcd-guide/ch06s03.html 4 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

EntityBean_B entityBean_B1 = entityBean_A1.getEntityBean_B(); EntityBean_B entityBean_B2 = entityBean_A2.getEntityBean_B();

entityBean_A1.setEntityBean_B(entityBean_A2.getEntityBean_B()); if (entityBean_A2.getEntityBean_B() == null) { ... } // true

3. One-to-many bidirectional relationships

http://java.boot.by/bcd-guide/ch06s03.html 5 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

Collection entityBeans_B1 = entityBean_A1.getEntityBean_B(); Collection entityBeans_B2 = entityBean_A2.getEntityBean_B();

entityBean_A1.setEntityBean_B(entityBean_A2.getEntityBean_B()); if (entityBean_A2.getEntityBean_B().isEmpty()) { ... } // true if (entityBeans_B2.isEmpty()) { ... } // true if (entityBean_B11.getEntityBean_A() == null) { ... } // true if (entityBean_A1.isIdentical(entityBean_B21.getEntityBean_A())) { ... // true }

http://java.boot.by/bcd-guide/ch06s03.html 6 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_B21.setEntityBean_A(entityBean_B11.getEntityBean_A()); if (entityBean_A1.isIdentical(entityBean_B21.getEntityBean_A())) { ... // true } if (entityBeans_B1.contains(entityBean_B21)) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 7 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A1.getEntityBean_B().add(entityBean_B21); if (entityBean_A1.isIdentical(entityBean_B21.getEntityBean_A())) { ... // true } if (entityBeans_B1.contains(entityBean_B21)) { ... } // true

entityBean_A1.getEntityBean_B().remove(entityBean_B12); if (entityBean_B12.getEntityBean_A() == null) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 8 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

4. One-to-many unidirectional relationships

Collection entityBeans_B1 = entityBean_A1.getEntityBean_B(); Collection entityBeans_B2 = entityBean_A2.getEntityBean_B();

http://java.boot.by/bcd-guide/ch06s03.html 9 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A1.setEntityBean_B(entityBean_A2.getEntityBean_B()); if (entityBean_A2.getEntityBean_B().isEmpty()) { ... } // true if (entityBeans_B2.isEmpty()) { ... } // true if (entityBean_A1.getEntityBean_B().contains(entityBean_B21)) { ... // true } if (entityBeans_B1.contains(entityBean_B21)) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 10 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A1.getEntityBean_B().add(entityBean_B21); if (entityBeans_B1 == entityBean_A1.getEntityBean_B()) { ... // true } if (entityBeans_B1.contains(entityBean_B21)) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 11 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A1.getEntityBean_B().remove(entityBean_B12); if !(entityBean_A1.getEntityBean_B().contains(entityBean_B12)) { ... // true }

5. Many-to-one unidirectional relationships

if entityBean_A1.isIdentical(entityBean_B11.getEntityBean_A()) { ... } // true if entityBean_A1.isIdentical(entityBean_B12.getEntityBean_A()) { ... } // true if entityBean_A2.isIdentical(entityBean_B21.getEntityBean_A()) { ... } // true if entityBean_A2.isIdentical(entityBean_B22.getEntityBean_A()) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 12 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_B12.setEntityBean_A(entityBean_B22.getEntityBean_A()); if entityBean_A1.isIdentical(entityBean_B11.getEntityBean_A()) { ... } // true if entityBean_A2.isIdentical(entityBean_B12.getEntityBean_A()) { ... } // true if entityBean_A2.isIdentical(entityBean_B21.getEntityBean_A()) { ... } // true if entityBean_A2.isIdentical(entityBean_B22.getEntityBean_A()) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 13 / 20 2004/6/12 11:57:20

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

6. Many-to-many bidirectional relationships

if entityBean_A11.getEntityBean_B().contains(entityBean_B11) { ... } // true if entityBean_A11.getEntityBean_B().contains(entityBean_B12) { ... } // true if entityBean_A12.getEntityBean_B().contains(entityBean_B11) { ... } // true if entityBean_A12.getEntityBean_B().contains(entityBean_B12) { ... } // true if entityBean_A12.getEntityBean_B().contains(entityBean_B21) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 14 / 20 2004/6/12 11:57:21

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A11.setEntityBean_B(entityBean_A22.getEntityBean_B()); if entityBean_A11.getEntityBean_B().contains(entityBean_B21) { ... } // true if entityBean_A11.getEntityBean_B().contains(entityBean_B22) { ... } // true if entityBean_A22.getEntityBean_B().contains(entityBean_B21) { ... } // true if entityBean_A22.getEntityBean_B().contains(entityBean_B22) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 15 / 20 2004/6/12 11:57:21

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A11.getEntityBean_B().add(entityBean_B21); if entityBean_A11.getEntityBean_B().contains(entityBean_B11) { ... } // true if entityBean_A11.getEntityBean_B().contains(entityBean_B12) { ... } // true if entityBean_A11.getEntityBean_B().contains(entityBean_B21) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 16 / 20 2004/6/12 11:57:21

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A12.getEntityBean_B().remove(entityBean_B12); if entityBean_A12.getEntityBean_B().contains(entityBean_B11) { ... } // true if entityBean_A12.getEntityBean_B().contains(entityBean_B21) { ... } // true if entityBean_B12.getEntityBean_A().contains(entityBean_A11) { ... } // true if entityBean_B12.getEntityBean_A().contains(entityBean_A21) { ... } // true

7. Many-to-many unidirectional relationships

if entityBean_A11.getEntityBean_B().contains(entityBean_B11) { ... } // true if entityBean_A11.getEntityBean_B().contains(entityBean_B12) { ... } // true if entityBean_A12.getEntityBean_B().contains(entityBean_B11) { ... } // true if entityBean_A12.getEntityBean_B().contains(entityBean_B12) { ... } // true if entityBean_A12.getEntityBean_B().contains(entityBean_B21) { ... } // true
http://java.boot.by/bcd-guide/ch06s03.html 17 / 20 2004/6/12 11:57:21

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A11.setEntityBean_B(entityBean_A22.getEntityBean_B()); if entityBean_A11.getEntityBean_B().contains(entityBean_B21) { ... } // true if entityBean_A11.getEntityBean_B().contains(entityBean_B22) { ... } // true if entityBean_A22.getEntityBean_B().contains(entityBean_B21) { ... } // true if entityBean_A22.getEntityBean_B().contains(entityBean_B22) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 18 / 20 2004/6/12 11:57:21

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A11.getEntityBean_B().add(entityBean_B21); if entityBean_A11.getEntityBean_B().contains(entityBean_B11) { ... } // true if entityBean_A11.getEntityBean_B().contains(entityBean_B12) { ... } // true if entityBean_A11.getEntityBean_B().contains(entityBean_B21) { ... } // true

http://java.boot.by/bcd-guide/ch06s03.html 19 / 20 2004/6/12 11:57:21

Identify correct and incorrect statements or examples about the rules ... for relationship assignment and relationship updating in a CMP bean.

entityBean_A12.getEntityBean_B().remove(entityBean_B12); if entityBean_A12.getEntityBean_B().contains(entityBean_B11) { ... } // true if entityBean_A12.getEntityBean_B().contains(entityBean_B21) { ... } // true

Prev Identify correct and incorrect statements or examples about persistent relationships, remove protocols, and about the abstract schema type of a CMP entity bean.

Up

Next Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: ejb-name, abstract-schemaname, ejb-relation, ejb-relationship-role, cmr-field, cmr-field-type, and relationship-role-source.

Home

http://java.boot.by/bcd-guide/ch06s03.html 20 / 20 2004/6/12 11:57:21

Match the name with a description of purpose or functionality, for each...ionship-role, cmr-field, cmr-field-type, and relationship-role-source.

Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: ejb-name, abstract-schema-name, ejb-relation, ejbrelationship-role, cmr-field, cmr-field-type, and relationship-role-source. Prev Chapter 6. Component Contract for Container-Managed Persistence (CMP) Next

Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: ejb-name, abstract-schema-name, ejb-relation, ejbrelationship-role, cmr-field, cmr-field-type, and relationship-role-source.
The deployment descriptor provides the following information about the abstract persistence schemas of entity beans and their container-managed relationships:

An ejb-name element for each entity bean. The ejb-name MUST be a valid Java identifier and MUST be UNIQUE within the ejb-jar file. An abstract-schema-name element for each entity bean. The abstract-schema-name MUST be a valid Java identifier and MUST be unique within the ejb-jar file. The abstract-schema-name element is used in the specification of EJB QL queries. A set of ejb-relation elements, each of which contains a PAIR of ejb-relationship-role elements to describe the two roles in the relationship. Each ejb-relationship-role element describes a relationship role: its name, its multiplicity within a relation, and its navigability. It specifies the name of the cmr-field that is used from the perspective of the relationship participant. The cmr-field-type element MUST be specified if the type of the cmr-field is java.util.Collection or java.util.Set. Each relationship role refers to an entity bean by means of an ejb-name element contained in the relationshiprole-source element.

<ejb-jar> ... <enterprise-beans> ... </enterprise-beans> <relationships> <!-ONE-TO-MANY: Order LineItem --> <ejb-relation> <ejb-relation-name>Order-LineItem</ejb-relation-name> <ejb-relationship-role> <ejb-relationship-role-name> order-has-lineitems </ejb-relationship-role-name>
http://java.boot.by/bcd-guide/ch06s04.html 1 / 4 2004/6/12 11:57:25

Match the name with a description of purpose or functionality, for each...ionship-role, cmr-field, cmr-field-type, and relationship-role-source.

<multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>OrderEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>lineItems</cmr-field-name> <cmr-field-type>java.util.Collection</cmr-field-type> </cmr-field> </ejb-relationship-role> <ejb-relationship-role> <ejb-relationship-role-name> lineitem-belongsto-order </ejb-relationship-role-name> <multiplicity>Many</multiplicity> <cascade-delete/> <relationship-role-source> <ejb-name>LineItemEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>order</cmr-field-name> </cmr-field> </ejb-relationship-role> </ejb-relation> <!-ONE-TO-MANY unidirectional relationship: Product is not aware of its relationship with LineItem --> <ejb-relation> <ejb-relation-name>Product-LineItem</ejb-relation-name> <ejb-relationship-role> <ejb-relationship-role-name> product-has-lineitems </ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>ProductEJB</ejb-name> </relationship-role-source> <!-- since Product does not know about LineItem there is no cmr field in Product for accessing Lineitem --> </ejb-relationship-role> <ejb-relationship-role> <ejb-relationship-role-name> lineitem-for-product
http://java.boot.by/bcd-guide/ch06s04.html 2 / 4 2004/6/12 11:57:25

Match the name with a description of purpose or functionality, for each...ionship-role, cmr-field, cmr-field-type, and relationship-role-source.

</ejb-relationship-role-name> <multiplicity>Many</multiplicity> <relationship-role-source> <ejb-name>LineItemEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>product</cmr-field-name> </cmr-field> </ejb-relationship-role> </ejb-relation> <!-ONE-TO-MANY: Order Customer: --> <ejb-relation> <ejb-relation-name>Order-Customer</ejb-relation-name> <ejb-relationship-role> <ejb-relationship-role-name> customer-has-orders </ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>CustomerEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>orders</cmr-field-name> <cmr-field-type> java.util.Collection </cmr-field-type> </cmr-field> </ejb-relationship-role> <ejb-relationship-role> <ejb-relationship-role-name> order-belongsto-customer </ejb-relationship-role-name> <multiplicity>Many</multiplicity> <relationship-role-source> <ejb-name>OrderEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>customer</cmr-field-name> </cmr-field> </ejb-relationship-role> </ejb-relation> </relationships> ...
http://java.boot.by/bcd-guide/ch06s04.html 3 / 4 2004/6/12 11:57:25

Match the name with a description of purpose or functionality, for each...ionship-role, cmr-field, cmr-field-type, and relationship-role-source.

</ejb-jar>

Prev Identify correct and incorrect statements or examples about the rules and semantics for relationship assignment and relationship updating in a CMP bean.

Up

Next Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships).

Home

http://java.boot.by/bcd-guide/ch06s04.html 4 / 4 2004/6/12 11:57:25

Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships).

Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships). Prev Chapter 6. Component Contract for Container-Managed Persistence (CMP) Next

Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships).
The deployment descriptor is part of the contract between the ejb-jar file producer and consumer. The entity element declares an entity bean. The declaration consists of:

an optional description an optional display-name an optional small icon file name an optional large icon file name a unique name assigned to the enterprise bean in the deployment descriptor the names of the entity beans home and remote interfaces, if any the names of the entity beans local home and local interfaces, if any the entity beans implementation class the entity beans persistence management type the entity beans primary key class name an indication of the entity beans reentrancy an optional specification of the entity beans cmp-version (2.x default) an optional specification of the entity beans abstract schema name (CMP only) an optional list of container-managed fields (CMP only) an optional specification of the primary key field (CMP only) an optional declaration of the beans environment entries an optional declaration of the beans EJB references an optional declaration of the beans local EJB references an optional declaration of the security role references an optional declaration of the security identity to be used for the execution of the beans methods an optional declaration of the beans resource manager connection factory references an optional declaration of the beans resource environment references

An optional set of query declarations for finder and select methods for an entity bean with cmpversion 2.x :

The optional abstract-schema-name element must be specified for an entity bean with container-managed persistence and cmp-version 2.x. The optional primkey-field may be present in the descriptor if the entitys persistence-type is Container. The optional cmp-version element may be present in the descriptor if the entitys persistencetype is Container. If the persistence-type is Container and the cmp-version element is not

http://java.boot.by/bcd-guide/ch06s05.html 1 / 4 2004/6/12 11:57:29

Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships).

specified, its value DEFAULTS to 2.x. The optional home and remote elements must be specified if the entity bean has a remote home and remote interface. The optional local-home and local elements must be specified if the entity bean has a local home and local interface. The optional query elements must be present if the persistence-type is Container and the cmp-version is 2.x and query methods other than findByPrimaryKey have been defined for the entity bean.

<!ELEMENT entity (description?, display-name?, small-icon?, large-icon?, ejb-name, home?, remote?, local-home?, local?, ejb-class, persistence-type, prim-key-class, reentrant, cmp-version?, abstract-schema-name?, cmp-field*, primkey-field?, env-entry*, ejb-ref*, ejb-local-ref*, security-role-ref*, security-identity?, resource-ref*, resource-env-ref*, query*)>

Mandatory elements are:


ejb-name ejb-class persistence-type prim-key-class reentrant

Example of Entity Bean deployment descriptor (with relationship):

<ejb-jar> <enterprise-beans> ... <entity> <ejb-name>ReservationEJB</ejb-name>

http://java.boot.by/bcd-guide/ch06s05.html 2 / 4 2004/6/12 11:57:29

Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships).

<local-home>com.titan.reservation.ReservationHomeLocal</local-home> <local>com.titan.reservation.ReservationLocal</local> <ejb-class>com.titan.reservation.ReservationBean</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.lang.Integer</prim-key-class> <reentrant>False</reentrant> <cmp-version>2.x</cmp-version> <abstract-schema-name>Reservation</abstract-schema-name> <cmp-field><field-name>id</field-name></cmp-field> <cmp-field><field-name>amountPaid</field-name></cmp-field> <cmp-field><field-name>date</field-name></cmp-field> <primkey-field>id</primkey-field> <security-identity><use-caller-identity/></security-identity> <query> <query-method> <method-name>findWithPaymentGreaterThan</method-name> <method-params> <method-param>java.lang.Double</method-param> </method-params> </query-method> <ejb-ql> SELECT OBJECT( r ) FROM Reservation r WHERE r.amountPaid &gt; ?1 </ejb-ql> </query> </entity> <entity> <ejb-name>CabinEJB</ejb-name> <local-home>com.titan.cabin.CabinHomeLocal</local-home> <local>com.titan.cabin.CabinLocal</local> <ejb-class>com.titan.cabin.CabinBean</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.lang.Integer</prim-key-class> <reentrant>False</reentrant> <cmp-version>2.x</cmp-version> <abstract-schema-name>Cabin</abstract-schema-name> <cmp-field><field-name>id</field-name></cmp-field> <cmp-field><field-name>name</field-name></cmp-field> <cmp-field><field-name>deckLevel</field-name></cmp-field> <cmp-field><field-name>bedCount</field-name></cmp-field> <primkey-field>id</primkey-field> <security-identity><use-caller-identity/></security-identity> </entity> ... </enterprise-beans> <relationships>
http://java.boot.by/bcd-guide/ch06s05.html 3 / 4 2004/6/12 11:57:29

Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships).

<ejb-relation> <ejb-relation-name>Cabin-Reservation</ejb-relation-name> <ejb-relationship-role> <ejb-relationship-role-name> Cabin-has-many-Reservations </ejb-relationship-role-name> <multiplicity>Many</multiplicity> <relationship-role-source> <ejb-name>CabinEJB</ejb-name> </relationship-role-source> </ejb-relationship-role> <ejb-relationship-role> <ejb-relationship-role-name> Reservation-has-many-Cabins </ejb-relationship-role-name> <multiplicity>Many</multiplicity> <relationship-role-source> <ejb-name>ReservationEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>cabins</cmr-field-name> <cmr-field-type>java.util.Set</cmr-field-type> </cmr-field> </ejb-relationship-role> </ejb-relation> </relationships> ... </ejb-jar>

Prev Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: ejb-name, abstract-schemaname, ejb-relation, ejb-relationship-role, cmr-field, cmr-field-type, and relationship-role-source.

Up

Next Identify the interfaces and methods a CMP entity bean must and must not implement.

Home

http://java.boot.by/bcd-guide/ch06s05.html 4 / 4 2004/6/12 11:57:29

Identify the interfaces and methods a CMP entity bean must and must not implement.

Identify the interfaces and methods a CMP entity bean must and must not implement. Prev Chapter 6. Component Contract for Container-Managed Persistence (CMP) Next

Identify the interfaces and methods a CMP entity bean must and must not implement.
The following are the requirements for an entity bean class:

The class MUST implement, directly or indirectly, the javax.ejb.EntityBean interface.

public interface EntityBean extends EnterpriseBean { void ejbActivate() throws EJBException, RemoteException; void ejbLoad() throws EJBException, RemoteException; void ejbPassivate() throws EJBException, RemoteException; void ejbRemove() throws RemoveException, EJBException, RemoteException; void ejbStore() throws EJBException, RemoteException; void setEntityContext(EntityContext ctx) throws EJBException, RemoteException; void unsetEntityContext() throws EJBException, RemoteException; } public interface EnterpriseBean extends Serializable { }

The class MUST be defined as public and MUST be abstract. The class MUST define a public constructor that takes no arguments. The class MUST NOT define the finalize() method. The entity bean class MUST implement the BUSINESS methods, and the ejbCreate<METHOD> and ejbPostCreate<METHOD> methods. The entity bean class MUST implement the ejbHome<METHOD> methods that correspond to the home business methods specified in the beans home interface. These methods are executed on an instance in the POOLED state; hence they MUST NOT access state that is particular to a specific bean instance (e.g., the accessor methods for the beans abstract persistence schema MUST NOT be used by these methods). The entity bean class MUST implement the get and set accessor methods of the beans abstract persistence schema as abstract methods. The entity bean class may have superclasses and/or superinterfaces. If the entity bean has superclasses, the business methods, the ejbCreate<METHOD> and ejbPostCreate<METHOD> 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. The entity bean class DOES NOT implement the finder methods. The implementations of the finder methods are provided by the container.

http://java.boot.by/bcd-guide/ch06s06.html 1 / 6 2004/6/12 11:57:35

Identify the interfaces and methods a CMP entity bean must and must not implement.

The entity bean class MUST implement any ejbSelect<METHOD> methods as abstract methods.

The following are the requirements for a dependent value class:


The class MUST be defined as public and MUST NOT be abstract. The class MUST be SERIALIZABLE.

The entity bean class MUST implement the ejbCreate<METHOD>(...) methods that correspond to the create<METHOD>(...) methods specified in the entity beans home interface. The entity bean class may define ZERO or more ejbCreate<METHOD>(...) methods whose signatures must follow these rules:

The method name MUST have ejbCreate as its prefix. The method MUST be declared as public. The method MUST NOT be declared as final or static. The return type must be the entity beans PRIMARY KEY type (NOTE, the return type of HOME's create(...) method is COMPONENT INTERFACE type). If the ejbCreate<METHOD>(...) method corresponds to a create<METHOD>(...) on the entity beans remote home interface, the method arguments and return value types must be legal types for RMI-IIOP. The throws clause MUST define the javax.ejb.CreateException. The throws clause may define arbitrary application specific exceptions.

For each ejbCreate<METHOD>(...) method, the entity bean class MUST define a matching ejbPostCreate<METHOD>(...) method, using the following rules:

The method name MUST have ejbPostCreate as its prefix. 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>(...)method. The throws clause may define arbitrary application specific exceptions (the javax.ejb. CreateException MAY be thrown, but it is NOT a MANDATORY).

The entity bean class may define ZERO or more HOME methods whose signatures must follow the following rules:

An ejbHome<METHOD>(...) method MUST exist for EVERY home <METHOD>(...) method on the entity beans remote home or local home interface. The method name MUST have ejbHome as its prefix followed by the name of the <METHOD> method in which the first character has been uppercased. The method MUST be declared as public. The method MUST NOT be declared as static.

http://java.boot.by/bcd-guide/ch06s06.html 2 / 6 2004/6/12 11:57:35

Identify the interfaces and methods a CMP entity bean must and must not implement.

If the ejbHome<METHOD>(...) method corresponds to a home <METHOD>(...) on the entity beans REMOTE home interface, the method argument and return value types MUST be legal types for RMI-IIOP. The throws clause may define arbitrary application specific exceptions. The throws clause MUST NOT throw the java.rmi.RemoteException.

The entity bean class may define one or more SELECT methods whose signatures must follow the following rules:

The method name MUST have ejbSelect as its prefix. The method MUST be declared as public. The method MUST be declared as abstract. The throws clause MUST define the javax.ejb.FinderException. The throws clause may define arbitrary application specific exceptions.

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 method MUST be declared as public. The method MUST NOT be declared as final or static. If the business method corresponds to a method of the entity beans REMOTE interface, the method argument and return value types MUST be legal types for RMI-IIOP. The throws clause may define arbitrary application specific exceptions. The business methods of an entity bean with cmp-version 2.x MUST NOT throw the java.rmi. RemoteException.

public abstract class AddressBean implements javax.ejb.EntityBean { ... public Integer ejbCreateAddress(String street, String city, String state, String zip) throws CreateException { setId(..); setStreet(..); setCity(..); ... return null; // for CMP 2.x !!! } public void ejbPostCreateAddress(String street, String city, String state, String zip) { } // persistent fields public abstract Integer getId(); public abstract void setId(Integer id);
http://java.boot.by/bcd-guide/ch06s06.html 3 / 6 2004/6/12 11:57:35

Identify the interfaces and methods a CMP entity bean must and must not implement.

public abstract String getStreet(); public abstract void setStreet(String street); public abstract String getCity(); public abstract void setCity(String city); // ejbSelect methods public abstract Collection ejbSelectZipCodes(String state) throws FinderException; public abstract Collection ejbSelectAll() throws FinderException; public abstract CustomerLocal ejbSelectCustomer(AddressLocal addr) throws FinderException; // customer home methods. These are wrappers of ejbSelect methods public Collection ejbHomeQueryZipCodes(String state) throws FinderException { return ejbSelectZipCodes(state); } public Collection ejbHomeQueryAll() throws FinderException { return ejbSelectAll(); } public CustomerLocal ejbHomeQueryCustomer(AddressLocal addr) throws FinderException { return ejbSelectCustomer(addr); } // standard call back methods public void setEntityContext(EntityContext ec){} public void unsetEntityContext(){} public void ejbLoad(){} public void ejbStore(){} public void ejbActivate(){} public void ejbPassivate(){} public void ejbRemove(){} }

<entity> <ejb-name>AddressEJB</ejb-name>
http://java.boot.by/bcd-guide/ch06s06.html 4 / 6 2004/6/12 11:57:35

Identify the interfaces and methods a CMP entity bean must and must not implement.

... <prim-key-class>java.lang.Integer</prim-key-class> <reentrant>False</reentrant> <cmp-version>2.x</cmp-version> <abstract-schema-name>Address</abstract-schema-name> <cmp-field><field-name>id</field-name></cmp-field> <cmp-field><field-name>street</field-name></cmp-field> ... <primkey-field>id</primkey-field> <security-identity><use-caller-identity/></security-identity> <query> <query-method> <method-name>ejbSelectZipCodes</method-name> <method-params> <method-param>java.lang.String</method-param> </method-params> </query-method> <ejb-ql> SELECT a.zip FROM Address AS a WHERE a.state = ?1 </ejb-ql> </query> <query> <query-method> <method-name>ejbSelectAll</method-name> <method-params/> </query-method> <ejb-ql> SELECT OBJECT(a) FROM Address AS a </ejb-ql> </query> ... </entity>

Prev Identify correctly-implemented deployment descriptor elements for a CMP bean (including container-managed relationships).

Up Home

Next Chapter 7. CMP Entity Bean Life Cycle

http://java.boot.by/bcd-guide/ch06s06.html 5 / 6 2004/6/12 11:57:35

Identify the interfaces and methods a CMP entity bean must and must not implement.

http://java.boot.by/bcd-guide/ch06s06.html 6 / 6 2004/6/12 11:57:35

Chapter 7. CMP Entity Bean Life Cycle

Chapter 7. CMP Entity Bean Life Cycle Prev Part I. Exam Objectives Next

Chapter 7. CMP Entity Bean Life Cycle

Identify correct and incorrect statements or examples about the life cycle of a CMP entity bean.
An entity bean instance is in one of the following THREE states: 1. DOES NOT EXIST state. 2. POOLED state. An instance in the pooled state is not associated with any particular entity object identity. 3. READY state. An instance in the ready state is assigned an entity object identity. The following steps describe the life cycle of an entity bean instance:

An entity bean instances 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 beans FINDER methods (ejbFind<METHOD>(...)) or any of the entity beans HOME methods (ejbHome<METHOD> (...)). The instance DOES NOT move to the ready state during the execution of a finder or a home method. An ejbSelect<METHOD>(...) method may be called by an entity beans home method while the instance is in the pooled state.

public abstract class AddressBean implements javax.ejb.EntityBean { ... // Customer home methods. // These are wrappers of ejbSelect methods public Collection ejbHomeQueryZipCodes(String state) throws FinderException { return ejbSelectZipCodes(state); }
http://java.boot.by/bcd-guide/ch07.html 1 / 4 2004/6/12 11:57:40

Chapter 7. CMP Entity Bean Life Cycle

public Collection ejbHomeQueryAll() throws FinderException { return ejbSelectAll(); } public CustomerLocal ejbHomeQueryCustomer(AddressLocal addr) throws FinderException { return ejbSelectCustomer(addr); } ... }

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: 1. Through the ejbCreate<METHOD>(...) and ejbPostCreate<METHOD>(...) methods. The CONTAINER invokes the ejbCreate<METHOD>(...) and ejbPostCreate<METHOD>(...) 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 beans home object). 2. Through the ejbActivate() method. 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 clients 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 synchronize the state of the instance with the state of the entity in the underlying data source whenever it determines the need to, in the process invoking 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. An ejbSelect<METHOD> method CAN be called by a business method (or ejbLoad() or ejbStore() method) while the instance is in the READY 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 prepare itself for the synchronization of the database state with the instances state, and then the container invokes the ejbPassivate() method to return the instance to the POOLED state. The container will transition the instance to the pooled state. There are THREE possible transitions from the ready to the POOLED state:

http://java.boot.by/bcd-guide/ch07.html 2 / 4 2004/6/12 11:57:40

Chapter 7. CMP Entity Bean Life Cycle

1. Through the ejbPassivate() 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. 2. Through the ejbRemove() method. 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 objects component interface or a remove(...) method on the entity beans home interface). 3. Because of a transaction rollback for ejbCreate(), ejbPostCreate(), or ejbRemove(). If ejbCreate(), ejbPostCreate(), or ejbRemove() is called and the transaction rolls back, the container will transition the bean instance to the POOLED state.

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. The CONTAINER can REMOVE an instance in the pool by calling the unsetEntityContext() method on the instance.

NOTE:

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. A RuntimeException thrown from any method of an entity bean class (including the business methods and the callbacks invoked by the container) results in the transition to the DOES NOT EXIST state. From the callers perspective, the corresponding entity object CONTINUES to exist. The client CAN continue accessing the entity object through its component interface because the container can use a different entity bean instance to delegate the clients requests. 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.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch07.html 3 / 4 2004/6/12 11:57:40

Chapter 7. CMP Entity Bean Life Cycle

Identify the interfaces and methods a CMP entity bean must and must not implement. Home

From a list, identify the purpose, behavior, and responsibilities of the bean provider for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

http://java.boot.by/bcd-guide/ch07.html 4 / 4 2004/6/12 11:57:40

From a list, identify the purpose, behavior, and responsibilities of th...sivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

From a list, identify the purpose, behavior, and responsibilities of the bean provider for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect. Prev Chapter 7. CMP Entity Bean Life Cycle Next

From a list, identify the purpose, behavior, and responsibilities of the bean provider for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.
The entity Bean Provider is responsible for implementing the following methods in the abstract entity bean class:

A public constructor that takes NO arguments. 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 An identity of an entity object is NOT available during this method. The entity bean MUST NOT attempt to access its persistent state and relationships using the accessor methods 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 entity bean MUST NOT attempt to access its persistent state and relationships using the accessor methods 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 [primary key class] ejbCreate<METHOD>(...); There are ZERO or more ejbCreate<METHOD>(...) methods, whose signatures match the signatures of the create<METHOD>(...) methods of the entity beans home interface. The CONTAINER invokes an ejbCreate<METHOD>(...) method on an entity bean instance when a CLIENT invokes a matching create<METHOD>(...) method on the entity beans home interface. The entity Bean Providers responsibility is to INITIALIZE the instance in the

http://java.boot.by/bcd-guide/ch07s02.html 1 / 7 2004/6/12 11:57:44

From a list, identify the purpose, behavior, and responsibilities of th...sivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

ejbCreate<METHOD>(...) methods from the input arguments, using the get and set accessor methods, such that when the ejbCreate<METHOD>(...) method returns, the persistent representation of the instance can be created. The entity Bean Provider is guaranteed that the values that will be initially returned by the instances get methods for containermanaged fields will be the Java language defaults (e.g. 0 for integer, null for pointers), except for collection-valued cmr-fields, which will have the empty collection (or set) as their value. The entity Bean Provider MUST NOT attempt to modify the values of cmrfields in an ejbCreate<METHOD>(...) method. This should be done in the ejbPostCreate<METHOD>(...) method instead. The entity object created by the ejbCreate<METHOD> 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. However, it is LEGAL to reuse the primary key of a previously removed entity object. The implementation of the Bean Providers ejbCreate<METHOD>(...) methods should be coded to return a NULL. An ejbCreate<METHOD>(...) method executes in the transaction context determined by the transaction attribute of the matching create<METHOD>(...) method, as described in subsection. The database insert operations are performed by the container within the same transaction context after the Bean Providers ejbCreate<METHOD>(...) method completes. public void ejbPostCreate<METHOD>(...); For each ejbCreate<METHOD>(...) method, there is a matching ejbPostCreate<METHOD>(...) method that has the same input parameters but whose return type is void. The container invokes the matching ejbPostCreate<METHOD>(...) method on an instance after it invokes the ejbCreate<METHOD>(...) method with the same arguments. The instance CAN discover the primary key by calling getPrimaryKey() on its entity context object. The entity object identity is AVAILABLE during the ejbPostCreate<METHOD>(...) method. The instance MAY, for example, obtain the component interface of the associated entity object and pass it to another enterprise bean as a method argument. The entity Bean Provider MAY use the ejbPostCreate<METHOD>(...) to set the values of cmrfields to complete the initialization of the entity bean instance. An ejbPostCreate<METHOD>(...) method executes in the SAME transaction context as the previous ejbCreate<METHOD>(...) 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 entity bean MUST NOT attempt to access its persistent state or relationships using the accessor methods during this method.
http://java.boot.by/bcd-guide/ch07s02.html 2 / 7 2004/6/12 11:57:44

From a list, identify the purpose, behavior, and responsibilities of th...sivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

The instance CAN obtain the IDENTITY of the entity object via the getPrimaryKey(), getEJBLocalObject(), 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(). 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 entity bean MUST NOT attempt to access its persistent state or relationships using the accessor methods during this method. The instance CAN still obtain the IDENTITY of the entity object via the getPrimaryKey(), getEJBLocalObject(), or getEJBObject() method of the EntityContext interface. public void ejbRemove(); The container invokes the ejbRemove() method on an entity bean instance in response to a client-invoked remove operation on the entity beans home or component interface or as the result of a cascade-delete operation. The instance is in the ready state when ejbRemove () is invoked and it will be entered into the POOL when the method completes. The entity Bean Provider CAN use the ejbRemove method to implement any actions that must be done BEFORE the entity objects persistent representation is removed. The CONTAINER synchronizes the instances state BEFORE it invokes the ejbRemove method. This means that the state of the instance at the beginning of the ejbRemove method is the same as it would be at the beginning of a business method. This method and the database delete operation(s) execute 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(), getEJBLocalObject(), or getEJBObject() method of the EntityContext interface. After the entity Bean Providers ejbRemove returns, and in the same transaction context, the Container removes the entity bean from all relationships in which it participates before removing the entity objects persistent representation. 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();

http://java.boot.by/bcd-guide/ch07s02.html 3 / 7 2004/6/12 11:57:44

From a list, identify the purpose, behavior, and responsibilities of th...sivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

When the container needs to synchronize the state of an enterprise bean instance with the entity objects persistent state, the container calls the ejbLoad() method. The entity Bean Provider CAN assume that the instances persistent state HAS BEEN LOADED just BEFORE the ejbLoad() method is invoked. It is the responsibility of the Bean Provider to use the ejbLoad() method to recompute or initialize the values of any instance variables that depend on the entity beans persistent state. In general, any transient state that depends on the persistent state of an entity bean should be recalculated using the ejbLoad() method. The entity bean can use the ejbLoad() method, for instance, to perform some computation on the values returned by the accessor methods (for example, uncompressing text fields). This method executes in the transaction context determined by the transaction attribute of the business method that triggered the ejbLoad method. public void ejbStore(); When the container needs to synchronize the state of the entity objects persistent state with the state of the enterprise bean instance, the container first calls the ejbStore() method on the instance. The entity Bean Provider should use the ejbStore() method to UPDATE the instance using the accessor methods BEFORE its persistent state is synchronized. For example, the ejbStore() method may perform compression of text before the text is stored in the database. The Bean Provider CAN assume that AFTER the ejbStore() method returns, the persistent state of the instance is synchronized. 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> method and this ejbStore method are also invoked in the SAME transaction context. public [primary key type] or [collection] ejbFind<METHOD>(...); The Bean Provider of an entity bean with container-managed persistence DOES NOT write the finder (ejbFind<METHOD>(...)) methods. The finder methods are generated at the entity bean DEPLOYMENT time using the Container Providers tools. Every finder method except findByPrimaryKey(key) MUST be associated with a query element in the deployment descriptor. The entity Bean Provider declaratively specifies the EJB QL finder query and associates it with the finder method in the deployment descriptor. A finder method is normally characterized by an EJB QL query string specified in the query element.

http://java.boot.by/bcd-guide/ch07s02.html 4 / 7 2004/6/12 11:57:44

From a list, identify the purpose, behavior, and responsibilities of th...sivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

<entity> ... <query> <query-method> <method-name>findAllCustomersWithReservations</method-name> <method-params/> </query-method> <ejb-ql> SELECT OBJECT(cust) FROM Reservation res, IN (res.customers) cust </ejb-ql> </query> ... </entity>

public [some type] ejbHome<METHOD>(...); The container invokes this method on the instance when the container selects the instance to execute a matching client-invoked <METHOD>(...) home 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 ejbHome<METHOD> method on it, and it is returned to the POOLED state when the execution of the ejbHome<METHOD> method completes. The ejbHome<METHOD> method executes in the transaction context determined by the transaction attribute of the matching <METHOD>(...) home method. The entity bean provider provides the implementation of the ejbHome<METHOD> method. The entity bean MUST NOT attempt to access its persistent state or relationships using the accessor methods during this method because a home method is NOT SPECIFIC to a particular bean instance. public abstract [some type] ejbSelect<METHOD>(...); The Bean Provider may provide ZERO or more SELECT METHODS. A select method is a query method that is NOT DIRECTLY EXPOSED to the client in the home or component interface. The Bean Provider typically calls a select method within a business method. The Bean Provider defines the select methods as abstract methods. The select methods are generated at the entity bean deployment time using the Container Providers tools. The ejbSelect<METHOD> method executes in the transaction context determined by the transaction attribute of the invoking business method.

http://java.boot.by/bcd-guide/ch07s02.html 5 / 7 2004/6/12 11:57:44

From a list, identify the purpose, behavior, and responsibilities of th...sivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

The semantics of a select method, like those of a finder method, are defined by an EJB QL query string. A select method is similar to a finder method, but unlike a finder method it can return values that correspond to ANY cmp-field or cmr-field type. Every select method MUST be associated with a query element in the deployment descriptor. The entity Bean Provider declaratively specifies the EJB QL query and associates it with the select method in the deployment descriptor. A select method is normally characterized by an EJB QL query string specified in the query element.

<entity> ... <query> <query-method> <method-name>ejbSelectZipCodes</method-name> <method-params> <method-param>java.lang.String</method-param> </method-params> </query-method> <ejb-ql> SELECT a.zip FROM Address AS a WHERE a.state = ?1 </ejb-ql> </query> ... </entity>

Typically an ejbSelect<METHOD>(...) method that returns entity objects returns these as EJBLocalObjects. If the ejbSelect<METHOD>(...) method returns an EJBObject or collection of EJBObjects, the Bean Provider MUST specify the value of the result-type-mapping element in the query deployment descriptor element for the select method as Remote. An ejbSelect<METHOD>(...) is NOT based on the IDENTITY of the entity bean instance on which it is invoked. However, the Bean Provider CAN use the primary key of an entity bean as an argument to an ejbSelect<METHOD>(...) to define a query that is logically scoped to a particular entity bean instance.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch07s02.html 6 / 7 2004/6/12 11:57:44

From a list, identify the purpose, behavior, and responsibilities of th...sivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

Chapter 7. CMP Entity Bean Life Cycle

Home

From a list, identify the responsibility of the container for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

http://java.boot.by/bcd-guide/ch07s02.html 7 / 7 2004/6/12 11:57:44

From a list, identify the responsibility of the container for a CMP en...ivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

From a list, identify the responsibility of the container for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect. Prev Chapter 7. CMP Entity Bean Life Cycle Next

From a list, identify the responsibility of the container for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.
The container MUST call the following methods:

public void setEntityContext(EntityContext 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 [primary key class] ejbCreate<METHOD>(...); public void ejbPostCreate<METHOD>(...); The container invokes these two methods during the creation of an entity object as a result of a client invoking a create<METHOD>(...) method on the entity beans home interface. The container invokes the ejbCreate<METHOD>(...) method whose signature matches the create<METHOD>(...) method invoked by the client. Prior to invoking the ejbCreate<METHOD>(...) method provided by the Bean Provider, the container MUST ensure that the values that will be initially returned by the instances get methods for container-managed fields will be the Java language defaults (e.g. 0 for integer, null for pointers), except for collection-valued cmr-fields, which MUST have the empty collection (or set) as their value.

http://java.boot.by/bcd-guide/ch07s03.html 1 / 6 2004/6/12 11:57:47

From a list, identify the responsibility of the container for a CMP en...ivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

The container is responsible for calling the ejbCreate<METHOD>(...) method, for obtaining the primary key fields of the newly created entity object persistent representation, and for creating an entity EJBObject reference and/or EJBLocalObject reference for the newly created entity object. The Container MUST establish the primary key BEFORE it invokes the ejbPostCreate<METHOD>(...) method. The entity object created by the ejbCreate<METHOD> 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. However, it is legal to reuse the primary key of a previously removed entity object. The container MAY, but is NOT REQUIRED to, throw the DuplicateKeyException on the Bean Providers attempt to create an entity object with a duplicate primary key. The container may create the representation of the entity in the database immediately, or it CAN DEFER it to a later time (for example to the time after the matching ejbPostCreate<METHOD>(...) has been called, or to the end of the transaction), depending on the caching strategy that it uses. The container then invokes the matching ejbPostCreate<METHOD>(...) method with the SAME arguments on the instance to allow the instance to fully initialize itself. The instance can discover the primary key by calling getPrimaryKey() on its entity context object. Finally, the container returns the entity objects remote interface (i.e., a reference to the entity EJBObject) to the client if the client is a remote client or the entity objects local interface (i.e., a reference to the entity EJBLocalObject) if the client is a local client. The container MUST invoke ejbCreate<METHOD> and ejbPostCreate<METHOD> and create the representation of the persistent instance in the database in the transaction context determined by the transaction attribute of the matching create<METHOD>(...) method. 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(), getEJBLocalObject(), 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

http://java.boot.by/bcd-guide/ch07s03.html 2 / 6 2004/6/12 11:57:47

From a list, identify the responsibility of the container for a CMP en...ivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

still available to the instance if the instance invokes the getPrimaryKey(), getEJBLocalObject (), 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 the ejbRemove() method in response to a client-invoked remove(...) operation on the entity beans home or component interface or as the result of a cascadedelete operation. The instance is in the READY STATE when ejbRemove() is invoked and it will be entered into the POOL when the method completes. The container synchronizes the instances state before it invokes the ejbRemove method. This means that the persistent state of the instance at the beginning of the ejbRemove method is the SAME as it would be at the beginning of a business 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). 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 (), getEJBLocalObject(), or getEJBObject() method on its EntityContext in the ejbRemove() method). After the entity Bean Providers ejbRemove() method returns, and in the same transaction context, the Container removes the entity bean instance from all relationships in which it participates and then removes the entity objects persistent representation. The container may delete the representation of the entity in the database immediately, or it can defer it to a later time (for example to the end of the transaction), depending on the caching strategy that it uses. The container MUST ensure that the ejbRemove method and database delete operations are performed in the transaction context determined by the transaction attribute of the invoked remove method. public void ejbLoad(); When the container needs to synchronize the state of an enterprise bean instance with the entity objects state in the database, the container calls the ejbLoad() method. Depending on its caching strategy, the container may first read the entity objects state from the database, before invoking the ejbLoad() method, or it may use a lazy loading strategy in making this state visible to the instance. 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,

http://java.boot.by/bcd-guide/ch07s03.html 3 / 6 2004/6/12 11:57:47

From a list, identify the responsibility of the container for a CMP en...ivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

the container will call ejbLoad before the first business method within a transaction. 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(); 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 calls the ejbStore() method on the instance. 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. The container MUST invoke this method in the SAME transaction context as the previous ejbLoad or ejbCreate<METHOD> method invoked on the instance. All business methods invoked between the previous ejbLoad or ejbCreate<METHOD> method and this ejbStore method are also invoked in the SAME transaction context. After the ejbStore() method returns, the container may store the persistent state of the instance to the database, depending on its caching strategy. If the container uses a lazy storing caching strategy, it is the containers responsibility to write the representation of the persistent object to the database in the same transaction context as that of the ejbStore method. public [primary key type] or [collection] ejbFind<METHOD>(...); The implementation of the ejbFind<METHOD>(...) method is SUPPLIED BY THE CONTAINER. The container invokes the ejbFind<METHOD>(...) method on an instance when a client invokes a matching find<METHOD>(...) method on the entity beans 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. The container must invoke the ejbFind<METHOD>(...) method in the transaction context determined by the transaction attribute of the matching find<METHOD>(...) method. The Container is responsible for ensuring that updates to the states of all entity beans in the same transaction context as the ejbFind<METHOD>(...) method are visible in the results of the ejbFind<METHOD>(...) method. Before invoking the ejbFind<METHOD>(...) method, the container must therefore first synchronize the state of any entity bean instances that are participating in the same transaction context as is used to execute the ejbFind<METHOD>(...) by invoking the ejbStore() method on those entity bean instances. After the ejbFind<METHOD>(...) method completes, the instance remains in the pooled state. The container may, but is NOT REQUIRED to, immediately activate the objects that were located by the finder using the transition through the ejbActivate() method.
http://java.boot.by/bcd-guide/ch07s03.html 4 / 6 2004/6/12 11:57:47

From a list, identify the responsibility of the container for a CMP en...ivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

If the ejbFind<METHOD>(...) method is declared to return a single primary key, the container creates an entity EJBObject (EJBLocalObject) reference for the primary key and returns it to the client (local client). If the ejbFind<METHOD>(...) method is declared to return a collection of primary keys, the container creates a collection of entity EJBObject (EJBLocalObject) references for the primary keys returned from the ejbFind<METHOD>(...), and returns the collection to the client (local client). The implementations of the finder methods are generated at the entity bean deployment time using the container providers tools. public abstract [some type] ejbSelect<METHOD>(...); A SELECT METHOD is a query method that is NOT DIRECTLY EXPOSED to the client in the home or component interface. The Bean Provider typically calls a select method within a business method or home method. A select method executes in the transaction context determined by the transaction attribute of the invoking business method. The container is responsible for ensuring that all updates to the states of all entity beans in the same transaction context as the ejbSelect<METHOD> method are visible in the results of the ejbSelect<METHOD> method. The implementations of the select methods are generated at the entity bean deployment time using the container providers tools. public [some type] ejbHome<METHOD>(...); The container invokes the ejbHome<METHOD>(...) method on an instance when a client invokes a matching <METHOD>(...) home method on the entity beans 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 ejbHome<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 home method. After the ejbHome<METHOD>(...) method completes, the instance remains in the POOLED state. The container must invoke the ejbHome<METHOD>(...) method in the transaction context determined by the transaction attribute of the matching <METHOD>(...) home method.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch07s03.html 5 / 6 2004/6/12 11:57:47

From a list, identify the responsibility of the container for a CMP en...ivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

From a list, identify the purpose, behavior, and responsibilities of the bean provider for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

Chapter 8. Entity Beans

Home

http://java.boot.by/bcd-guide/ch07s03.html 6 / 6 2004/6/12 11:57:47

Chapter 8. Entity Beans

Chapter 8. Entity Beans Prev Part I. Exam Objectives Next

Chapter 8. Entity Beans

From a list of behaviors, match them with the appropriate EntityContext method responsible for that behavior.
A CONTAINER provides the entity bean instances with an EntityContext, which gives the entity bean instance access to the instances context maintained by the container. The EntityContext interface has the following methods:

The getEJBObject method returns the entity beans REMOTE [component] interface. The getEJBHome method returns the entity beans REMOTE HOME interface. The getEJBLocalObject method returns the entity beans LOCAL [component] interface. The getEJBLocalHome method returns the entity beans LOCAL HOME interface. The getCallerPrincipal method returns the java.security.Principal that identifies the invoker of the bean instances EJB object. The isCallerInRole method tests if the entity bean instances 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 (EntityBeans support ONLY CMT). The getRollbackOnly method allows the instance to test if the current transaction has been marked for rollback. (EntityBeans support ONLY CMT). The getPrimaryKey method returns the entity beans primary key. The getUserTransaction method returns the javax.transaction.UserTransaction interface. Entity bean instances MUST NOT call this method. It is derived from EJBContext interface, which is parent for contexts for all 3 types of EJB, but it is used ONLY with BMT in Session Beans and Messages Driven Beans.

public interface EntityContext extends EJBContext { EJBLocalObject getEJBLocalObject() throws IllegalStateException; EJBObject getEJBObject() throws IllegalStateException; Object getPrimaryKey() throws IllegalStateException; } public interface EJBContext { EJBHome getEJBHome(); EJBLocalHome getEJBLocalHome(); Principal getCallerPrincipal(); boolean isCallerInRole(String roleName); UserTransaction getUserTransaction() throws IllegalStateException; void setRollbackOnly() throws IllegalStateException;

http://java.boot.by/bcd-guide/ch08.html 1 / 2 2004/6/12 11:57:53

Chapter 8. Entity Beans

boolean getRollbackOnly() throws IllegalStateException; }

Prev From a list, identify the responsibility of the container for a CMP entity bean, including but not limited to: setEntityContext, unsetEntityContext, ejbCreate, ejbPostCreate, ejbActivate, ejbPassivate, ejbRemove, ejbLoad, ejbStore, ejbFind, ejbHome, and ejbSelect.

Up

Next Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.

Home

http://java.boot.by/bcd-guide/ch08.html 2 / 2 2004/6/12 11:57:53

Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.

Identify correct and incorrect statements or examples about an entity bean's primary key and object identity. Prev Chapter 8. Entity Beans Next

Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.
From the viewpoint of the Bean Provider, entity objects have a runtime object identity that is maintained by the Container. The Container maintains the persistent identity of an entity object on the basis of its PRIMARY KEY. The primary key of an entity bean may or may not be visible as one or more cmp-fields of the instance, depending on the way in which it is specified. Once it has been set, the Bean Provider MUST NOT attempt to change the value of a primary key field by means of a set method on its cmp-fields. When a new instance of an entity bean whose primary key fields are visible in the entity bean class is created, the Bean Provider MUST use the ejbCreate<METHOD>(...) method to set all the primary key fields of the entity bean instance before the instance can participate in a relationship, e.g. be used in a set accessor method for a cmr-field. The Bean Provider MUST NOT reset a primary key value by means of a set method on any of its cmp-fields after it has been set in the ejbCreate<METHOD>(...) method. The container must be able to manipulate the primary key type of an entity bean. Therefore, the primary key type for an entity bean with container-managed persistence MUST follow the rules:

The Bean Provider MUST specify a primary key class in the deployment descriptor. (In case the class is not known until deployment, Bean Provider specify java.lang.Object class). The primary key type MUST be a legal Value Type in RMI-IIOP (serializable). The class MUST provide suitable implementation of the hashCode() and equals(Object obj) methods to simplify the management of the primary keys by the Container.

There are two ways to specify a primary key class for an entity bean with container-managed persistence: 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 fields type must be the primary key type.

http://java.boot.by/bcd-guide/ch08s02.html 1 / 5 2004/6/12 11:57:56

Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.

<entity> <ejb-name>CabinEJB</ejb-name> <home>com.titan.cabin.CabinHomeRemote</home> <remote>com.titan.cabin.CabinRemote</remote> <ejb-class>com.titan.cabin.CabinBean</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.lang.Integer</prim-key-class> <reentrant>False</reentrant> <cmp-version>2.x</cmp-version> <abstract-schema-name>Cabin</abstract-schema-name> <cmp-field><field-name>id</field-name></cmp-field> <cmp-field><field-name>name</field-name></cmp-field> <cmp-field><field-name>deckLevel</field-name></cmp-field> <cmp-field><field-name>shipId</field-name></cmp-field> <cmp-field><field-name>bedCount</field-name></cmp-field> <primkey-field>id</primkey-field> <security-identity><use-caller-identity/></security-identity> </entity>

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.

public class ItemKey implements java.io.Serializable { public String productId; // public - mandatory public String vendorId; // public - mandatory public ItemKey() { }; // no-args constructor - mandatory public ItemKey(String productId, String vendorId) { this.productId = productId; this.vendorId = vendorId; } public String getProductId() { return productId; }

http://java.boot.by/bcd-guide/ch08s02.html 2 / 5 2004/6/12 11:57:56

Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.

public String getVendorId() { return vendorId; } public boolean equals(Object other) { // mandatory if (other instanceof ItemKey) { return (productId.equals(((ItemKey)other).productId) && vendorId.equals(((ItemKey)other).vendorId)); } return false; } public int hashCode() { // mandatory return productId.hashCode(); } }

A primary key class MUST meet these requirements:


The access control modifier of the class is public. All fields are declared as public. Field names in the primary key clsss MUST match the corresponding container-managed fields in the entity bean class. The class has a public default (no-args) constructor. The class implements the hashCode() and equals(Object obj) methods. The class is SERIALIZABLE (implements java.io.Serializable).

In special situations, the entity Bean Provider may choose not to specify the primary key class or the primary key fields for an entity bean with container-managed persistence. This case usually happens when the entity bean does not have a natural primary key, and/or the Bean Provider wants to allow the Deployer using the Container Providers tools to select the primary key fields at deployment time. The entity beans 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. In this special case, entity bean must meet these requirements:

In the deployment descriptor, the primary key class is defined (by Bean Provider) as a java.lang.Object. The primary key field is not specified. In the HOME interface, the argument of the findByPrimaryKey method MUST be a java.lang. Object. In the entity bean CLASS, the return type of the ejbCreate method MUST be a java.lang. Object.

http://java.boot.by/bcd-guide/ch08s02.html 3 / 5 2004/6/12 11:57:56

Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.

We are using 2 elements in DD for defining primary keys: <prim-key-class> and <primkey-field> :

SINGLE-FIELD primary key: <prim-key-class> is a MANDATORY, <primkey-field> is a MANDATORY. COMPOUND primary key: <prim-key-class> is a MANDATORY, <primkey-field> MUST NOT be defined.

The primary key class can be specific to a particular entity bean class. That is, each entity bean can define its own primary key class. Or multiple entity beans CAN share the same primary key class. If two entity objects with the SAME home interface have the SAME primary key, they are considered IDENTICAL entity objects. If they have a different primary key, they are considered different entity objects. There are 2 ways of comparing Entity Beans: 1. Using isIdentical(EJBObject obj) method of javax.ejb.EJBObject interface on bean's REMOTE interface, or isIdentical(EJBLocalObject obj) method of javax.ejb.EJBLocalObject interface on bean's LOCAL interface.

Item item1 = ...; Item item2 = ...; if (item1.isIdentical(item2)) { // item1 and item2 refer to the same entity object }

2. Comparing primary keys of two entity object references (ONLY FROM THE SAME HOME INTERFACE !).

ItemHome itemHome = ...; // get home interface Item item1 = itemHome.findByName(...); Item item2 = itemHome.findByCountry(...); if (item1.getPrimaryKey().equals(item2.getPrimaryKey())) { // item1 and item2 refer to the same entity object }

Prev Chapter 8. Entity Beans

Up Home

Next Chapter 9. EJB-QL

http://java.boot.by/bcd-guide/ch08s02.html 4 / 5 2004/6/12 11:57:56

Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.

http://java.boot.by/bcd-guide/ch08s02.html 5 / 5 2004/6/12 11:57:56

Chapter 9. EJB-QL

Chapter 9. EJB-QL Prev Part I. Exam Objectives Next

Chapter 9. EJB-QL

Identify correct and incorrect syntax for an EJB QL query including the SELECT, FROM, and WHERE clauses.
EJB QL is a query specification language for the FINDER and SELECT methods of entity beans with container-managed persistence (CMP). EJB QL can be compiled to a target language, such as SQL, of a database or other persistent store. This allows the execution of queries to be shifted to the native language facilities provided by the persistent store, instead of requiring queries to be executed on the runtime representation of the entity beans' state. As a result, query methods can be optimizable as well as portable. The Enterprise JavaBeans query language uses the abstract persistence schemas of entity beans, including their relationships, for its data model. It defines operators and expressions based on this data model. The Bean Provider uses EJB QL to write queries based on the abstract persistence schemas and the relationships defined in the deployment descriptor. EJB QL depends on navigation and selection based on the cmp-fields and cmr-fields of the related entity beans. The Bean Provider can navigate from an entity bean to other entity beans by using the names of cmr-fields in EJB QL queries. When defining EJB QL, we are limited to referring only to elements described below:

Names of the entity beans defined in the abstract schema. Each bean by default is given the schema name of the bean (such as Customer, which is defined in the abstract-schemaname xml tag in DD).

<entity> <ejb-name>CustomerEJB</ejb-name> ... <abstract-schema-name>Customer</abstract-schema-name> ... </entity>

CMP field names within these beans (such as firstName, lastName, anything in a cmp-field tag in DD).

http://java.boot.by/bcd-guide/ch09.html 1 / 8 2004/6/12 11:58:00

Chapter 9. EJB-QL

<entity> <ejb-name>CustomerEJB</ejb-name> ... <abstract-schema-name>Customer</abstract-schema-name> <cmp-field><field-name>id</field-name></cmp-field> <cmp-field><field-name>lastName</field-name></cmp-field> <cmp-field><field-name>firstName</field-name></cmp-field> <cmp-field><field-name>hasGoodCredit</field-name></cmp-field> ... </entity>

CMR field names within these beans to navigate along relationships (such as anything defined in a cmr-field).

<ejb-relation> <ejb-relation-name>Customer-HomeAddress</ejb-relation-name> <ejb-relationship-role> <ejb-relationship-role-name> Customer-has-a-Address </ejb-relationship-role-name> <multiplicity>One</multiplicity> <relationship-role-source> <ejb-name>CustomerEJB</ejb-name> </relationship-role-source> <cmr-field> <cmr-field-name>homeAddress</cmr-field-name> </cmr-field> </ejb-relationship-role> <ejb-relationship-role> ... </ejb-relationship-role> </ejb-relation>

An EJB QL query is a string which consists of the following three clauses:


a SELECT clause, which determines the TYPE of the objects or values to be selected. a FROM clause, which provides declarations that designate the DOMAIN to which the expressions specified in the SELECT clause and WHERE clause of the query apply.

http://java.boot.by/bcd-guide/ch09.html 2 / 8 2004/6/12 11:58:00

Chapter 9. EJB-QL

an optional WHERE clause, which may be used to RESTRICT the results that are returned by the query.

EJB QL :: = SELECT_clause FROM_clause [WHERE_clause] An EJB QL query MUST always have a SELECT and a FROM clause. The WHERE clause is OPTIONAL. An EJB QL query MAY have parameters that correspond to the parameters of the finder or select method for which it is defined. An EJB QL query is statically defined in the ejb-ql deployment descriptor element. There must be ONE ejb-ql tag per query definition for each finder and select method.

<entity> <ejb-name>CustomerEJB</ejb-name> ... <abstract-schema-name>Customer</abstract-schema-name> <cmp-field><field-name>id</field-name></cmp-field> <cmp-field><field-name>lastName</field-name></cmp-field> <cmp-field><field-name>firstName</field-name></cmp-field> <cmp-field><field-name>hasGoodCredit</field-name></cmp-field> ... <query> <query-method> <method-name>findByName</method-name> <method-params> <method-param>java.lang.String</method-param> <method-param>java.lang.String</method-param> </method-params> </query-method> <ejb-ql> SELECT OBJECT(c) FROM Customer c WHERE c.lastName = ?1 AND c.firstName = ?2 </ejb-ql> </query> <query> <query-method> <method-name>findByGoodCredit</method-name> <method-params/> </query-method> <ejb-ql> SELECT OBJECT(c) FROM Customer c
http://java.boot.by/bcd-guide/ch09.html 3 / 8 2004/6/12 11:58:00

Chapter 9. EJB-QL

WHERE c.hasGoodCredit = TRUE </ejb-ql> </query> <query> <query-method> <method-name>ejbSelectLastNames</method-name> <method-params/> </query-method> <ejb-ql> SELECT c.lastName FROM Customer AS c </ejb-ql> </query> ... </entity>

EJB QL is used for two types of query methods:

FINDER METHODS. Finder methods are defined in the HOME interface(s) of an entity bean and return entity objects or local entity objects (NOTE, they can return ONLY COMPONENT INTERFACES). A finder method that is defined on the remote home interface must return either an EJBObject or a collection of EJBObjects; a finder method that is defined on the local home interface must return either an EJBLocalObject or a collection of EJBLocalObjects. The result type of a finder method defined on the remote home interface of an entity bean is the entity bean's remote interface (or a collection of objects implementing the entity bean's remote interface). The result type of a finder method defined on the local home interface of an entity bean is the entity bean's local interface (or a collection of objects implementing the entity bean's local interface). SELECT METHODS. Select methods are a special type of query method NOT DIRECTLY EXPOSED through the client view. The Bean Provider typically uses select methods to select the persistent state of an entity object or to select entities that are related to the entity bean for which the query is defined. The result type of a select method can be an EJBLocalObject (or a collection of EJBLocalObjects), an EJBObject (or a collection of EJBObjects), or a cmp-field value (or a collection of such). NOTE, the SELECT method can return not only component interfaces, but also java.lang.Object, or COLLECTION of java.lang. Object.

Reserved words are (keywords are NOT case sensitive): SELECT, FROM, WHERE, DISTINCT, OBJECT, NULL, TRUE, FALSE, NOT, AND, OR, BETWEEN, LIKE, IN, AS, UNKNOWN, EMPTY, MEMBER, OF, IS and ?. SELECT clause The SELECT clause defines the objects that are returned from a query.

http://java.boot.by/bcd-guide/ch09.html 4 / 8 2004/6/12 11:58:00

Chapter 9. EJB-QL

select_clause ::== SELECT [DISTINCT] {single-valued-path-expr} | OBJECT(ident_var) All standalone identification variables in the SELECT clause must be qualified by the OBJECT operator. The SELECT clause must not use the OBJECT operator to qualify path expressions. The following example returns a collection of the CMP fields of type lastName (a collection of Strings):

SELECT cust.lastName FROM Customer AS cust

The following example returns a collection of Customer instances:

SELECT OBJECT(cust) FROM Customer AS cust

The optional keyword DISTINCT effects a removal of duplicates in the returned collection. If the EJB QL query is specified for a method whose return type is java.util.Collection, the collection of values returned by the Container may contain duplicates if DISTINCT is not specified in the SELECT clause. If the query is specified for a method whose result type is java. util.Set, but does not specify DISTINCT, the container must interpret the query as if SELECT DISTINCT had been specified. FROM clause The FROM clause defines the set of beans from which the query results are formed and which are used in the WHERE clause. FROM_clause ::== FROM ident_variable_d {,ident_variable_d} ident_variable_d ::= collection_member_d | range_variable_d Identification variables can be either declared by using a range variable declaration (AS) or a collection member declaration (IN). Identification variables can only be declared in the FROM clause. Keep in mind that the statement is evaluated from the left to the right side. This is important for referencing within declarations to other variable declarations; referenced identifiers must already be declared. Unlike a Java variable, an EJB QL identifier IS NOT case sensitive. range_variable_d ::= abstract_schema_name [AS] identifier The AS keyword is optional. It is assumed if we omit it.
http://java.boot.by/bcd-guide/ch09.html 5 / 8 2004/6/12 11:58:00

Chapter 9. EJB-QL

SELECT OBJECT(cust) FROM Customer AS cust SELECT OBJECT(cust) FROM Customer cust

collection_member_d ::== IN collection_valued_path_expr [AS] identifier A collection member declaration declares an identification variable that represents an entity that is reached by navigating a CMR field in one-to-many or many-to-many relationships:

SELECT OBJECT(cust) FROM Customer AS cust, IN(cust.accounts) SELECT OBJECT(acct) FROM Account AS acct, IN(acct.transrecords)

The IN specification enables us to use attributes of related entities in the WHERE clause of the EJB QL statement. With a PATH EXPRESSION, we can address a CMP or a CMR field of a specified type. With path expressions, we are able to navigate along the container-managed relationships between entity beans. The navigation operator dot separates the type from the attribute, for example customer. accounts. A path expression that ends in a cmp-field is terminal and cannot be further composed. Navigation to a related entity beans results in a value of the related entity bean's abstract schema type. It is syntactically illegal to compose a path expression from a path expression that evaluates to a collection. To handle such a navigation, an identification variable must be declared in the FROM clause to range over the elements of the collection. Another path expression must be used to navigate over each such element in the WHERE clause of the query.

SELECT OBJECT(o) FROM Order AS o, IN(o.lineItems) l WHERE l.product.name = 'widget'

WHERE clause As in SQL the WHERE clause contains a conditional expression. The WHERE clause is optional in a query statement. WHERE_clause ::== WHERE conditional_expr

http://java.boot.by/bcd-guide/ch09.html 6 / 8 2004/6/12 11:58:00

Chapter 9. EJB-QL

conditional_expr ::== conditional_term | conditional_expr {OR | AND} conditional_term A conditional expression consists of other conditional expressions, logical or comparison operations or path expressions. At the end they have to evaluate to boolean values or boolean literals. Conditional expressions can use:

operators (+ - * /) comparisons (= > >= < <= <>), for strings only = and <> NOT BETWEEN arithmetic-expression AND arithmetic-expression IN: value IN (value1, value2, ...) LIKE, using wild card characters _ and % null comparison: IS NULL empty comparison: collection-valued-path-expr IS EMPTY collection member expression: MEMBER OF collection-valued-path-expr functional expressions: CONCAT, SUBSTRING, LOCATE, LENGTH, ABS, SQRT

To pass parameters to the query statement, the declared parameters of the finder method are accessible in the query statement as a question mark followed by a number, such as, ?1, ?2, ?3. The number is the position of the declaration in the finder method's signature. Input parameters are numbered starting from 1. The number of distinct input parameters in an EJB QL query must not exceed the number of input parameters for the FINDER or SELECT method. It is not required that the EJB QL query use all of the input parameters for the FINDER or SELECT method. For example, matching finder method declaration and EJB QL statements are:

findCustomerByName(String lastName, String firstName);

SELECT OBJECT(c) FROM Customer c WHERE c.lastName = ?1 AND c.firstName = ?2

The type of the parameter in the statement is defined by the declaration of the correspondent parameter in the finder method signature. Parameters can be primitive types (int), wrapper classes (Integer) or EJB objects. Using a parameter is only allowed in the WHERE clause within a conditional expression that involves a single-valued path expression, such as x.lastName.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch09.html 7 / 8 2004/6/12 11:58:00

Chapter 9. EJB-QL

Identify correct and incorrect statements or examples about an entity bean's primary key and object identity.

Home

Identify correct and incorrect statements or examples about the purpose and use of EJB QL.

http://java.boot.by/bcd-guide/ch09.html 8 / 8 2004/6/12 11:58:00

Identify correct and incorrect statements or examples about the purpose and use of EJB QL.

Identify correct and incorrect statements or examples about the purpose and use of EJB QL. Prev Chapter 9. EJB-QL Next

Identify correct and incorrect statements or examples about the purpose and use of EJB QL.

Find all orders:

SELECT OBJECT(o) FROM Order o

Find all orders that need to be shipped to Colorado:

SELECT OBJECT(o) FROM Order o WHERE o.shipping_address.state = 'CO'

Find all states for which there are orders:

http://java.boot.by/bcd-guide/ch09s02.html 1 / 4 2004/6/12 11:58:03

Identify correct and incorrect statements or examples about the purpose and use of EJB QL.

SELECT DISTINCT o.shipping_address.state FROM Order o

Find all orders that have line items:

SELECT DISTINCT OBJECT(o) FROM Order o, IN(o.lineItems) l

This query can also be written as:

SELECT OBJECT(o) FROM Order o WHERE o.lineItems IS NOT EMPTY

Find all orders that have no line items:

SELECT OBJECT(o) FROM Order o WHERE o.lineItems IS EMPTY

Find all pending orders:

SELECT DISTINCT OBJECT(o) FROM Order o, IN(o.lineItems) l WHERE l.shipped = FALSE

Find all orders in which the shipping address differs from the billing address. This example assumes that the Bean Provider uses two distinct entity beans to designate shipping and billing addresses:

SELECT OBJECT(o) FROM Order o WHERE NOT (o.shipping_address.state = o.billing_address.state AND o.shipping_address.city = o.billing_address.city AND o.shipping_address.street = o.billing_address.street)
http://java.boot.by/bcd-guide/ch09s02.html 2 / 4 2004/6/12 11:58:03

Identify correct and incorrect statements or examples about the purpose and use of EJB QL.

If the Bean Provider uses a single entity bean in two different relationships for both the shipping address and the billing address, the above expression can be rewritten as:

SELECT OBJECT(o) FROM Order o WHERE o.shipping_address <> o.billing_address

Find all orders for a book titled 'Head First EJB':

SELECT DISTINCT OBJECT(o) FROM Order o, IN(o.lineItems) l WHERE l.product.type = 'book' AND l.product.name = 'Head First EJB'

The following query finds the orders for a product whose name is designated by an input parameter (the input parameter must be of the type of the product name, i.e., a String):

SELECT DISTINCT OBJECT(o) FROM Order o, IN(o.lineItems) l WHERE l.product.name = ?1

The following EJB QL query selects the names of all products that have been ordered. It illustrates the selection of values other than entity beans, therefore it can be used only for SELECT methods, not for FINDER methods:

SELECT DISTINCT l.product.name FROM Order o, IN(o.lineItems) l

The following query finds the names of all products in the order specified by a particular order number.

SELECT l.product.name FROM Order o, IN(o.lineItems) l WHERE o.ordernumber = ?1


http://java.boot.by/bcd-guide/ch09s02.html 3 / 4 2004/6/12 11:58:03

Identify correct and incorrect statements or examples about the purpose and use of EJB QL.

The following query returns the names of all the cities of the shipping addresses of all orders. The result type of the SELECT method, which is either java.util.Collection or java.util.Set, determines whether the query may return duplicate city names.

SELECT o.shipping_address.city FROM Order o

Prev Chapter 9. EJB-QL

Up

Next Identify correct and incorrect conditional expressions, BETWEEN expressions, IN expressions, LIKE expressions, and comparison expressions.

Home

http://java.boot.by/bcd-guide/ch09s02.html 4 / 4 2004/6/12 11:58:03

Identify correct and incorrect conditional expressions, BETWEEN exp...ons, IN expressions, LIKE expressions, and comparison expressions.

Identify correct and incorrect conditional expressions, BETWEEN expressions, IN expressions, LIKE expressions, and comparison expressions. Prev Chapter 9. EJB-QL Next

Identify correct and incorrect conditional expressions, BETWEEN expressions, IN expressions, LIKE expressions, and comparison expressions.
Conditional expressions Conditional expressions are composed of other conditional expressions, comparison operations, logical operations, path expressions that evaluate to boolean values, and boolean literals. Arithmetic expressions can be used in comparison expressions. Arithmetic expressions are composed of other arithmetic expressions, arithmetic operations, path expressions that evaluate to numeric values, and numeric literals. Arithmetic operations use Java numeric promotion. Standard bracketing () for ordering expression evaluation is supported. BETWEEN expressions The syntax for the use of the comparison operator [NOT] BETWEEN in an conditional expression is as follows: arithmetic_expression [NOT] BETWEEN arithmetic-expr AND arithmetic-expr

p.age BETWEEN 15 AND 19

is equivalent to

p.age >= 15 AND p.age <= 19

p.age NOT BETWEEN 15 AND 19


http://java.boot.by/bcd-guide/ch09s03.html 1 / 4 2004/6/12 11:58:06

Identify correct and incorrect conditional expressions, BETWEEN exp...ons, IN expressions, LIKE expressions, and comparison expressions.

is equivalent to

p.age < 15 OR p.age > 19

IN expressions The syntax for the use of the comparison operator [NOT] IN in a conditional expression is as follows: single_valued_path_expression [NOT] IN (string-literal [, string-literal]* ) The single_valued_path_expression must have a String value.

o.country IN ('UK', 'US', 'BY')

is equivalent to

(o.country = 'UK') OR (o.country = 'US') OR (o.country = 'BY')

o.country NOT IN ('UK', 'US', 'BY')

is equivalent to

NOT ((o.country = 'UK') OR (o.country = 'US') OR (o.country = 'BY'))

LIKE expressions The syntax for the use of the comparison operator [NOT] LIKE in a conditional expression is as follows: single_valued_path_expression [NOT] LIKE pattern-value [ESCAPE escape-character]
http://java.boot.by/bcd-guide/ch09s03.html 2 / 4 2004/6/12 11:58:06

Identify correct and incorrect conditional expressions, BETWEEN exp...ons, IN expressions, LIKE expressions, and comparison expressions.

The single_valued_path_expression must have a String value. The pattern-value is a string literal in which an underscore (_) stands for ANY SINGLE character, a percent (%) character stands for ANY SEQUENCE of characters (including the empty sequence), and all other characters stand for themselves. The optional escape-character is a single character string literal and is used to escape the special meaning of the underscore and percent characters in pattern-value.

address.phone LIKE '12%3'

TRUE for '123' '12993', FALSE for '1234'.

asentence.word LIKE 'l_se'

TRUE for 'lose', FALSE for 'loose'.

aword.underscored LIKE '\_%' ESCAPE '\'

TRUE for '_foo', FALSE for 'bar'.

address.phone NOT LIKE '12%3'

TRUE for '1234', FALSE for '123' and '12993'. NOTE, input parameters CANNOT be used in LIKE expression. NULL comparison expressions The syntax for the use of the comparison operator IS NULL in a conditional expression is as follows: single_valued_path_expression IS [NOT ] NULL A null comparison expression tests whether or not the single valued path expression is a NULL value. Path expressions containing NULL values during evaluation return NULL values. EMPTY collection comparison expressions

http://java.boot.by/bcd-guide/ch09s03.html 3 / 4 2004/6/12 11:58:06

Identify correct and incorrect conditional expressions, BETWEEN exp...ons, IN expressions, LIKE expressions, and comparison expressions.

The syntax for the use of the comparison operator IS EMPTY in an empty_collection_comparison_expression is as follows: collection_valued_path_expression IS [NOT] EMPTY This expression tests whether or not the collection designated by the collection-valued path expression is empty (i.e, has no elements). The collection designated by the collection-valued path expression used in an empty collection comparison expression MUST NOT be used in the FROM clause for the declaration of an identification variable. An identification variable declared as a member of a collection IMPLICITLY designates the existence of a non-empty relationship; testing whether the same collection is empty is CONTRADICTORY. Collection member expressions The syntax for the use of the comparison operator MEMBER OF in an collection_member_expression is as follows: {single_valued_navigation | identification_variable | input_parameter } [NOT] MEMBER [OF] collection_valued_path_expression This expression tests whether the designated value is a member of the collection specified by the collection-valued path expression. String Functions:

CONCAT(String, String) returns a String SUBSTRING(String, start, length) returns a String LOCATE(String, String [, start]) returns an int LENGTH(String) returns an int

Arithmetic Functions:

ABS(number) returns a number (int, float, or double) SQRT(double) returns a double

Prev Identify correct and incorrect statements or examples about the purpose and use of EJB QL.

Up Home

Next Chapter 10. Message-Driven Bean Component Contract

http://java.boot.by/bcd-guide/ch09s03.html 4 / 4 2004/6/12 11:58:06

Chapter 10. Message-Driven Bean Component Contract

Chapter 10. Message-Driven Bean Component Contract Prev Part I. Exam Objectives Next

Chapter 10. Message-Driven Bean Component Contract

Identify correct and incorrect statements or examples about the client view of a messagedriven bean, and the life cycle of a message-driven bean.
To a client, a message-driven bean is simply a JMS message consumer. The client sends messages to the Destination (Queue or Topic) for which the message-driven bean is the MessageListener just as it would to any other Destination. The message-driven bean, like any other JMS message consumer, handles the processing of the messages. From the perspective of the client, the existence of a message-driven bean is completely hidden behind the JMS destination for which the message-driven bean is the message listener. A client locates the JMS Destination associated with a message-driven bean by using JNDI. For example, the Queue for the StockInfo message-driven bean can be located using the following code segment:

Context initialContext = new InitialContext(); Queue stockInfoQueue = (javax.jms.Queue)initialContext.lookup ("java:comp/env/jms/stockInfoQueue");

Message-driven beans don't have home/local home and remote/local interfaces. A client's JNDI name space may be configured to include the JMS Destinations of messagedriven 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. When a client sends a message to a Destination for which a message-driven bean is the consumer, the container selects one of its METHOD-READY instances and invokes the instance's onMessage method. The following steps describe the lifecyle of a message-driven bean instance:

A message-driven bean instance's life starts when the container invokes newInstance() on the message-driven bean class to create a new instance. Next, the container calls setMessageDrivenContext(...) followed by ejbCreate() on the instance. The message-driven bean instance is now READY to be delivered a message sent to its

http://java.boot.by/bcd-guide/ch10.html 1 / 3 2004/6/12 11:58:08

Chapter 10. Message-Driven Bean Component Contract

Destination by any client. When the CONTAINER no longer needs the instance (which usually happens 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 message-driven bean instance.

The table defines the methods of a message-driven bean class in which the message-driven bean instances can access the methods of the javax.ejb.MessageDrivenContext interface, the java: comp/env environment naming context, resource managers, and other enterprise beans. Table 10.1. Operations allowed in the methods of a message-driven bean class
Bean method can perform the following operations Bean method Container-managed transaction demarcation JNDI access to java:comp/env JNDI access to java:comp/env JNDI access to java:comp/env MessageDrivenContext methods: getUserTransaction() JNDI access to java:comp/env MessageDrivenContext methods: getRollbackOnly(), setRollbackOnly () JNDI access to java:comp/env Resource manager access Enterprise bean access JNDI access to java:comp/env Resource manager access Enterprise bean access MessageDrivenContext methods: getUserTransaction() UserTransaction methods onMessage() Bean-managed transaction demarcation

constructor setMessageDrivenContext ejbCreate() ejbRemove()

Additional restrictions:

The getRollbackOnly() and setRollbackOnly() methods of the MessageDrivenContext interface should be used ONLY in the message-driven 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 the table:

Invoking the getCallerPrincipal() and isCallerInRole(...) methods is DISALLOWED in the

http://java.boot.by/bcd-guide/ch10.html 2 / 3 2004/6/12 11:58:08

Chapter 10. Message-Driven Bean Component Contract

message-driven bean methods because the Container DOES NOT HAVE a client security context. The Container MUST throw and log the java.lang.IllegalStateException if either of these methods is invoked. Invoking the getRollbackOnly() and setRollbackOnly() methods is DISALLOWED in the message-driven bean methods for which the Container DOES NOT HAVE a meaningful transaction context, and for all message-driven beans with bean-managed transaction demarcation (BMT). The UserTransaction interface is UNAVAILABLE to message-driven beans with containermanaged transaction demarcation (CMT). Invoking getEJBHome() or getEJBLocalHome() is DISALLOWED in message-driven bean methods because THERE ARE NO EJBHome or EJBLocalHome objects for message-driven beans. The Container MUST throw and log the java.lang.IllegalStateException if these methods are invoked.

Prev Identify correct and incorrect conditional expressions, BETWEEN expressions, IN expressions, LIKE expressions, and comparison expressions.

Up Home

Next Identify the interfaces and methods a JMS message-driven bean must implement.

http://java.boot.by/bcd-guide/ch10.html 3 / 3 2004/6/12 11:58:08

Identify the interfaces and methods a JMS message-driven bean must implement.

Identify the interfaces and methods a JMS message-driven bean must implement. Prev Chapter 10. Message-Driven Bean Component Contract Next

Identify the interfaces and methods a JMS message-driven bean must implement.
All message-driven beans MUST implement, directly or indirectly, the MessageDrivenBean interface. The class MUST be defined as public and it cannot be defined as final nor abstract. The MessageDrivenBean interface defines TWO methods all message-driven beans must implement: 1. The setMessageDrivenContext(...) method is called by the bean's container to associate a message-driven bean instance with its context maintained by the container. Typically a message-driven bean instance retains its message-driven context as part of its state. The container calls this method at the beginning of the bean's life cycle. 2. The ejbRemove() notification signals that the instance is in the process of being removed by the container. In the ejbRemove() method, the instance releases the resources that it is holding (possibly allocated in the ejbCreate() method). The Bean Provider CANNOT assume that the Container will always invoke the ejbRemove() method on a message-driven 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.

If the message-driven bean instance allocates resources in the ejbCreate() method and/or in the onMessage(...) method, and releases normally the resources in the ejbRemove() method, these resources will NOT be automatically released in the above scenarios. The application using the message-driven bean should provide some clean up mechanism to periodically clean up the unreleased resources. The MessageDrivenBean extends the EnterpriseBean interface:

package javax.ejb; public interface MessageDrivenBean extends javax.ejb.EnterpriseBean { public void setMessageDrivenContext(MessageDrivenContext context) throws EJBException; public void ejbRemove() throws EJBException; } public interface EnterpriseBean extends java.io.Serializable { }

http://java.boot.by/bcd-guide/ch10s02.html 1 / 4 2004/6/12 11:58:14

Identify the interfaces and methods a JMS message-driven bean must implement.

All message-driven beans MUST implement, directly or indirectly, the javax.jms.MessageListener interface. The onMessage(...) method is called by the bean's CONTAINER when a message has arrived for the bean to service. The onMessage(...) method contains the business logic that handles the processing of the message. The onMessage(...) method has a single argument, the incoming message. ONLY message-driven beans can asynchronously receive messages. Session and entity beans are NOT PERMITTED to be JMS MessageListeners.

package javax.jms; public interface MessageListener { public void onMessage(Message message); }

The container creates an instance of a message-driven bean in THREE steps. First, the container calls the bean class' newInstance() method to create a new message-driven bean instance. Second, the container calls the setMessageDrivenContext(...) method to pass the context object to the instance. Third, the container calls the instance's ejbCreate() method. Each message-driven bean class MUST have one ejbCreate() method, with NO ARGUMENTS. EVERY message-driven bean class MUST implement following FOUR methods: 1. public void setMessageDrivenContext(MessageDrivenContext mdc) The container normally calls this method exactly once, after instantiation, to pass in the associated MessageDrivenContext. 2. public void ejbCreate() Called after the setMessageDrivenContext(...) method. This is a good time to access or obtain any resources that will be used for the life of the bean. 3. public void onMessage(Message msg) Called by the container when a message has arrived on the bean's associated Queue or Topic. Your code should check for the expected message types, using the instanceof operator, because there is nothing to stop a client from sending any of the available message types. Other than those that deal with the Message object, no JMS methods need be invoked by the bean; it just cracks or parses the received message and performs any associated operations.

http://java.boot.by/bcd-guide/ch10s02.html 2 / 4 2004/6/12 11:58:14

Identify the interfaces and methods a JMS message-driven bean must implement.

4. public void ejbRemove() Called when the container intends to terminate the bean. All resources should be released at this time.

public class ReservationProcessorBean implements javax.ejb.MessageDrivenBean, javax.jms.MessageListener { MessageDrivenContext ejbContext; Context jndiContext; public void setMessageDrivenContext (MessageDrivenContext mdc) { ejbContext = mdc; try { jndiContext = new InitialContext (); } catch(NamingException ne) { throw new EJBException (ne); } } public void ejbCreate () {} public void onMessage (Message message) { try { MapMessage reservationMsg = (MapMessage)message; Integer customerPk = (Integer) reservationMsg.getObject ("CustomerID"); Integer cruisePk = (Integer) reservationMsg.getObject ("CruiseID"); .... // can access other EJBs ReservationHomeLocal resHome = (ReservationHomeLocal) jndiContext.lookup ("java:comp/env/ejb/ReservationHomeLocal"); ReservationLocal reservation = resHome.create (customer, cruise, cabin, price, new Date ()); .... } catch(Exception e) { // can throw only runtime (unchecked) exceptions throw new EJBException (e);

http://java.boot.by/bcd-guide/ch10s02.html 3 / 4 2004/6/12 11:58:14

Identify the interfaces and methods a JMS message-driven bean must implement.

} } ... public void ejbRemove () { try { jndiContext.close (); ejbContext = null; } catch(NamingException ignored) { } } }

Prev Chapter 10. Message-Driven Bean Component Contract

Up Home

Next Identify the use and behavior of the MessageDrivenContext interface methods.

http://java.boot.by/bcd-guide/ch10s02.html 4 / 4 2004/6/12 11:58:14

Identify the use and behavior of the MessageDrivenContext interface methods.

Identify the use and behavior of the MessageDrivenContext interface methods. Prev Chapter 10. Message-Driven Bean Component Contract Next

Identify the use and behavior of the MessageDrivenContext interface methods.


The container provides the message-driven bean instance with a MessageDrivenContext. This gives the message-driven bean instance access to the instance's context maintained by the container. The MessageDrivenContext interface has the following methods:

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 message-driven bean with container-managed transaction (CMT) 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 message-driven bean with container-managed transaction (CMT) demarcation can use this method. The getUserTransaction method returns the javax.transaction.UserTransaction interface that the instance can use to demarcate transactions, and to obtain transaction status. ONLY instances of a message-driven bean with bean-managed transaction (BMT) demarcation can use this method. The getCallerPrincipal method is inherited from the EJBContext interface. Message-driven bean instances MUST NOT call this method (caller is unknown for MDB). The isCallerInRole method is inherited from the EJBContext interface. Message-driven bean instances MUST NOT call this method (caller is unknown for MDB). The getEJBHome and getEJBLocalHome methods are inherited from the EJBContext interface. Message-driven bean instances MUST NOT call these methods (MDB has no home/local-home interfaces, as well do not have component interfaces).

package javax.ejb; public interface MessageDrivenContext extends EJBContext { } public interface EJBContext { EJBHome getEJBHome(); EJBLocalHome getEJBLocalHome(); java.security.Principal getCallerPrincipal(); boolean isCallerInRole(String roleName); UserTransaction getUserTransaction() throws IllegalStateException; void setRollbackOnly() throws IllegalStateException; boolean getRollbackOnly() throws IllegalStateException; }

http://java.boot.by/bcd-guide/ch10s03.html 1 / 2 2004/6/12 11:58:16

Identify the use and behavior of the MessageDrivenContext interface methods.

Prev Identify the interfaces and methods a JMS message-driven bean must implement.

Up Home

Next From a list, identify the responsibility of the bean provider and the responsibility of the container provider for a messagedriven bean.

http://java.boot.by/bcd-guide/ch10s03.html 2 / 2 2004/6/12 11:58:16

From a list, identify the responsibility of the bean provider and the responsibility of the container provider for a message-driven bean.

From a list, identify the responsibility of the bean provider and the responsibility of the container provider for a message-driven bean. Prev Chapter 10. Message-Driven Bean Component Contract Next

From a list, identify the responsibility of the bean provider and the responsibility of the container provider for a message-driven bean.
Bean Provider responsibility The message-driven bean provider is responsible for providing message-driven bean class. The following are the requirements for the message-driven bean class:

The class MUST implement, directly or indirectly, the javax.ejb.MessageDrivenBean interface. The class MUST implement, directly or indirectly, the javax.jms.MessageListener 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 arguments. The Container uses this constructor to create instances of the message-driven bean class. The class MUST NOT define the finalize() method. The class MUST implement the ejbCreate() method (it can be empty). The message-driven bean class may have superclasses and/or superinterfaces. If the message-driven bean has superclasses, the ejbCreate method, and the methods of the MessageDrivenBean and MessageListener interfaces may be defined in the message-driven bean class or in any of its superclasses. The message-driven bean class is allowed to implement other methods (for example, helper methods invoked internally by the onMessage method) in addition to the methods required by the EJB specification.

The message-driven bean class MUST define ONE ejbCreate() method whose signature must follow these rules:

The The The The The The

method name MUST be ejbCreate. method MUST be declared as public. method MUST NOT be declared as final or static. return type MUST be void. method MUST HAVE NO arguments. throws clause MUST NOT define any APPLICATION exceptions.

The message-driven bean class MUST define ONE onMessage method whose signature must follow these rules:

The The The The The

method MUST be declared as public. method MUST NOT be declared as final or static. return type MUST be void. method MUST HAVE a single argument of type javax.jms.Message. throws clause MUST NOT define any APPLICATION exceptions.

http://java.boot.by/bcd-guide/ch10s04.html 1 / 2 2004/6/12 11:58:19

From a list, identify the responsibility of the bean provider and the responsibility of the container provider for a message-driven bean.

The message-driven bean class MUST define ONE ejbRemove() method whose signature must follow these rules:

The The The The The The

method name MUST be ejbRemove. method MUST be declared as public. method MUST NOT be declared as final or static. return type MUST be void. method MUST HAVE NO arguments. throws clause MUST NOT define any APPLICATION exceptions.

Container Provider responsibility The container provider must support the deployment of a message-driven bean as the consumer of a JMS queue or a durable subscription. The container must ensure that ONLY ONE thread can be executing an instance at any time. The container must follow the rules with respect to transaction scoping, security checking, and exception handling.

Prev Identify the use and behavior of the MessageDrivenContext interface methods.

Up Home

Next Chapter 11. Transactions

http://java.boot.by/bcd-guide/ch10s04.html 2 / 2 2004/6/12 11:58:19

Chapter 11. Transactions

Chapter 11. Transactions Prev Part I. Exam Objectives Next

Chapter 11. Transactions

Identify correct and incorrect statements or examples about EJB transactions, including bean-managed transaction demarcation and container-managed transaction demarcation.
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. 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 (BMT) demarcation, the enterprise bean code demarcates transactions using the javax.transaction.UserTransaction interface. All resource manager accesses between the UserTransaction.begin() and UserTransaction.commit() calls are part of a transaction.

package javax.transaction; public interface UserTransaction { public void begin() throws NotSupportedException, SystemException; public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException; public void rollback() throws IllegalStateException, SecurityException, SystemException; public void setRollbackOnly() throws IllegalStateException, SystemException;
http://java.boot.by/bcd-guide/ch11.html 1 / 6 2004/6/12 11:58:22

Chapter 11. Transactions

public int getStatus() throws SystemException; public void setTransactionTimeout (int seconds) throws SystemException; }

The terms "resource" and "resource manager" refer to the resources declared in the enterprise bean's deployment descriptor using the resource-ref element. This includes not only database resources, but also JMS Connections. These resources are considered to be "managed" by the Container. With container-managed transaction (CMT) 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". The Enterprise JavaBeans architecture supports FLAT transactions. A flat transaction cannot have any child (nested) transactions. The EJB architecture DOES NOT require the EJB Container to support the JTS interfaces. The EJB architecture REQUIRES that the EJB Container support the JTA API. 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 or a Message-driven Bean can be designed with bean-managed transaction (BMT) demarcation OR with container-managed transaction (CMT) demarcation. (But it CANNOT be both at the same time.) An Entity Bean MUST ALWAYS be designed with container-managed transaction (CMT) 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. An entity bean with container-managed persistence can access its persistent state in a transaction ONLY in the enterprise bean's methods in which there is a TRANSACTION CONTEXT available. 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.

http://java.boot.by/bcd-guide/ch11.html 2 / 6 2004/6/12 11:58:22

Chapter 11. Transactions

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 containermanaged 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. Requirements for the Bean Provider of an enterprise bean with bean-managed transaction (BMT) demarcation. The enterprise bean with bean-managed transaction demarcation MUST be a Session bean or a Message-driven bean (NOT Entity bean).

<ejb-jar> <enterprise-beans> <session> <ejb-name>CompanySearch</ejb-name> <home>com.ejb.CompanySearchHome</home> <remote>com.ejb.CompanySearch</remote> <ejb-class>com.ejb.CompanySearchEJB</ejb-class> <session-type>Stateless</session-type> <transaction-type>Bean</transaction-type> <resource-ref> <res-ref-name>jdbc/mydb</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </session> ... </enterprise-beans> ... </ejb-jar>

NOTE, Entity beans declarations DO NOT have transaction-type element, since all of them use CMT ONLY. 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
http://java.boot.by/bcd-guide/ch11.html 3 / 6 2004/6/12 11:58:22

Chapter 11. Transactions

invoke the commit() or rollback() method on the java.sql.Connection interface or on the javax.jms. Session 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. A STATELESS session bean instance MUST COMMIT a transaction before a business method returns. A message-driven bean instance MUST COMMIT a transaction before the onMessage method returns. 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 rollback a transaction using the rollback() method of the javax.transaction.UserTransaction interface.

NOTE, that method setRollbackOnly() exists in BOTH interfaces javax.transaction.UserTransaction AND javax.ejb.EJBContext. The following code illustrates the use of JTA interface to specify transactions in an enterprise bean with bean-managed transaction demarcation:

UserTransaction ut = ejbContext.getUserTransaction(); ut.begin(); // Transactional work is done here ut.commit();

or

Context ctx = new InitialContext(); UserTransaction ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction"); try { ut.begin();

http://java.boot.by/bcd-guide/ch11.html 4 / 6 2004/6/12 11:58:22

Chapter 11. Transactions

//Do some work... ut.commit(); } catch(Exception e) { ut.rollback(); }

NOTE, javax:comp/UserTransaction is a standard JNDI name used to look up a user transaction object in a J2EE container. The begin() and commit() method calls can be in SEPARATE methods (only for STATEFUL session beans). Just perform an additional lookup in your new method to obtain a handle on the SAME javax.transaction.UserTransaction object associated with this session. Requirements for the Bean Provider of an enterprise bean with container-managed transaction (CMT) demarcation. The enterprise bean's business methods or onMessage(...) method MUST NOT use any resourcemanager 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() or the following methods of the javax.jms.Session interface: commit() and rollback(). The enterprise bean's business methods or onMessage(...) method must not attempt to obtain or use the javax.transaction.UserTransaction interface. A STATEFUL Session Bean with container-managed transaction demarcation can optionally implement the javax.ejb.SessionSynchronization interface. 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 rollback the transaction. 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 of the EJB specification scope) of the transaction processing infrastructure.

Prev

Up

Next

http://java.boot.by/bcd-guide/ch11.html 5 / 6 2004/6/12 11:58:22

Chapter 11. Transactions

From a list, identify the responsibility of the bean provider and the responsibility of the container provider for a messagedriven bean.

Home

Identify correct and incorrect statements about the Application Assembler's responsibilities, including the use of deployment descriptor elements related to transactions and the identification of the methods of a particular bean type for which a transaction attribute must be specified.

http://java.boot.by/bcd-guide/ch11.html 6 / 6 2004/6/12 11:58:22

Identify correct and incorrect statements about the Application Assemb...icular bean type for which a transaction attribute must be specified.

Identify correct and incorrect statements about the Application Assembler's responsibilities, including the use of deployment descriptor elements related to transactions and the identification of the methods of a particular bean type for which a transaction attribute must be specified. Prev Chapter 11. Transactions Next

Identify correct and incorrect statements about the Application Assembler's responsibilities, including the use of deployment descriptor elements related to transactions and the identification of the methods of a particular bean type for which a transaction attribute must be specified.
There is NO mechanism for an Application Assembler to affect enterprise beans with beanmanaged transaction (BMT) 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 to manage transaction demarcation for enterprise beans using container-managed transaction demarcation. NOTE, the transaction attributes may be specified either by the Bean Provider or by the Application Assembler. The Application Assembler uses the container-transaction elements to define the transaction attributes for the methods of session and entity bean home and component interfaces and for the onMessage methods of message-driven beans. 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.

</ejb-jar> ... <container-transaction> <method> <ejb-name>Employee</ejb-name> <method-intf>LocalHome</method-intf> <method-name>create</method-name> <method-params> <method-param>java.lang.String</method-param> </method-params> </method> <trans-attribute>Required</trans-attribute> </container-transaction> <container-transaction> <method>
http://java.boot.by/bcd-guide/ch11s02.html 1 / 4 2004/6/12 11:58:26

Identify correct and incorrect statements about the Application Assemb...icular bean type for which a transaction attribute must be specified.

<ejb-name>Employee</ejb-name> <method-intf>LocalHome</method-intf> <method-name>findAll</method-name> <method-params /> </method> <trans-attribute>Supports</trans-attribute> </container-transaction> ... </ejb-jar>

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 component interfaces. There are THREE legal styles of composing the method element:

<!-- Style 1 --> <method> <ejb-name>EJBName</ejb-name> <method-name>*</method-name> </method>

<!-- Style 2 --> <method> <ejb-name>EJBName</ejb-name> <method-name>MethodName</method-name> </method>

<!-- Style 3 --> <method> <ejb-name>EJBName</ejb-name> <method-name>MethodName</method-name> <method-params> <method-param>ParameterType_1</method-param> ... <method-param>ParameterType_N</method-param>

http://java.boot.by/bcd-guide/ch11s02.html 2 / 4 2004/6/12 11:58:26

Identify correct and incorrect statements about the Application Assemb...icular bean type for which a transaction attribute must be specified.

</method-params> </method>

Style 2 element takes precedence over Style 1 element. Style 3 element takes precedence over Style 2 and Style 1 elements. The optional method-intf element can be used to differentiate between methods with the same name and signature that are multiply defined across the component and/or home interfaces (must be one of the following: Home, Remote, LocalHome, Local). 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>
http://java.boot.by/bcd-guide/ch11s02.html 3 / 4 2004/6/12 11:58:26

Identify correct and incorrect statements about the Application Assemb...icular bean type for which a transaction attribute must be specified.

<trans-attribute>RequiresNew</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar>

Prev Chapter 11. Transactions

Up Home

Next Given a list of transaction behaviors, match them with the appropriate transaction attributes.

http://java.boot.by/bcd-guide/ch11s02.html 4 / 4 2004/6/12 11:58:26

Given a list of transaction behaviors, match them with the appropriate transaction attributes.

Given a list of transaction behaviors, match them with the appropriate transaction attributes. Prev Chapter 11. Transactions Next

Given a list of transaction behaviors, match them with the appropriate transaction attributes.
A transaction attribute is a value associated with a method of a session or entity bean's home or component interface or with the onMessage(...) method of a message-driven bean. The transaction attribute specifies how the Container must manage transactions for a method when a client invokes the method via the enterprise bean's home or component interface or when the method is invoked as the result of the arrival of a JMS message. The transaction attribute must be specified for the following methods:

For a SESSION bean, the transaction attributes MUST be specified for the methods defined in the bean's COMPONENT interface and all the direct and indirect superinterfaces of the component interface, excluding the methods of the javax.ejb.EJBObject or javax.ejb. EJBLocalObject 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 COMPONENT interface and all the direct and indirect superinterfaces of the component interface, excluding the getEJBHome, getEJBLocalHome, 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 specific to the remote home interface (remove, create, and find methods can all have transaction attributes). For a MESSAGE-DRIVEN bean, the transaction attribute MUST be specified for the bean's onMessage(...) method.

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 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 (SIX) values for the transaction attribute:

NotSupported Required Supports RequiresNew Mandatory Never

For MESSAGE-DRIVEN beans, ONLY the Required and NotSupported transaction attributes may be
http://java.boot.by/bcd-guide/ch11s03.html 1 / 5 2004/6/12 11:58:29

Given a list of transaction behaviors, match them with the appropriate transaction attributes.

used. For ENTITY beans that use EJB 2.0 container-managed persistence, only the Required, RequiresNew, or Mandatory transaction attributes should be used for the methods defined in the bean's component interface and all the direct and indirect superinterfaces of the component interface, excluding the getEJBHome, getEJBLocalHome, 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 specific to the remote home interface. Containers may optionally support the use of the NotSupported, Supports, and Never transaction attributes for the methods of entity beans with container-managed persistence. However, entity beans with container-managed persistence that use these transaction attributes WILL NOT BE PORTABLE. 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. This 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. Container-managed transaction demarcation for Session and Entity Beans.

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

http://java.boot.by/bcd-guide/ch11s03.html 2 / 5 2004/6/12 11:58:29

Given a list of transaction behaviors, match them with the appropriate transaction attributes.

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. Supports The Container invokes an enterprise Bean method whose transaction attribute is set to Supports as follows:
r

If the client calls with a transaction context, the Container performs the same steps as described in the Required case (uses client's transaction). If the client calls without a transaction context, the Container performs the same steps as described in the NotSupported case (with an unspecified transaction context).

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

If the client calls with a transaction context, the Container performs the same steps as described in the Required case (uses client's transaction). If the client calls without a transaction context, the Container throws the javax. transaction.TransactionRequiredException exception if the client is a remote client, or the javax.ejb.TransactionRequiredLocalException if the client is a local client.

Never

http://java.boot.by/bcd-guide/ch11s03.html 3 / 5 2004/6/12 11:58:29

Given a list of transaction behaviors, match them with the appropriate transaction attributes.

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

If the client calls with a transaction context, the Container throws the java.rmi. RemoteException exception if the client is a remote client, or the javax.ejb. EJBException if the client is a local client. If the client calls without a transaction context, the Container performs the same steps as described in the NotSupported case (with an unspecified transaction context).

Container-managed transaction demarcation for Message-driven Beans. Only the NotSupported and Required transaction attributes may be used for message-driven beans. The use of the other transaction attributes is not meaningful for message-driven beans because there can be no pre-existing transaction context (RequiresNew, Supports) and no client to handle exceptions (Mandatory, Never).

NotSupported The Container invokes a message-driven Bean method whose transaction attribute is set to NotSupported with an unspecified transaction context. If the onMessage(...) method invokes other enterprise beans, the Container passes NO transaction context with the invocation. Required The Container must invoke a message-driven Bean method whose transaction attribute is set to Required with a valid transaction context. Because there is never a client transaction context available for a message-driven bean, the container automatically starts a new transaction before the dequeuing of the JMS message and, hence, before the invocation of the message-driven bean's onMessage(...) method. The Container automatically enlists the resource manager associated with the arriving message and all the resource managers accessed by the onMessage(...) method with the transaction. If the onMessage(...) method invokes other enterprise beans, the Container passes the transaction context with the invocation. The Container ATTEMPTS TO COMMIT the transaction when the onMessage (...) method has completed. If the onMessage(...) method does not successfully complete or the transaction is rolled back by the Container, JMS message redelivery semantics apply.

Table 11.1. Transaction attribute summary


Transaction associated with business method none Transaction associated with resource managers none

Transaction attribute

Client's transaction none

NotSupported
http://java.boot.by/bcd-guide/ch11s03.html 4 / 5 2004/6/12 11:58:29

Given a list of transaction behaviors, match them with the appropriate transaction attributes.

T1 none Required T1 none Supports T1 none RequiresNew T1 none Mandatory T1 none Never T1

none T2 T1 none T1 T2 T2 ERROR T1 none ERROR

none T2 T1 none T1 T2 T2 n/a T1 none n/a

Prev Identify correct and incorrect statements about the Application Assembler's responsibilities, including the use of deployment descriptor elements related to transactions and the identification of the methods of a particular bean type for which a transaction attribute must be specified.

Up

Next Given a list of responsibilities, identify whose which are the Container's with respect to transactions, including the handling of getRollbackOnly, setRollbackOnly, getUserTransaction, SessionSynchronzation callbacks, for both container and bean-managed transactions.

Home

http://java.boot.by/bcd-guide/ch11s03.html 5 / 5 2004/6/12 11:58:29

Given a list of responsibilities, identify whose which are the Contain...ronzation callbacks, for both container and bean-managed transactions.

Given a list of responsibilities, identify whose which are the Container's with respect to transactions, including the handling of getRollbackOnly, setRollbackOnly, getUserTransaction, SessionSynchronzation callbacks, for both container and bean-managed transactions. Prev Chapter 11. Transactions Next

Given a list of responsibilities, identify whose which are the Container's with respect to transactions, including the handling of getRollbackOnly, setRollbackOnly, getUserTransaction, SessionSynchronzation callbacks, for both container and beanmanaged transactions.
Bean-managed transaction demarcation (BMT) NOTE, only Session and Message-driven 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 make the javax.transaction.UserTransaction interface available to the enterprise bean's business method or onMessage 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. 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 if the client is a remote client, or throw the javax.ejb.EJBException if the client is a local client.

If a message-driven bean instance starts a transaction in the onMessage method, it must commit the transaction before the onMessage method returns. The Container must detect the case in
http://java.boot.by/bcd-guide/ch11s04.html 1 / 3 2004/6/12 11:58:32

Given a list of responsibilities, identify whose which are the Contain...ronzation callbacks, for both container and bean-managed transactions.

which a transaction was started, but not completed, in the onMessage 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.

When an instance attempts to start a transaction using the begin() method of the javax.transaction. UserTransaction interface while the instance has not committed 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 beanmanaged transaction demarcation attempts to invoke the setRollbackOnly() or getRollbackOnly() method of the javax.ejb.EJBContext interface. Container-managed transaction demarcation (CMT) The Container must handle the EJBContext.setRollbackOnly() method invoked from a business method executing with the Required, RequiresNew, or Mandatory (for MDB - ONLY with Required) 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 (for MDB - ONLY with NotSupported) transaction attribute. The Container must handle the EJBContext.getRollbackOnly() method invoked from a business method executing with the Required, RequiresNew, or Mandatory (for MDB - ONLY with Required) transaction attribute. The Container must throw (and log - MDB ONLY) the java.lang.IllegalStateException if the EJBContext.getRollbackOnly() method is invoked from a business method executing with the Supports, NotSupported, or Never (for MDB - ONLY with NotSupported) transaction attribute. 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 (and log - MDB ONLY) the java.lang.IllegalStateException.

http://java.boot.by/bcd-guide/ch11s04.html 2 / 3 2004/6/12 11:58:32

Given a list of responsibilities, identify whose which are the Contain...ronzation callbacks, for both container and bean-managed transactions.

If a Session Bean (STATEFUL ONLY) 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 rollback. 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.

Prev Given a list of transaction behaviors, match them with the appropriate transaction attributes.

Up Home

Next Chapter 12. Exceptions

http://java.boot.by/bcd-guide/ch11s04.html 3 / 3 2004/6/12 11:58:32

Chapter 12. Exceptions

Chapter 12. Exceptions Prev Part I. Exam Objectives Next

Chapter 12. Exceptions

Identify correct and incorrect statements or examples about exception handling in EJB.
An APPLICATION EXCEPTION is an exception defined in the throws clause of a method of the enterprise Bean's home and component 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.

An application exception class MUST be a subclass (direct or indirect) of java.lang.Exception. An

http://java.boot.by/bcd-guide/ch12.html 1 / 2 2004/6/12 11:58:34

Chapter 12. Exceptions

application exception class MUST NOT be defined as a subclass of the java.lang.RuntimeException OR of the java.rmi.RemoteException. 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 rollback 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.

Prev Given a list of responsibilities, identify whose which are the Container's with respect to transactions, including the handling of getRollbackOnly, setRollbackOnly, getUserTransaction, SessionSynchronzation callbacks, for both container and bean-managed transactions.

Up

Next Given a list of responsibilities related to exceptions, identify those which are the bean provider's, and those which are the responsibility of the container provider. Be prepared to recognize responsibilities for which neither the bean provider or the container provider are responsible.

Home

http://java.boot.by/bcd-guide/ch12.html 2 / 2 2004/6/12 11:58:34

Given a list of responsibilities related to exceptions, identify those w...ch neither the bean provider or the container provider are responsible.

Given a list of responsibilities related to exceptions, identify those which are the bean provider's, and those which are the responsibility of the container provider. Be prepared to recognize responsibilities for which neither the bean provider or the container provider are responsible. Prev Chapter 12. Exceptions Next

Given a list of responsibilities related to exceptions, identify those which are the bean provider's, and those which are the responsibility of the container provider. Be prepared to recognize responsibilities for which neither the bean provider or the container provider are responsible.
The Bean Provider defines the APPLICATION exceptions [BUSINESS exceptions] in the throws clauses of the methods of the home and component 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 class MUST be a subclass (direct or indirect) of java.lang.Exception. An application exception class MUST NOT be defined as a subclass of the java.lang.RuntimeException, or of the java.rmi.RemoteException. These are reserved for SYSTEM exceptions. 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). The enterprise bean business method, onMessage method, or container callback method 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 exceptions, unexpected RemoteException from invocation of other enterprise beans, unexpected RuntimeException, JVM errors, and so on. Bean Providers MAY define subclasses of the standard EJB application exceptions and throw instances of the subclasses in the enterprise bean methods. A subclass will typically provide more information to the client that catches the exception. If the enterprise bean method encounters a SYSTEM-level exception or error that does not allow the method to successfully complete (failure to obtain a database connection, JNDI exceptions, unexpected RemoteException from invocation of other enterprise beans, unexpected RuntimeException, JVM errors), the method should throw a suitable non-application exception that is compatible with the method's throws
http://java.boot.by/bcd-guide/ch12s02.html 1 / 3 2004/6/12 11:58:38

Given a list of responsibilities related to exceptions, identify those w...ch neither the bean provider or the container provider are responsible.

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 that the bean method CANNOT recover, the bean method should throw the javax.ejb.EJBException that wraps the original exception. 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 [SYSTEM] exception; logs it (which can result in ALERTING the SYSTEM Administrator); and, unless the bean is a message-driven bean, throws the java.rmi. RemoteException (or subclass thereof) to the client if the client is a REMOTE client, or throws the javax.ejb. EJBException (or subclass thereof) to the client if the client is a LOCAL 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 nonapplication [SYSTEM] exception. It is the Container that is responsible for the cleanup.

The NoSuchEntityException is a subclass of EJBException. It should be thrown by the ENTITY bean class
http://java.boot.by/bcd-guide/ch12s02.html 2 / 3 2004/6/12 11:58:38

Given a list of responsibilities related to exceptions, identify those w...ch neither the bean provider or the container provider are responsible.

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 COMPONENT interface.

Prev Chapter 12. Exceptions

Up Home

Next Identify correct and incorrect statements or examples about application exceptions and system exceptions in entity beans, session beans, and message-driven beans.

http://java.boot.by/bcd-guide/ch12s02.html 3 / 3 2004/6/12 11:58:38

Identify correct and incorrect statements or examples about applicatio... exceptions in entity beans, session beans, and message-driven beans.

Identify correct and incorrect statements or examples about application exceptions and system exceptions in entity beans, session beans, and message-driven beans. Prev Chapter 12. Exceptions Next

Identify correct and incorrect statements or examples about application exceptions and system exceptions in entity beans, session beans, and message-driven beans.
Table 12.1. Handling of exceptions thrown by a business method of a bean with containermanaged transaction demarcation (CMT)
Method condition Method exception APPLICATION exception Bean method runs in the context of the caller's transaction. This case may happen with Required, Mandatory, and Supports attributes.

Container's action re-throw APPLICATION exception

Client's view Receives APPLICATION exception. Can attempt to continue computation in the transaction, and eventually commit the transaction (the commit would fail if the instance called setRollbackOnly()). Receives javax.transaction. TransactionRolledbackException or javax.ejb. TransactionRolledbackLocalException Continuing transaction is fruitless.

SYSTEM exception

1. LOG the exception or error (to notify SYSTEM Administrator). 2. MARK the transaction for rollback. 3. DISCARD the instance. 4. Throw javax.transaction. TransactionRolledbackException to REMOTE client; throw javax.ejb. TransactionRolledbackLocalException to LOCAL client.

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.

APPLICATION exception

If the instance called setRollbackOnly(), then rollback the transaction, and re-throw APPLICATION exception. Otherwise, attempt to COMMIT the transaction, and then rethrow APPLICATION exception.

Receives APPLICATION exception. If the client executes in a transaction, the client's transaction is NOT marked for rollback, and client can continue its work. Receives RemoteException or EJBException. If the client executes in a transaction, the client's transaction MAY or MAY NOT be marked for rollback.

SYSTEM exception

1. LOG the exception or error (to notify SYSTEM Administrator). 2. ROLLBACK the container-started transaction. 3. DISCARD the instance. 4. Throw RemoteException to REMOTE client; throw EJBException to LOCAL client.

http://java.boot.by/bcd-guide/ch12s03.html 1 / 4 2004/6/12 11:58:41

Identify correct and incorrect statements or examples about applicatio... exceptions in entity beans, session beans, and message-driven beans.

Bean method runs with an UNSPECIFIED transaction context. This case may happen with the NotSupported, Never, and Supports attributes.

APPLICATION exception

re-throw APPLICATION exception

Receives APPLICATION exception. If the client executes in a transaction, the client's transaction is NOT marked for rollback, and client can continue its work. Receives RemoteException or EJBException. If the client executes in a transaction, the client's transaction MAY or MAY NOT be marked for rollback.

SYSTEM exception

1. LOG the exception or error (to notify SYSTEM Administrator). 2. DISCARD the instance. 3. Throw RemoteException to REMOTE client; throw EJBException to LOCAL client.

Table 12.2. Handling of exceptions thrown by a business method of a session with beanmanaged transaction demarcation (BMT)
Bean method condition Bean method exception APPLICATION exception SYSTEM exception Bean is STATEFUL or STATLESS Session.

Container's action re-throw APPLICATION exception

Client receives Receives APPLICATION exception. Receives RemoteException or EJBException.

1. LOG the exception or error (to notify SYSTEM Administrator). 2. MARK for rollback a transaction that has been started, but not yet completed, by the instance. 3. DISCARD the instance. 4. Throw RemoteException to REMOTE client; throw EJBException to LOCAL client.

Table 12.3. Handling of exceptions thrown by a method of a message-driven bean (MDB) with container-managed transaction demarcation (CMT).
Method condition Bean method runs in the context of a transaction that the Container started immediately before dispatching the method. This case happens with Required attribute. Method exception SYSTEM exception Container's action 1. LOG the exception or error (to notify SYSTEM Administrator). 2. Rollback the container-started a transaction. 3. DISCARD the instance.

http://java.boot.by/bcd-guide/ch12s03.html 2 / 4 2004/6/12 11:58:41

Identify correct and incorrect statements or examples about applicatio... exceptions in entity beans, session beans, and message-driven beans.

Bean method runs with an UNSPECIFIED transaction context. This case happens with the NotSupported attribute.

SYSTEM exception

1. LOG the exception or error (to notify SYSTEM Administrator). 2. DISCARD the instance.

Table 12.4. Handling of exceptions thrown by a method of a message-driven bean (MDB) with bean-managed transaction demarcation (BMT).
Bean method condition Bean method exception SYSTEM exception Bean is messagedriven bean (MDB)

Container's action 1. LOG the exception or error (to notify SYSTEM Administrator). 2. MARK for rollback a transaction that has been started, but not yet completed, by the instance. 3. DISCARD the instance.

If exception happens in callback method (EntityBean.ejbActivate(), EntityBean.ejbLoad(), EntityBean.ejbPassivate (), EntityBean.ejbStore(), EntityBean.setEntityContext(EntityContext), EntityBean.unsetEntityContext(), SessionBean. ejbActivate(), SessionBean.ejbPassivate(), SessionBean.setSessionContext(SessionContext), MessageDrivenBean. setMessageDrivenContext(MessageDrivenContext), SessionSynchronization.afterBegin(), SessionSynchronization. beforeCompletion(), and SessionSynchronization.afterCompletion(boolean)) the Container must handle all exception as follows: 1. 2. 3. 4. 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. If the exception or error happened during the processing of a client invoked method, throw the java. rmi.RemoteException to the client if the client is a REMOTE client or throw the javax.ejb.EJBException to the client if the client is a LOCAL client. If the instance executed IN the client's transaction, the Container should throw the javax.transaction.TransactionRolledbackException to a REMOTE client or the javax.ejb.TransactionRolledbackLocalException to a LOCAL client, because it provides more information to the client. (The client knows that it is fruitless to continue the transaction.)

If a client makes a call to a SESSION object that has been REMOVED, the Container should throw the java. rmi.NoSuchObjectException (which is a subclass of java.rmi.RemoteException) to a REMOTE client

, or the javax.ejb.NoSuchObjectLocalException to a local client.

http://java.boot.by/bcd-guide/ch12s03.html 3 / 4 2004/6/12 11:58:41

Identify correct and incorrect statements or examples about applicatio... exceptions in entity beans, session beans, and message-driven beans.

Prev Given a list of responsibilities related to exceptions, identify those which are the bean provider's, and those which are the responsibility of the container provider. Be prepared to recognize responsibilities for which neither the bean provider or the container provider are responsible.

Up

Next Given a particular method condition, identify the following: whether an exception will be thrown, the type of exception thrown, the container's action, and the client's view.

Home

http://java.boot.by/bcd-guide/ch12s03.html 4 / 4 2004/6/12 11:58:42

Given a particular method condition, identify the following: whether an...pe of exception thrown, the container's action, and the client's view.

Given a particular method condition, identify the following: whether an exception will be thrown, the type of exception thrown, the container's action, and the client's view. Prev Chapter 12. Exceptions Next

Given a particular method condition, identify the following: whether an exception will be thrown, the type of exception thrown, the container's action, and the client's view.
See previous section.

Prev Identify correct and incorrect statements or examples about application exceptions and system exceptions in entity beans, session beans, and message-driven beans.

Up

Next Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.

Home

http://java.boot.by/bcd-guide/ch12s04.html2004/6/12 11:58:44

Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.

Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation. Prev Chapter 12. Exceptions Next

Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.
A client accesses an enterprise Bean either through the enterprise Bean's remote home and remote interfaces or through the enterprise Bean's local home and local interfaces, depending on the client view that the enterprise bean provides and whether the client is a remote client or a local client. The remote home and remote interfaces are both 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. The local home and local interfaces are both Java local interfaces, and the throws clauses of all their methods (including those inherited from superinterfaces) MUST NOT include the java.rmi.RemoteException. The throws clauses MAY include an arbitrary number of application exceptions. Application exceptions

http://java.boot.by/bcd-guide/ch12s05.html 1 / 5 2004/6/12 11:58:48

Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.

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. 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. 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. System exceptions

http://java.boot.by/bcd-guide/ch12s05.html 2 / 5 2004/6/12 11:58:48

Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.

A remote client receives the java.rmi.RemoteException and a local client receives the javax.ejb.EJBException 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 or the javax.ejb.EJBException 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. 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 or an EJBException 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 rollback 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 rollback 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 or EJBException was thrown to the client, the commit will

http://java.boot.by/bcd-guide/ch12s05.html 3 / 5 2004/6/12 11:58:48

Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.

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. If a client receives the javax.transaction.TransactionRolledbackException

or the javax.ejb.TransactionRolledbackLocalException

, 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. The javax.transaction.TransactionRequiredException or javax.ejb.TransactionRequiredLocalException 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.

http://java.boot.by/bcd-guide/ch12s05.html 4 / 5 2004/6/12 11:58:48

Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.

The java.rmi.NoSuchObjectException is thrown to the client if a REMOTE business method cannot complete because the EJB object no longer exists.

The javax.ejb.NoSuchObjectLocalException is thrown to the client if a LOCAL business method cannot complete because the EJB object no longer exists.

Prev Given a particular method condition, identify the following: whether an exception will be thrown, the type of exception thrown, the container's action, and the client's view.

Up Home

Next Chapter 13. Enterprise Bean Environment

http://java.boot.by/bcd-guide/ch12s05.html 5 / 5 2004/6/12 11:58:48

Chapter 13. Enterprise Bean Environment

Chapter 13. Enterprise Bean Environment Prev Part I. Exam Objectives Next

Chapter 13. Enterprise Bean Environment

Identify correct and incorrect statements or examples about an enterprise bean's environment JNDI API naming.
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 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. 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.

<!-The env-entry element contains the declaration of an enterprise


http://java.boot.by/bcd-guide/ch13.html 1 / 5 2004/6/12 11:58:52

Chapter 13. Enterprise Bean Environment

bean's environment entry. The declaration consists of an optional description, the name of the environment entry, and an optional value. If a value is not specified, one must be supplied during deployment. Used in: entity, message-driven, and session --> <!ELEMENT env-entry (description?, env-entry-name, env-entry-type, env-entry-value?)>

An environment entry is scoped to the enterprise 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 enventry-name without causing a name conflict. The environment entry values may be one of the following Java types: String, Character, Integer, Boolean, Double, Byte, Short, Long, and Float. The environment entry value must be a string that is valid for the constructor of the specified type that takes a single String parameter, or for java.lang.Character, a single character. The ejb-ref element contains an optional description element; and the MANDATORY ejb-ref-name, ejb-ref-type (value must be either Entity or Session), home, and remote elements.

<!-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 enterprise bean that is referencing the enterprise bean; the expected type of the referenced enterprise bean; the expected home and remote interfaces of the referenced enterprise bean; and optional ejb-link information, used to specify the referenced enterprise bean. Used in: entity, message-driven, and session --> <!ELEMENT ejb-ref (description?, ejb-ref-name, ejb-ref-type, home, remote, ejb-link?)>

The ejb-local-ref element contains an optional description element; and the MANDATORY ejb-refname, ejb-ref-type (value must be either Entity or Session), local-home, and local elements.

http://java.boot.by/bcd-guide/ch13.html 2 / 5 2004/6/12 11:58:52

Chapter 13. Enterprise Bean Environment

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

The ejb-ref-name element specifies the EJB reference name; its value is the environment entry name used in the enterprise bean CODE. An EJB REFERENCE is scoped to the enterprise bean whose declaration contains the ejb-ref or ejblocal-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 and/or ejb-local-ref elements with the same ejb-ref-name without causing a name conflict. 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. Each resource-ref element describes a single resource manager connection factory reference. The resource-ref element consists of the description element; the THREE mandatory res-ref-name, restype, and res-auth elements; and the optional res-sharing-scope element. The res-ref-name element contains the name of the environment entry used in the enterprise bean's CODE. The name of the environment entry is relative to the java:comp/env context (e.g., the name should be jdbc/ EmployeeAppDB rather than java:comp/env/jdbc/EmployeeAppDB). The res-type element contains the Java type of the resource manager connection FACTORY. 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. The res-sharing-scope element indicates whether connections to the resource manager obtained through the given resource manager connection factory reference can be shared (by default) or whether connections are unshareable.

http://java.boot.by/bcd-guide/ch13.html 3 / 5 2004/6/12 11:58:52

Chapter 13. Enterprise Bean Environment

A resource manager connection factory reference is scoped to the enterprise 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 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, the type of authentication (Application or Container), and an optional specification of the shareability of connections obtained from the resource (Shareable or Unshareable). Used in: entity, message-driven, and session Example: <resource-ref> <res-ref-name>jdbc/EmployeeAppDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> --> <!ELEMENT resource-ref (description?, res-ref-name, res-type, res-auth, res-sharing-scope?)>

The Bean Provider is allowed to refer to administered objects that are associated with resources (for example, JMS Destinations) by using "logical" names called RESOURCE ENVIRONMENT REFERENCES. Resource environment references are special entries in the enterprise bean's environment. Each resource-env-ref element describes the requirements that the referencing enterprise bean has for the referenced administered object. The resource-env-ref element contains an optional description element; and the MANDATORY resource-env-ref-name and resource-env-ref-type elements. The resource-env-ref-name element specifies the resource environment reference name; its value is the environment entry name used in the enterprise bean CODE. The name of the environment entry is relative to the java:comp/env context (e.g., the name should be jms/StockQueue rather than java:comp/env/jms/StockQueue). The resource-env-ref-type element specifies the expected type of the referenced object. For example, in the case of a JMS Destination, its value must be either javax.
http://java.boot.by/bcd-guide/ch13.html 4 / 5 2004/6/12 11:58:52

Chapter 13. Enterprise Bean Environment

jms.Queue or javax.jms.Topic.

<!-The resource-env-ref element contains a declaration of an enterprise bean's reference to an administered object associated with a resource in the enterprise bean's environment. It consists of an optional description, the resource environment reference name, and an indication of the resource environment reference type expected by the enterprise bean code. Used in: entity, message-driven and session Examples: <resource-env-ref> <resource-env-ref-name>jms/StockQueue</resource-env-ref-name> <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type> </resource-env-ref> --> <!ELEMENT resource-env-ref (description?, resource-env-ref-name, resource-env-ref-type)>

Prev Identify correct and incorrect statements or examples about the client's view of exceptions received from an enterprise bean invocation.

Up

Next Identify correct and incorrect statements about the purpose and use of the deployment descriptor elements for environment entries, EJB references, and resource manager connection factory references; including whether a given code listing is appropriate and correct with respect to a particular deployment descriptor element.

Home

http://java.boot.by/bcd-guide/ch13.html 5 / 5 2004/6/12 11:58:52

Identify correct and incorrect statements about the purpose and use of...d correct with respect to a particular deployment descriptor element.

Identify correct and incorrect statements about the purpose and use of the deployment descriptor elements for environment entries, EJB references, and resource manager connection factory references; including whether a given code listing is appropriate and correct with respect to a particular deployment descriptor element. Prev Chapter 13. Enterprise Bean Environment Next

Identify correct and incorrect statements about the purpose and use of the deployment descriptor elements for environment entries, EJB references, and resource manager connection factory references; including whether a given code listing is appropriate and correct with respect to a particular deployment descriptor element.
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.

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 > Integer.intValue(max) || numberOfExemptions < Integer.intValue(min)) 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.
http://java.boot.by/bcd-guide/ch13s02.html 1 / 8 2004/6/12 11:58:58

Identify correct and incorrect statements about the purpose and use of...d correct with respect to a particular deployment descriptor element.

Integer val3 = (Integer) initCtx.lookup("java:comp/env/name3"); Integer val4 = (Integer) initCtx.lookup("java:comp/env/foo/name4"); ... }

<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>
http://java.boot.by/bcd-guide/ch13s02.html 2 / 8 2004/6/12 11:58:58

Identify correct and incorrect statements about the purpose and use of...d correct with respect to a particular deployment descriptor element.

</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>

The following example illustrates how an enterprise bean uses an EJB REFERENCE to locate the remote 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); ... } }

<session>
http://java.boot.by/bcd-guide/ch13s02.html 3 / 8 2004/6/12 11:58:58

Identify correct and incorrect statements about the purpose and use of...d correct with respect to a particular deployment descriptor element.

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

The following illustrates an ejb-link in the deployment descriptor. 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.

<session> ... <ejb-name>EmployeeService</ejb-name> <ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class> ... <ejb-ref> <ejb-ref-name>ejb/EmplRecord</ejb-ref-name>


http://java.boot.by/bcd-guide/ch13s02.html 4 / 8 2004/6/12 11:58:58

Identify correct and incorrect statements about the purpose and use of...d correct with respect to a particular deployment descriptor element.

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

The following example illustrates using the ejb-link element to indicate an enterprise bean reference to the ProductEJB enterprise bean that is in the same J2EE application unit but in a different ejb-jar file:

<entity> ... <ejb-name>OrderEJB</ejb-name> <ejb-class>com.wombat.orders.OrderBean</ejb-class> ... <ejb-ref> <ejb-ref-name>ejb/Product</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <home>com.acme.orders.ProductHome</home> <remote>com.acme.orders.Product</remote> <ejb-link>../products/product.jar#ProductEJB</ejb-link> </ejb-ref> ... </entity>

The following code sample illustrates obtaining a JDBC connection:

public class EmployeeServiceBean implements SessionBean {


http://java.boot.by/bcd-guide/ch13s02.html 5 / 8 2004/6/12 11:58:58

Identify correct and incorrect statements about the purpose and use of...d correct with respect to a particular deployment descriptor element.

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(); ... } }

The following example is the declaration of resource manager connection factory references used by the EmployeeService enterprise bean:

<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> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> ... </session>
http://java.boot.by/bcd-guide/ch13s02.html 6 / 8 2004/6/12 11:58:58

Identify correct and incorrect statements about the purpose and use of...d correct with respect to a particular deployment descriptor element.

</enterprise-beans>

The following example illustrates the declaration of the JMS resource manager connection factory references:

<enterprise-beans> <session> ... <resource-ref> <description> A queue connection factory used by the MySession enterprise bean to send notifications. </description> <res-ref-name>jms/QueueConnFactory</res-ref-name> <res-type>javax.jms.QueueConnectionFactory</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Unshareable</res-sharing-scope> </resource-ref> ... </session> </enterprise-beans>

The following example illustrates how an enterprise bean uses a RESOURCE ENVIRONMENT REFERENCE to locate a JMS Destination:

public class StockServiceBean implements SessionBean { public void processStockInfo(...) { ... // Obtain the default initial JNDI context Context initCtx = new InitialContext(); // Look up the JMS StockQueue in the environment. Object result = initCtx.lookup("java:comp/env/jms/StockQueue"); // Convert the result to the proper type. javax.jms.Queue queue = (javax.jms.Queue)result; }
http://java.boot.by/bcd-guide/ch13s02.html 7 / 8 2004/6/12 11:58:58

Identify correct and incorrect statements about the purpose and use of...d correct with respect to a particular deployment descriptor element.

In the example, the Bean Provider of the StockServiceBean enterprise bean has ASSIGNED the environment entry jms/StockQueue as the RESOURCE ENVIRONMENT REFERENCE name to refer to a JMS queue. The following example illustrates the declaration of RESOURCE ENVIRONMENT REFERENCES in the deployment descriptor:

... <resource-env-ref> <description> This is a reference to a JMS queue used in the processing of Stock info </description> <resource-env-ref-name>jms/StockQueue</resource-env-ref-name> <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type> </resource-env-ref> ...

Prev Chapter 13. Enterprise Bean Environment

Up

Next Given a list of responsibilities, identify which belong to the deployer, bean provider, application assembler, container provider, system administrator, or any combination.

Home

http://java.boot.by/bcd-guide/ch13s02.html 8 / 8 2004/6/12 11:58:58

Given a list of responsibilities, identify which belong to the deployer...sembler, container provider, system administrator, or any combination.

Given a list of responsibilities, identify which belong to the deployer, bean provider, application assembler, container provider, system administrator, or any combination. Prev Chapter 13. Enterprise Bean Environment Next

Given a list of responsibilities, identify which belong to the deployer, bean provider, application assembler, container provider, system administrator, or any combination.
Bean Provider's responsibility The value of an environment entry is of the Java TYPE declared by the Bean Provider in the deployment descriptor. 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. 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 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. 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 Bean Provider MUST DECLARE all the EJB REFERENCES using the ejb-ref and ejb-local-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. 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. 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. The EJB specification recommends, but does not require, that all RESOURCE MANAGER

http://java.boot.by/bcd-guide/ch13s03.html 1 / 5 2004/6/12 11:59:02

Given a list of responsibilities, identify which belong to the deployer...sembler, container provider, system administrator, or any combination.

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. Lookup 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 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 can control the SHAREABILITY of the connections (element res-sharing-scope) acquired from the resource manager connection factory. By default, connections to a resource manager are SHAREABLE across other enterprise beans in the application that use the same resource in the same transaction context. 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 signon 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. The Bean Provider must use the javax.sql.DataSource resource manager connection factory type for obtaining JDBC connections, the javax.jms.QueueConnectionFactory or the javax.jms. TopicConnectionFactory for obtaining JMS connection, the javax.mail.Session resource manager connection factory type for obtaining JavaMail connections, and the java.net.URL resource manager connection factory type for obtaining URL connections. The Bean Provider assigns an entry in the enterprise bean's environment to the reference. The EJB specification recommends, but does not require, that all RESOURCE ENVIRONMENT REFERENCES be organized in the appropriate subcontext of the bean's environment for the resource type (e.g. in the java:comp/env/jms JNDI context for JMS Destinations). The Bean Provider must DECLARE all references to administered objects associated with resources using the resource-env-ref elements of the deployment descriptor. This allows the ejb-jar consumer to discover all the RESOURCE ENVIRONMENT REFERENCES used by the enterprise bean. Application Assembler's responsibility

http://java.boot.by/bcd-guide/ch13s03.html 2 / 5 2004/6/12 11:59:02

Given a list of responsibilities, identify which belong to the deployer...sembler, container provider, system administrator, or any combination.

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. The Application Assembler can use the ejb-link element in the deployment descriptor to LINK an EJB reference to a target enterprise bean. 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 or ejb-local-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 any ejb-jar file in the same J2EE application as the referencing application component. Alternatively, to avoid the need to rename enterprise beans to have unique names within an entire J2EE application, the Application Assembler may use the following syntax in the ejb-link element of the referencing application component. The Application Assembler specifies the path name of the ejb-jar file containing the referenced enterprise bean and appends the ejb-name of the target bean separated from the path name by '#' (../products/ product.jar#ProductEJB). The path name is relative to the referencing application component jar file. In this manner, multiple beans with the same ejb-name may be uniquely identified when the Application Assembler cannot change ejb-names. 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 component interfaces of the target enterprise bean must be Java type-compatible with the interfaces declared in the EJB reference.

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 Deployer BINDS the EJB references to the enterprise bean homes in the target operational environment. 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 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 component interfaces of the target
http://java.boot.by/bcd-guide/ch13s03.html 3 / 5 2004/6/12 11:59:02

Given a list of responsibilities, identify which belong to the deployer...sembler, container provider, system administrator, or any combination.

enterprise bean must be Java type-compatible with the home and component interfaces declared in the EJB reference. If an EJB reference declaration includes the ejb-link element, the Deployer should BIND the enterprise bean reference to the home of the enterprise bean specified as the link's target. The Deployer BINDS the RESOURCE MANAGER CONNECTION FACTORY (i.e. Datasources) references to the actual resource manager connection factories that are configured in the Container (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 resource manager connection factory type must be compatible with the type declared in the res-type element. 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.

The Deployer BINDS the RESOURCE ENVIRONMENT REFERENCES to administered objects in the target operational environment. The Deployer must ensure that all the declared resource environment references ARE BOUND to administered objects that exist in the operational environment. The Deployer must ensure that the target object is type-compatible with the type declared for the resource environment reference. This means that the target object must be of the type indicated in the resource-env-ref-type element. Container Provider's 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.

http://java.boot.by/bcd-guide/ch13s03.html 4 / 5 2004/6/12 11:59:02

Given a list of responsibilities, identify which belong to the deployer...sembler, container provider, system administrator, or any combination.

The Container Provider must provide the deployment tools which must be able to process the information supplied in the ejb-ref and ejb-local-ref elements in the deployment descriptor. 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 sets the res-auth of a resource manager connection factory reference to Application, the Container must allow the bean to perform explicit programmatic sign-on 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. The Container MAY (not required) provide 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. At the minimum, the deployment tools provided by the Container Provider must be able to inform the Deployer of any unresolved resource environment references, and allow him or her to resolve a resource environment reference by binding it to a specified compatible target object in the environment.

Prev Identify correct and incorrect statements about the purpose and use of the deployment descriptor elements for environment entries, EJB references, and resource manager connection factory references; including whether a given code listing is appropriate and correct with respect to a particular deployment descriptor element.

Up

Next Chapter 14. Security Management

Home

http://java.boot.by/bcd-guide/ch13s03.html 5 / 5 2004/6/12 11:59:02

Chapter 14. Security Management

Chapter 14. Security Management Prev Part I. Exam Objectives Next

Chapter 14. Security Management

Identify correct and incorrect statements about the EJB support for security management including security roles, security role references, and method permissions.
Security roles A SECURITY ROLE is a semantic grouping of permissions that a given type of users of the application must have in order to successfully use the application. 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 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 component interfaces to the security roles to define the security view of the application.

<!-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)>

http://java.boot.by/bcd-guide/ch14.html 1 / 4 2004/6/12 11:59:05

Chapter 14. Security Management

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 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. Security role references 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 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 Bean Provider must declare each security role referenced in the code using the security-roleref 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. Optionally 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. 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-rolehttp://java.boot.by/bcd-guide/ch14.html 2 / 4 2004/6/12 11:59:05

Chapter 14. Security Management

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 rolelink 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. Method permissions 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 component interfaces. 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 home and component interfaces that each security role is allowed to invoke.

<!-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 or an indicator to specify that the methods are not to be checked for authorization, and a list of method elements. The security roles used in the method-permission element must be defined in the security-role elements of the deployment descriptor, and the methods must be methods defined in the enterprise bean's component and/or home interfaces. Used in: assembly-descriptor --> <!ELEMENT method-permission (description?, (role-name+|unchecked), method+)>

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.

http://java.boot.by/bcd-guide/ch14.html 3 / 4 2004/6/12 11:59:05

Chapter 14. Security Management

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.

The Application Assembler can indicate that some methods should not be checked for authorization prior to invocation by the Container. The Application Assembler uses the unchecked element instead of a role name in the method-permission element to indicate that a method should not be checked for authorization. Bean's security identity In addition to specifying the security roles (or principals) that have access to an enterprise bean, the Application Assembler can also specify the run-as role for the entire enterprise bean. 'Run-as' defines the identity that a bean runs with when it calls other beans. This does not change the identity of the caller of the bean. The IDENTITY is configured using the security-identity element in the deployment descriptor. Because this is a per-bean setting, it must be declared for every EJB.

<!-The security-identity element specifies whether the caller's security identity is to be used for the execution of the methods of the enterprise bean or whether a specific run-as identity is to be used. It contains an optional description and a specification of the security identity to be used. Used in: session, entity, message-driven --> <!ELEMENT security-identity (description?, (use-caller-identity| run-as))>

Prev Given a list of responsibilities, identify which belong to the deployer, bean provider, application assembler, container provider, system administrator, or any combination.

Up

Next From a list of responsibilities, identify which belong to the application assembler, bean provider, deployer, container provider, or system administrator.

Home

http://java.boot.by/bcd-guide/ch14.html 4 / 4 2004/6/12 11:59:05

From a list of responsibilities, identify which belong to the applicatio..., bean provider, deployer, container provider, or system administrator.

From a list of responsibilities, identify which belong to the application assembler, bean provider, deployer, container provider, or system administrator. Prev Chapter 14. Security Management Next

From a list of responsibilities, identify which belong to the application assembler, bean provider, deployer, container provider, or system administrator.
In the life cycle of an application, different people perform different roles. From a security point of view, we can say that:

The bean provider can use programmatic security:

if ( isUserInRole("manager") ) { showAllCustomers(); } else { showCurrentCustomer(); }

The application assembler will use declarative security to set permissions on methods of beans. The application deployer links users and groups to roles. The system administrator tells the application server where to find the users (for example in an LDAP directory).

Bean Provider's responsibilities 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. 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. Application Assembler's responsibilities

http://java.boot.by/bcd-guide/ch14s02.html 1 / 4 2004/6/12 11:59:07

From a list of responsibilities, identify which belong to the applicatio..., bean provider, deployer, container provider, or system administrator.

The Application Assembler 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 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 successfully use the application. The Application 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 component 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. 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. If the Application Assembler has defined security roles for the enterprise beans in the ejb-jar file, he or she can also specify (using the method-permission elements) the methods of the home and component interfaces that each security role is allowed to invoke. The Application Assembler can indicate that some methods should not be checked for authorization prior to invocation by the Container. The Application Assembler uses the unchecked element instead of a role name in the method-permission element to indicate that a method should not be checked for authorization. The Application Assembler can use the exclude-list element to indicate the set of methods that should not be called. The Deployer should configure the enterprise bean's security such that NO ACCESS is permitted to any method contained in the exclude-list. The Application Assembler uses the security-identity deployment descriptor element to specify whether the caller's security identity should be used for the execution of the methods of an enterprise bean or whether a specific run-as identity should be used. The value of the securityidentity element is either use-caller-identity or run-as. The use-caller-identity element cannot be specified for message-driven beans (there is NO caller). Because the Application Assembler does not, in general, know the security environment of the operational environment, the run-as identity is designated by a LOGICAL role-name, which corresponds to one of the security roles defined by the Application Assembler in the deployment descriptor. Deployer's responsibilities

http://java.boot.by/bcd-guide/ch14s02.html 2 / 4 2004/6/12 11:59:07

From a list of responsibilities, identify which belong to the applicatio..., bean provider, deployer, container provider, or system administrator.

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 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. It is possible that some methods are not assigned to any security roles nor contained in the exclude-list element. In this case, it is the responsibility of the Deployer to assign method permissions for all of the unspecified methods, either by assigning them to security roles, or by marking them as unchecked. EJB Container Provider's responsibilities The EJB Container Provider is responsible for providing the deployment tools that the Deployer can use to perform his tasks. 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 Container must be capable of allowing the Deployer to specify that, for all calls from a single application within a single J2EE product, 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()). The EJB Container must be capable of allowing the Deployer to specify that a run-as principal be used for the execution of the home and component methods of a session or entity bean or for the onMessage method of a message-driven bean. If the Container denies a client access to a business method, the Container must throw the java. rmi.RemoteException to the REMOTE client, or the javax.ejb.EJBException to the LOCAL client. System Administrator's responsibilities

http://java.boot.by/bcd-guide/ch14s02.html 3 / 4 2004/6/12 11:59:07

From a list of responsibilities, identify which belong to the applicatio..., bean provider, deployer, container provider, or system administrator.

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.

Prev Chapter 14. Security Management

Up Home

Next Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context.

http://java.boot.by/bcd-guide/ch14s02.html 4 / 4 2004/6/12 11:59:07

Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context.

Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context. Prev Chapter 14. Security Management Next

Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context.
The javax.ejb.EJBContext interface provides TWO methods that allow the Bean Provider to access security information about the enterprise bean's caller:

package javax.ejb; public interface EJBContext { // The following two methods allow the EJB class // to access security information: // Returns the principal that represents the CALLER of the // enterprise bean, not the principal that corresponds to the // run-as security identity for the bean, if any. java.security.Principal getCallerPrincipal(); // Tests the principal that represents the CALLER of the // enterprise bean, not the principal that corresponds // to the run-as security identity for the bean, if any. boolean isCallerInRole(String roleName); ... }

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

public class EmployeeServiceBean implements SessionBean { EJBContext ejbContext;


http://java.boot.by/bcd-guide/ch14s03.html 1 / 4 2004/6/12 11:59:11

Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context.

public void changePhoneNumber(...) { ... // Obtain the default initial JNDI context. Context initCtx = new InitialContext(); // Look up the remote 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(...); ... } }

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, and are assigned to principals or principal groups that exist in the operational environment by the Deployer.

public class PayrollBean ... { EntityContext ejbContext; public void updateEmployeeInfo(EmplInfo info) { oldInfo = ... // read from database;

http://java.boot.by/bcd-guide/ch14s03.html 2 / 4 2004/6/12 11:59:11

Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context.

// The salary field can be changed only by callers // who have the security role "payroll" if (info.salary != oldInfo.salary && !ejbContext.isCallerInRole("payroll")) { throw new SecurityException(...); } ... } ... }

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. The ROLE NAME name must be the security role name that is used as a parameter to the isCallerInRole (String roleName) method.

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

Full description of security-role-ref element is:

<!-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.
http://java.boot.by/bcd-guide/ch14s03.html 3 / 4 2004/6/12 11:59:11

Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context.

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?)>

Prev From a list of responsibilities, identify which belong to the application assembler, bean provider, deployer, container provider, or system administrator.

Up

Next Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag.

Home

http://java.boot.by/bcd-guide/ch14s03.html 4 / 4 2004/6/12 11:59:11

Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag.

Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag. Prev Chapter 14. Security Management Next

Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag.
The following example illustrates a security role definition (made by Application Assembler) 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>

http://java.boot.by/bcd-guide/ch14s04.html 1 / 5 2004/6/12 11:59:15

Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag.

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

The following example illustrates how an enterprise bean's references to security roles are declared in the deployment descriptor (defined by Bean Provider):

<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. The following deployment descriptor example shows how to link (by Application Assembler) the security role reference named payroll to the security role named payroll-department:

http://java.boot.by/bcd-guide/ch14s04.html 2 / 5 2004/6/12 11:59:15

Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag.

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

The following example illustrates how security roles are assigned method permissions (by Application Assembler) in the deployment descriptor:

<assembly-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>
http://java.boot.by/bcd-guide/ch14s04.html 3 / 5 2004/6/12 11:59:15

Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag.

</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> </assembly-descriptor>

The following example illustrates the definition of a security-identity identity in the deployment descriptor (by Application Assembler):

<enterprise-beans> <entity>
http://java.boot.by/bcd-guide/ch14s04.html 4 / 5 2004/6/12 11:59:15

Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag.

<ejb-name>Account</ejb-name> ...... <security-identity> <description>security description</description> <run-as> <description>role 'accountRole' description</description> <role-name>accountRole</role-name> </run-as> </security-identity> </entity> <entity> <ejb-name>Customer</ejb-name> ...... <security-identity> <use-caller-identity/> </security-identity> </entity> </enterprise-beans>

NOTE, use-caller-identity cannot be used for message-driven.

Prev Given a code listing, determine whether it is a legal and appropriate way to programmatically access a caller's security context.

Up Home

Next Part II. Appendixes

http://java.boot.by/bcd-guide/ch14s04.html 5 / 5 2004/6/12 11:59:15

Part II. Appendixes

Part II. Appendixes Prev Next

Appendixes
Bibliography
[EJB_2.0] Enterprise JavaBeansTM Specification, Version 2.0. [JavaRanch] JavaRanch.com forum for SCBCD Certification. [EnterpriseJavaBeans] Enterprise JavaBeans, 3-rd Edition, by Richard Monson-Haefel, published by O'Reilly & Associates, Inc., 2001 .

Prev Given a security-related deployment descriptor tag, identify correct and incorrect statements and code related to that tag.

Up Home

Next Appendix A. First Appendix

http://java.boot.by/bcd-guide/pt02.html2004/6/12 11:59:17

Appendix A. First Appendix

Appendix A. First Appendix Prev Part II. Appendixes Next

Appendix A. First Appendix

First Section
sdsds

Prev Part II. Appendixes

Up Home

Next Second Section

http://java.boot.by/bcd-guide/apa.html2004/6/12 11:59:19

Second Section

Second Section Prev Appendix A. First Appendix Next

Second Section
sdsds

Prev Appendix A. First Appendix

Up Home

Next Third Section

http://java.boot.by/bcd-guide/apas02.html2004/6/12 11:59:21

Third Section

Third Section Prev Appendix A. First Appendix Next

Third Section
sdsds

Prev Second Section

Up Home

Next Bibliography

http://java.boot.by/bcd-guide/apas03.html2004/6/12 11:59:23

SCWCD 1.4 Study Guide

SCWCD 1.4 Study Guide Next

SCWCD 1.4 Study Guide


IBA JV Mikalai Zaikin
<NZaikin[at]iba.by>

Copyright 2004 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. May 2004
Revision History Revision 0.6 Proposed Final Draft 3. Revision 0.5 Proposed Final Draft 2. Revision 0.4 Proposed Final Draft 1. Revision 0.3 Chapters 9-10 updates. Revision 0.2 Chapters 1-8 updates. Revision 0.1 Initial release. 22 Dec 2003 MZ 12 Jan 2004 MZ 15 Jan 2004 MZ 19 Jan 2004 MZ 5 Apr 2004 MZ 7 May 2004 MZ

Abstract The purpose of this document is to help in preparation for exam CX-310-081 (Sun Certified Web Component Developer using the J2EE Platform 1.4).

http://java.boot.by/wcd-guide/ 1 / 5 2004/6/12 11:59:26

SCWCD 1.4 Study Guide

This document should not be used as the only study material for SCWCD 1.4 test. It covers all objective topics, but it is not enough. I tried to make this document as much accurate as possible, but if you find any error, please let me know.

Table of Contents Foreword Preface I. Exam Objectives 1. The Servlet Technology Model For each of the HTTP Methods (such as GET, POST, HEAD, and so on) describe the purpose of the method and the technical characteristics of the HTTP Method protocol, list triggers that might cause a Client (usually a Web browser) to use the method; and identify the HttpServlet method that corresponds to the HTTP Method. Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request. Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response. Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method. 2. The Structure and Deployment of Web Applications Construct the file and directory structure of a Web Application that may contain (a) static content, (b) JSP pages, (c) servlet classes, (d) the deployment descriptor, (e) tag libraries, (f) JAR files, and (g) Java class files; and describe how to protect resource files from HTTP access. Describe the purpose and semantics for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servletclass, servlet-mapping, servlet-name, and welcome-file. Construct the correct structure for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servlet-class, servletmapping, servlet-name, and welcome-file. Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed. 3. The Web Container Model For the ServletContext initialization parameters: write servlet code to access initialization parameters; and create the deployment descriptor elements for declaring initialization parameters.
http://java.boot.by/wcd-guide/ 2 / 5 2004/6/12 11:59:26

SCWCD 1.4 Study Guide

For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multi-threading issues associated with each scope. Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper. Describe the Web container life cycle event model for requests, sessions, and web applications; create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use. Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource. 4. Session Management Write servlet code to store objects into a session object and retrieve objects from a session object. Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed. Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another. Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting. 5. Web Application Security Based on the servlet specification, compare and contrast the following security mechanisms: (a) authentication, (b) authorization, (c) data integrity, and (d) confidentiality. In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role. Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type. 6. The JavaServer Pages (JSP) Technology Model Identify, describe, or write the JSP code for the following elements: (a) template text, (b) scripting elements (comments, directives, declarations, scriptlets, and expressions), (c) standard and custom actions, and (d) expression language elements. Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

http://java.boot.by/wcd-guide/ 3 / 5 2004/6/12 11:59:26

SCWCD 1.4 Study Guide

Write a JSP Document (XML-based document) that uses the correct syntax. Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method. Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception. Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language. Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp:include standard action). 7. Building JSP Pages Using the Expression Language (EL) Given a scenario, write EL code that accesses the following implicit variables including: pageScope, requestScope, sessionScope, and applicationScope, param and paramValues, header and headerValues, cookie, initParam and pageContext. Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator). Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators. Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor. 8. Building JSP Pages Using Standard Actions Given a design goal, create a code snippet using the following standard actions: jsp:useBean (with attributes: 'id', 'scope', 'type', and 'class'), jsp:getProperty, and jsp:setProperty (with all attribute combinations). Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param. 9. Building JSP Pages Using Tag Libraries For a custom tag library or a library of Tag Files, create the 'taglib' directive for a JSP page. Given a design goal, create the custom tag structure in a JSP page to support that goal. Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library. 10. Building a Custom Tag Library Describe the semantics of the "Classic" custom tag event model when each event method (doStartTag, doAfterBody, and doEndTag) is executed, and explain what the return value for each event method means; and write a tag handler class. Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes. Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.

http://java.boot.by/wcd-guide/ 4 / 5 2004/6/12 11:59:26

SCWCD 1.4 Study Guide

Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag. Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag. 11. J2EE Patterns Given a scenario description with a list of issues, select a pattern that would solve the issues. The list of patterns you must know are: Intercepting Filter, Model-ViewController, Front Controller, Service Locator, Business Delegate, and Transfer Object. Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-View-Controller, Front Controller, Service Locator, Business Delegate, and Transfer Object. II. Appendixes A. First Appendix First Section Second Section Third Section Bibliography

Next Foreword

http://java.boot.by/wcd-guide/ 5 / 5 2004/6/12 11:59:26

Foreword

Foreword Prev Next

Foreword
A preface.

Prev SCWCD 1.4 Study Guide

Up Home

Next Preface

http://java.boot.by/wcd-guide/pr01.html2004/6/12 11:59:28

SCWCD 1.4 Study Guide

SCWCD 1.4 Study Guide Next

SCWCD 1.4 Study Guide


IBA JV Mikalai Zaikin
<NZaikin[at]iba.by>

Copyright 2004 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. May 2004
Revision History Revision 0.6 Proposed Final Draft 3. Revision 0.5 Proposed Final Draft 2. Revision 0.4 Proposed Final Draft 1. Revision 0.3 Chapters 9-10 updates. Revision 0.2 Chapters 1-8 updates. Revision 0.1 Initial release. 22 Dec 2003 MZ 12 Jan 2004 MZ 15 Jan 2004 MZ 19 Jan 2004 MZ 5 Apr 2004 MZ 7 May 2004 MZ

Abstract The purpose of this document is to help in preparation for exam CX-310-081 (Sun Certified Web Component Developer using the J2EE Platform 1.4).

http://java.boot.by/wcd-guide/index.html 1 / 5 2004/6/12 11:59:33

SCWCD 1.4 Study Guide

This document should not be used as the only study material for SCWCD 1.4 test. It covers all objective topics, but it is not enough. I tried to make this document as much accurate as possible, but if you find any error, please let me know.

Table of Contents Foreword Preface I. Exam Objectives 1. The Servlet Technology Model For each of the HTTP Methods (such as GET, POST, HEAD, and so on) describe the purpose of the method and the technical characteristics of the HTTP Method protocol, list triggers that might cause a Client (usually a Web browser) to use the method; and identify the HttpServlet method that corresponds to the HTTP Method. Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request. Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response. Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method. 2. The Structure and Deployment of Web Applications Construct the file and directory structure of a Web Application that may contain (a) static content, (b) JSP pages, (c) servlet classes, (d) the deployment descriptor, (e) tag libraries, (f) JAR files, and (g) Java class files; and describe how to protect resource files from HTTP access. Describe the purpose and semantics for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servletclass, servlet-mapping, servlet-name, and welcome-file. Construct the correct structure for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servlet-class, servletmapping, servlet-name, and welcome-file. Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed. 3. The Web Container Model For the ServletContext initialization parameters: write servlet code to access initialization parameters; and create the deployment descriptor elements for declaring initialization parameters.
http://java.boot.by/wcd-guide/index.html 2 / 5 2004/6/12 11:59:33

SCWCD 1.4 Study Guide

For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multi-threading issues associated with each scope. Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper. Describe the Web container life cycle event model for requests, sessions, and web applications; create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use. Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource. 4. Session Management Write servlet code to store objects into a session object and retrieve objects from a session object. Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed. Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another. Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting. 5. Web Application Security Based on the servlet specification, compare and contrast the following security mechanisms: (a) authentication, (b) authorization, (c) data integrity, and (d) confidentiality. In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role. Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type. 6. The JavaServer Pages (JSP) Technology Model Identify, describe, or write the JSP code for the following elements: (a) template text, (b) scripting elements (comments, directives, declarations, scriptlets, and expressions), (c) standard and custom actions, and (d) expression language elements. Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

http://java.boot.by/wcd-guide/index.html 3 / 5 2004/6/12 11:59:33

SCWCD 1.4 Study Guide

Write a JSP Document (XML-based document) that uses the correct syntax. Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method. Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception. Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language. Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp:include standard action). 7. Building JSP Pages Using the Expression Language (EL) Given a scenario, write EL code that accesses the following implicit variables including: pageScope, requestScope, sessionScope, and applicationScope, param and paramValues, header and headerValues, cookie, initParam and pageContext. Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator). Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators. Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor. 8. Building JSP Pages Using Standard Actions Given a design goal, create a code snippet using the following standard actions: jsp:useBean (with attributes: 'id', 'scope', 'type', and 'class'), jsp:getProperty, and jsp:setProperty (with all attribute combinations). Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param. 9. Building JSP Pages Using Tag Libraries For a custom tag library or a library of Tag Files, create the 'taglib' directive for a JSP page. Given a design goal, create the custom tag structure in a JSP page to support that goal. Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library. 10. Building a Custom Tag Library Describe the semantics of the "Classic" custom tag event model when each event method (doStartTag, doAfterBody, and doEndTag) is executed, and explain what the return value for each event method means; and write a tag handler class. Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes. Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.

http://java.boot.by/wcd-guide/index.html 4 / 5 2004/6/12 11:59:33

SCWCD 1.4 Study Guide

Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag. Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag. 11. J2EE Patterns Given a scenario description with a list of issues, select a pattern that would solve the issues. The list of patterns you must know are: Intercepting Filter, Model-ViewController, Front Controller, Service Locator, Business Delegate, and Transfer Object. Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-View-Controller, Front Controller, Service Locator, Business Delegate, and Transfer Object. II. Appendixes A. First Appendix First Section Second Section Third Section Bibliography

Next Foreword

http://java.boot.by/wcd-guide/index.html 5 / 5 2004/6/12 11:59:33

Preface

Preface Prev Next

Preface
This document is available in 2 formats: single page and chunked pages If you would like to have PDF (printable eBook for Adobe Acrobat Reader) version or CHM (single file copy of web-site to browse offline) version of SCWCD Study Guide, please, contact me.

Prev Foreword

Up Home

Next Part I. Exam Objectives

http://java.boot.by/wcd-guide/pr02.html2004/6/12 11:59:35

Part I. Exam Objectives

Part I. Exam Objectives Prev Next

Exam Objectives
Prev Preface Up Home Next Chapter 1. The Servlet Technology Model

http://java.boot.by/wcd-guide/pt01.html2004/6/12 11:59:37

Chapter 1. The Servlet Technology Model

Chapter 1. The Servlet Technology Model Prev Part I. Exam Objectives Next

Chapter 1. The Servlet Technology Model

For each of the HTTP Methods (such as GET, POST, HEAD, and so on) describe the purpose of the method and the technical characteristics of the HTTP Method protocol, list triggers that might cause a Client (usually a Web browser) to use the method; and identify the HttpServlet method that corresponds to the HTTP Method.
The HttpServlet abstract subclass adds additional methods beyond the basic Servlet interface that are automatically called by the service method in the HttpServlet class to aid in processing HTTPbased requests. These methods are (HTTP 1.1):

doGet for handling HTTP GET requests.

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a GET request. Overriding this method to support a GET request also automatically supports an HTTP HEAD request. A HEAD request is a GET request that returns NO BODY in the response, only the request header fields. When overriding this method, read the request data, write the response headers, get the response's writer or output stream object, and finally, write the response data. It's best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DisplayServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<html><head><title>Display Information");
http://java.boot.by/wcd-guide/ch01.html 1 / 8 2004/6/12 11:59:41

Chapter 1. The Servlet Technology Model

out.println("</title></head><body>"); out.println("Hello, World"); out.println("</body></html>"); } }

The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body. The GET method should be safe, that is, without any side effects for which users are held responsible. For example, most form queries have no side effects. If a client request is intended to change stored data, the request should use some other HTTP method (for example, POST method). The GET method should also be idempotent, meaning that it can be safely repeated. Sometimes making a method safe also makes it idempotent. For example, repeating queries is both safe and idempotent, but buying a product online or modifying data is neither safe nor idempotent. GET method purpose. The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. In short, this method should be used for getting (retrieving) data only. It should not be used for storing data in DB. GET method technical characteristics. Query string or form data during this method is simply appended to the URL as namevalue pairs separated with '&'.

name1=value1&name2=value2&name3=value3

Query length is limited (it depends on servlet container's plaform, but usually should not exceed 1024 bytes). Users can see data in the browser's address bar.

http://java.boot.by/wcd-guide/ch01.html 2 / 8 2004/6/12 11:59:41

Chapter 1. The Servlet Technology Model

http://some-server.com/some-script?name1=value1&name2=value2&name3=value3

Only ASCII (text) data can be sent to server with GET method. Easy to bookmark. GET method triggers. The web browser sends an HTTP GET request when:
r r r

The user types a URL in the browser's address bar. The user clicks a link. Retrieve a resource which was defined in src (image) or href (cascade style sheet) attributes.

<img src="image.gif">

<link href="style.css" rel="stylesheet" type="text/css">

The user (or JavaScript) submits a form that specifies attribute method="GET":

<form action="/servlet/display" method="GET"> First Name: <input type="text" name="firstName"><p> Last Name: <input type="text" name="lastName"><p> <input type="submit" value="Display"> </form>

The user (or JavaScript) submits a form that specifies NO method attribute (forms use method GET BY DEFAULT):

<form action="/servlet/display">

http://java.boot.by/wcd-guide/ch01.html 3 / 8 2004/6/12 11:59:41

Chapter 1. The Servlet Technology Model

First Name: <input type="text" name="firstName"><p> Last Name: <input type="text" name="lastName"><p> <input type="submit" value="Display"> </form>

doPost for handling HTTP POST requests.

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of UNLIMITED length to the Web server a single time and is useful when posting information such as credit card numbers. When overriding this method, read the request data, write the response headers, get the response's writer or output stream object, and finally, write the response data. It's best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DisplayServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<html><head><title>Display Information"); out.println("</title></head><body>"); out.println("Hello, World"); out.println("</body></html>"); } }

The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body. This method does not need to be either safe or idempotent. Operations requested through

http://java.boot.by/wcd-guide/ch01.html 4 / 8 2004/6/12 11:59:41

Chapter 1. The Servlet Technology Model

POST can have side effects for which the user can be held accountable, for example, updating stored data or buying items online. POST method purpose. The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:
r r

Annotation of existing resources; Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; Providing a block of data, such as the result of submitting a form, to a datahandling process; Extending a database through an append operation.

In short, this method should be used for posting newgroups messages, submitting long data fields to a database (such as a SQL insert of lengthy string), or sending binary files to server. POST method technical characteristics. Sends information to the server such as form fields, large text bodies, and key-value pairs. Hides form data from users because it is not passed as a query string, but in the message body. Sends UNLIMITED length data as part of its HTTP request body. For sending ASCII (text) or binary data. Disallows bookmarks. POST method triggers. The web browser sends an HTTP POST request when:
r

The user (or JavaScript) submits a form that specifies attribute method="POST":

<form action="/servlet/display" method="POST"> First Name: <input type="text" name="firstName"><p> Last Name: <input type="text" name="lastName"><p>
http://java.boot.by/wcd-guide/ch01.html 5 / 8 2004/6/12 11:59:41

Chapter 1. The Servlet Technology Model

<input type="submit" value="Display"> </form>

doPut for handling HTTP PUT requests.

protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a PUT request. The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP. When overriding this method, leave intact any content headers sent with the request (including Content-Length, Content-Type, Content-Transfer-Encoding, Content-Encoding, ContentBase, Content-Language, Content-Location, Content-MD5, and Content-Range). If your method cannot handle a content header, it must issue an error message and discard the request. This method does not need to be either safe or idempotent. Operations that doPut performs can have side effects for which the user can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage. The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource.

<form enctype="multipart/form-data" action="some_url" method="PUT"> <input type="file" name="fileToUpload" value="Select File"> <input type="submit" value="Upload"> <input type="reset" value="Reset"> </form>

doDelete for handling HTTP DELETE requests.

protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException


http://java.boot.by/wcd-guide/ch01.html 6 / 8 2004/6/12 11:59:41

Chapter 1. The Servlet Technology Model

Called by the server (via the service method) to allow a servlet to handle a DELETE request. The DELETE operation allows a client to remove a document or Web page from the server. This method does not need to be either safe or idempotent. Operations requested through DELETE can have side effects for which users can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage. doHead for handling HTTP HEAD requests.

protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Receives an HTTP HEAD request from the protected service method and handles the request. The client sends a HEAD request when it wants to see ONLY the HEADERS of a response, such as Content-Type or Content-Length. The HTTP HEAD method counts the output bytes in the response to set the Content-Length header accurately. The doHead method in HttpServlet is a specialized form of the doGet method that returns only the headers produced by the doGet method. doOptions for handling HTTP OPTIONS requests.

protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a OPTIONS request. The OPTIONS request determines which HTTP methods the server supports and returns an appropriate header. For example, if a servlet overrides doGet, this method returns the following header:

Allow: GET, HEAD, TRACE, OPTIONS

doTrace for handling HTTP TRACE requests.

protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

http://java.boot.by/wcd-guide/ch01.html 7 / 8 2004/6/12 11:59:41

Chapter 1. The Servlet Technology Model

Called by the server (via the service method) to allow a servlet to handle a TRACE request. The doTrace method generates a response containing all instances of the headers sent in the TRACE request to the client, so that they can be used in debugging. There's no need to override this method. Typically when developing HTTP-based servlets, a Servlet Developer will only concern himself with the doGet and doPost methods. The other methods are considered to be methods for use by programmers very familiar with HTTP programming.

Prev Part I. Exam Objectives

Up

Next Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request.

Home

http://java.boot.by/wcd-guide/ch01.html 8 / 8 2004/6/12 11:59:41

Using the HttpServletRequest interface, write code to retrieve HTML f...TP request header information, or retrieve cookies from the request.

Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request. Prev Chapter 1. The Servlet Technology Model Next

Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request.
HTTP Protocol Parameters. Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request. When the request is an HttpServletRequest object, the container populates the parameters from the URI query string and POST-ed data. The parameters are stored 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 Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data. You should only use this method when you are sure the parameter has only ONE value. If the parameter might have MORE than one value, use getParameterValues(String). If you use this method with a multivalued parameter, the value returned is equal to the FIRST value in the array returned by getParameterValues. If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method. getParameterNames Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an EMPTY Enumeration. getParameterValues Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. If the parameter has a single value, the array has a length of 1. getParameterMap

http://java.boot.by/wcd-guide/ch01s02.html 1 / 6 2004/6/12 11:59:44

Using the HttpServletRequest interface, write code to retrieve HTML f...TP request header information, or retrieve cookies from the request.

Returns an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.

public interface ServletRequest { public java.lang.String getParameter(java.lang.String name); public java.util.Enumeration getParameterNames(); public java.lang.String[] getParameterValues(java.lang.String name); public java.util.Map getParameterMap(); }

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 be the FIRST value in the array of String objects returned by getParameterValues. The getParameterMap method returns a java.util.Map of the parameter of the request, which contains names as keys and parameter values as map values.

public void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException { Enumeration e = request.getParameterNames(); PrintWriter out = res.getWriter (); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getParameter(name); out.println(name + " = " + value); } }
Data from the query string and the post body are aggregated into the request parameter set. Query string data is presented BEFORE post body 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). The following are the conditions that must be met before post FORM data will be populated to the parameter set: 1. 2. 3. 4. The The The The request is an HTTP or HTTPS request. HTTP method is POST. content type is application/x-www-form-urlencoded. servlet has made an initial call of any of the 'getParameter' family of methods on the

http://java.boot.by/wcd-guide/ch01s02.html 2 / 6 2004/6/12 11:59:44

Using the HttpServletRequest interface, write code to retrieve HTML f...TP request header information, or retrieve cookies from the request.

request object. If the conditions are not met and the post form data is not included in the parameter set, the post data must still be available to the servlet via the request object's input stream. If the conditions are met, post form data will no longer be available for reading directly from the request object's input stream. Headers. A servlet can access the headers of an HTTP request through the following methods of the HttpServletRequest interface:

getHeader Returns the value of the specified request header as a String. If the request did not include a header of the specified name, this method returns null. If there are multiple headers with the same name, this method returns the first head in the request. The header name is case insensitive. You can use this method with any request header. getHeaders Returns all the values of the specified request header as an Enumeration of String objects. Some headers, such as Accept-Language can be sent by clients as several headers each with a different value rather than sending the header as a comma separated list. If the request did not include any headers of the specified name, this method returns an EMPTY Enumeration. The header name is case INSENSITIVE. You can use this method with any request header. getHeaderNames Returns an enumeration of all the header names this request contains. If the request has no headers, this method returns an empty enumeration.

The getHeader method returns a header given the name of the header. There can be multiple headers with the same name, e.g. Cache-Control headers, in an HTTP request. If there are multiple headers with the same name, the getHeader method returns the first header 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.

public interface HttpServletRequest { public java.lang.String getHeader(java.lang.String name); public java.util.Enumeration getHeaders(java.lang.String name); public java.util.Enumeration getHeaderNames(); }

http://java.boot.by/wcd-guide/ch01s02.html 3 / 6 2004/6/12 11:59:44

Using the HttpServletRequest interface, write code to retrieve HTML f...TP request header information, or retrieve cookies from the request.

Headers may contain String representations of int or Date data. The following convenience methods of the HttpServletRequest interface provide access to header data in a one of these formats:

getIntHeader Returns the value of the specified request header as an int. If the request does not have a header of the specified name, this method returns -1. If the header cannot be converted to an integer, this method throws a NumberFormatException. The header name is case INSENSITIVE. getDateHeader Returns the value of the specified request header as a long value that represents a Date object. Use this method with headers that contain dates, such as If-Modified-Since. The date is returned as the number of milliseconds since January 1, 1970 GMT. The header name is case insensitive. If the request did not have a header of the specified name, this method returns -1. If the header can't be converted to a date, the method throws an IllegalArgumentException.

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.

public interface HttpServletRequest { public int getIntHeader(java.lang.String name); public long getDateHeader(java.lang.String name); }

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getHeader(name);
http://java.boot.by/wcd-guide/ch01s02.html 4 / 6 2004/6/12 11:59:44

Using the HttpServletRequest interface, write code to retrieve HTML f...TP request header information, or retrieve cookies from the request.

out.println(name + " = " + value); } }

Cookies. The HttpServletRequest interface provides the getCookies method to obtain an array of cookies that are present in the request. This method returns null if no cookies were sent. The 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. Several cookies might have the same name but different path attributes.

public interface HttpServletRequest { public Cookie[] getCookies(); }

package javax.servlet.http; public class Cookie implements java.lang.Cloneable { ... public Cookie(java.lang.String name, java.lang.String value); public java.lang.String getName(); public java.lang.String getPath(); public java.lang.String getValue(); ... }

Prev

Up

Next

http://java.boot.by/wcd-guide/ch01s02.html 5 / 6 2004/6/12 11:59:44

Using the HttpServletRequest interface, write code to retrieve HTML f...TP request header information, or retrieve cookies from the request.

Chapter 1. The Servlet Technology Model Home

Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response.

http://java.boot.by/wcd-guide/ch01s02.html 6 / 6 2004/6/12 11:59:44

Using the HttpServletResponse interface, write code to set an HTTP r...ect an HTTP request to another URL, or add cookies to the response.

Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response. Prev Chapter 1. The Servlet Technology Model Next

Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response.
Headers. A servlet can set headers of an HTTP response via the following methods of the HttpServletResponse interface:

setHeader Sets a response header with the given name and value. If the header had already been set, the new value OVERWRITES the previous one. The containsHeader method can be used to test for the presence of a header before setting its value. addHeader Adds a response header with the given name and value. This method allows response headers to have multiple values.

public interface HttpServletResponse extends javax.servlet.ServletResponse { public void setHeader(java.lang.String name, java.lang.String value); public void addHeader(java.lang.String name, java.lang.String value); }

The setHeader method sets a header with a given name and value. A previous header is replaced by the new header. Where a set of header values exist for the name, the values are cleared and replaced with the new value. The addHeader method adds a header value to the set with a given name. If there are no headers already associated with the name, a new set is created. Headers may contain data that represents 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:
http://java.boot.by/wcd-guide/ch01s03.html 1 / 5 2004/6/12 11:59:47

Using the HttpServletResponse interface, write code to set an HTTP r...ect an HTTP request to another URL, or add cookies to the response.

setIntHeader Sets a response header with the given name and integer value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value. setDateHeader Sets a response header with the given name and date-value. The date is specified in terms of milliseconds since the epoch. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value. addIntHeader Adds a response header with the given name and integer value. This method allows response headers to have multiple values. addDateHeader Adds a response header with the given name and date-value. The date is specified in terms of milliseconds since the epoch. This method allows response headers to have multiple values.

public interface HttpServletResponse extends javax.servlet.ServletResponse { public void setIntHeader(java.lang.String name, int value); public void setDateHeader(java.lang.String name, long date); public void addIntHeader(java.lang.String name, int value); public void addDateHeader(java.lang.String name, long date); }

To be successfully transmitted back to the client, headers must be set before the response is committed. Headers set after the response is committed will be IGNORED by the servlet container. Content type. The charset for the MIME body response can be specified explicitly using the setContentType (String) method. Explicit specifications take precedence over implicit specifications. If no charset is specified, ISO-8859-1 will be used. The setContentType method MUST be called BEFORE getWriter and BEFORE committing the response for the character encoding to be used. There are 2 ways to define content type:

http://java.boot.by/wcd-guide/ch01s03.html 2 / 5 2004/6/12 11:59:47

Using the HttpServletResponse interface, write code to set an HTTP r...ect an HTTP request to another URL, or add cookies to the response.

ServletResponse.setContentType(String); HttpServletResponse.setHeader("Content-Type", "text/html");

Acquire a text stream. To send CHARACTER data, use the PrintWriter object returned by ServletResponse.getWriter()

public interface ServletResponse { public java.io.PrintWriter getWriter() throws IOException; }

Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). Calling flush() on the PrintWriter commits the response. Either this method or getOutputStream() may be called to write the body, NOT BOTH. Acquire a binary stream. ServletResponse.getOutputStream() provides an output stream for sending BINARY data to the client. A ServletOutputStream object is normally retrieved via this method.

public interface ServletResponse { public ServletOutputStream getOutputStream() throws IOException; }

The servlet container does NOT encode the binary data. Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, NOT BOTH. Redirect an HTTP request to another URL. The HttpServletResponse.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.
http://java.boot.by/wcd-guide/ch01s03.html 3 / 5 2004/6/12 11:59:47

Using the HttpServletResponse interface, write code to set an HTTP r...ect an HTTP request to another URL, or add cookies to the response.

public interface HttpServletResponse extends javax.servlet.ServletResponse { public void sendRedirect(java.lang.String location) throws IOException; }

Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading / the container interprets it as relative to the current request URI. If the location is relative with a leading / the container interprets it as relative to the servlet container root. If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to. This method will have the side effect of committing the response, if it has 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 this method 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, this method must throw an IllegalStateException. Add cookies to the response. The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

public interface HttpServletResponse extends javax.servlet.ServletResponse { public void addCookie(Cookie cookie); }

Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.

http://java.boot.by/wcd-guide/ch01s03.html 4 / 5 2004/6/12 11:59:47

Using the HttpServletResponse interface, write code to set an HTTP r...ect an HTTP request to another URL, or add cookies to the response.

Prev Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request.

Up

Next Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method.

Home

http://java.boot.by/wcd-guide/ch01s03.html 5 / 5 2004/6/12 11:59:47

Describe the purpose and event sequence of the servlet life cycle: (1) s... init method, (4) call the service method, and (5) call destroy method.

Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method. Prev Chapter 1. The Servlet Technology Model Next

Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method.
A servlet is managed through a well defined life cycle that defines how it is loaded and instantiated, is initialized, handles requests from clients, and 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 implement directly or indirectly through the GenericServlet or HttpServlet abstract classes. Servlet class loading and instantiation. The servlet container is responsible for loading and instantiating servlets. The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is needed to service a request. When the servlet engine is started, needed servlet classes must be located by the servlet container. The servlet container loads the servlet class using normal Java class loading facilities. The loading may be from a local file system, a remote file system, or other network services. After loading the Servlet class, the container instantiates it for use. Servlet class initialization. After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read persistent configuration data, initialize costly resources (such as JDBC connections), and perform other onetime activities. The container initializes the servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface.

public interface Servlet { public void init(ServletConfig config) throws ServletException; }

http://java.boot.by/wcd-guide/ch01s04.html 1 / 3 2004/6/12 11:59:50

Describe the purpose and event sequence of the servlet life cycle: (1) s... init method, (4) call the service method, and (5) call destroy method.

This configuration object allows the servlet to access name-value initialization parameters from theWeb application's configuration information. The configuration object also gives the servlet access to an object (implementing the ServletContext interface) that describes the servlet's runtime environment. During initialization, the servlet instance can throw an UnavailableException or a ServletException. In this case, the servlet must not be placed into active service and must be released by the servlet container. The destroy method is not called as it is considered unsuccessful initialization. A new instance may be instantiated and initialized by the container after a failed initialization. The exception to this rule is when an UnavailableException indicates a minimum time of unavailability, and the container must wait for the period to pass before creating and initializing a new servlet instance. Request handling. After a servlet is properly initialized, the servlet container may use it to handle client requests. Requests are represented by request objects of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface.

public interface Servlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; }

In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.

public abstract class HttpServlet extends javax.servlet.GenericServlet implements java.io.Serializable { protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException; }

Note that a servlet instance placed into service by a servlet container may handle NO requests during its lifetime.

http://java.boot.by/wcd-guide/ch01s04.html 2 / 3 2004/6/12 11:59:50

Describe the purpose and event sequence of the servlet life cycle: (1) s... init method, (4) call the service method, and (5) call destroy method.

End of service. The servlet container is not required to keep a servlet loaded for any particular period of time. A servlet instance may be kept active in a servlet container for a period of milliseconds, for the lifetime of the servlet container (which could be a number of days, months, or years), or any amount of time in between. When the servlet container determines that a servlet should be removed from service, it calls the destroy method of the Servlet interface to allow the servlet to release any resources it is using and save any persistent state. For example, the container may do this when it wants to conserve memory resources, or when it is being shut down.

public interface Servlet { public void destroy(); }

Before the servlet container calls the destroy method, it must allow any threads that are currently running in the service method of the servlet to complete execution, or exceed a serverdefined time limit. Once the destroy method is called on a servlet instance, the container may not route other requests to that 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.

Prev Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response.

Up

Next Chapter 2. The Structure and Deployment of Web Applications

Home

http://java.boot.by/wcd-guide/ch01s04.html 3 / 3 2004/6/12 11:59:50

Chapter 2. The Structure and Deployment of Web Applications

Chapter 2. The Structure and Deployment of Web Applications Prev Part I. Exam Objectives Next

Chapter 2. The Structure and Deployment of Web Applications

Construct the file and directory structure of a Web Application that may contain (a) static content, (b) JSP pages, (c) servlet classes, (d) the deployment descriptor, (e) tag libraries, (f) JAR files, and (g) Java class files; and describe how to protect resource files from HTTP access.
A Web application exists as a structured hierarchy of directories. The root of this hierarchy serves as the document root for files that are part of the application. For example, for a Web application with the context path /catalog in a Web container, the index.html file at the base of the Web application hierarchy can be served to satisfy a request from /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. 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 by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls. Hence, if the Application Developer needs access, from servlet code, to application specific configuration information that he does not wish to be exposed directly to the Web client, he may place it under this directory. Since requests are matched to resource mappings in a case-sensitive manner, client requests for /WEB-INF/foo, /WEb-iNf/foo, for example, should not result in contents of the Web application located under /WEB-INF being returned, nor any form of directory listing thereof. The contents of the WEB-INF directory are:

The /WEB-INF/web.xml deployment descriptor. The /WEB-INF/classes/ directory for servlet and utility classes. The classes in this directory must be available to the application class loader. The /WEB-INF/lib/*.jar area for Java ARchive files. These files contain servlets, beans, and other utility classes useful to the Web application. The Web application class loader must be able to load classes from any of these archive files.

The Web application class loader must load classes from the WEB-INF/classes directory first, and then from library JARs in the WEB-INF/lib directory. Also, any requests from the client to access the resources in WEB-INF/ directory MUST be returned with a SC_NOT_FOUND (404) response. Web applications can be packaged and signed into a Web ARchive format (WAR) file using the standard Java archive tools. For example, an application for issue tracking might be distributed
http://java.boot.by/wcd-guide/ch02.html 1 / 3 2004/6/12 11:59:52

Chapter 2. The Structure and Deployment of Web Applications

in an archive file called issuetrack.war. When packaged into such a form, a META-INF directory will be present which contains information useful to Java archive tools. This directory MUST NOT be directly served as content by the container in response to a Web client's request, though its contents are visible to servlet code via the getResource and getResourceAsStream calls on the ServletContext. Also, any requests to access the resources in META-INF directory must be returned with a SC_NOT_FOUND (404) response. Tag extensions written in JSP using tag files can be placed in one of two locations. The first possibility is in the /META-INF/tags/ directory (or a subdirectory of /META-INF/tags/) in a JAR file installed in the /WEB-INF/lib/ directory of the web application. Tags placed here are typically part of a reusable library of tags that can be easily dropped into any web application. The second possibility is in the /WEB-INF/tags/ directory (or a subdirectory of /WEB-INF/tags/) of the web application. Tags placed here are within easy reach and require little packaging. Only files with a .tag or .tagx extension are recognized by the container to be tag files. Tag files that appear in any other location are not considered tag extensions and must be ignored by the JSP container. For example, a tag file that appears in the root of a web application would be treated as content to be served. The following 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/lib/jstl.jar /WEB-INF/jsp/example-taglib.tld /WEB-INF/jsp/debug-taglib.tld /WEB-INF/jsp2/jsp2-example-taglib.tld /WEB-INF/tags/displayProducts.tag /WEB-INF/tags/helloWorld.tag /WEB-INF/tags/panel.tag /WEB-INF/tags/xhtmlbasic.tag /WEB-INF/classes/com/mycorp/servlets/MyServlet.class /WEB-INF/classes/com/mycorp/util/MyUtils.class

http://java.boot.by/wcd-guide/ch02.html 2 / 3 2004/6/12 11:59:52

Chapter 2. The Structure and Deployment of Web Applications

Prev Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method.

Up

Next Describe the purpose and semantics for each of the following deployment descriptor elements: error-page, initparam, mime-mapping, servlet, servletclass, servlet-mapping, servlet-name, and welcome-file.

Home

http://java.boot.by/wcd-guide/ch02.html 3 / 3 2004/6/12 11:59:52

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

Describe the purpose and semantics for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servlet-class, servlet-mapping, servlet-name, and welcome-file. Prev Chapter 2. The Structure and Deployment of Web Applications Next

Describe the purpose and semantics for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servlet-class, servlet-mapping, servlet-name, and welcome-file.
Error pages. To allow developers to customize the appearance of content returned to a Web client when a servlet generates an error, the deployment descriptor defines a list of error page descriptions. The syntax allows the configuration of resources to be returned by the container either when a servlet or filter calls sendError on the response for specific status codes, or if the servlet generates an exception or error that propagates to the container. If the sendError method is called on the response, the container consults the list of error page declarations for the Web application that use the status-code syntax and attempts a match. If there is a match, the container returns the resource as indicated by the location entry. A servlet or filter may throw the following exceptions during processing of a request:

runtime exceptions or errors ServletExceptions or subclasses thereof IOExceptions or subclasses thereof

The Web application may have declared error pages using the exception-type element. In this case the container matches the exception type by comparing the exception thrown with the list of error-page definitions that use the exception-type element. A match results in the container returning the resource indicated in the location entry. The closest match in the class heirarchy wins. If no error-page declaration containing an exception-type fits using the class-heirarchy match, and the exception thrown is a ServletException or subclass thereof, the container extracts the wrapped exception, as defined by the ServletException.getRootCause method. A second pass is made over the error page declarations, again attempting the match against the error page declarations, but using the wrapped exception instead. error-page declarations using the exception-type element in the deployment descriptor MUST be unique up to the class name of the exception-type. Similarly, error-page declarations using the status-code element MUST be unique in the deployment descriptor up to the status code.

http://java.boot.by/wcd-guide/ch02s02.html 1 / 12 2004/6/12 11:59:58

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

If a servlet generates an error that is not handled by the error page mechanism as described above, the container must ensure to send a response with status 500. The default servlet and container will use the sendError method to send 4xx and 5xx status responses, so that the error mechanism may be invoked. The default servlet and container will use the setStatus method for 2xx and 3xx responses and will not invoke the error page mechanism. You can specify a mapping between the status code returned in an HTTP response or a Java programming language exception returned by any Web component and a Web resource. To set up the mapping, you add an error-page element to the Web application deployment descriptor.

<!-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-page contains a mapping between an error code or an exception type to the path of a resource in the Web application. The sub-element exception-type contains a fully qualified class name of a Java exception type. The sub-element location element contains the location of the resource in the web application relative to the root of the web application. The value of the location MUST have a leading '/'.

<web-app> ... <error-page> <exception-type>exception.BookNotFoundException</exception-type>


http://java.boot.by/wcd-guide/ch02s02.html 2 / 12 2004/6/12 11:59:58

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

<location>/errorpage.html</location> </error-page> </web-app>

<web-app> ... <error-page> <exception-type>exception.OrderException</exception-type> <location>/errorpage.jsp</location> </error-page> </web-app>

<web-app> ... <error-page> <error-code>404</error-code> <location>/404.html</location> </error-page> </web-app>

Init parameters. After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read persistent configuration data, initialize costly resources (such as JDBC connections), and perform other onetime activities. The container initializes the servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface. This configuration object allows the servlet to access name-value initialization parameters from the Web application's configuration information.

<!-The init-param element contains a name/value pair as an initialization param of the servlet -->

http://java.boot.by/wcd-guide/ch02s02.html 3 / 12 2004/6/12 11:59:58

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

<!ELEMENT init-param (param-name, param-value, description?)>

A servlet configuration object used by a servlet container to pass information to a servlet during initialization.

getInitParameter Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. getInitParameterNames Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an EMPTY Enumeration if the servlet has no initialization parameters.

public interface ServletConfig { public java.lang.String getInitParameter(java.lang.String name); public java.util.Enumeration getInitParameterNames(); }

<web-app> ... <servlet> <servlet-name>catalog</servlet-name> <servlet-class>com.mycorp.CatalogServlet</servlet-class> <init-param> <param-name>bgcolor</param-name> <param-value>yellow</param-value> </init-param> </servlet> ... </web-app>

... private String bgcolor;


http://java.boot.by/wcd-guide/ch02s02.html 4 / 12 2004/6/12 11:59:58

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

public void init(ServletConfig config) throws ServletException { super.init(config); try { bgcolor = config.getInitParameter("bgcolor"); System.out.println("bgcolor: " + bgcolor); } catch (Exception e) { System.out.println("error: " + e.toString()); } }

MIME mapping. The mime-mapping defines a mapping between an extension and a mime type (example: "text/ plain"). The extension element contains a string describing an extension, such as "txt".

<!-The mime-mapping element defines a mapping between an extension and a mime type. --> <!ELEMENT mime-mapping (extension, mime-type)>

<web-app> ... <mime-mapping> <extension>pdf</extension> <mime-type>application/pdf</mime-type> </mime-mapping> ...


http://java.boot.by/wcd-guide/ch02s02.html 5 / 12 2004/6/12 11:59:58

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

</web-app>

Servlet. The servlet is used to declare a servlet. It contains the declarative data of a servlet. The jsp-file element contains the full path to a JSP file within the web application beginning with a "/". If a jsp-file is specified and the load-on-startup element is present, then the JSP should be precompiled and loaded. The servlet-name element contains the canonical name of the servlet. Each servlet name is UNIQUE within the web application. The element content of servlet-name MUST NOT be empty. The servlet-class contains the fully qualified class name of the servlet. The run-as element specifies the identity to be used for the execution of a component. It contains an optional description, and the name of a security role specified by the role-name element. The element loadon-startup indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the Web application. The element content of this element must be an INTEGER indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-startup value. The security-role-ref element declares the security role reference in a component's or in a deployment component's code. It consists of an optional description, the security role name used in the code (role-name), and an optional link to a security role (role-link). If the security role is not specified, the deployer must choose an appropriate security role.

http://java.boot.by/wcd-guide/ch02s02.html 6 / 12 2004/6/12 11:59:59

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

http://java.boot.by/wcd-guide/ch02s02.html 7 / 12 2004/6/12 11:59:59

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

The servlet-class element contains the fully qualified class name of the servlet.

<!-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*)>

Servlet mapping. The servlet-mapping defines a mapping between a servlet and a URL pattern. The path used for mapping to a servlet is the request URL from the request object minus the context path and the path parameters. The URL path mapping rules below are used in order. The first successful match is used with no further matches attempted: 1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet. 2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the '/' character as a path separator. The longest match determines the servlet selected. 3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last '.' character. 4. If neither of the previous three rules result 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. The container MUST use case-sensitive string comparisons for matching. In the Web application deployment descriptor, the following syntax is used to define mappings:

A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping. A string beginning with a '*.' prefix is used as an extension mapping. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.

http://java.boot.by/wcd-guide/ch02s02.html 8 / 12 2004/6/12 11:59:59

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

All other strings are used for exact matches only.

Request_URI = Context_Path [1] + Servlet_Path [2] + Path_Info [3] + Query_String [4] http://server.com/my_app_context[1]/catalog[2]/product[3]?mode=view[4] Context path. Specifies the path prefix associated with a web application mapping. For a default application (rooted at the base of the web server's URL namespace), the context path is an empty string. For a non-default application, the context path starts with a forward slash ('/') but does not end with one. For example, /my_app_context maps requests that include /my_app_context to the my_app_context application. The HttpServletRequest.getContextPath() method returns a string representing the context path. Servlet path. Specifies the portion of the URL that matches the servlet mapping. This starts with a slash ('/'). The HttpServletRequest.getServletPath() method returns a string representing the servlet path. Path information. Comprises the remaining portion of the request path prior to query string parameters. The HttpServletRequest.getPathInfo() method returns a string representing the remainder of the path. Query string. Is contained in the request URL after the path. The HttpServletRequest.getQueryString() method returns null if the URL does not have a query string. Same as the value of the CGI variable QUERY_STRING.

<web-app> ... <servlet-mapping>

http://java.boot.by/wcd-guide/ch02s02.html 9 / 12 2004/6/12 11:59:59

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

<servlet-name>catalog</servlet-name> <url-pattern>/catalog/*</url-pattern> </servlet-mapping> ... </web-app>

<!-The servlet-mapping element defines a mapping between a servlet and a url pattern --> <!ELEMENT servlet-mapping (servlet-name, url-pattern)>

Welcome files. Web Application developers can define an ordered list of partial URIs called welcome files in the Web application deployment descriptor. The purpose of this mechanism is to allow the deployer to specify an ordered list of partial URIs for the container to use for appending to URIs when there is a request for a URI that corresponds to a directory entry in the WAR not mapped to a Web component. This kind of request is known as a valid partial request. The use for this facility is made clear by the following common example: A welcome file of 'index. html' can be defined so that a request to a URL like host:port/webapp/directory/, where 'directory' is an entry in the WAR that is not mapped to a servlet or JSP page, is returned to the client as 'host: port/webapp/directory/index.html'. If a Web container receives a valid partial request, the Web container must examine the welcome file list defined in the deployment descriptor. The welcome file list is an ordered list of partial URLs with no trailing or leading '/'. The Web server must append each welcome file in the order specified in the deployment descriptor to the partial request and check whether a static resource or servlet in the WAR is mapped to that request URI. The Web container must send the request to the first resource in the WAR that matches. If no matching welcome file is found in the manner described, the container may handle the request in a manner it finds suitable. For some configurations this may mean returning a directory listing or for others returning a 404 response. Consider a Web application where:
http://java.boot.by/wcd-guide/ch02s02.html 10 / 12 2004/6/12 11:59:59

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

<welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list>

/foo/index.html /foo/default.jsp /foo/orderform.html /foo/home.gif /catalog/default.jsp /catalog/products/shop.jsp /catalog/products/register.jsp

A request URI of /foo will be redirected to a URI of /foo/. A request URI of /foo/ will be returned as /foo/index.html. A request URI of /catalog will be redirected to a URI of /catalog/. A request URI of /catalog/ will be returned as /catalog/default.jsp. A request URI of /catalog/index.html will cause a 404 (not found). A request URI of /catalog/products will be redirected to a URI of /catalog/products/. A request URI of /catalog/products/ will be passed to the "default" servlet, if any. If no "default" servlet is mapped, the request may cause a 404 (not found), may cause a directory listing including shop.jsp and register.jsp, or may cause other behavior defined by the container.

<web-app> ... <welcome-file-list> <welcome-file>index.jsp</welcome-file>


http://java.boot.by/wcd-guide/ch02s02.html 11 / 12 2004/6/12 11:59:59

Describe the purpose and semantics for each of the following deployme...let, servlet-class, servlet-mapping, servlet-name, and welcome-file.

<welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> </welcome-file-list> ... </web-app>

Prev Chapter 2. The Structure and Deployment of Web Applications

Up

Next Construct the correct structure for each of the following deployment descriptor elements: error-page, init-param, mimemapping, servlet, servlet-class, servletmapping, servlet-name, and welcomefile.

Home

http://java.boot.by/wcd-guide/ch02s02.html 12 / 12 2004/6/12 11:59:59

Construct the correct structure for each of the following deployment d...vlet, servlet-class, servlet-mapping, servlet-name, and welcome-file.

Construct the correct structure for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servlet-class, servlet-mapping, servlet-name, and welcome-file. Prev Chapter 2. The Structure and Deployment of Web Applications Next

Construct the correct structure for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servlet-class, servlet-mapping, servletname, and welcome-file.
Error pages.

<!-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)>

Init parameters.

<!-The init-param element contains a name/value pair as an initialization param of the servlet --> <!ELEMENT init-param (param-name, param-value, description?)>

MIME mapping.

<!-The mime-mapping element defines a mapping between an extension and a mime type. -->

http://java.boot.by/wcd-guide/ch02s03.html 1 / 4 2004/6/13 12:00:02

Construct the correct structure for each of the following deployment d...vlet, servlet-class, servlet-mapping, servlet-name, and welcome-file.

<!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)>

Servlet.

<!-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*)>

<!--

http://java.boot.by/wcd-guide/ch02s03.html 2 / 4 2004/6/13 12:00:02

Construct the correct structure for each of the following deployment d...vlet, servlet-class, servlet-mapping, servlet-name, and welcome-file.

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)>

Servlet mapping.

<!-The servlet-mapping element defines a mapping between a servlet and a url pattern --> <!ELEMENT servlet-mapping (servlet-name, url-pattern)>

Welcome files.

http://java.boot.by/wcd-guide/ch02s03.html 3 / 4 2004/6/13 12:00:02

Construct the correct structure for each of the following deployment d...vlet, servlet-class, servlet-mapping, servlet-name, and welcome-file.

<!-The welcome-file-list contains an ordered list of welcome files elements. --> <!ELEMENT welcome-file-list (welcome-file+)>

Prev Describe the purpose and semantics for each of the following deployment descriptor elements: error-page, initparam, mime-mapping, servlet, servletclass, servlet-mapping, servlet-name, and welcome-file.

Up

Next Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed.

Home

http://java.boot.by/wcd-guide/ch02s03.html 4 / 4 2004/6/13 12:00:02

Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed.

Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed. Prev Chapter 2. The Structure and Deployment of Web Applications Next

Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed.
Web applications can be packaged and signed into a Web ARchive format (WAR) file using the standard Java archive tools. For example, an application for issue tracking might be distributed in an archive file called issuetrack.war. When packaged into such a form, a META-INF directory will be present which contains information useful to Java archive tools. This directory must not be directly served as content by the container in response to a Web clients request, though its contents are visible to servlet code via the getResource and getResourceAsStream calls on the ServletContext. Also, any requests to access the resources in META-INF directory must be returned with a SC_NOT_FOUND(404) response. A WAR usually contains following resources:

Servlets, JavaServer Pages (JSP), Custom Tag Libraries. Server-side utility classes (database beans, shopping carts, and so on). Static web resources (HTML, image, and sound files, and so on). Client-side classes (applets and utility classes).

The directory structure of a Web application consists of two parts. The first part is the public directory structure containing HTML/XML documents, JSP pages, images, applets, and so on. The container appropriately serves the directory's contents against incoming requests. The second part is a special WEB-INF directory that contains the following files and directories:

web.xml - the web application deployment descriptor. Tag Library Descriptor files. classes/ - a directory that contains server-side classes: servlet, utility classes, and JavaBeans components. lib/ - a directory that contains JAR archives of libraries (tag libraries and any utility libraries called by server-side classes). tags/ - a directory that contains Tag files (made easily accessible to JSPs without the need to explicitly write a Tag Library Descriptor files).

The structure of the WAR files looks like this:

WEB-INF/ WEB-INF/web.xml WEB-INF/classes/ WEB-INF/lib/


http://java.boot.by/wcd-guide/ch02s04.html 1 / 2 2004/6/13 12:00:04

Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed.

WEB-INF/tags/

To prepare the web application for deployment, package it in a WAR file using the following jar utility command from the top-level directory of the application:

jar cvf web_app.war .

where web_app is the web application name.

Prev Construct the correct structure for each of the following deployment descriptor elements: error-page, init-param, mimemapping, servlet, servlet-class, servletmapping, servlet-name, and welcomefile.

Up

Next Chapter 3. The Web Container Model

Home

http://java.boot.by/wcd-guide/ch02s04.html 2 / 2 2004/6/13 12:00:04

Chapter 3. The Web Container Model

Chapter 3. The Web Container Model Prev Part I. Exam Objectives Next

Chapter 3. The Web Container Model

For the ServletContext initialization parameters: write servlet code to access initialization parameters; and create the deployment descriptor elements for declaring initialization parameters.
The following methods of the ServletContext interface allow the servlet access to context initialization parameters associated with a Web application as specified by the Application Developer in the deployment descriptor:

getInitParameter Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. This method can make available configuration information useful to an entire "web application". For example, it can provide a webmasters email address or the name of a system that holds critical data. getInitParameterNames Returns the names of the context's initialization parameters as an Enumeration of String objects, or an EMPTY Enumeration if the context has NO initialization parameters.

Initialization parameters are used by an Application Developer to convey setup information. Typical examples are a Webmasters e-mail address, or the name of a system that holds critical data.

public interface ServletContext { public java.lang.String getInitParameter(java.lang.String name); public java.util.Enumeration getInitParameterNames(); }

Context initialization parameters that define shared String constants used within your application, which can be customized by the system administrator who is installing your application. The values actually assigned to these parameters can be retrieved in a servlet or JSP page by calling:

http://java.boot.by/wcd-guide/ch03.html 1 / 3 2004/6/13 12:00:07

Chapter 3. The Web Container Model

javax.servlet.ServletContext context = getServletContext(); String value = context.getInitParameter("webmaster");

where "webmaster" matches the param-name element of one of these initialization parameters. You can define any number of context initialization parameters, including zero:

<web-app> ... <context-param> <param-name>webmaster</param-name> <param-value>myaddress@mycompany.com</param-value> <description> The EMAIL address of the administrator to whom questions and comments about this application should be addressed. </description> </context-param> ... </web-app>

<!-The context-param element contains the declaration of a web applications servlet context initialization parameters. --> <!ELEMENT context-param (param-name, param-value, description?)>

Prev Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed.

Up

Next For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multithreading issues associated with each scope.

Home

http://java.boot.by/wcd-guide/ch03.html 2 / 3 2004/6/13 12:00:07

Chapter 3. The Web Container Model

http://java.boot.by/wcd-guide/ch03.html 3 / 3 2004/6/13 12:00:07

For the fundamental servlet attribute scopes (request, session, and con...ibute; and identify multi-threading issues associated with each scope.

For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multi-threading issues associated with each scope. Prev Chapter 3. The Web Container Model Next

For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multi-threading issues associated with each scope.
Request 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 the RequestDispatcher). Attributes are accessed with the following methods of the ServletRequest interface:

getAttribute Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. Attributes can be set two ways. The servlet container may set attributes to make available custom information about a request. Attributes can also be set programatically using setAttribute(String, Object). This allows information to be embedded into a request before a RequestDispatcher call. Attribute names should follow the same conventions as package names. This specification reserves names matching java.*, javax.*, and sun.*. getAttributeNames Returns an Enumeration containing the names of the attributes available to this request. This method returns an EMPTY Enumeration if the request has no attributes available to it. setAttribute Stores an attribute in this request. Attributes are reset between requests. This method is most often used in conjunction with RequestDispatcher. Attribute names should follow the same conventions as package names. Names beginning with java.*, javax.*, and com.sun.*, are reserved for use by Sun Microsystems. If the object passed in is null, the effect is the same as calling removeAttribute(String). removeAttribute Removes an attribute from this request. This method is not generally needed as attributes only persist as long as the request is being handled.

Only ONE attribute value may be associated with an attribute name.

package javax.servlet;
http://java.boot.by/wcd-guide/ch03s02.html 1 / 5 2004/6/13 12:00:10

For the fundamental servlet attribute scopes (request, session, and con...ibute; and identify multi-threading issues associated with each scope.

public interface ServletRequest { public java.lang.Object getAttribute(java.lang.String name); public java.util.Enumeration getAttributeNames(); public void setAttribute(java.lang.String name, java.lang.Object o); public void removeAttribute(java.lang.String name); }

Attribute names beginning with the prefixes of "java." and "javax." are RESERVED for definition by this specification. Similarly, attribute names beginning with the prefixes of "sun.", and "com. sun." are reserved for definition by Sun Microsystems. It is suggested that all attributes placed in the attribute set be named in accordance with the reverse domain name convention suggested by the Java Programming Language Specification for package naming. Session Attributes. 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 handles a request identified as being a part of the same session.

getAttribute Returns the object bound with the specified name in this session, or null if no object is bound under the name. getAttributeNames Returns an Enumeration of String objects containing the names of all the objects bound to this session. setAttribute Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced. After this method executes, and if the new object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueBound. The container then notifies any HttpSessionAttributeListeners in the web application. If an object was already bound to this session of this name that implements HttpSessionBindingListener, its HttpSessionBindingListener.valueUnbound method is called. If the value passed in is null, this has the same effect as calling removeAttribute(). removeAttribute Removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing. After this method executes, and if the object implements HttpSessionBindingListener, the container

http://java.boot.by/wcd-guide/ch03s02.html 2 / 5 2004/6/13 12:00:10

For the fundamental servlet attribute scopes (request, session, and con...ibute; and identify multi-threading issues associated with each scope.

calls HttpSessionBindingListener.valueUnbound. The container then notifies any HttpSessionAttributeListeners in the web application.

package javax.servlet.http; public interface HttpSession { public java.lang.Object getAttribute(java.lang.String name); public java.util.Enumeration getAttributeNames(); public void setAttribute(java.lang.String name, java.lang.Object value); public void removeAttribute(java.lang.String name); }

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. Multiple servlets executing request threads may have active access to a single session object at the same time. The Developer has the responsibility for synchronizing access to session resources as appropriate. Within an application marked as distributable, all requests that are part of a session must be handled by one Java Virtual Machine (JVM) at a time. The container must be able to handle all objects placed into instances of the HttpSession class using the setAttribute or putValue methods appropriately. The following restrictions are imposed to meet these conditions:

The container must accept objects that implement the Serializable interface. The container may choose to support storage of other designated objects in the HttpSession, such as references to Enterprise JavaBeans components and transactions. Migration of sessions will be handled by container-specific facilities.

The distributed servlet container must throw an IllegalArgumentException for objects where the container cannot support the mechanism necessary for migration of the session storing them. Containers must notify any session attributes implementing the HttpSessionActivationListener
http://java.boot.by/wcd-guide/ch03s02.html 3 / 5 2004/6/13 12:00:10

For the fundamental servlet attribute scopes (request, session, and con...ibute; and identify multi-threading issues associated with each scope.

during migration of a session. They must notify listeners of passivation prior to serialization of a session, and of activation after deserialization of a session. Application Developers writing distributed applications should be aware that since the container may run in more than one Java virtual machine, the developer cannot depend on static variables for storing an application state. They should store such states using an enterprise bean or a database. Context Attributes. A servlet can bind an object attribute into the context by name. Any attribute 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 Binds an object to a given attribute name in this servlet context. If the name specified is already used for an attribute, this method will REPLACE the attribute with the new to the new attribute. If listeners are configured on the ServletContext the container notifies them accordingly. If a null value is passed, the effect is the same as calling removeAttribute(). Attribute names should follow the same convention as package names. The Java Servlet API specification reserves names matching java.*, javax.*, and sun.*. getAttribute Returns the servlet container attribute with the given name, or null if there is no attribute by that name. An attribute allows a servlet container to give the servlet additional information not already provided by this interface. See your server documentation for information about its attributes. A list of supported attributes can be retrieved using getAttributeNames. The attribute is returned as a java.lang.Object or some subclass. Attribute names should follow the same convention as package names. The Java Servlet API specification reserves names matching java.*, javax.*, and sun.*. getAttributeNames Returns an Enumeration containing the attribute names available within this servlet context. Use the getAttribute(String) method with an attribute name to get the value of an attribute. removeAttribute Removes the attribute with the given name from the servlet context. After removal, subsequent calls to getAttribute(String) to retrieve the attributes value will return null. If listeners are configured on the ServletContext the container notifies them accordingly.

package javax.servlet; public interface ServletContext {

http://java.boot.by/wcd-guide/ch03s02.html 4 / 5 2004/6/13 12:00:10

For the fundamental servlet attribute scopes (request, session, and con...ibute; and identify multi-threading issues associated with each scope.

public void setAttribute(java.lang.String name, java.lang.Object object); public java.lang.Object getAttribute(java.lang.String name); public java.util.Enumeration getAttributeNames(); public void removeAttribute(java.lang.String name); }

Context attributes are LOCAL to the JVM in which they were created. This prevents ServletContext attributes from being a shared memory store in a distributed container. When information needs to be shared between servlets running in a distributed environment, the information should be placed into a session, stored in a database, or set in an Enterprise JavaBeans component.

Prev Chapter 3. The Web Container Model

Up

Next Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper.

Home

http://java.boot.by/wcd-guide/ch03s02.html 5 / 5 2004/6/13 12:00:10

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper. Prev Chapter 3. The Web Container Model Next

Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper.
Request processing model. The container, when receiving an incoming request, processes the request as follows:

Identifies the target Web resource according to the rules of mappings. If there are filters matched by servlet name and the Web resource has a <servlet-name>, the container builds the chain of filters matching in the order declared in the deployment descriptor. The last filter in this chain corresponds to the last <servlet-name> matching filter and is the filter that invokes the target Web resource. If there are filters using <url-pattern> matching and the <url-pattern> matches the request URI according to the rules of mappings, the container builds the chain of <url-pattern> matched filters in the same order as declared in the deployment descriptor. The last filter in this chain is the last <url-pattern> matching filter in the deployment descriptor for this request URI. The last filter in this chain is the filter that invokes the first filter in the <servlet-name> matching chain, or invokes the target Web resource if there are none.

The order the container uses in building the chain of filters to be applied for a particular request URI is as follows: 1. First, the <url-pattern> matching filter mappings in the same order that these elements appear in the deployment descriptor. 2. Next, the <servlet-name> matching filter mappings in the same order that these elements appear in the deployment descriptor. Writing and configuring a filter. Filters are Java components that allow on the fly transformations of payload and header information in both the request into a resource and the response from a resource. Filters differ from Web components in that they usually do not themselves create a response. Instead, a filter provides functionality that can be "attached" to any kind of Web resource. As a consequence, a filter should not have any dependencies on a Web resource for which it is acting as a filter, so that it can be composable with more than one type of Web resource. A filter is a reusable piece of code that can transform the content of HTTP requests, responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt
http://java.boot.by/wcd-guide/ch03s03.html 1 / 10 2004/6/13 12:00:15

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

responses from a resource. Filters can act on dynamic or static content. The main tasks that a filter can perform are as follows:

Query the request and act accordingly. Block the request-and-response pair from passing any further. Modify the request headers and data. You do this by providing a customized version of the request. Modify the response headers and data. You do this by providing a customized version of the response. Interact with external resources.

You can configure a Web resource to be filtered by a chain of zero, one, or more filters in a specific order. This chain is specified when the Web application containing the component is deployed and is instantiated when a Web container loads the component. The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. The application developer creates a filter by implementing the javax.servlet.Filter interface and providing a public constructor taking NO arguments. The class is packaged in the Web Archive along with the static content and servlets that make up the Web application. A filter is declared using the <filter> element in the deployment descriptor. A filter or collection of filters can be configured for invocation by defining <filter-mapping> elements in the deployment descriptor. This is done by mapping filters to a particular servlet by the servlet's logical name, or mapping to a group of servlets and static content resources by mapping a filter to a URL pattern.

package javax.servlet; public interface Filter { public void init(FilterConfig filterConfig) throws ServletException; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException; public void destroy(); }

The most important method in this interface is the doFilter method, which is passed request, response, and filter chain objects. This method can perform the following actions:

Examine the request headers. Customize the request object if it wishes to modify request headers or data. Customize the response object if it wishes to modify response headers or data. Invoke the next entity in the filter chain. If the current filter is the last filter in the chain that ends with the target Web component or static resource, the next entity is the

http://java.boot.by/wcd-guide/ch03s03.html 2 / 10 2004/6/13 12:00:15

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

resource at the end of the chain; otherwise, it is the next filter that was configured in the WAR. It invokes the next entity by calling the doFilter method on the chain object (passing in the request and response it was called with, or the wrapped versions it may have created). Alternatively, it can choose to block the request by not making the call to invoke the next entity. In the latter case, the filter is responsible for filling out the response. Examine response headers after it has invoked the next filter in the chain. Throw an exception to indicate an error in processing.

In addition to doFilter, you must implement the init and destroy methods. The init method is called by the container when the filter is instantiated. If you wish to pass initialization parameters to the filter, you retrieve them from the FilterConfig object passed to init. After deployment of the Web application, and before a request causes the container to access a Web resource, the container must locate the list of filters that must be applied to the Web resource as described below. The container must ensure that it has instantiated a filter of the appropriate class for each filter in the list, and called its init(FilterConfig config) method. The filter may throw an exception to indicate that it cannot function properly. If the exception is of type UnavailableException, the container may examine the isPermanent attribute of the exception and may choose to retry the filter at some later time. Only ONE instance per <filter> declaration in the deployment descriptor is instantiated per Java Virtual Machine (JVM) of the container. The container provides the filter config as declared in the filter's deployment descriptor, the reference to the ServletContext for the Web application, and the set of initialization parameters. When the container receives an incoming request, it takes the first filter instance in the list and calls its doFilter method, passing in the ServletRequest and ServletResponse, and a reference to the FilterChain object it will use. The doFilter method of a filter will typically be implemented following this or some subset of the following pattern: 1. The method examines the request's headers. 2. The method may wrap the request object with a customized implementation of ServletRequest or HttpServletRequest in order to modify request headers or data. 3. The method may wrap the response object passed in to its doFilter method with a customized implementation of ServletResponse or HttpServletResponse to modify response headers or data. 4. The filter may invoke the next entity in the filter chain. The next entity may be another filter, or if the filter making the invocation is the last filter configured in the deployment descriptor for this chain, the next entity is the target Web resource. The invocation of the next entity is effected by calling the doFilter method on the FilterChain object, and passing in the request and response with which it was called or passing in wrapped versions it may have created. The filter chain's implementation of the doFilter method, provided by the container, must

http://java.boot.by/wcd-guide/ch03s03.html 3 / 10 2004/6/13 12:00:15

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

locate the next entity in the filter chain and invoke its doFilter method, passing in the appropriate request and response objects. Alternatively, the filter chain can block the request by not making the call to invoke the next entity, leaving the filter responsible for filling out the response object. After invocation of the next filter in the chain, the filter may examine response headers. Alternatively, the filter may have thrown an exception to indicate an error in processing. If the filter throws an UnavailableException during its doFilter processing, the container must not attempt continued processing down the filter chain. It may choose to retry the whole chain at a later time if the exception is not marked permanent. When the last filter in the chain has been invoked, the next entity accessed is the target servlet or resource at the end of the chain. Before a filter instance can be removed from service by the container, the container must first call the destroy method on the filter to enable the filter to release any resources and perform other cleanup operations.

5. 6.

7. 8.

public final class ExampleFilter implements Filter { private String attribute = null; private FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.attribute = filterConfig.getInitParameter("attribute"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Store ourselves as a request attribute (if requested) if (attribute != null) { request.setAttribute(attribute, this); } // Time and log the subsequent processing long startTime = System.currentTimeMillis(); chain.doFilter(request, response); long stopTime = System.currentTimeMillis(); filterConfig.getServletContext().log (this.toString() + ": " + (stopTime - startTime) + " milliseconds"); } public void destroy() { this.attribute = null; this.filterConfig = null; }
http://java.boot.by/wcd-guide/ch03s03.html 4 / 10 2004/6/13 12:00:15

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

<web-app> ... <!-- Define servlet-mapped and path-mapped example filters --> <filter> <filter-name>Servlet Mapped Filter</filter-name> <filter-class>filters.ExampleFilter</filter-class> <init-param> <param-name>attribute</param-name> <param-value>filters.ExampleFilter.SERVLET_MAPPED</param-value> </init-param> </filter> <filter> <filter-name>Path Mapped Filter</filter-name> <filter-class>filters.ExampleFilter</filter-class> <init-param> <param-name>attribute</param-name> <param-value>filters.ExampleFilter.PATH_MAPPED</param-value> </init-param> </filter> <!-- Define filter mappings for the defined filters --> <filter-mapping> <filter-name>Servlet Mapped Filter</filter-name> <servlet-name>invoker</servlet-name> </filter-mapping> <filter-mapping> <filter-name>Path Mapped Filter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping> ... </web-app>

Here is another example of a filter declaration:

http://java.boot.by/wcd-guide/ch03s03.html 5 / 10 2004/6/13 12:00:15

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

<filter> <filter-name>Image Filter</filter-name> <filter-class>com.acme.ImageServlet</filter-class> </filter>

Once a filter has been declared in the deployment descriptor, the assembler uses the filtermapping element to define servlets and static resources in the Web application to which the filter is to be applied. Filters can be associated with a servlet using the servlet-name element. For example, the following code example maps the Image Filter filter to the ImageServlet servlet:

<filter-mapping> <filter-name>Image Filter</filter-name> <servlet-name>ImageServlet</servlet-name> </filter-mapping>

Filters can be associated with groups of servlets and static content using the url-pattern style of filter mapping:

<filter-mapping> <filter-name>Logging Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

Here the Logging Filter is applied to all the servlets and static content pages in the Web application, because every request URI matches the '/*' URL pattern. The url-pattern matching takes precedence (is applied first) over the servlet-name matching (is applied next).

<!-Declares a filter in the web application. The filter is mapped to either a servlet or a URL pattern in the filter-mapping element, using the filter-name value to reference. Filters can access the initialization parameters declared in the deployment descriptor at
http://java.boot.by/wcd-guide/ch03s03.html 6 / 10 2004/6/13 12:00:15

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

runtime via the FilterConfig interface. Used in: web-app --> <!ELEMENT filter (icon?, filter-name, display-name?, description?, filter-class, init-param*)>

<!-Declaration of the filter mappings in this web application. The container uses the filter-mapping declarations to decide which filters to apply to a request, and in what order. The container matches the request URI to a Servlet in the normal way. To determine which filters to apply it matches filter-mapping declarations either on servlet-name, or on url-pattern for each filter-mapping element, depending on which style is used. The order in which filters are invoked is the order in which filter-mapping declarations that match a request URI for a servlet appear in the list of filter-mapping elements.The filter-name value must be the value of the <filter-name> sub-elements of one of the <filter> declarations in the deployment descriptor. Used in: web-app --> <!ELEMENT filter-mapping (filter-name, (url-pattern | servlet-name), dispatcher*)>

The dispatcher has four legal values: FORWARD, REQUEST, INCLUDE, and ERROR. A value of FORWARD means the Filter will be applied under RequestDispatcher.forward() calls. A value of REQUEST means the Filter will be applied under ordinary client calls to the PATH or SERVLET. A value of INCLUDE means the Filter will be applied under RequestDispatcher.include() calls. A value of ERROR means the Filter will be applied under the error page mechanism. The absence of any dispatcher elements in a filter-mapping indicates a default of applying filters only under ordinary client calls to the PATH or SERVLET (REQUEST).

<filter-mapping> <filter-name>Logging Filter</filter-name> <url-pattern>/products/*</url-pattern>

http://java.boot.by/wcd-guide/ch03s03.html 7 / 10 2004/6/13 12:00:15

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

<dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping>

This example would result in the Logging Filter being invoked by client requests starting / products/... and underneath a request dispatcher forward() call where the request dispatcher has path commencing /products/.... Wrapping request and response objects. As well as performing basic pre and post processing operations a filter can also wrap up the request or response objects in a custom wrapper. Such custom wrappers can then modify the information provided to the servlet via a request object or process information generated by the servlet via the response object. There are four classes that make up the Wrapping API. These are the javax.servlet.ServletRequestWrapper, javax.servlet.ServletResponseWrapper, javax.servlet.http. HttpServletRequestWrapper and javax.servlet.http.HttpServletResponseWrapper. These classes implement the respective interfaces (e.g. ServletRequest, ServletResponse, HttpServletRequest and HttpServletResponse) and can thus be used anywhere that these interfaces are specified. Most notably they can therefore be used inside a Filter to wrap the actual request or response object up so that the filter can control either the data accessed by the Servlet (or JSP) or generated by the Servlet or JSP. A particular use of these wrappers is to perform some pre or post processing of the data being used or generated by the Servlet so that the Servlet does not need to know about this processing. A filter that modifies a response must usually capture the response before it is returned to the client. The way to do this is to pass a stand-in stream to the servlet that generates the response. The stand-in stream prevents the servlet from closing the original response stream when it completes and allows the filter to modify the servlet's response. To pass this stand-in stream to the servlet, the filter creates a response wrapper that overrides the getWriter or getOutputStream method to return this stand-in stream. The wrapper is passed to the doFilter method of the filter chain. Wrapper methods default to calling through to the wrapped request or response object. This approach follows the well-known Wrapper or Decorator pattern described in 'Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995)'. To override request methods, you wrap the request in an object that extends ServletRequestWrapper or HttpServletRequestWrapper. To override response methods, you wrap the response in an object that extends ServletResponseWrapper or HttpServletResponseWrapper. Example of filter with wrapper (post processing of servlet's output):

public final class HitCounterFilter implements Filter {


http://java.boot.by/wcd-guide/ch03s03.html 8 / 10 2004/6/13 12:00:16

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

private FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Counter counter = (Counter)filterConfig.getServletContext(). getAttribute("hitCounter"); writer.println(); writer.println("==============="); writer.println("The number of hits is: " + counter.incCounter()); writer.println("==============="); // Log the resulting string writer.flush(); filterConfig.getServletContext().log(sw.getBuffer().toString()); PrintWriter out = response.getWriter(); CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse)response); chain.doFilter(request, wrapper); CharArrayWriter caw = new CharArrayWriter(); caw.write(wrapper.toString(). substring(0, wrapper.toString().indexOf("</body>")-1)); caw.write("<p>\n<center><center>" + messages.getString("Visitor") + "<font color='red'>" + counter.getCounter() + "</font><center>"); caw.write("\n</body></html>"); response.setContentLength(caw.toString().length()); out.write(caw.toString()); out.close(); } public void destroy() { this.filterConfig = null; } }

http://java.boot.by/wcd-guide/ch03s03.html 9 / 10 2004/6/13 12:00:16

Describe the Web container request processing model; write and configu... given a design problem, describe how to apply a filter or a wrapper.

public class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; public String toString() { return output.toString(); } public CharResponseWrapper(HttpServletResponse response) { super(response); output = new CharArrayWriter(); } public PrintWriter getWriter() { return new PrintWriter(output); } }

HitCounterFilter wraps the response in a CharResponseWrapper. The wrapped response is passed to the next object in the filter chain. Next servlet writes (buffers) its response into the stream created by CharResponseWrapper. When chain.doFilter returns, HitCounterFilter retrieves the servlet's response from PrintWriter and writes it to a buffer (CharArrayWriter). The filter inserts the value of the counter into the buffer, resets the content length header of the response, and finally writes the contents of the buffer to the response stream.

Prev For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multithreading issues associated with each scope.

Up

Next Describe the Web container life cycle event model for requests, sessions, and web applications; create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use.

Home

http://java.boot.by/wcd-guide/ch03s03.html 10 / 10 2004/6/13 12:00:16

Describe the Web container life cycle event model for requests, sessions...s; and given a scenario, identify the proper attribute listener to use.

Describe the Web container life cycle event model for requests, sessions, and web applications; create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use. Prev Chapter 3. The Web Container Model Next

Describe the Web container life cycle event model for requests, sessions, and web applications; create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use.
The application events facility gives the Web Application Developer greater control over the lifecycle of the ServletContext and HttpSession and ServletRequest, allows for better code factorization, and increases efficiency in managing the resources that the Web application uses. Application event listeners are classes that implement one or more of the servlet event listener interfaces. They are instantiated and registered in the Web container at the time of the deployment of the Web application. They are provided by the Developer in the WAR. Servlet event listeners support event notifications for state changes in the ServletContext, HttpSession and ServletRequest objects. Servlet context listeners are used to manage resources or state held at a JVM level for the application. HTTP session listeners are used to manage state or resources associated with a series of requests made into a Web application from the same client or user. Servlet request listeners are used to manage state across the lifecycle of servlet requests. There may be multiple listener classes listening to each event type, and the Developer may specify the order in which the container invokes the listener beans for each event type. Servlet Context Events and Listeners. Implementations of the following interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application. All ServletContextListeners are notified of context initialization before any filter or servlet in the web application is initialized. All servlets and filters have been destroyed before any ServletContextListeners are notified of context destruction.

package javax.servlet; public interface ServletContextListener extends java.util.EventListener { public void contextDestroyed(ServletContextEvent sce); public void contextInitialized(ServletContextEvent sce);
http://java.boot.by/wcd-guide/ch03s04.html 1 / 8 2004/6/13 12:00:20

Describe the Web container life cycle event model for requests, sessions...s; and given a scenario, identify the proper attribute listener to use.

This is the event class for notifications about changes to the servlet context of a web application:

package javax.servlet; public class ServletContextEvent extends java.util.EventObject { public ServletContext getServletContext(); }

Implementations of the following interface receive notifications of changes to the attribute list on the servlet context of a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

attributeAdded notifies that a new attribute was added to the servlet context. Called after the attribute is added. attributeRemoved notifies that an existing attribute has been removed from the servlet context. Called after the attribute is removed. attributeReplaced( notifies that an attribute on the servlet context has been replaced. Called after the attribute is replaced.

package javax.servlet; public interface ServletContextAttributeListener extends java.util.EventListener { public void attributeAdded(ServletContextAttributeEvent scae); public void attributeRemoved(ServletContextAttributeEvent scae); public void attributeReplaced(ServletContextAttributeEvent scae); }

This is the event class for notifications about changes to the attributes of the servlet context of a web application:

package javax.servlet; public class ServletContextAttributeEvent extends javax.servlet.ServletContextEvent {


http://java.boot.by/wcd-guide/ch03s04.html 2 / 8 2004/6/13 12:00:20

Describe the Web container life cycle event model for requests, sessions...s; and given a scenario, identify the proper attribute listener to use.

public java.lang.String getName(); public java.lang.Object getValue(); }

HTTP Session Events and Listeners. Implementations of the following interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

package javax.servlet.http; public interface HttpSessionListener extends java.util.EventListener { public void sessionCreated(HttpSessionEvent hse); public void sessionDestroyed(HttpSessionEvent hse); }

This is the class representing event notifications for changes to sessions within a web application:

package javax.servlet.http; public class HttpSessionEvent extends java.util.EventObject { public HttpSession getSession(); }

Following listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application:

attributeAdded notifies that a new attribute was added to the session. Called after the attribute is added. attributeRemoved notifies that an existing attribute has been removed from the session. Called after the attribute is removed. attributeReplaced notifies that an attribute has been replaced in the session. Called after the attribute is replaced.

http://java.boot.by/wcd-guide/ch03s04.html 3 / 8 2004/6/13 12:00:20

Describe the Web container life cycle event model for requests, sessions...s; and given a scenario, identify the proper attribute listener to use.

package javax.servlet.http; public interface HttpSessionAttributeListener extends java.util.EventListener { public void attributeAdded(HttpSessionBindingEvent hsbe); public void attributeRemoved(HttpSessionBindingEvent hsbe); public void attributeReplaced(HttpSessionBindingEvent hsbe); }

Events of the following type are either sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the deployment descriptor when any attribute is bound, unbound or replaced in a session. The session binds the object by a call to HttpSession.setAttribute and unbinds the object by a call to HttpSession.removeAttribute. The getValue function returns the value of the attribute that has been added, removed or replaced. If the attribute was added (or bound), this is the value of the attribute. If the attribute was removed (or unbound), this is the value of the removed attribute. If the attribute was replaced, this is the OLD value of the attribute.

package javax.servlet.http; public class HttpSessionBindingEvent extends javax.servlet.http.HttpSessionEvent { public java.lang.String getName(); public HttpSession getSession(); public java.lang.Object getValue(); // returns : // new value for added (bounded) attributes, // old value for replaced and removed (unbounded) attributes }

When container migrates a session between VMs in a distributed container setting, all session attributes implementing the HttpSessionActivationListener interface are notified. Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.

package javax.servlet.http;

http://java.boot.by/wcd-guide/ch03s04.html 4 / 8 2004/6/13 12:00:20

Describe the Web container life cycle event model for requests, sessions...s; and given a scenario, identify the proper attribute listener to use.

public interface HttpSessionActivationListener extends java.util.EventListener { public void sessionDidActivate(HttpSessionEvent hse); public void sessionWillPassivate(HttpSessionEvent hse); }

The following interface causes an OBJECT to be notified when it is bound to or unbound from a session. The object is notified by an HttpSessionBindingEvent object. This may be as a result of a servlet programmer explicitly unbinding an attribute from a session, due to a session being invalidated, or due to a session timing out.

package javax.servlet.http; public interface HttpSessionBindingListener extends java.util.EventListener { public void valueBound(HttpSessionBindingEvent hsbe); public void valueUnbound(HttpSessionBindingEvent hsbe); }

Servlet Request Events and Listeners. A ServletRequestListener can be implemented by the developer interested in being notified of requests coming in and out of scope in a web component. A request is defined as coming into scope when it is about to enter the first servlet or filter in each web application, as going out of scope when it exits the last servlet or the first filter in the chain.

package javax.servlet; public interface ServletRequestListener { requestInitialized(ServletRequestEvent sre); requestDestroyed(ServletRequestEvent sre); }

Events of this kind indicate lifecycle events for a ServletRequest. The source of the event is the ServletContext of this web application.

http://java.boot.by/wcd-guide/ch03s04.html 5 / 8 2004/6/13 12:00:20

Describe the Web container life cycle event model for requests, sessions...s; and given a scenario, identify the proper attribute listener to use.

package javax.servlet; public class ServletRequestEvent extends java.util.EventObject { public ServletRequest getServletRequest(); public ServletContext getServletContext(); }

A ServletRequestAttributeListener can be implemented by the developer interested in being notified of request attribute changes. Notifications will be generated while the request is within the scope of the web application in which the listener is registered. A request is defined as coming into scope when it is about to enter the first servlet or filter in each web application, as going out of scope when it exits the last servlet or the first filter in the chain.

package javax.servlet; public interface ServletRequestAttributeListener { public void attributeAdded(ServletRequestAttributeEvent srae); public void attributeRemoved(ServletRequestAttributeEvent srae); public void attributeReplaced(ServletRequestAttributeEvent srae); }

The following is the event class for notifications of changes to the attributes of ServletRequest in an application. The getValue() function returns the value of the attribute that has been added, removed or replaced. If the attribute was added, this is the value of the attribute. If the attribute was removed, this is the value of the REMOVED attribute. If the attribute was replaced, this is the OLD value of the attribute.

package javax.servlet; public class ServletRequestAttributeEvent extends ServletRequestEvent { public java.lang.String getName(); public java.lang.Object getValue(); }

Table 3.1. Events and Listener Interfaces

http://java.boot.by/wcd-guide/ch03s04.html 6 / 8 2004/6/13 12:00:20

Describe the Web container life cycle event model for requests, sessions...s; and given a scenario, identify the proper attribute listener to use.

Scope

Event Initialization and destruction Attribute added, removed, or replaced Created and destroyed Activated and passivated (migrated)

Listener Interface and Event Class ServletContextListener, ServletContextEvent ServletContextAttributeListener, ServletContextAttributeEvent HttpSessionListener, HttpSessionEvent HttpSessionActivationListener, HttpSessionEvent HttpSessionAttributeListener, HttpSessionBindingEvent (note the class name !) HttpSessionBindingListener (note, interface must be implemented by attribute class !), HttpSessionBindingEvent ServletRequestListener, ServletRequestEvent ServletRequestAttributeListener, ServletRequestAttributeEvent

Servlet Context

HTTP Session

Attribute added, removed, or replaced Object bound or unbound Initialized and destroyed Attribute added, removed, or replaced

Servlet Request

The Developer of the Web application provides listener classes implementing one or more of the listener classes in the servlet API. Each listener class must have a public constructor taking NO arguments. The listener classes are packaged into the WAR, either under the WEB-INF/classes archive entry, or inside a JAR in the WEB-INF/lib directory. Listener classes are declared in the Web application deployment descriptor using the listener element. They are listed by class name in the order in which they are to be invoked. During Web application execution, listeners are invoked in the order of their registration. On application shutdown, listeners are notified in REVERSE order to their declarations with notifications to session listeners preceeding notifications to context listeners. Session listeners must be notified of session invalidations prior to context listeners being notified of application shutdown.

<web-app> ... <listener> <listener-class>listeners.ContextListener</listener-class> </listener> ... </web-app>

http://java.boot.by/wcd-guide/ch03s04.html 7 / 8 2004/6/13 12:00:20

Describe the Web container life cycle event model for requests, sessions...s; and given a scenario, identify the proper attribute listener to use.

In distributed Web containers, HttpSession instances are scoped to the particular JVM servicing session requests, and the ServletContext object is scoped to the Web container's JVM. Distributed containers are not required to propagate either servlet context events or HttpSession events to other JVMs. Listener class instances are scoped to one per deployment descriptor declaration per Java Virtual Machine.

Prev Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper.

Up

Next Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource.

Home

http://java.boot.by/wcd-guide/ch03s04.html 8 / 8 2004/6/13 12:00:20

Describe the RequestDispatcher mechanism; write servlet code to create...t-scoped attributes provided by the container to the target resource.

Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource. Prev Chapter 3. The Web Container Model Next

Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource.
RequestDispatcher description. RequestDispatcher defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. An object implementing the RequestDispatcher interface may be obtained via the following methods:

ServletContext.getRequestDispatcher(String path) ServletContext.getNamedDispatcher(String name) ServletRequest.getRequestDispatcher(String path)

The ServletContext.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 and begin with a '/'. The method uses the path to look up a servlet, using the servlet path matching rules, wraps it with a RequestDispatcher object, and returns the resulting object. If no servlet can be resolved based on the given path, a RequestDispatcher is provided that returns the content for that path. The ServletContext.getNamedDispatcher method takes a String argument indicating the NAME of a servlet known to the ServletContext. If a servlet is found, it is wrapped with a RequestDispatcher object and the object is 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 that are relative to the path of the current request (not relative to the root of the ServletContext), the ServletRequest. getRequestDispatcher method is provided in the ServletRequest interface. The behavior of this method is similar to the method of the same name in the ServletContext. The servlet container uses information in the request object to transform the given relative path against the current servlet to a complete path. For example, in a context rooted at '/' and a request to /garden/tools. html, a request dispatcher obtained via ServletRequest.getRequestDispatcher("header.html") will

http://java.boot.by/wcd-guide/ch03s05.html 1 / 5 2004/6/13 12:00:23

Describe the RequestDispatcher mechanism; write servlet code to create...t-scoped attributes provided by the container to the target resource.

behave exactly like a call to ServletContext.getRequestDispatcher("/garden/header.html"). RequestDispatcher creation and using.

public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { RequestDispatcher dispatcher = request.getRequestDispatcher("/template.jsp"); if (dispatcher != null) dispatcher.forward(request, response); } }

forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner"); if (dispatcher != null) dispatcher.include(request, response); } }

Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes. The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

package javax.servlet; public interface RequestDispatcher { public void forward(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException; public void include(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException; }

http://java.boot.by/wcd-guide/ch03s05.html 2 / 5 2004/6/13 12:00:23

Describe the RequestDispatcher mechanism; write servlet code to create...t-scoped attributes provided by the container to the target resource.

The include method of the RequestDispatcher interface may be called at ANY time. The target servlet of the include method has access to all aspects of the request object, but its use of the response object is more limited. It can only write information to the ServletOutputStream or Writer of the response object and commit a response by writing content past the end of the response buffer, or by explicitly calling the flushBuffer method of the ServletResponse interface. It CANNOT set headers or call any method that affects the headers of the response. Any attempt to do so must be ignored. The forward method of the RequestDispatcher interface may be called by the calling servlet ONLY when NO output has been committed to the client. If output data exists in the response buffer that has not been committed, the content must be cleared 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 must reflect those of the original request. Before the forward method of the RequestDispatcher interface returns, the response content MUST be sent and committed, and closed by the servlet container. The ServletContext and ServletRequest methods that create RequestDispatcher objects using path information allow the optional attachment of query string information to the path. For example, a Developer may obtain a RequestDispatcher by using the following code:

String path = "/raisins.jsp?orderno=5"; RequestDispatcher rd = context.getRequestDispatcher(path); rd.include(request, response);

Parameters specified in the query string used to create the RequestDispatcher take precedence over other parameters of the same name passed to the included servlet. The parameters associated with a RequestDispatcher are scoped to apply only for the duration of the include or forward call. Additional request-scoped attributes. Except for servlets obtained by using the getNamedDispatcher method, a servlet that has been invoked by another servlet using the include method of RequestDispatcher has access to the path by which it was invoked. The following request attributes must be set:

javax.servlet.include.request_uri javax.servlet.include.context_path

http://java.boot.by/wcd-guide/ch03s05.html 3 / 5 2004/6/13 12:00:23

Describe the RequestDispatcher mechanism; write servlet code to create...t-scoped attributes provided by the container to the target resource.

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 request object and their values must be equal to the request URI, context path, servlet path, path info, and query string of the INCLUDED servlet, respectively. If the request is subsequently included, these attributes are replaced for that include. If the included servlet was obtained by using the getNamedDispatcher method, these attributes MUST NOT be set. Except for servlets obtained by using the getNamedDispatcher method, a servlet that has been invoked by another servlet using the forward method of RequestDispatcher has access to the path of the ORIGINAL request. The following request attributes must be set:

javax.servlet.forward.request_uri javax.servlet.forward.context_path javax.servlet.forward.servlet_path javax.servlet.forward.path_info javax.servlet.forward.query_string

The values of these attributes must be equal to the return values of the HttpServletRequest methods getRequestURI, getContextPath, getServletPath, getPathInfo, getQueryString respectively, invoked on the request object passed to the first servlet object in the call chain that received the request from the client. These attributes are accessible from the forwarded servlet via the getAttribute method on the request object. Note that these attributes must always reflect the information in the original request even under the situation that multiple forwards and subsequent includes are called. If the forwarded servlet was obtained by using the getNamedDispatcher method, these attributes must not be set.

Prev Describe the Web container life cycle event model for requests, sessions, and web applications; create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use.

Up

Next Chapter 4. Session Management

Home

http://java.boot.by/wcd-guide/ch03s05.html 4 / 5 2004/6/13 12:00:23

Describe the RequestDispatcher mechanism; write servlet code to create...t-scoped attributes provided by the container to the target resource.

http://java.boot.by/wcd-guide/ch03s05.html 5 / 5 2004/6/13 12:00:23

Chapter 4. Session Management

Chapter 4. Session Management Prev Part I. Exam Objectives Next

Chapter 4. Session Management

Write servlet code to store objects into a session object and retrieve objects from a session object.
Sessions are represented by an HttpSession object. You access a session by calling the HttpServletRequest.getSession() or HttpServletRequest.getSession(boolean) method of a request object. This method returns the current session associated with this request, or, if the request does not have a session, it creates one (unless boolean argument is false). You can associate object-valued attributes with a session by name. Such attributes are accessible by any Web component that belongs to the same Web context and is handling a request that is part of the same session. For example, you can save shopping cart as a session attribute. This allows the shopping cart to be saved between requests and also allows cooperating servlets to access the cart. Some servlet adds items to the cart; another servlet displays, deletes items from, and clears the cart; and next servlet retrieves the total cost of the items in the cart.

public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal(); ... } }

package javax.servlet.http; public interface HttpSession {

http://java.boot.by/wcd-guide/ch04.html 1 / 2 2004/6/13 12:00:26

Chapter 4. Session Management

public java.lang.Object getAttribute(java.lang.String name); public java.util.Enumeration getAttributeNames(); public void removeAttribute(java.lang.String name); public void setAttribute(java.lang.String name, java.lang.Object value); }

Prev Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource.

Up

Next Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed.

Home

http://java.boot.by/wcd-guide/ch04.html 2 / 2 2004/6/13 12:00:26

Given a scenario describe the APIs used to access the session object, ...anisms used to destroy the session object, and when it was destroyed.

Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed. Prev Chapter 4. Session Management Next

Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed.
A session is considered 'new' when it is only a prospective session and has not been established. Because HTTP is a request-response based protocol, an HTTP session is considered to be new until a client 'joins' it. A client joins a session when session tracking information has been 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 a 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.

These conditions define the situation where the servlet container has no mechanism by which to associate a request with a previous request. To obtain a session, use the getSession() or getSession(boolean) method of the javax.servlet.http. HttpServletRequest object. When you first obtain the HttpSession object, the one of three ways used to establish tracking of the session: cookies, URL rewriting, or Secure Sockets Layer (SSL) information. Assume the servlet container uses cookies. In such a case the servlet container creates a unique session ID and typically sends it back to the browser as a cookie. Each subsequent request from this user (at the same browser) passes the cookie containing the session ID, and the servlet container uses this ID to find the user's existing HttpSession object. If argument in getSession(boolean) method is set to true, the HttpSession object is created if it does not already exist (the same as call of getSession() method). If argument in getSession(boolean) method is set to false, the HttpSession object is NOT created if it does not already exist and method returns null. You can end a session:

Automatically by servlet container if a session is inactive for a specified time. The administrators provide a way to specify the amount of time after which to invalidate a session. By coding the servlet to call the HttpSession.invalidate() method on the session object.

http://java.boot.by/wcd-guide/ch04s02.html 1 / 3 2004/6/13 12:00:28

Given a scenario describe the APIs used to access the session object, ...anisms used to destroy the session object, and when it was destroyed.

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 int HttpSession.getMaxInactiveInterval() (sec.) method of the HttpSession interface. This timeout can be changed by the Developer using the HttpSession.setMaxInactiveInterval(int) (sec.) method of the HttpSession interface. The timeout periods used by these methods are defined in SECONDS. By definition, if the timeout period for a session is set to -1 (or ANY NEGATIVE), the session will never expire. The session invalidation will not take effect until all servlets using that session have exited the service method. Once the session invalidation is initiated, a new request must not be able to see that session.

package javax.servlet.http; public interface HttpSession { public int getMaxInactiveInterval(); public void setMaxInactiveInterval(int interval); public void invalidate(); public boolean isNew(); }

Another way to configure session timeout (for all sessions within one web-application) is to use deployment descriptor (web.xml). 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. If the timeout is 0 or less, the container ensures the default behaviour of sessions is NEVER to time out. If this element is not specified, the container must set its default timeout period.

<web-app> ... <session-config> <session-timeout>30</session-timeout> <!-- 30 minutes --> </session-config> </web-app>

Prev

Up

Next

http://java.boot.by/wcd-guide/ch04s02.html 2 / 3 2004/6/13 12:00:28

Given a scenario describe the APIs used to access the session object, ...anisms used to destroy the session object, and when it was destroyed.

Chapter 4. Session Management Home

Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another.

http://java.boot.by/wcd-guide/ch04s02.html 3 / 3 2004/6/13 12:00:28

Using session listeners, write code to respond to an event when an ob...d to an event when a session object migrates from one VM to another.

Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another. Prev Chapter 4. Session Management Next

Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another.
Object is added to session. Listener notification.

package listeners; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public final class SessionListener implements HttpSessionAttributeListener { public void attributeAdded(HttpSessionBindingEvent event) { System.out.println("attributeAdded"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } public void attributeRemoved(HttpSessionBindingEvent event) { System.out.println("attributeRemoved"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } public void attributeReplaced(HttpSessionBindingEvent event) { System.out.println("attributeReplaced"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } }

<web-app> ... <listener> <listener-class>listeners.SessionListener</listener-class>


http://java.boot.by/wcd-guide/ch04s03.html 1 / 4 2004/6/13 12:00:32

Using session listeners, write code to respond to an event when an ob...d to an event when a session object migrates from one VM to another.

</listener> </web-app>

Object is added to session. Object notification.

package beans; import javax.servlet.http.HttpSessionBindingListener; import javax.servlet.http.HttpSessionBindingEvent; public class CounterBean implements HttpSessionBindingListener { private int count = 1; public int getValue() { return count; } public void increment() { count++; } public void valueBound(HttpSessionBindingEvent event) { System.out.println("attributeBounded"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } public void valueUnbound(HttpSessionBindingEvent event) { System.out.println("attributeUnbounded"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } }

Note, you don't need to (and must not) configure HttpSessionBindingListener in the deployment descriptor, just make a class implementing this interface. Object migrates from one VM to another. Object notification.

package beans;
http://java.boot.by/wcd-guide/ch04s03.html 2 / 4 2004/6/13 12:00:32

Using session listeners, write code to respond to an event when an ob...d to an event when a session object migrates from one VM to another.

import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionEvent; public class CounterBean implements HttpSessionActivationListener { private int count = 1; public int getValue() { return count; } public void increment() { count++; } public void sessionWillPassivate(HttpSessionEvent se) { System.out.println("session is about to be passivated"); // save counter's value to persistent storage .... } public void sessionDidActivate(HttpSessionEvent se) { System.out.println("session has just been activated"); // retrieve counter's value from persistent storage .... } }

Note, you don't need to (and must not) configure HttpSessionActivationListener in the deployment descriptor, just make a class implementing this interface.

Prev Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed.

Up

Next Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting.

Home

http://java.boot.by/wcd-guide/ch04s03.html 3 / 4 2004/6/13 12:00:32

Using session listeners, write code to respond to an event when an ob...d to an event when a session object migrates from one VM to another.

http://java.boot.by/wcd-guide/ch04s03.html 4 / 4 2004/6/13 12:00:32

Given a scenario, describe which session management mechanism the W... manage sessions, and write servlet code to perform URL rewriting.

Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting. Prev Chapter 4. Session Management Next

Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting.
The following approaches are using for tracking a user's sessions:

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' (uppercase !).

Set-Cookie: JSESSIONID=49EBBB19A1B2F8D10EE075F6F14CB8C9; Path=/

SSL Sessions Secure Sockets Layer, the encryption technology used in the HTTPS protocol, has a builtin mechanism allowing multiple requests from a client to be unambiguously identified as being part of a session. A servlet container can easily use this data to define a session. URL Rewriting URL rewriting is the lowest common denominator of session tracking. When a client will not accept a cookie, URL rewriting may be used by the server as the basis for session tracking. URL rewriting involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session. The session ID must be encoded as a path parameter in the URL string. The name of the parameter must be 'jsessionid' (lowercase !). Here is an example of a URL containing encoded path information:

http://www.myserver.com/catalog/index.html; jsessionid=1234

http://java.boot.by/wcd-guide/ch04s04.html 1 / 3 2004/6/13 12:00:44

Given a scenario, describe which session management mechanism the W... manage sessions, and write servlet code to perform URL rewriting.

package javax.servlet.http; public interface HttpSession { public boolean isRequestedSessionIdFromCookie(); public boolean isRequestedSessionIdFromURL(); public boolean isRequestedSessionIdValid(); }

There are 2 methods in the HttpServletResponse for URL rewriting:

encodeURL(String) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary. For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies. encodeRedirectURL(String) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. Because the rules for making this determination can differ from those used to decide whether to encode a normal link, this method is separated from the encodeURL method. All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

package javax.servlet.http; public interface HttpServletResponse extends javax.servlet.ServletResponse { public java.lang.String encodeURL(java.lang.String url); public java.lang.String encodeRedirectURL(java.lang.String url) }

public void doGet(HttpServletRequest req, HttpServletResponse res)


http://java.boot.by/wcd-guide/ch04s04.html 2 / 3 2004/6/13 12:00:44

Given a scenario, describe which session management mechanism the W... manage sessions, and write servlet code to perform URL rewriting.

throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ... out.print("<form action='"); out.print(response.encodeURL("SessionExample")); out.print("' "); out.println("method='post'>"); }

Prev Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another.

Up

Next Chapter 5. Web Application Security

Home

http://java.boot.by/wcd-guide/ch04s04.html 3 / 3 2004/6/13 12:00:44

Chapter 5. Web Application Security

Chapter 5. Web Application Security Prev Part I. Exam Objectives Next

Chapter 5. Web Application Security

Based on the servlet specification, compare and contrast the following security mechanisms: (a) authentication, (b) authorization, (c) data integrity, and (d) confidentiality.
Authentication. Authentication means by which communicating entities prove to one another that they are acting on behalf of specific identities that are authorized for access. Authentication is any process by which you verify that someone is who they claim they are. This usually involves a username and a password, but can include any other method of demonstrating identity, such as a smart card, retina scan, voice recognition, or fingerprints. Authentication is equivalent to showing your drivers license at the ticket counter at the airport. Authorization (access control for resources). Authorization means by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints. Authorization is finding out if the person, once identified, is permitted to have the resource. This is usually determined by finding out if that person is a part of a particular group, if that person has paid admission, or has a particular level of security clearance. Authorization is equivalent to checking the guest list at an exclusive party, or checking for your ticket when you go to the opera. Data Integrity. Data integrity means used to prove that information has not been modified by a third party while in transit. Confidentiality (Data Privacy). Confidentiality means used to ensure that information is made available only to users who are authorized to access it.

http://java.boot.by/wcd-guide/ch05.html 1 / 2 2004/6/13 12:00:46

Chapter 5. Web Application Security

Prev Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting.

Up

Next In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role.

Home

http://java.boot.by/wcd-guide/ch05.html 2 / 2 2004/6/13 12:00:46

In the deployment descriptor, declare a security constraint, a Web reso...the transport guarantee, the login configuration, and a security role.

In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role. Prev Chapter 5. Web Application Security Next

In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role.
Specifying Security Constraints. Security constraints are a declarative way of defining the protection of web content. A security constraint associates authorization and or user data constraints with HTTP operations on web resources. A security constraint, which is represented by security-constraint in deployment descriptor, consists of the following elements:

web resource collection (web-resource-collection in deployment descriptor) authorization constraint (auth-constraint in deployment descriptor) user data constraint (user-data-constraint in deployment descriptor)

A security constraint that does not contain an authorization constraint shall combine with authorization constraints that name or imply roles to allow unauthenticated access. The special case of an authorization constraint that names NO roles shall combine with any other constraints to OVERRIDE their affects and cause access to be PRECLUDED. The HTTP operations and web resources to which a security constraint applies (i.e. the constrained requests) are identified by one or more web resource collections. A web resource collection consists of the following elements:

URL patterns (url-pattern in deployment descriptor) HTTP methods (http-method in deployment descriptor)

An authorization constraint establishes a requirement for authentication and names the authorization roles permitted to perform the constrained requests. A user must be a member of at least one of the named roles to be permitted to perform the constrained requests. The special role name '*' is a shorthand for all role names defined in the deployment descriptor. An authorization constraint that names NO roles indicates that access to the constrained requests MUST NOT be permitted under any circumstances. An authorization constraint consists of the following element:

role name (role-name in deployment descriptor)

A user data constraint establishes a requirement that the constrained requests be received over a protected transport layer connection. The strength of the required protection is defined by the value of the transport guarantee. A transport guarantee of INTEGRAL is used to establish a requirement for content integrity and a transport guarantee of CONFIDENTIAL is used to establish a requirement for confidentiality. The transport guarantee of NONE indicates that the
http://java.boot.by/wcd-guide/ch05s02.html 1 / 6 2004/6/13 12:00:50

In the deployment descriptor, declare a security constraint, a Web reso...the transport guarantee, the login configuration, and a security role.

container must accept the constrained requests when received on any connection including an unprotected one. A user data constraint consists of the following element:

transport guarantee (transport-guarantee in deployment descriptor)

If no authorization constraint applies to a request, the container must accept the request without requiring user authentication. If no user data constraint applies to a request, the container must accept the request when received over any connection including an unprotected one.

<security-constraint> <web-resource-collection> <web-resource-name>restricted methods</web-resource-name> <url-pattern>/*</url-pattern> <url-pattern>/acme/wholesale/*</url-pattern> <url-pattern>/acme/retail/*</url-pattern> <http-method>DELETE</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint/> </security-constraint>

'/*' DELETE access precluded '/*' PUT access precluded '/acme/wholesale/*' DELETE access precluded

<security-constraint> <web-resource-collection> <web-resource-name>wholesale</web-resource-name> <url-pattern>/acme/wholesale/*</url-pattern> <http-method>GET</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint> <role-name>SALESCLERK</role-name> </auth-constraint> </security-constraint>

http://java.boot.by/wcd-guide/ch05s02.html 2 / 6 2004/6/13 12:00:50

In the deployment descriptor, declare a security constraint, a Web reso...the transport guarantee, the login configuration, and a security role.

'/acme/wholesale/*' GET SALESCLERK

<security-constraint> <web-resource-collection> <web-resource-name>wholesale</web-resource-name> <url-pattern>/acme/wholesale/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>CONTRACTOR</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint>

'/acme/wholesale/*' POST CONTRACTOR CONFIDENTIAL

<!-The security-constraint element is used to associate security constraints with one or more web resource collections Used in: web-app --> <!ELEMENT security-constraint (display-name?, web-resource-collection+, auth-constraint?, user-data-constraint?)>

Web resource.

<!-The web-resource-collection element is used to identify a subset of the resources and HTTP methods on those resources within a web
http://java.boot.by/wcd-guide/ch05s02.html 3 / 6 2004/6/13 12:00:50

In the deployment descriptor, declare a security constraint, a Web reso...the transport guarantee, the login configuration, and a security role.

application to which a security constraint applies. If no HTTP methods are specified, then the security constraint applies to all HTTP methods. Used in: security-constraint --> <!ELEMENT web-resource-collection (web-resource-name, description?, url-pattern*, http-method*)>

Transport guarantee.

<!-The user-data-constraint element is used to indicate how data communicated between the client and container should be protected. Used in: security-constraint --> <!ELEMENT user-data-constraint (description?, transport-guarantee)>

Login configuration.

<!-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. Used in: web-app --> <!ELEMENT login-config (auth-method?, realm-name?, form-login-config?)>

http://java.boot.by/wcd-guide/ch05s02.html 4 / 6 2004/6/13 12:00:50

In the deployment descriptor, declare a security constraint, a Web reso...the transport guarantee, the login configuration, and a security role.

<!-- login configuration uses form-based authentication --> <login-config> <auth-method>FORM</auth-method> <realm-name>Form-Based Authentication Area</realm-name> <form-login-config> <form-login-page>/protected/login.jsp</form-login-page> <form-error-page>/protected/error.jsp</form-error-page> </form-login-config> </login-config>

Security role.

<!-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: web-app 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)>

<!-- Security roles referenced by web application --> <security-role> <role-name>user</role-name> </security-role> <security-role> <role-name>admin</role-name>
http://java.boot.by/wcd-guide/ch05s02.html 5 / 6 2004/6/13 12:00:50

In the deployment descriptor, declare a security constraint, a Web reso...the transport guarantee, the login configuration, and a security role.

</security-role>

Prev Chapter 5. Web Application Security

Up

Next Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type.

Home

http://java.boot.by/wcd-guide/ch05s02.html 6 / 6 2004/6/13 12:00:50

Compare and contrast the authentication types (BASIC, DIGEST, FORM,... the type works; and given a scenario, select an appropriate type.

Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type. Prev Chapter 5. Web Application Security Next

Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENTCERT); describe how the type works; and given a scenario, select an appropriate type.
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

HTTP Basic Authentication. HTTP Basic Authentication, which is based on a username and password, is the authentication mechanism defined in the HTTP/1.0 specification. A web server requests a web client to authenticate the user. As part of the request, the web server passes the realm (a string) in which the user is to be authenticated. The realm string of Basic Authentication does not have to reflect any particular security policy domain (confusingly also 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. User passwords are sent in simple base64 ENCODING (not ENCRYPTED !), and the target server is not authenticated. Additional protection can alleviate some of these concerns: a secure transport mechanism (HTTPS), or security at the network level (such as the IPSEC protocol or VPN strategies) is applied in some deployment scenarios.

<web-app> <security-constraint> <web-resource-collection> <web-resource-name>User Auth</web-resource-name> <url-pattern>/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>manager</role-name> </auth-constraint> </security-constraint> <login-config>
http://java.boot.by/wcd-guide/ch05s03.html 1 / 6 2004/6/13 12:00:54

Compare and contrast the authentication types (BASIC, DIGEST, FORM,... the type works; and given a scenario, select an appropriate type.

<auth-method>BASIC</auth-method> <realm-name>User Auth</realm-name> </login-config> <security-role> <role-name>admin</role-name> </security-role> <security-role> <role-name>manager</role-name> </security-role> </web-app>

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, e.g. HTTPS Client Authentication. As Digest Authentication is not currently in widespread use, servlet containers are encouraged but NOT REQUIRED to support it. The advantage of this method is that the cleartext password is protected in transmission, it cannot be determined from the digest that is submitted by the client to the server. Digested password authentication supports the concept of digesting user passwords. This causes the stored version of the passwords to be encoded in a form that is not easily reversible, but that the Web server can still utilize for authentication. From a user perspective, digest authentication acts almost identically to basic authentication in that it triggers a login dialog. The difference between basic and digest authentication is that on the network connection between the browser and the server, the password is encrypted, even on a non-SSL connection. In the server, the password can be stored in clear text or encrypted text, which is true for all login methods and is independent of the choice that the application deployer makes.

<web-app> <security-constraint> <web-resource-collection> <web-resource-name>User Auth</web-resource-name> <url-pattern>/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>manager</role-name> </auth-constraint>

http://java.boot.by/wcd-guide/ch05s03.html 2 / 6 2004/6/13 12:00:54

Compare and contrast the authentication types (BASIC, DIGEST, FORM,... the type works; and given a scenario, select an appropriate type.

</security-constraint> <login-config> <auth-method>DIGEST</auth-method> <realm-name>User Auth</realm-name> </login-config> <security-role> <role-name>admin</role-name> </security-role> <security-role> <role-name>manager</role-name> </security-role> </web-app>

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 a single-sign-on from within the browser. Servlet containers that are not J2EE technology compliant are not required to support the HTTPS protocol. Client-certificate authentication is a more secure method of authentication than either BASIC or FORM authentication. It uses HTTP over SSL, in which the server and, optionally, the client authenticate one another with Public Key Certificates. Secure Sockets Layer (SSL) provides data encryption, server authentication, message integrity, and optional client authentication for a TCP/IP connection. You can think of a public key certificate as the digital equivalent of a passport. It is issued by a trusted organization, which is called a certificate authority (CA), and provides identification for the bearer. If you specify client-certificate authentication, the Web server will authenticate the client using the client's X.509 certificate, a public key certificate that conforms to a standard that is defined by X.509 Public Key Infrastructure (PKI). Prior to running an application that uses SSL, you must configure SSL support on the server and set up the public key certificate.

<web-app> <security-constraint> <web-resource-collection> <web-resource-name>User Auth</web-resource-name> <url-pattern>/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name>


http://java.boot.by/wcd-guide/ch05s03.html 3 / 6 2004/6/13 12:00:54

Compare and contrast the authentication types (BASIC, DIGEST, FORM,... the type works; and given a scenario, select an appropriate type.

<role-name>manager</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>CLIENT-CERT</auth-method> <realm-name>User Auth</realm-name> </login-config> <security-role> <role-name>admin</role-name> </security-role> <security-role> <role-name>manager</role-name> </security-role> </web-app>

Form Based Authentication. The look and feel of the 'login screen' cannot be varied using the web browser's built-in authentication mechanisms. This specification introduces a required 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. The login form must contain fields for entering a username and a 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 the user's authentication. If the user is authenticated and possesses authority to access the resource, the requested web resource is activated and a reference to it is returned. If the user is not authenticated, all of the following steps occur: 1. The login form associated with the security constraint is sent to the client and the URL path triggering the authentication is stored by the container. 2. The user is asked to fill out the form, including the username and password fields. 3. The client posts the form back to the server. 4. The container attempts to authenticate the user using the information from the form. 5. If authentication fails, the error page is returned using either a forward or a redirect, and the status code of the response is set to 200. 6. If authentication succeeds, the authenticated user's principal is checked to see if it is in an authorized role for accessing the resource. 7. If the user is authorized, the client is redirected to the resource using the stored URL path.

http://java.boot.by/wcd-guide/ch05s03.html 4 / 6 2004/6/13 12:00:54

Compare and contrast the authentication types (BASIC, DIGEST, FORM,... the type works; and given a scenario, select an appropriate type.

The error page sent to a user that is not authenticated contains information about the failure. Form Based Authentication has the same lack of security as Basic Authentication since the user password is transmitted as plain text and the target server is not authenticated. Again additional protection can alleviate some of these concerns: a secure transport mechanism (HTTPS), or security at the network level (such as the IPSEC protocol or VPN strategies) is applied in some deployment scenarios. Form based login and URL based session tracking can be problematic to implement. Form based login should be used only when sessions are 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 work no matter which resource it is for, and to avoid requiring the server to specify the action field of the outbound form. Here is an example 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>

<web-app> <security-constraint> <web-resource-collection> <web-resource-name>User Auth</web-resource-name> <url-pattern>/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>manager</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>FORM</auth-method> <realm-name>User Auth</realm-name> <form-login-config>

http://java.boot.by/wcd-guide/ch05s03.html 5 / 6 2004/6/13 12:00:54

Compare and contrast the authentication types (BASIC, DIGEST, FORM,... the type works; and given a scenario, select an appropriate type.

<form-login-page>login.jsp</form-login-page> <form-error-page>error.jsp</form-error-page> </form-login-config> </login-config> <security-role> <role-name>admin</role-name> </security-role> <security-role> <role-name>manager</role-name> </security-role> </web-app>

Prev In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role.

Up Home

Next Chapter 6. The JavaServer Pages (JSP) Technology Model

http://java.boot.by/wcd-guide/ch05s03.html 6 / 6 2004/6/13 12:00:54

Chapter 6. The JavaServer Pages (JSP) Technology Model

Chapter 6. The JavaServer Pages (JSP) Technology Model Prev Part I. Exam Objectives Next

Chapter 6. The JavaServer Pages (JSP) Technology Model

Identify, describe, or write the JSP code for the following elements: (a) template text, (b) scripting elements (comments, directives, declarations, scriptlets, and expressions), (c) standard and custom actions, and (d) expression language elements.
Template text. 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 Quoting and Escape Conventions. XML syntax:

<jsp:text> hi you all </jsp:text>

Quoting in Template Text:


A literal <% is quoted by <\% Only when the EL is enabled for a page, a literal $ can be quoted by \$. This is not required but is useful for quoting EL expressions.

Scripting elements. Scripting elements are commonly used to manipulate objects and to perform computation that affects the content generated. Disabling scripting elements can be done by setting the scripting-invalid element to true in the JSP configuration. For example, the following web.xml fragment defines a group that disables scripting elements for all JSP pages delivered using the .jsp extension:

http://java.boot.by/wcd-guide/ch06.html 1 / 9 2004/6/13 12:00:57

Chapter 6. The JavaServer Pages (JSP) Technology Model

<jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group>

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. Scriptlets 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 inserted into the output stream. 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 %>. XML syntax:

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

Declarations. Declarations are used to declare VARIABLES and METHODS in the scripting language used in a JSP page. A declaration must 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.

http://java.boot.by/wcd-guide/ch06.html 2 / 9 2004/6/13 12:00:57

Chapter 6. The JavaServer Pages (JSP) Technology Model

For example, the following declaration below declares an integer, global to the page:

<%! int i; %>

The following declaration does the same and initializes it to zero. This type of initialization should be done with care in the presence of multiple requests on the page:

<%! int i = 0; %>

The next declaration declares a method GLOBAL to the page:

<%! public String someMethod(int i) { if (i<3) return("..."); ... } %>

Scriptlets. Scriptlets can contain any code fragments that are valid for the scripting language specified in the language attribute of the page directive. Scriptlets are executed at request-processing time. Whether or not they produce any output into the out stream depends on the code in the scriptlet. Scriptlets CAN have side-effects, modifying the objects visible to them. When all scriptlet fragments in a given translation unit are combined in the order they appear in the JSP page, they must yield a valid statement, or sequence of statements, in the specified scripting language. Here is a simple example where the page changed dynamically depending on the time of day.

http://java.boot.by/wcd-guide/ch06.html 3 / 9 2004/6/13 12:00:57

Chapter 6. The JavaServer Pages (JSP) Technology Model

<% if (Calendar.getInstance().get(Calendar.AM_PM) == Calendar.AM) {%> Good Morning <% } else { %> Good Afternoon <% } %>

A scriptlet can also have a LOCAL variable declaration, for example the following scriptlet just declares and initializes an integer, and later increments it.

<% int i; i= 0; %> About to increment i... <% i++; %>

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

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

http://java.boot.by/wcd-guide/ch06.html 4 / 9 2004/6/13 12:00:57

Chapter 6. The JavaServer Pages (JSP) Technology Model

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

<!-- HTML comments ... -->

These comments are treated as uninterpreted template text by the JSP container. Dynamic content that appears within HTML/XML comments, such as actions, scriptlets and expressions, is still processed by the container. If the generated comment is to have dynamic data, this can be obtained through an expression syntax, as in:

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

A JSP comment is of the form:

<%-- page code comments --%>

The body of the content is ignored completely. Comments are useful for documentation but also are used to 'comment out' some portions of a JSP page. Note that JSP comments do not nest. An alternative way to place a comment in JSP is to use the comment mechanism of the scripting language. For example:

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

http://java.boot.by/wcd-guide/ch06.html 5 / 9 2004/6/13 12:00:57

Chapter 6. The JavaServer Pages (JSP) Technology Model

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

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

There may be optional white space after the <%@ and before %>. Directives DO NOT produce any output into the current out stream. There are three directives: the page, the taglib and the include. The page Directive. The page directive defines a number of page dependent properties and communicates these to the JSP container. This <jsp:directive.page> element describes the same information following the XML syntax. 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). An exception to this position independence is the use of the pageEncoding and contentType attributes in the determination of the page character encoding; for this purpose, they should appear at the beginning of the page. There shall be ONLY ONE occurrence of any attribute/value pair defined by this directive in a given translation unit, unless the values for the duplicate attributes are IDENTICAL for all occurrences. The import and pageEncoding attributes are exempt from this rule and can appear multiple times. Multiple uses of the import attribute are cumulative (with ordered set union semantics). The pageEncoding attribute can occur at most once per file (or a translation error will result), and applies only to the file in which it appears. Other such multiple attribute/value (re) definitions result in a fatal translation error if the values do not match. The following directive provides some user-visible information on this JSP page:

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

http://java.boot.by/wcd-guide/ch06.html 6 / 9 2004/6/13 12:00:57

Chapter 6. The JavaServer Pages (JSP) Technology Model

The following directive requests no buffering, and provides an error page.

<%@ page buffer="none" errorPage="/oops.jsp" %>

The following directive indicates that the scripting language is based on Java, that the types declared in the package com.myco are directly available to the scripting code, and that a buffering of 16KB should be used.

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

<%@ 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" } { pageEncoding="peinfo" } { isELIgnored="true|false" }

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.
http://java.boot.by/wcd-guide/ch06.html 7 / 9 2004/6/13 12:00:57

Chapter 6. The JavaServer Pages (JSP) Technology Model

If a JSP container implementation cannot locate a tag library description, a fatal translation error shall result. It is a fatal translation error for the taglib directive to appear after actions or functions using the prefix. 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>

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

tagdir indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory. An implicit tag library descriptor is used. A translation error must occur if the value does not start with /WEB-INF/tags/. A translation error must occur if the value does not point to a directory that exists. A translation error must occur if used in conjunction with the uri attribute. 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 page or tag file. The included file is subject to the access control available to the JSP container. The <jsp:directive.include> element describes the same information following the XML syntax. The following example requests the inclusion, at translation time, of a copyright file. The file may have elements which will be processed too:

http://java.boot.by/wcd-guide/ch06.html 8 / 9 2004/6/13 12:00:57

Chapter 6. The JavaServer Pages (JSP) Technology Model

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

Syntax:

<%@ include file="relativeURLspec" %>

Summary of Include Mechanisms in JSP 2.0: <%@ include file="..." %>


file relative static Content IS parsed by JSP container

<jsp:include page="..." />


page relative static OR dynamic Content is NOT parsed - it is included in place

Prev Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type.

Up

Next Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

Home

http://java.boot.by/wcd-guide/ch06.html 9 / 9 2004/6/13 12:00:57

Write JSP code that uses the directives: (a) 'page' (with attributes 'impo...ion', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'. Prev Chapter 6. The JavaServer Pages (JSP) Technology Model Next

Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.
page Directive with import attribute. Lets you specify the packages that should be imported by the servlet into which the JSP page gets translated. Generates import statements at top of servlet definition. Default imports: java.lang.*; javax.servlet.*; javax.servlet.jsp.*; javax.servlet.http.*.

<%@ page import="package.class" %>

or multiple classes/packages (separated by comma, NOT semicolon).

<%@ page import="package.classA, package.classB, other.package.*" %>

page Directive with session attribute. Controls whether or not page participates in HTTP sessions. Indicates that session (of type HttpSession) should be bound to existing session. false value means NO sessions will be used automatically. Attempts to access session variable by servlet will cause RUN-TIME failure. By default, it IS part of a session. All related pages have to do this for it to be useful.

<%@ page session="true" %> <%-- default !!! --%>

http://java.boot.by/wcd-guide/ch06s02.html 1 / 5 2004/6/13 12:01:02

Write JSP code that uses the directives: (a) 'page' (with attributes 'impo...ion', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

or

<%@ page session="false" %>

page Directive with contentType attribute. Specify the MIME type of the page generated by the servlet that results from the JSP page. Attribute value cannot be computed at request time.

<%@ page contentType="MIME-Type" %>

or

<%@ page contentType="MIME-Type; charset=Character-Set" %>

it is the same as (scriptlet):

<% response.setContentType("MIME-Type; charset=Character-Set"); %>

Note, you CANNOT use the contentType attribute for conditional run-time task. The following ALWAYS results in the Excel MIME type (page directive is evaluated only once during translation phase, and not during execution phase):

<% boolean usingExcel = checkUserRequest(request); %> <% if (usingExcel) { %> <%@ page contentType="application/vnd.ms-excel" %> <% } %>

http://java.boot.by/wcd-guide/ch06s02.html 2 / 5 2004/6/13 12:01:02

Write JSP code that uses the directives: (a) 'page' (with attributes 'impo...ion', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

the following approach should be used instead :

<% boolean usingExcel = checkUserRequest(request); %> <% if (usingExcel) { %> <% response.setContentType("application/vnd.ms-excel"); %> <% } %>

page Directive with isELIgnored attribute. The attribute is used to control whether the JSP 2.0 Expression Language (EL) is ignored (true) or evaluated normally (false). EL expressions will be ignored by default in JSP 1.2 applications. When upgrading a web application to JSP 2.0, EL expressions WILL BE INTERPRETED by default. The escape sequence '\ $' can be used to escape EL expressions that should not be interpreted by the container. Alternatively, the isELIgnored page directive attribute, or the <el-ignored> configuration element can be used to deactivate EL for entire translation units.

<%@ page isELIgnored="false" %> <!-- default for JSP 2.0 -->

or

<%@ page isELIgnored="true" %> <!-- default for JSP 1.2 -->

include Directive. Lets you insert a file into servlet class at time the JSP file is translated into servlet. Should be placed in document at point where you want file inserted. The include directive lets you reuse navigation bars, tables, and other elements in multiple pages. The include directive includes a file in a JSP document at DOCUMENT TRANSLATION TIME. Included file can contain JSP code. Inclusion is recursive: included files may include files.
http://java.boot.by/wcd-guide/ch06s02.html 3 / 5 2004/6/13 12:01:02

Write JSP code that uses the directives: (a) 'page' (with attributes 'impo...ion', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

<html> <head> <title>Including Files at Translation Time (JSP)</title> </head> <body> <%@ include file="somePage.jsp" %> </body> </html>

taglib Directive. Can be used to define custom tags.

<%@ taglib prefix="example" uri="http://www.server.com/example-taglib" %>

and web.xml:

<taglib> <taglib-uri>http://www.server.com/example-taglib</taglib-uri> <taglib-location>/WEB-INF/example-taglib.tld</taglib-location> </taglib>

Notice the taglib-location specifies the location of the TLD. The taglib-uri is, for the most part, an arbitrary name given to the tag library. The name you give it can't conflict with other tag libraries in your deployment descriptor. In fact, adding the taglib element to the deployment descriptor is actually optional. You could instead reference the TLD directly in the taglib directive:

<%@ taglib prefix="example" uri="/WEB-INF/example-taglib.tld" %>

http://java.boot.by/wcd-guide/ch06s02.html 4 / 5 2004/6/13 12:01:02

Write JSP code that uses the directives: (a) 'page' (with attributes 'impo...ion', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

This isn't recommended because it reduces flexibility if you ever choose to rename or move the TLD. The uri would have to be changed in every JSP that used it.

Prev Chapter 6. The JavaServer Pages (JSP) Technology Model

Up Home

Next Write a JSP Document (XML-based document) that uses the correct syntax.

http://java.boot.by/wcd-guide/ch06s02.html 5 / 5 2004/6/13 12:01:02

Write a JSP Document (XML-based document) that uses the correct syntax.

Write a JSP Document (XML-based document) that uses the correct syntax. Prev Chapter 6. The JavaServer Pages (JSP) Technology Model Next

Write a JSP Document (XML-based document) that uses the correct syntax.
JSP syntax comment:

<%-- comment --%>

has no XML syntax analog. JSP syntax page directive:

<%@ page ... %>

XML syntax page directive:

<jsp:directive.page ... />

JSP syntax taglib directive:

<%@ taglib ... %>

has no XML syntax analog. jsp:root element is annotated with namespace information:

http://java.boot.by/wcd-guide/ch06s03.html 1 / 6 2004/6/13 12:01:05

Write a JSP Document (XML-based document) that uses the correct syntax.

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

A taglib directive of the form

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

is translated into an xmlns:prefix attribute on the root of the JSP document, with a value that depends on uriValue.

If uriValue is a RELATIVE path, then the value used is urn:jsptld:uriValue. If uriValue is a ABSOLUTE path, then uriValue is used directly.

A taglib directive of the form:

<%@ taglib tagdir="tagDirValue" prefix="prefix" %>

is translated into an xmlns:prefix attribute on the root of the JSP document, with a value of the form urn:jsptagdir:tagDirValue. JSP syntax include directive:

<%@ include file="relativeURL" %>

http://java.boot.by/wcd-guide/ch06s03.html 2 / 6 2004/6/13 12:01:05

Write a JSP Document (XML-based document) that uses the correct syntax.

XML syntax include directive:

<jsp:directive.include file="relativeURL" />

A file on the local system to be included when the JSP page is translated into a servlet. The URL must be a relative one. JSP syntax declaration:

<%! ... %>

XML syntax declaration:

<jsp:declaration> ... </jsp:declaration>

Declarations are translated into a jsp:declaration element. For example:

<%! public String someFunc(int i) { if (i<3) return("..."); } %>

is translated into the following:

<jsp:declaration> <![CDATA[ public String someFunc(int i) {


http://java.boot.by/wcd-guide/ch06s03.html 3 / 6 2004/6/13 12:01:05

Write a JSP Document (XML-based document) that uses the correct syntax.

if (i<3) return("..."); } ]]> </jsp:declaration>

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

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

JSP syntax scriptlet:

<% ... %>

XML syntax scriptlet:

<jsp:scriptlet> ... </jsp:scriptlet>

JSP syntax expression:

<%= ... %>

XML syntax expression:

http://java.boot.by/wcd-guide/ch06s03.html 4 / 6 2004/6/13 12:01:05

Write a JSP Document (XML-based document) that uses the correct syntax.

<jsp:expression> ... </jsp:expression>

JSP syntax template text:

some template text

XML syntax template text:

<jsp:text> some template text </jsp:text>

A JSP document syntax:

<html> <title>positiveTagLib</title> <body> <%@ taglib uri="http://java.apache.org/tomcat/examples-taglib" prefix="eg" %> <%@ taglib uri="/tomcat/taglib" prefix="test" %> <%@ taglib uri="WEB-INF/tlds/my.tld" prefix="temp" %> <eg:test toBrowser="true" att1="Working"> Positive Test taglib directive </eg:test> </body> </html>

A XML document syntax:

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
http://java.boot.by/wcd-guide/ch06s03.html 5 / 6 2004/6/13 12:01:05

Write a JSP Document (XML-based document) that uses the correct syntax.

xmlns:eg="http://java.apache.org/tomcat/examples-taglib" xmlns:test="urn:jsptld:/tomcat/taglib" xmlns:temp="urn:jsptld:/WEB-INF/tlds/my.tld" version="2.0"> <jsp:text><![CDATA[ <html> <title>positiveTagLib</title> <body> ]]></jsp:text> <eg:test toBrowser="true" att1="Working"> <jsp:text>Positive test taglib directive</jsp:text> </eg:test> <jsp:text><![CDATA[ </body> </html> ]]></jsp:text> </jsp:root>

Prev Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.

Up

Next Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method.

Home

http://java.boot.by/wcd-guide/ch06s03.html 6 / 6 2004/6/13 12:01:05

Describe the purpose and event sequence of the JSP page life cycle: (1)..., (6) call the _jspService method, and (7) call the jspDestroy method.

Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method. Prev Chapter 6. The JavaServer Pages (JSP) Technology Model Next

Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method.
JSP page translation. During the translation phase the container locates or creates the JSP page implementation class that corresponds to a given JSP page. This process is determined by the semantics of the JSP page. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page. A tag library may optionally provide a validation method acting on the XML View of a JSP page, to validate that a JSP page is correctly using the library. The translation of a JSP source page into its implementation class can occur at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page. The JSP container creates a JSP page implementation class for each JSP page. The name of the JSP page implementation class is implementation dependent. The JSP Page implementation object belongs to an implementation-dependent named package. The package used may vary between one JSP and another, so minimal assumptions should be made. As of JSP 2.0, it is illegal to refer to any classes from the unnamed (a.k.a. default) package. This may result in a translation error on some containers, The contract on the JSP page implementation class:

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

http://java.boot.by/wcd-guide/ch06s04.html 1 / 4 2004/6/13 12:01:08

Describe the purpose and event sequence of the JSP page life cycle: (1)..., (6) call the _jspService method, and (7) call the jspDestroy method.

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

Removal of the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request. Reduction of the footprint needed to run a JSP container, as the Java compiler is not needed.

Compilation of a JSP page in the context of a web application provides resolution of relative URL specifications in include directives and elsewhere, tag library references, and translation-time actions used in custom actions. A JSP page can also be compiled at deployment time. JSP class loading. JSP servlet is loaded. Creating instance of JSP class. JSP servlet instance is created. The enforcement of the contract between the JSP container and the JSP page author is aided by the requirement that the Servlet class corresponding to the JSP page must implement the javax. servlet.jsp.HttpJspPage interface (or the javax.servlet.jsp.JspPage interface if the protocol is not HTTP).

package javax.servlet.jsp; public interface JspPage extends javax.servlet.Servlet { public void jspInit(); public void jspDestroy(); public void _jspService(ServletRequestSubtype request, ServletResponseSubtype response) throws ServletException, IOException; // _jspService - depends on the specific protocol used and // cannot be expressed in a generic way in Java. }

http://java.boot.by/wcd-guide/ch06s04.html 2 / 4 2004/6/13 12:01:08

Describe the purpose and event sequence of the JSP page life cycle: (1)..., (6) call the _jspService method, and (7) call the jspDestroy method.

package javax.servlet.jsp; public interface HttpJspPage extends JspPage { public void _jspService(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException; }

The jspInit method. The jspInit method, if present, will be called to prepare the page BEFORE the first request is delivered.

<%! public void jspInit() { ... } %>

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. The _jspService method. 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. The formal types of the request/response parameters:

void _jspService(javax.servlet.ServletRequest req, javax.servlet.ServletResponse res) throws IOException, ServletException { ... }

The request and response interfaces together describe a protocol-dependent contract between
http://java.boot.by/wcd-guide/ch06s04.html 3 / 4 2004/6/13 12:01:08

Describe the purpose and event sequence of the JSP page life cycle: (1)..., (6) call the _jspService method, and (7) call the jspDestroy method.

the JSP container and the class that implements the JSP page. The HTTP contract is defined by the javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse interfaces:

void _jspService(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) throws IOException, ServletException { ... }

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. The jspDestroy method. The JSP container can reclaim resources used by a JSP page when a request is not being serviced by the JSP page by invoking its jspDestroy method, if present.

<%! public void jspDestroy() { ... } %>

Method is optionally defined in JSP page. Method is invoked BEFORE destroying the page.

Prev Write a JSP Document (XML-based document) that uses the correct syntax.

Up

Next Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception.

Home

http://java.boot.by/wcd-guide/ch06s04.html 4 / 4 2004/6/13 12:01:08

Given a design goal, write JSP code using the appropriate implicit object...) config, (f) application, (g) page, (h) pageContext, and (i) exception.

Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception. Prev Chapter 6. The JavaServer Pages (JSP) Technology Model Next

Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception.
The request object. Protocol dependent subtype of javax.servlet.ServletRequest, e.g: javax.servlet.http.HttpServletRequest. This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, referer, etc.). The request triggering the service invocation. Has a request scope.

<% String path = request.getContextPath(); String name = request.getParameter("name"); %>

The response object. Protocol dependent subtype of javax.servlet.ServletResponse, e.g: javax.servlet.http. HttpServletResponse. This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client. The response to the request. Has a page scope. The out object. An object of type javax.servlet.jsp.JspWriter.
http://java.boot.by/wcd-guide/ch06s05.html 1 / 5 2004/6/13 12:01:11

Given a design goal, write JSP code using the appropriate implicit object...) config, (f) application, (g) page, (h) pageContext, and (i) exception.

This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly. An object that writes into the output stream. Has a page scope.

<html> <body> <% out.println("Hello !"); %> </body> </html>

NOTE, JSP page authors are prohibited from writing directly to either the PrintWriter or OutputStream associated with the ServletResponse. The following example is INVALID:

<html> <body> <% response.getWriter().println("Hello !"); %> </body> </html>

The session object. An object of type javax.servlet.http.HttpSession. This is the HttpSession object associated with the request. Sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet.

http://java.boot.by/wcd-guide/ch06s05.html 2 / 5 2004/6/13 12:01:11

Given a design goal, write JSP code using the appropriate implicit object...) config, (f) application, (g) page, (h) pageContext, and (i) exception.

The session object created for the requesting client (if any). This variable is only valid for HTTP protocols. Has a session scope. The config object. An object of type javax.servlet.ServletConfig. The ServletConfig for this JSP page. Has a page scope. The application object. An object of type javax.servlet.ServletContext. The servlet context obtained from the servlet configuration object (as in the call this. getServletConfig().getContext()). Has an application scope.

<% javax.servlet.RequestDispatcher rd; rd = application.getRequestDispatcher("/NextPage.jsp"); rd.forward(request, response); %>

The page object. An object of type java.lang.Object. This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java. The instance of this page's implementation class processing the current request. Has a page scope. The pageContext object. A PageContext is an object that provides a context to store references to objects used by the page, encapsulates implementation-dependent features, and provides convenience methods. A JSP page implementation class can use a PageContext to run unmodified in any compliant JSP container while taking advantage of implementation-specific improvements like high performance JspWriters.
http://java.boot.by/wcd-guide/ch06s05.html 3 / 5 2004/6/13 12:01:11

Given a design goal, write JSP code using the appropriate implicit object...) config, (f) application, (g) page, (h) pageContext, and (i) exception.

public abstract class PageContext extends JspContext { public abstract java.lang.Exception getException(); public abstract java.lang.Object getPage(); // instance of Servlet public abstract javax.servlet.ServletRequest getRequest(); public abstract javax.servlet.ServletResponse getResponse(); public abstract javax.servlet.ServletConfig getServletConfig(); public abstract javax.servlet.ServletContext getServletContext(); public abstract javax.servlet.http.HttpSession getSession(); public abstract void handlePageException(java.lang.Exception e); public abstract void include(java.lang.String relativeUrlPath); public abstract void forward(java.lang.String relativeUrlPath); }

PageContext extends JspContext to provide useful context information for when JSP technology is used in a Servlet environment. A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically. The PageContext class is an abstract class, designed to be extended to provide implementation dependent implementations thereof, by conformant JSP engine runtime environments. The following methods provide convenient access to implicit objects: getException(), getPage(), getRequest(), getResponse(), getSession(), getServletConfig() and getServletContext(). The following methods provide support for forwarding, inclusion and error handling: forward(), include(), and handlePageException(). The exception object. An object of type java.lang.Throwable. The uncaught Throwable that resulted in the error page being invoked. Has a page scope. A JSP is considered an Error Page if it sets the page directive's isErrorPage attribute to true. If a page has isErrorPage set to true, then the exception implicit scripting language variable of that page is initialized. error.jsp:

<%@ page isErrorPage="true" %> ... <%= exception.getMessage() %> <br>


http://java.boot.by/wcd-guide/ch06s05.html 4 / 5 2004/6/13 12:01:11

Given a design goal, write JSP code using the appropriate implicit object...) config, (f) application, (g) page, (h) pageContext, and (i) exception.

With the following stack trace: <br> <% ByteArrayOutputStream baos = new ByteArrayOutputStream(); exception.printStackTrace(new PrintStream(baos)); out.print(baos); %>

Prev Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method.

Up

Next Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language.

Home

http://java.boot.by/wcd-guide/ch06s05.html 5 / 5 2004/6/13 12:01:11

Configure the deployment descriptor to declare one or more tag librari...ivate the evaluation language, and deactivate the scripting language.

Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language. Prev Chapter 6. The JavaServer Pages (JSP) Technology Model Next

Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language.
A tag library is a collection of actions that encapsulate some functionality to be used from within a JSP page. A tag library is made available to a JSP page through a taglib directive that identifies the tag library via a URI (Universal Resource 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. The URI identifying the tag library is associated with a Tag Library Description (TLD) file and with tag handler classes. Both Classic and Simple Tag Handlers (implemented either in Java or as tag files) can be packaged together. The explicit web.xml map provides a explicit description of the tag libraries that are being used in a web application. The implicit map from TLDs means that a JAR file implementing a tag library can be dropped in and used immediatedly through its stable URIs. The use of relative URI specifications in the taglib map enables very short names in the taglib directive. For example, if the map is:

<taglib> <taglib-uri>/myPRlibrary</taglib-uri> <taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib-location> </taglib>

then it can be used as:

<%@ taglib uri="/myPRlibrary" prefix="x" %>

http://java.boot.by/wcd-guide/ch06s06.html 1 / 3 2004/6/13 12:01:14

Configure the deployment descriptor to declare one or more tag librari...ivate the evaluation language, and deactivate the scripting language.

Finally, the fallback rule allows a taglib directive to refer directly to the TLD. This arrangement is very convenient for quick development at the expense of less flexibility and accountability. For example, in the case above, it enables:

<%@ taglib uri="/WEB-INF/tlds/PRlibrary_1_4.tld" prefix="x" %>

EL expressions will be ignored by default in JSP 1.2 applications. When upgrading a web application to JSP 2.0, EL expressions will be interpreted by default. The escape sequence '\$' can be used to escape EL expressions that should not be interpreted by the container. Alternatively, the isELIgnored page directive attribute, or the <el-ignored> configuration element can be used to deactivate EL for entire translation units. The default mode for JSP pages in a Web Application delivered using a web.xml using the Servlet 2.4 format is to evaluate EL expressions; this automatically provides the default that most applications want. The default mode can be explicitly changed by setting the value of the el-ignored element. The elignored element is a subelement of jsp-property-group. It has no subelements. Its valid values are true and false. For example, the following web.xml fragment defines a group that deactivates EL evaluation for all JSP pages delivered using the .jsp extension:

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

Page authors can override the default mode through the isELIgnored attribute of the page directive. With the addition of the EL, some JSP page authors, or page authoring groups, may want to follow a methodology where scripting elements are not allowed. The scripting-invalid element is a subelement of jsp-property-group. It has no subelements. Its valid values are true and false. Scripting is ENABLED by default. Disabling scripting elements can be done by setting the scripting-invalid element to true in the JSP configuration.

http://java.boot.by/wcd-guide/ch06s06.html 2 / 3 2004/6/13 12:01:14

Configure the deployment descriptor to declare one or more tag librari...ivate the evaluation language, and deactivate the scripting language.

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

<jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group>

Prev Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception.

Up

Next Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp:include standard action).

Home

http://java.boot.by/wcd-guide/ch06s06.html 3 / 3 2004/6/13 12:01:14

Given a specific design goal for including a JSP segment in another pa...mechanism (the include directive or the jsp:include standard action).

Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp:include standard action). Prev Chapter 6. The JavaServer Pages (JSP) Technology Model Next

Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp: include standard action).
The include directive. Includes a STATIC file in a JSP page, parsing the file's JSP elements. The include directive is processed when the JSP page is TRANSLATED into a servlet class. JSP Syntax:

<%@ include file="relativeFileName" %>

XML Syntax:

<jsp:directive.include file="relativeFileName" />

Example: include.jsp:

<html> <head><title>An Include Test</title></head> <body bgcolor="white"> The current date and time are : <%@ include file="date.jsp" %>

http://java.boot.by/wcd-guide/ch06s07.html 1 / 5 2004/6/13 12:01:17

Given a specific design goal for including a JSP segment in another pa...mechanism (the include directive or the jsp:include standard action).

</body> </html>

date.jsp:

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

The jsp:include action. Includes a static file OR the result from another web component. The difference with the include directive is that not the source of the JSP, but it's output is included. The include JSP page is being executed within the servlet engine and it's output is returned to the calling page. The main benefit of using the jsp:include action is that the URL to include can be constructed during execution of the page. However, every included page results in a new request to the servlet engine, which means there is a bit of a performance impact when compared to the include directive. JSP Syntax:

<jsp:include page="{relativeURL | <%= expression %>}" flush="true | false" />

or

<jsp:include page="{relativeURL | <%= expression %>}" flush="true | false" > <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+ </jsp:include>

http://java.boot.by/wcd-guide/ch06s07.html 2 / 5 2004/6/13 12:01:17

Given a specific design goal for including a JSP segment in another pa...mechanism (the include directive or the jsp:include standard action).

XML Syntax:

<jsp:include page="{relativeURL | %= expression %}" [ flush="true | false" ] />

or

<jsp:include page="{relativeURL | %= expression %}" [ flush="true | false" ] > [ <jsp:param name="parameterName" value="{parameterValue | %= expression %}" /> ]+ </jsp:include>

Examples:

<jsp:include page="scripts/login.jsp" flush="true" />

The following example shows that there are two ways of passing named variables: either pass them on directly in the URL, or add them using jsp:param tags:

<jsp:include page="includes/page.jsp?param1=value" flush="true"> <jsp:param name="param2" value="value2" /> </jsp:include>

It is also possible to dynamically choose the file to include. This example determines the file to include from a request parameter:

<jsp:include page='<%= request.getParameter("incFile") %>' />

http://java.boot.by/wcd-guide/ch06s07.html 3 / 5 2004/6/13 12:01:17

Given a specific design goal for including a JSP segment in another pa...mechanism (the include directive or the jsp:include standard action).

Defining Implicit Includes. The include-prelude element is an optional subelement of jsp-property-group. It has no subelements. Its value is a context-relative path that must correspond to an element in the Web Application. When the element is present, the given path will be automatically included (as in an include directive) at the beginning of the JSP page in the jsp-property-group. When there are more than one include-prelude element in a group, they are to be included in the order they appear. When more than one jsp-property-group applies to a JSP page, the corresponding includeprelude elements will be processed in the same order as they appear in the JSP configuration section of web.xml. The include-coda element is an optional subelement of jsp-property-group. It has no subelements. Its value is a context-relative path that must correspond to an element in the Web Application. When the element is present, the given path will be automatically included (as in an include directive) at the end of the JSP page in the jsp-property-group. When there are more than one include-coda element in a group, they are to be included in the order they appear. When more than one jsp-property-group applies to a JSP page, the corresponding include-coda elements will be processed in the same order as they appear in the JSP configuration section of web.xml. Note that these semantics are in contrast to the way url-patterns are matched for other configuration elements. Preludes and codas follow the same rules as statically included JSP segments. In particular, start tags and end tags must appear in the same file. For example, the following web.xml fragment defines two groups. Together they indicate that everything in directory /two/ have /WEB-INF/jspf/prelude1.jspf and /WEB-INF/jspf/prelude2.jspf at the beginning and /WEB-INF/jspf/coda1.jspf and /WEB-INF/jspf/coda2.jspf at the end, in that order, while other .jsp files only have /WEB-INF/jspf/prelude1.jspf at the beginning and /WEB-INF/jspf/coda1.jspf at the end:

<jsp-property-group> <url-pattern>*.jsp</url-pattern> <include-prelude>/WEB-INF/jspf/prelude1.jspf</include-prelude> <include-coda>/WEB-INF/jspf/coda1.jspf</include-coda> </jsp-property-group> <jsp-property-group> <url-pattern>/two/*</url-pattern> <include-prelude>/WEB-INF/jspf/prelude2.jspf</include-prelude> <include-coda>/WEB-INF/jspf/coda2.jspf</include-coda> </jsp-property-group>

http://java.boot.by/wcd-guide/ch06s07.html 4 / 5 2004/6/13 12:01:17

Given a specific design goal for including a JSP segment in another pa...mechanism (the include directive or the jsp:include standard action).

Prev Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language.

Up Home

Next Chapter 7. Building JSP Pages Using the Expression Language (EL)

http://java.boot.by/wcd-guide/ch06s07.html 5 / 5 2004/6/13 12:01:17

Chapter 7. Building JSP Pages Using the Expression Language (EL)

Chapter 7. Building JSP Pages Using the Expression Language (EL) Prev Part I. Exam Objectives Next

Chapter 7. Building JSP Pages Using the Expression Language (EL)

Given a scenario, write EL code that accesses the following implicit variables including: pageScope, requestScope, sessionScope, and applicationScope, param and paramValues, header and headerValues, cookie, initParam and pageContext.
There are several implicit objects that are available to EL expressions used in JSP pages. These objects are always available under these names:

pageContext - the PageContext object. Provides an API to access various objects including:
r

r r

context - the context for the JSP page's servlet and any Web components contained in the same application. session - the session object for the client. request - the request triggering the execution of the JSP page.

pageScope - a java.util.Map that maps page-scoped attribute names to their values. requestScope - a java.util.Map that maps request-scoped attribute names to their values. sessionScope - a java.util.Map that maps session-scoped attribute names to their values. applicationScope - a java.util.Map that maps application-scoped attribute names to their values. param - a java.util.Map that maps parameter names to a single String parameter value (obtained by calling ServletRequest.getParameter(String name)). paramValues - a java.util.Map that maps parameter names to a String[] of all values for that parameter (obtained by calling ServletRequest.getParameterValues(String name)). header - a java.util.Map that maps header names to a single String header value (obtained by calling HttpServletRequest.getHeader(String name)). headerValues - a java.util.Map that maps header names to a String[] of all values for that header. cookie - a java.util.Map that maps cookie names to a single Cookie object. Cookies are retrieved according to the semantics of HttpServletRequest.getCookies(). If the same name is shared by multiple cookies, an implementation must use the FIRST one encountered in the array of Cookie objects returned by the getCookies() method. However, users of the cookie implicit object must be aware that the ordering of cookies is currently unspecified in the servlet specification. initParam - a java.util.Map that maps context initialization parameter names to their String parameter value (obtained by calling ServletContext.getInitParameter(String name)).

Examples:

http://java.boot.by/wcd-guide/ch07.html 1 / 4 2004/6/13 12:01:20

Chapter 7. Building JSP Pages Using the Expression Language (EL)

The request's URI (obtained from HttpServletRequest):

${pageContext.request.requestURI}

The value of the numberOfItems property of the session-scoped attribute named cart:

${sessionScope.cart.numberOfItems}

The context path:

${pageContext.request.contextPath}

The session-scoped attribute named 'profile' (null if not found):

${sessionScope.profile}

The String value of the productId parameter, or null if not found:

${param.productId}

The value of the productId request parameter:

${param["productId"]}

The String[] containing all values of the productId parameter, or null if not found:

${paramValues.productId}

A collection's members can be accessed using square brackets as shown by retrieval of the userName parameter from the param object. Members of an array or List can be accessed if the value in square brackets can be coerced to an int.

http://java.boot.by/wcd-guide/ch07.html 2 / 4 2004/6/13 12:01:20

Chapter 7. Building JSP Pages Using the Expression Language (EL)

<html> <head><title>Customer Profile for ${param["userName"]}</title></head> <body> ... </body> </html>

Maps can be accessed using the dot operator OR square brackets. For example, ${param. userName} is EQUIVALENT to ${param["userName"]}. The host HTTP attribute:

${header["host"]}

Here is an example of accessing a page-scoped object that is called pageColor:

<body bgcolor="${pageScope.pageColor}">

it is equivalent to:

<body bgcolor="${pageScope['pageColor']}">

Prev Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp:include standard action).

Up

Next Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator).

Home

http://java.boot.by/wcd-guide/ch07.html 3 / 4 2004/6/13 12:01:20

Chapter 7. Building JSP Pages Using the Expression Language (EL)

http://java.boot.by/wcd-guide/ch07.html 4 / 4 2004/6/13 12:01:20

Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator).

Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator). Prev Chapter 7. Building JSP Pages Using the Expression Language (EL) Next

Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator).
The EL borrows the JavaScript syntax for accessing structured data as either a property of an object (with the '.' operator) or as a named array element (with the ["name"] operator). JavaBeans component properties and java.util.Map entries, using the key as the property name, can be accessed this way. Here are some examples:

${myObj.myProperty} ${myObj["myProperty"]} ${myObj['myProperty']} ${myObj[varWithThePropertyName]}

As shown here, an EL expression must always be enclosed within '${' and '}' characters. The first three expressions access a property named myProperty in an object represented by a variable named myObj. The fourth expression access a property with a name that's held by a variable. Instead of a single variable, this syntax can be used with any expression that evaluates to the property name. The ARRAY ACCESS operator is also used for data represented as a collection of indexed elements, such as a Java array or a java.util.List:

${myList[2]} ${myList[aVar + 1]}

Expressions with syntax '${identifier[subexpression]}' are evaluated as follows: 1. Evaluate the identifier and the subexpression; if either resolves to null, the expression is null. 2. If the identifier is a BEAN: The subexpression is coerced to a String value and that string is regarded as a name of one of the bean's properties. The expression resolves to the value of that property; for example, the expression ${name.["lastName"]} translates into the value returned by name. getLastName(). 3. If the identifier is an ARRAY:
http://java.boot.by/wcd-guide/ch07s02.html 1 / 3 2004/6/13 12:01:22

Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator).

The subexpression is coerced to an int value and the expression resolves to identifier [subexpression]. For example, for an array named colors, colors[3] represents the fourth object in the array. Because the subexpression is coerced to an int, you can also access that color like this: colors["3"]; in that case, JSTL coerces "3" into 3. 4. If the identifier is a LIST: The subexpression is also coerced to an int and the expression resolves to the value returned from identifier.get(subexpression), for example: colorList[3] and colorList["3"] both resolve to the fourth element in the list. 5. If the identifier is a MAP: The subexpression is regarded as one of the map's keys. That expression is not coerced to a value because map keys can be any type of object. The expression evaluates to identifier.get(subexpression), for example, colorMap[Red] and colorMap["Red"]. The former expression is valid only if a scoped variable named Red exists in one of the four JSP scopes and was specified as a key for the map named colorMap. Table 7.1. Summary of [] collection access operator
Identifier type Example use ${colorBean.red} JavaBean ${colorBean["red"]} ${colorBean['red']} ${colorArray[2]} Array ${colorArray["2"]} ${colorList[2]} List ${colorList["2"]} ${colorMap[red]} Map ${colorMap["red"]} colorMap.get(pageContext.findAttribute("red")) colorMap.get("red") colorList.get(2) Array.get(colorArray, 2) colorBean.getRed() Method invoked

You access a map's values through its keys, which you can specify with the [] operator, for example, in table above, ${colorMap[red]} and ${colorMap["red"]}. The former specifies an IDENTIFIER for the key, whereas the latter specifies a STRING. For the identifier, the PageContext. findAttribute method searches all FOUR JSP scopes (searching the page, request, session, and application scopes) for a scoped variable with the name that you specify, in this case, red. On the other hand, if you specify a string, it's passed directly to the map's get method.

http://java.boot.by/wcd-guide/ch07s02.html 2 / 3 2004/6/13 12:01:22

Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator).

Prev Chapter 7. Building JSP Pages Using the Expression Language (EL)

Up Home

Next Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators.

http://java.boot.by/wcd-guide/ch07s02.html 3 / 3 2004/6/13 12:01:22

Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators.

Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators. Prev Chapter 7. Building JSP Pages Using the Expression Language (EL) Next

Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators.
There are the arithmetic operators here: '+', '-', '*', '/', '%'. You can also use the following for the '/' (division) and '%' (remainder or modulo) operators: div and mod. You can see examples of these being used below:

6 + 7 = ${6+7}<br> 8 x 9 = ${8*9}<br>

The relational operators are shown below: Table 7.2. The relational operators
Symbol version == != < > >= <= eq ne lt gt ge le Text Version

Here are some basic comparisons:

Is 1 less than 2? ${1<2} <br> Does 5 equal 5? ${5==5} <br> Is 6 greater than 7? ${6 gt 7}<br>

http://java.boot.by/wcd-guide/ch07s03.html 1 / 2 2004/6/13 12:01:24

Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators.

The logical operators are the same as the Java Programming Language, but they also have their textual equivalents within the EL. Table 7.3. The logical operators
Symbol version && || ! and or not Text Version

The empty operator allows you to test the following:


Object references to see if they are null. Strings to see if they are empty. Arrays to see if they are empty. Lists to see if they are empty. Maps to see if they are empty.

You use the operator in the following way:

empty variableName

If any of the above conditions are met, then the operator returns true.

Prev Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator).

Up Home

Next Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.

http://java.boot.by/wcd-guide/ch07s03.html 2 / 2 2004/6/13 12:01:24

Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.

Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor. Prev Chapter 7. Building JSP Pages Using the Expression Language (EL) Next

Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.
The EL has qualified functions, reusing the notion of qualification from XML namespaces (and attributes), XSL functions, and JSP custom actions. Functions are mapped to public static methods in Java classes. In JSP 2.0 the map is specified in the TLD. The full syntax:

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

As with the rest of EL, this element can appear in attributes and directly in template text. The prefix ns must match the prefix of a tag library that contains a function whose name and signature matches the function being invoked (func), or a translation error must occur. If the prefix is omitted, the tag library associated with the default namespace is used (this is only possible in JSP documents). In the following standard syntax example, func1 is associated with some-taglib:

<%@ taglib prefix="some" uri="http://acme.com/some-taglib" %> ${some:func1(true)}

In the following JSP document example, both func2 and func3 are associated with default-taglib:

<some:tag xmlns="http://acme.com/default-taglib" xmlns:some="http://acme.com/some-taglib" xmlns:jsp="http://java.sun.com/JSP/Page"> <some:other value="${func2(true)}"> ${func3(true)}


http://java.boot.by/wcd-guide/ch07s04.html 1 / 4 2004/6/13 12:01:27

Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.

</some:other> </some:tag>

The Tag Library Descriptor (TLD) associated with a tag library lists the functions. Each such function is given a name (as seen in the EL), and a static method in a specific class that will implement the function. The class specified in the TLD must be a public class, and must be specified using a fully-qualified class name (INCLUDING PACKAGES). The specified method must be a public static method in the specified class, and must be specified using a fully-qualified return type followed by the method name, followed by the fully-qualified argument types in parenthesis, separated by COMMAS. Failure to satisfy these requirements shall result in a translation-time error. A tag library can have only one function element in the same tag library with the same value for their name element. If two functions have the same name, a translation-time error shall be generated. The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD). Write class with STATIC function:

package com.example; public class MyELFunctions { public static String concat(String str1, String str2) { return str1 + str2; } }

In order to use concat method we have to add a function element to our tag library descriptor (TLD). You'll have to create a TLD file if it doesn't already exist. A tag library descriptor defines and configures tags in a tag library. Here is /WEB-INF/example-taglib.tld:

<?xml version="1.0" encoding="UTF-8"?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>1.0</tlib-version>
http://java.boot.by/wcd-guide/ch07s04.html 2 / 4 2004/6/13 12:01:27

Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.

<function> <description>Concatenates two strings</description> <name>concat</name> <function-class>com.example.MyELFunctions</function-class> <function-signature> java.lang.String concat(java.lang.String, java.lang.String) </function-signature> </function> </taglib>

Add a taglib element to the deployment descriptor ( /WEB-INF/web.xml):

<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd" version="2.4"> <taglib> <taglib-uri>http://www.server.com/example-taglib</taglib-uri> <taglib-location>/WEB-INF/example-taglib.tld</taglib-location> </taglib> </web-app>

Notice the taglib-location specifies the location of the TLD. The taglib-uri is, for the most part, an arbitrary name given to the tag library. The name you give it can't conflict with other tag libraries in your deployment descriptor. Adding the taglib element to the deployment descriptor is actually OPTIONAL. You could instead reference the TLD directly in the taglib directive on JSP:

<%@ taglib prefix="my" uri="/WEB-INF/example-taglib.tld" %>

This is NOT recommended because it reduces flexibility if you ever choose to rename or move the TLD. The uri would have to be changed in every JSP that used it.

http://java.boot.by/wcd-guide/ch07s04.html 3 / 4 2004/6/13 12:01:27

Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.

The new JSP looks like the following:

<%@ taglib prefix="my" uri="http://www.server.com/example-taglib" %> <html> <head><title>EL Function example</title></head> <body> str1 is : ${param["str1"]} <br> str2 is : ${param["str2"]} <br> concatenated : ${my:concat(param["str1"], param["str2"])} </body> </html>

The prefix 'my' given in the taglib directive is whatever you choose to distinguish it from tags and functions in other tag libraries used in the JSP.

Prev Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators.

Up Home

Next Chapter 8. Building JSP Pages Using Standard Actions

http://java.boot.by/wcd-guide/ch07s04.html 4 / 4 2004/6/13 12:01:27

Chapter 8. Building JSP Pages Using Standard Actions

Chapter 8. Building JSP Pages Using Standard Actions Prev Part I. Exam Objectives Next

Chapter 8. Building JSP Pages Using Standard Actions

Given a design goal, create a code snippet using the following standard actions: jsp: useBean (with attributes: 'id', 'scope', 'type', and 'class'), jsp:getProperty, and jsp: setProperty (with all attribute combinations).
Action jsp:useBean. A jsp:useBean action associates an instance of a Java programming language object defined within a given scope and available with a given id with a newly declared scripting variable of the same id. When a jsp:useBean action is used in an scriptless page, or in an scriptless context (as in the body of an action so indicated), there are no Java scripting variables created but instead an EL variable is created. The jsp:useBean action is quite flexible; its exact semantics depends on the attributes given. The basic semantic tries to find an existing object using id and scope. If the object is not found it will attempt to create the object using the other attributes. It is also possible to use this action to give a local name to an object defined elsewhere, as in another JSP page or in a servlet. This can be done by using the type attribute and not providing class or beanName attributes. At least ONE of type and class MUST be present, and it is NOT VALID to provide both class and beanName. If type and class are present, class must be assignable to type (in the Java platform sense). For it not to be assignable is a translation time error. The attribute beanName specifies the name of a Bean, as specified in the JavaBeans specification. It is used as an argument to the instantiate method in the java.beans.Beans class. It must be of the form a.b.c, which may be either a class, or the name of a resource of the form a/b/c.ser that will be resolved in the current ClassLoader. If this is not true, a request-time exception, as indicated in the semantics of the instantiate method will be raised. The value of this attribute can be a request-time attribute expression. In the following example, a Bean with name connection of type com.myco.myapp.Connection is available after actions on this element, either because it was already created and found, or because it is newly created.

http://java.boot.by/wcd-guide/ch08.html 1 / 6 2004/6/13 12:01:34

Chapter 8. Building JSP Pages Using Standard Actions

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

In the next example, the timeout property is set to 33 if the Bean was instantiated:

<jsp:useBean id="connection" class="com.myco.myapp.Connection"> <jsp:setProperty name="connection" property="timeout" value="33"> </jsp:useBean>

In the following example, the object should have been present in the session. If so, it is given the local name wombat with WombatType. A ClassCastException may be raised if the object is of the wrong class, and an InstantiationException may be raised if the object is not defined:

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

Syntax:

<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"

or

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


http://java.boot.by/wcd-guide/ch08.html 2 / 6 2004/6/13 12:01:34

Chapter 8. Building JSP Pages Using Standard Actions

[body] </jsp:useBean>

In this case, the [body] will be invoked if the Bean denoted by the action is CREATED. Typically, the body will contain either scriptlets or jsp:setProperty tags that will be used to modify the newly created object, but the contents of the body are not restricted. Table 8.1. jsp:useBean attributes
Attribute Description The name used to identify the object instance in the specified scopes 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. The scope within which the reference is available. The DEFAULT value is page. See the description of the scope attribute defined earlier herein. A translation error must occur if scope is not one of page, request, session or application. 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. 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. If specified, it defines the type of the scripting variable defined. This allows the type of the scripting variable to be distinct from, but related to, the type of the implementation class specified. The type is required to be either the class itself, a superclass of the class, or an interface implemented by the class specified. The object referenced is required to be of this type, otherwise a java.lang. ClassCastException shall occur at request time when the assignment of the object referenced to the scripting variable is attempted. If unspecified, the value is the same as the value of the class attribute.

id

scope

class

beanName

type

Action jsp:getProperty. The jsp:getProperty action places the value of a bean instance property, converted to a String, into the implicit out object, from which the value can be displayed as output. The bean instance must be defined as indicated in the name attribute before this point in the page (usually via a jsp: useBean action). The conversion to String is done as in the println methods, i.e. the toString() method of the object is used for Object instances, and the primitive types are converted directly.

http://java.boot.by/wcd-guide/ch08.html 3 / 6 2004/6/13 12:01:34

Chapter 8. Building JSP Pages Using Standard Actions

If the object is not found, a request-time exception is raised. The value of the name attribute in jsp:setProperty and jsp:getProperty will refer to an object that is obtained from the pageContext object through its findAttribute method. The object named by the name must have been "introduced" to the JSP processor using either the jsp:useBean action or a custom action with an associated VariableInfo entry for this name. If the object was not introduced in this manner, the container implementation is recommended (but not required) to raise a translation error, since the page implementation is in violation of the specification. NOTE, a consequence of the previous paragraph is that objects that are stored in, say, the session by a front component are not automatically visible to jsp:setProperty and jsp:getProperty actions in that page unless a jsp:useBean action, or some other action, makes them visible. If the JSP processor can ascertain that there is an alternate way guaranteed to access the same object, it can use that information. For example it may use a scripting variable, but it must guarantee that no intervening code has invalidated the copy held by the scripting variable. The truth is always the value held by the pageContext object. Examples:

<jsp:getProperty name="user" property="name" />

Syntax:

<jsp:getProperty name="name" property="propertyName" />

Table 8.2. jsp:getProperty attributes


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

Action jsp:setProperty.

http://java.boot.by/wcd-guide/ch08.html 4 / 6 2004/6/13 12:01:34

Chapter 8. Building JSP Pages Using Standard Actions

The jsp:setProperty action sets the values of properties in a bean. The name attribute that denotes the bean must be defined before this action appears. There are two variants of the jsp:setProperty action. Both variants set the values of one or more properties in the bean based on the type of the properties. The usual bean introspection is done to discover what properties are present, and, for each, its name, whether it is simple or indexed, its type, and the setter and getter methods. Properties in a Bean can be set from one or more parameters in the request object, from a String constant, or from a computed request-time expression. Simple and indexed properties can be set using jsp:setProperty. When assigning values to indexed properties the value must be an array. The following two actions set a value from the request parameter values:

<jsp:setProperty name="request" property="*" /> <jsp:setProperty name="user" property="user" param="username" />

The following two elemenst set a property from a value:

<jsp:setProperty name="results" property="col" value="${i mod 4}" /> <jsp:setProperty name="results" property="row" value="<%= i/4 %>" />

Syntax:

<jsp:setProperty name="beanName" prop_expr /> prop_expr ::= property="*" | property="propertyName" | property="propertyName" param="parameterName" | property="propertyName" value="propertyValue" propertyValue ::= string

http://java.boot.by/wcd-guide/ch08.html 5 / 6 2004/6/13 12:01:34

Chapter 8. Building JSP Pages Using Standard Actions

Table 8.3. jsp:setProperty attributes


Attribute name Description The name of a bean instance defined by a jsp:useBean action or some other action. The bean instance must contain the property to be set. The defining action must appear before the jsp:setProperty action in the same file. The name of the property whose value will be set. If propertyName is set 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. The name of the request parameter whose value is given to a bean property. The name of the request parameter usually comes from a web form. If param is omitted, 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 action has no effect. An action MAY NOT have both param and value attributes. The value to assign to the given property. This attribute can accept a requesttime attribute expression as a value. An action MAY NOT have both param and value attributes.

property

param

value

Prev Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.

Up Home

Next Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param.

http://java.boot.by/wcd-guide/ch08.html 6 / 6 2004/6/13 12:01:34

Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param.

Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param. Prev Chapter 8. Building JSP Pages Using Standard Actions Next

Given a design goal, create a code snippet using the following standard actions: jsp: include, jsp:forward, and jsp:param.
Action jsp:include. A jsp:include action provides for the inclusion of static and dynamic resources in the same context as the current page. Inclusion is into the current value of out. The resource is specified using a relativeURLspec that is interpreted in the context of the web application (i.e. it is mapped). The page attribute of both the jsp:include and the jsp:forward actions are interpreted relative to the current JSP PAGE, while the file attribute in an include directive is interpreted relative to the current JSP FILE. An included page cannot change the response status code or set headers. This precludes invoking methods like setCookie. Attempts to invoke these methods will be IGNORED. The constraint is equivalent to the one imposed on the include method of the RequestDispatcher class. A jsp:include action may have jsp:param subelements that can provide values for some parameters in the request to be used for the inclusion. Request processing resumes in the calling JSP page, once the inclusion is completed. The flush attribute controls flushing. If true, then, if the page output is buffered and the flush attribute is given a true value, then the buffer is flushed prior to the inclusion, otherwise the buffer is not flushed. The default value for the flush attribute is false. Examples:

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

The above example is a simple inclusion of an object. The path is interpreted in the context of the Web Application. It is likely a static object, but it could be mapped into, for instance, a servlet via web.xml.

http://java.boot.by/wcd-guide/ch08s02.html 1 / 4 2004/6/13 12:01:36

Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param.

Syntax:

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

and

<jsp:include page="urlSpec" flush="true|false"> { <jsp:param .... /> }* </jsp:include>

The first syntax just does a request-time inclusion. In the second case, the values in the param subelements are used to augment the request for the purposes of the inclusion. Table 8.4. jsp:include attributes
Attribute page Description The URL is a relative urlSpec. Relative paths are interpreted relative to the current JSP page. Accepts a request-time attribute value (which must evaluate to a String that is a relative URL specification). Optional boolean attribute. If the value is true, the buffer is flushed now. The default value is false.

flush

Action jsp:forward. A jsp:forward action 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 request object will be adjusted according to the value of the page attribute. A jsp:forward action may have jsp:param subelements that can provide values for some parameters in the request to be used for the forwarding. If the page output is buffered, the buffer is CLEARED prior to forwarding.

http://java.boot.by/wcd-guide/ch08s02.html 2 / 4 2004/6/13 12:01:36

Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param.

If the page output is buffered and the buffer was flushed, an attempt to forward the request will result in an IllegalStateException. If the page output was unbuffered and anything has been written to it, an attempt to forward the request will result in an IllegalStateException. The following action might be used to forward to a static page based on some dynamic condition:

<% String whereTo = "/templates/" + someValue; %> <jsp:forward page="<%= whereTo %>" />

Syntax:

<jsp:forward page="relativeURLspec" />

and

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

Table 8.5. jsp:forward attributes


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

Action jsp:param. The jsp:param element is used to provide key/value information. This element is used in the jsp: include, jsp:forward, and jsp:params elements. A translation error shall occur if the element is used
http://java.boot.by/wcd-guide/ch08s02.html 3 / 4 2004/6/13 12:01:36

Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param.

elsewhere. When doing jsp:include or jsp:forward, the included page or forwarded page will see the original request object, with the original parameters augmented with the new parameters, with NEW VALUES TAKING PRECEDENCE over existing values when applicable. The scope of the new parameters is the jsp:include or jsp:forward call; i.e. in the case of an jsp:include the new parameters (and values) will not apply after the include. This is the same behavior as in the ServletRequest include and forward methods. 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. Syntax:

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

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

Prev Chapter 8. Building JSP Pages Using Standard Actions

Up Home

Next Chapter 9. Building JSP Pages Using Tag Libraries

http://java.boot.by/wcd-guide/ch08s02.html 4 / 4 2004/6/13 12:01:36

Chapter 9. Building JSP Pages Using Tag Libraries

Chapter 9. Building JSP Pages Using Tag Libraries Prev Part I. Exam Objectives Next

Chapter 9. Building JSP Pages Using Tag Libraries

For a custom tag library or a library of Tag Files, create the 'taglib' directive for a JSP page.
The set of significant tags a JSP container interprets can be extended through a tag library. The taglib directive in a JSP page declares that the page uses a tag library, uniquely identifies the tag library using a URI and associates a tag prefix that will distinguish usage of the actions in the library. If a JSP container implementation cannot locate a tag library description, a fatal translation error shall result. It is a fatal translation error for the taglib directive to appear after actions or functions using the prefix. In the following example, a tag library is introduced and made available to this page using the super prefix; no other tag libraries should be introduced in this page using this prefix. In this particular case, we assume the tag library includes a doMagic element type, which is used within the page.

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

Syntax:

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

http://java.boot.by/wcd-guide/ch09.html 1 / 2 2004/6/13 12:01:38

Chapter 9. Building JSP Pages Using Tag Libraries

Table 9.1. taglib Directive attributes


Attribute uri Description Either an absolute URI or a relative URI specification that uniquely identifies the tag library descriptor associated with this prefix. The URI is used to locate a description of the tag library. Indicates this prefix is to be used to identify tag extensions installed in the /WEBINF/tags/ directory or a subdirectory. An implicit tag library descriptor is used. A translation error must occur if the value does not start with /WEB-INF/tags/. A translation error must occur if the value does not point to a directory that exists. A translation error must occur if used in conjunction with the uri attribute. Defines the prefix string in <prefix:tagname> that is used to distinguish a custom action, e.g <myPrefix:myTag>. Prefixes starting with jsp:, jspx:, java:, javax:, servlet:, sun:, and sunw: ARE RESERVED. A prefix must follow the naming convention specified in the XML namespaces specification. Empty prefixes are illegal in this version of the specification, and must result in a translation error.

tagdir

prefix

A fatal translation-time error will result if the JSP page translator encounters a tag with name prefix:Name using a prefix that is introduced using the taglib directive, and Name is not recognized by the corresponding tag library.

Prev Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param.

Up Home

Next Given a design goal, create the custom tag structure in a JSP page to support that goal.

http://java.boot.by/wcd-guide/ch09.html 2 / 2 2004/6/13 12:01:38

Given a design goal, create the custom tag structure in a JSP page to support that goal.

Given a design goal, create the custom tag structure in a JSP page to support that goal. Prev Chapter 9. Building JSP Pages Using Tag Libraries Next

Given a design goal, create the custom tag structure in a JSP page to support that goal.

<%@ taglib uri="mytags" prefix="codecamp" %> <ol> <!-- repeats N times. A null reps value means repeat once. --> <codecamp:repeat reps='<%=request.getParameter("repeats") %>'> <li><codecamp:prime length="40" /> </codecamp:repeat> </ol>

Prev Chapter 9. Building JSP Pages Using Tag Libraries

Up Home

Next Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

http://java.boot.by/wcd-guide/ch09s02.html2004/6/13 12:01:41

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library. Prev Chapter 9. Building JSP Pages Using Tag Libraries Next

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.
The center of JSTL is the core taglib. This can be split into five areas: 1. 2. 3. 4. 5. General purpose Variables support Conditional Iterator URL Related

To use the core library, use the following directive:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

The prefix attribute specifies the prefix used in the tag name for a particular library. For example, the core library includes a tag named out. When combined with a prefix of c, the full tag would be <c:out>. You are free to use any prefix you like, but you must use different prefixes for each of the four standard tag libraries. You must also put the corresponding .tld file for each tag library in your /WEB-INF directory and use the taglib element in your web.xml file to include the tag library:

<taglib> <taglib-uri>http://java.sun.com/jstl/core</taglib-uri> <taglib-location>/WEB-INF/tld/core.tld</taglib-location> </taglib>

General purpose tags. The general-purpose tags let you display variable values, and enclose a group of tags within a try-catch block.

http://java.boot.by/wcd-guide/ch09s03.html 1 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

The <c:out> action provides a capability similar to JSP expressions such as <%= scripting-languageexpression %> or ${el-expression}. For example:

You have <c:out value="${sessionScope.user.itemCount}"/> items.

By default, <c:out> converts the characters <, >, ', ", & to their corresponding character entity codes (e.g. < is converted to &lt;). If these characters are not converted, the page may not be rendered properly by the browser, and it could also open the door for cross-site scripting attacks. The conversion may be bypassed by specifying false to the escapeXml attribute. The <c: out> action also supports the notion of DEFAULT values for cases where the value of an EL expression is null. In the example below, the value "unknown" will be displayed if the property city is not accessible.

<c:out value="${customer.address.city}" default="unknown"/>

The second option is to specify the default value as the content of the <c:out> tag:

<c:out value="${customer.address.street}"> No address available </c:out>

Syntax: Without a body:

<c:out value="value" [escapeXml="{true|false}"] [default="defaultValue"] />

With a body (contains default value):

http://java.boot.by/wcd-guide/ch09s03.html 2 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

<c:out value="value" [escapeXml="{true|false}"]> default value </c:out>

The <c:catch> action allows page authors to handle errors from any action in a uniform fashion, and allows for error handling for multiple actions at once. <c:catch> provides page authors with granular error handling: Actions that are of central importance to a page should not be encapsulated in a <c:catch>, so their exceptions will propagate to an error page, whereas actions with secondary importance to the page should be wrapped in a <c:catch>, so they never cause the error page mechanism to be invoked. The exception thrown is stored in the scoped variable identified by var, which always has page scope. If no exception occurred, the scoped variable identified by var is removed if it existed. If var is missing, the exception is simply caught and not saved. Syntax:

<c:catch [var="varName"]> nested actions </c:catch>

Variables support tags. The action <c:set> is used to set the value of a JSP scoped attribute as follows:

<c:set var="foo" value="value"/>

In the following example, the <c:set> action sets the value of the att1 scoped variable to the output of the acme:foo action. <c:set> like all JSTL actions that create scoped attributes creates scoped attributes in 'page' scope by DEFAULT:

<c:set var="att1"> <acme:foo>mumbojumbo</acme:foo> </c:set>


http://java.boot.by/wcd-guide/ch09s03.html 3 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

<acme:atag att1="${att1}"/>

<c:set> may also be used to set the property of a JavaBeans object, or add or set a specific element in a java.util.Map object. For example:

<!-- set property in JavaBeans object --> <c:set target="${cust.address}" property="city" value="${city}"/> <!-- set/add element in Map object --> <c:set target="${preferences}" property="color" value="${param.color}"/>

Syntax. Syntax 1: Set the value of a scoped variable using attribute value:

<c:set value="value" var="varName" [scope={page|request|session|application}]/>

Syntax 2: Set the value of a scoped variable using body content:

<c:set var="varName" [scope="{page|request|session|application}"]> body content </c:set>

Syntax 3: Set a property of a target object (JavaBean object with setter property property, or a java.util.Map object) using attribute value:

<c:set value="value" target="target" property="propertyName"/>

http://java.boot.by/wcd-guide/ch09s03.html 4 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Syntax 4: Set a property of a target object (JavaBean object with setter property property, or a java.util.Map object) using body content:

<c:set target="target" property="propertyName"> body content </c:set>

The <c:remove> action removes a scoped variable. If attribute scope is not specified, the scoped variable is removed according to the semantics of PageContext.removeAttribute(varName). If attribute scope is specified, the scoped variable is removed according to the semantics of PageContext.removeAttribute(varName, scope). Syntax:

<c:remove var="varName" [scope="{page|request|session|application}"]/>

Conditional tags. A simple conditional execution action evaluates its body content only if the test condition associated with it is true. In the following example, a special greeting is displayed only if this is a users first visit to the site:

<c:if test="${user.visitCount == 1}"> This is your first visit. Welcome to the site! </c:if>

If the test condition evaluates to true, the JSP container processes the body content (JSP) and then writes it to the current JspWriter. Syntax:

http://java.boot.by/wcd-guide/ch09s03.html 5 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Syntax 1: Without body content:

<c:if test="testCondition" var="varName" [scope="{page|request|session|application}"]/>

Syntax 2: With body content:

<c:if test="testCondition" [var="varName"] [scope="{page|request|session|application}"]> body content (JSP) </c:if>

The name of the exported scoped variable var for the resulting value of the test condition. The type of the scoped variable is Boolean. The <c:choose> tag works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <c:choose> tag has <c:when> tags. In a switch statement, you can specify a default clause to specify a default action in case none of the cases match. The <c:choose> equivalent of default is <c:otherwise> (optional), but note, it MUST be the LAST action nested within <c:choose>. Syntax:

<c:choose> body content (<when> and <otherwise> subtags) </c:choose>

<c:when test="testCondition"> body content </c:when>

http://java.boot.by/wcd-guide/ch09s03.html 6 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

<c:otherwise> conditional block </c:otherwise>

Iterator tags. The <c:forEach> action repeats its nested body content over the collection of objects specified by the items attribute. For example, the JSP code below creates an HTML table with one column that shows the default display value of each item in the collection:

<table> <c:forEach var="customer" items="${customers}"> <tr><td>${customer}</td></tr> </c:forEach> </table>

A large number of collection types are supported by <c:forEach>, including all implementations of java.util.Collection (includes List, LinkedList, ArrayList, Vector, Stack, Set), and java.util.Map (includes HashMap, Hashtable, Properties, Provider, Attributes). Arrays of objects as well as arrays of primitive types (e.g. int) are also supported. For arrays of primitive types, the current item for the iteration is automatically wrapped with its standard wrapper class (e.g. Integer for int, Float for float, etc.). If the items attribute is of type java.util.Map, then the current item will be of type java.util.Map. Entry, which has the following two properties: key - the key under which this item is stored in the underlying Map; value - the value that corresponds to this key. Syntax. Syntax 1: Iterate over a collection of objects:

<c:forEach [var="varName"] items="collection" [varStatus="varStatusName"] [begin="begin"] [end="end"] [step="step"]>

http://java.boot.by/wcd-guide/ch09s03.html 7 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

body content (JSP) </c:forEach>

Syntax 2: Iterate a fixed number of times:

<c:forEach [var="varName"] [varStatus="varStatusName"] begin="begin" end="end" [step="step"]> body content (JSP) </c:forEach>

If specified, begin must be >= 0. If end is specified and it is less than begin, the loop is simply not executed. If specified, step must be >= 1. If items is null, it is treated as an empty collection, i.e., no iteration is performed. If begin is greater than OR EQUAL to the size of items, NO iteration is performed. Examples:

<c:forEach var="i" start="1" end="10"> Item <c:out value="${i}/><p> </c:forEach>

<c:forEach var="emp" items="employees"> Employee: <c:out value="${emp.name}"/> </c:forEach>

<c:forTokens> iterates over tokens, separated by the supplied delimiters. The items attribute specifies the string to tokenize and the delimiters attribute specifies a list of delimiters (similar to the way java.util.StringTokenizer works).
http://java.boot.by/wcd-guide/ch09s03.html 8 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Syntax:

<c:forTokens items="stringOfTokens" delims="delimiters" [var="varName"] [varStatus="varStatusName"] [begin="begin"] [end="end"] [step="step"]> body content </c:forTokens>

For example:

<c:forTokens items="moe,larry,curly" delimiters="," var="stooge"> <c:out value="${stooge}/><p> </c:forTokens>

URL Related tags. JSTL provides several tags for handling URLs and accessing Web resources. URLs can be difficult to work with when you must worry about URL rewriting (to insert the session ID when the browser doesn't support cookies), URL encoding of parameters, and referencing resources from a separate servlet context within the same servlet container. The <c:url> tag formats a URL into a string and stores it into a variable. The <c:url> tag automatically performs URL rewriting when necessary. The var attribute specifies the variable that will contain the formatted URL. The optional scope attribute specifies the scope of the variable (page is the default). The value attribute specifies the URL to be formatted. Syntax. Syntax 1: Without body content:

<c:url value="value" [context="context"] [var="varName"] [scope="{page|request|session|application}"]/>


http://java.boot.by/wcd-guide/ch09s03.html 9 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Syntax 2: With body content to specify query string parameters:

<c:url value="value" [context="context"] [var="varName"] [scope="{page|request|session|application}"]> <c:param> subtags </c:url>

As a security precaution, the URL is only rewritten for relative URLs.

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

<c:param name="name"> parameter value </c:param>

Examples:

<c:url var="trackURL" value="/tracking.html"/>

<c:url var="trackURL" value="/track.jsp" context="/tracking"/>

http://java.boot.by/wcd-guide/ch09s03.html 10 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

<c:url value="/track.jsp" var="trackingURL"> <c:param name="trackingId" value="1234"/> <c:param name="reportType" value="summary"/> </c:url>

The <c:import> tag is similar to the <jsp:import> tag, but it is much more powerful. For example, the <jsp:import> tag usually just imports resources from within the same servlet container. The <jsp:import> tag can import data from other servers as well as from within the same container. Also, the <jsp:import> tag automatically inserts the imported content directly into the JSP. Although the <c:import> tag can automatically insert content, it can also return the content as either a STRING or a READER. The only required attribute in the <c:import> tag is url, which specifies the URL to be imported. As with the <c:url> tag, the URL may be a relative URL, a context-relative URL, or an absolute URL. Syntax. Syntax 1: Resource content inlined or exported as a String object:

<c:import url="url" [context="context"] [var="varName"] [scope="{page|request|session|application}"] [charEncoding="charEncoding"]> optional body content for <c:param> subtags </c:import>

Syntax 2: Resource content exported as a Reader object:

<c:import url="url" [context="context"] varReader="varReaderName" [charEncoding="charEncoding"]> body content where varReader is consumed by another action </c:import>

http://java.boot.by/wcd-guide/ch09s03.html 11 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Examples:

<c:import var="data" url="/data.xml"/> <c:out value="${data}/>

is equivalent to:

<c:import url="/data.xml"/>

Using of reader:

<c:import url="/data.xml" varReader="dataReader" scope="session"/>

<c:redirect> sends an HTTP redirect to the client. Syntax. Syntax 1: Without body content:

<c:redirect url="value" [context="context"] />

Syntax 2: With body content to specify query string parameters:

<c:redirect url="value" [context="context"]> <c:param> subtags </c:redirect>


http://java.boot.by/wcd-guide/ch09s03.html 12 / 13 2004/6/13 12:01:46

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Prev Given a design goal, create the custom tag structure in a JSP page to support that goal.

Up Home

Next Chapter 10. Building a Custom Tag Library

http://java.boot.by/wcd-guide/ch09s03.html 13 / 13 2004/6/13 12:01:46

Chapter 10. Building a Custom Tag Library

Chapter 10. Building a Custom Tag Library Prev Part I. Exam Objectives Next

Chapter 10. Building a Custom Tag Library

Describe the semantics of the "Classic" custom tag event model when each event method (doStartTag, doAfterBody, and doEndTag) is executed, and explain what the return value for each event method means; and write a tag handler class.
The classes and interfaces used to implement classic tag handlers are contained in the javax. servlet.jsp.tagext package. Classic tag handlers implement either the Tag, IterationTag, or BodyTag interface. Interfaces can be used to take an existing Java object and make it a tag handler. For newly created classic tag handlers, you can use the TagSupport and BodyTagSupport classes as base classes. These classes and interfaces are contained in the javax.servlet.jsp.tagext package. Tag handler methods defined by the Tag and BodyTag interfaces are called by the JSP page's servlet at various points during the evaluation of the tag. When the start element of a custom tag is encountered, the JSP page's servlet calls methods to initialize the appropriate handler and then invokes the handler's doStartTag method. When the end element of a custom tag is encountered, the handler's doEndTag method is invoked for all but simple tags. Additional methods are invoked in between when a tag handler needs to manipulate the body of the tag. Table 10.1. Tag Handler Methods
Tag Type Basic Attributes Body Body, iterative evaluation Body, manipulation Interface Tag Tag Tag IterationTag BodyTag doStartTag, doEndTag doStartTag, doEndTag, setAttribute1, ..., setAttributeN , release doStartTag, doEndTag, release doStartTag, doAfterBody, doEndTag, release doStartTag, doInitBody, doAfterBody, doEndTag, release Methods

A tag handler has access to an API that allows it to communicate with the JSP page. The entry points to the API are two objects: the JSP context (javax.servlet.jsp.JspContext) for simple tag handlers and the page context (javax.servlet.jsp.PageContext) for classic tag handlers. JspContext provides access to implicit objects. PageContext extends JspContext with HTTP-specific behavior. A tag handler can retrieve all the other implicit objects (request, session, and application) accessible from a JSP page through these objects. In addition, implicit objects can have named attributes associated with them. Such attributes are accessed using [set|get]Attribute methods.
http://java.boot.by/wcd-guide/ch10.html 1 / 7 2004/6/13 12:01:51

Chapter 10. Building a Custom Tag Library

The Tag interface defines the basic protocol between a tag handler and a JSP page's servlet. It defines the life cycle and the methods to be invoked when the start and end tags are encountered. The JSP page's servlet invokes the setPageContext, setParent, and attribute setting methods before calling doStartTag. The JSP page's servlet also guarantees that release will be invoked on the tag handler before the end of the page. Here is a typical tag handler method invocation sequence:

ATag t = new ATag(); t.setPageContext(...); t.setParent(...); t.setAttribute1(value1); t.setAttribute2(value2); t.doStartTag(); t.doEndTag(); t.release();

The BodyTag interface extends Tag by defining additional methods that let a tag handler access its body. The interface provides three new methods:

setBodyContent - Creates body content and adds to the tag handler doInitBody - Called before evaluation of the tag body doAfterBody - Called after evaluation of the tag body

A typical invocation sequence is:

t.doStartTag(); out = pageContext.pushBody(); t.setBodyContent(out); // perform any initialization needed after body content is set t.doInitBody(); t.doAfterBody(); // while doAfterBody() returns EVAL_BODY_AGAIN we // iterate body evaluation ... t.doAfterBody(); t.doEndTag(); out = pageContext.popBody(); t.release();

http://java.boot.by/wcd-guide/ch10.html 2 / 7 2004/6/13 12:01:51

Chapter 10. Building a Custom Tag Library

If the tag handler does not need to manipulate the body, the tag handler should implement the Tag interface. If the tag handler implements the Tag interface and the body of the tag needs to be evaluated, the doStartTag method needs to return Tag.EVAL_BODY_INCLUDE; otherwise it should return Tag.SKIP_BODY. If a tag handler needs to iteratively evaluate the body, it should implement the IterationTag interface. The tag handler should return IterationTag.EVAL_BODY_AGAIN from doAfterBody method if it determines that the body needs to be evaluated again. If the tag handler needs to manipulate the body, the tag handler must implement BodyTag (or be derived from BodyTagSupport). When a tag handler implements the BodyTag interface, it must implement the doInitBody and the doAfterBody methods. These methods manipulate body content passed to the tag handler by the JSP page's servlet. Body content supports several methods to read and write its contents. A tag handler can use the body content's getString or getReader methods to extract information from the body, and the writeOut(out) method to write the body contents to an out stream. The writer supplied to the writeOut method is obtained using the tag handler's getPreviousOut method. This method is used to ensure that a tag handler's results are available to an enclosing tag handler. If the body of the tag needs to be evaluated, the doStartTag method needs to return BodyTag. EVAL_BODY_BUFFERED; otherwise, it should return Tag.SKIP_BODY. The doInitBody method is called after the body content is set but before it is evaluated. You generally use this method to perform any initialization that depends on the body content. The doAfterBody method is called AFTER the body content is evaluated. doAfterBody must return an indication of whether to continue evaluating the body. Thus, if the body should be evaluated again, as would be the case if you were implementing an iteration tag, doAfterBody should return IterationTag.EVAL_BODY_AGAIN; otherwise, doAfterBody should return Tag.SKIP_BODY. The following example reads the content of the body (which contains a SQL query) and passes it to an object that executes the query. Since the body does not need to be reevaluated, doAfterBody returns Tag.SKIP_BODY:

public class QueryTag extends BodyTagSupport { public int doAfterBody() throws JspTagException { BodyContent bc = getBodyContent(); // get the bc as string String query = bc.getString(); // clean up
http://java.boot.by/wcd-guide/ch10.html 3 / 7 2004/6/13 12:01:51

Chapter 10. Building a Custom Tag Library

bc.clearBody(); try { Statement stmt = connection.createStatement(); result = stmt.executeQuery(query); } catch (SQLException e) { throw new JspTagException("QueryTag: " + e.getMessage()); } return SKIP_BODY; } }

When you extend TagSupport, the doStartTag and doEndTag methods use the following return values (defined as constants):

doStartTag returns one of the following values:


r

Tag.EVAL_BODY_INCLUDE - Allow body text (including JSP code) between the start and end tags. Note, however, that body text is not available to the doEndTag method. Tag.SKIP_BODY - Ignore body text. Any text between the start and end tags is not evaluated or displayed.

doEndTag returns one of the following values:


r r

Tag.EVAL_PAGE - Continue evaluating the page. Tag.SKIP_PAGE - Ignore the remainder of the page.

The following tag handler outputs messages from the doStartTag and doEndTag methods. These messages form the contents of the tag in the JSP page:

import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.IOException; public class SimpleTag extends TagSupport { /** * Executes when the tag is started. */ public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello from doStartTag()"); // Allow text in the body of the tag.
http://java.boot.by/wcd-guide/ch10.html 4 / 7 2004/6/13 12:01:51

Chapter 10. Building a Custom Tag Library

return EVAL_BODY_INCLUDE; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } /** * Executes with the end tag. */ public int doEndTag() throws JspException { try { pageContext.getOut().print("Hello from doEndTag()"); // Continue evaluating the page. return EVAL_PAGE; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } }

If your custom tag must modify body content, extend the BodyTagSupport class. It implements BodyTag. Provides the doInitBody and doAfterBody methods. Extend this class when your tag handler must modify body content. The doStartTag method can return BodyTag. EVAL_BODY_BUFFERED in addition to Tag.EVAL_BODY_INCLUDE and Tag.SKIP_BODY. The BodyContent object is a subclass of JspWriter. JspWriter is the writer used internally for the JSP out variable. The BodyContent object is available to doInitBody, doAfterBody, and doEndTag through the bodyContent variable. You can integrate this object's contents with the original JspWriter in the doEndTag method. The BodyContent object contains methods that you use to write output as well as methods to read, clear, and retrieve its contents. For example, you can use bodyContent.getString() to retrieve the writer's contents, optionally modifying the contents before integrating them with the original JspWriter. The servlet container invokes the doInitBody method if the doStartTag method returns BodyTag. EVAL_BODY_BUFFERED. Use this method to initialize the body content, if necessary. Then the tag handler processes the body, and invokes the doAfterBody method. The doAfterBody method returns Tag.SKIP_BODY or IterationTag.EVAL_BODY_AGAIN. If it returns IterationTag.EVAL_BODY_AGAIN, the servlet container loops back and re-executes the body. This lets you loop over repetitive data, such as enumerations and database result sets. The following example shows using the doInitBody and doAfterBody methods. It also shows how to integrate bodyContent output with the output stream:

http://java.boot.by/wcd-guide/ch10.html 5 / 7 2004/6/13 12:01:51

Chapter 10. Building a Custom Tag Library

public class TestBody extends BodyTagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print("doStartTag()"); return EVAL_BODY_BUFFERED; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } public void doInitBody() throws JspException { try { // Note, that this is a different writer than the one // you have in doStartTag and doEndTag. bodyContent.print("doInitBody()"); } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } public int doAfterBody() throws JspException { try { // Note, that this is a different writer than the one // you have in doStartTag and doEndTag. bodyContent.print("doAfterBody()"); // return IterationTag.EVAL_BODY_AGAIN; // Use this to loop return SKIP_BODY; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } public int doEndTag() throws JspException { try { // Write from bodyContent writer to original writer. pageContext.getOut().print(bodyContent.getString()); // Now we're back to the original writer. pageContext.getOut().print("doEndTag()"); return EVAL_PAGE; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } }

http://java.boot.by/wcd-guide/ch10.html 6 / 7 2004/6/13 12:01:51

Chapter 10. Building a Custom Tag Library

Prev Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Up Home

Next Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes.

http://java.boot.by/wcd-guide/ch10.html 7 / 7 2004/6/13 12:01:51

Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes.

Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes. Prev Chapter 10. Building a Custom Tag Library Next

Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes.
A PageContext is an object that provides a context to store references to objects used by the page, encapsulates implementation-dependent features, and provides convenience methods. A JSP page implementation class can use a PageContext to run unmodified in any compliant JSP container while taking advantage of implementation-specific improvements like high performance JspWriters. The PageContext provides a number of facilities to the page/component author and page implementor, including:

a single API to manage the various scoped namespaces a number of convenience API's to access various public objects a mechanism to obtain the JspWriter for output a mechanism to manage session usage by the page a mechanism to expose page directive attributes to the scripting environment mechanisms to forward or include the current request to other active components in the application a mechanism to handle errorpage exception processing

public abstract class JspContext { public abstract void setAttribute(String name, Object value); public abstract void setAttribute(String name, Object value, int scope); public abstract Object getAttribute(String name); public abstract Object getAttribute(String name, int scope); public abstract Object findAttribute(String name); public abstract void removeAttribute(String name); public abstract void removeAttribute(String name, int scope); public abstract int getAttributesScope(String name); public abstract Enumeration getAttributeNamesInScope(int scope); public abstract JspWriter getOut(); }

public abstract class PageContext extends JspContext {

http://java.boot.by/wcd-guide/ch10s02.html 1 / 2 2004/6/13 12:01:54

Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes.

public abstract javax.servlet.http.HttpSession getSession(); public abstract java.lang.Object getPage(); public abstract javax.servlet.ServletRequest getRequest(); public abstract javax.servlet.ServletResponse getResponse(); public abstract java.lang.Exception getException(); public abstract javax.servlet.ServletConfig getServletConfig(); public abstract javax.servlet.ServletContext getServletContext(); public abstract void forward(java.lang.String relativeUrlPath) throws javax.servlet.ServletException, java.io.IOException; public abstract void include(java.lang.String relativeUrlPath) throws javax.servlet.ServletException, java.io.IOException; public abstract void handlePageException(java.lang.Exception e) throws javax.servlet.ServletException, java.io.IOException; }

Prev Chapter 10. Building a Custom Tag Library

Up Home

Next Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.

http://java.boot.by/wcd-guide/ch10s02.html 2 / 2 2004/6/13 12:01:54

Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.

Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor. Prev Chapter 10. Building a Custom Tag Library Next

Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.
An object created by the enclosing tag handler of a group of nested tags is available to all inner tag handlers. This form of object sharing has the advantage that it uses a private namespace for the objects, thus reducing the potential for naming conflicts. To access an object created by an enclosing tag, a tag handler must first obtain its enclosing tag with the static method TagSupport. findAncestorWithClass(from, class) or the TagSupport.getParent() method. The former method should be used when a specific nesting of tag handlers cannot be guaranteed. Once the ancestor has been retrieved, a tag handler can access any statically or dynamically created objects. Statically created objects are members of the parent. Private objects can also be created dynamically. Such objects can be stored in a tag handler with the setValue method and retrieved with the getValue method. The following example illustrates a tag handler that supports both the named and private object approaches to sharing objects. In the example, the handler for a query tag checks whether an attribute named connectionId has been set. If the connection attribute has been set, the handler retrieves the connection object from the page context. Otherwise, the tag handler first retrieves the tag handler for the enclosing tag, and then retrieves the connection object from that handler:

public class QueryTag extends BodyTagSupport { public int doStartTag() throws JspException { String cid = getConnectionId(); Connection connection; if (cid != null) { // there is a connection id, use it connection =(Connection)pageContext.getAttribute(cid); } else { ConnectionTag ancestorTag = (ConnectionTag) findAncestorWithClass(this, ConnectionTag.class); if (ancestorTag == null) { throw new JspTagException("A query without a connection attribute must be nested within a connection tag."); } connection = ancestorTag.getConnection(); ... }
http://java.boot.by/wcd-guide/ch10s03.html 1 / 3 2004/6/13 12:01:57

Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.

} }

The query tag implemented by this tag handler could be used in either of the following ways:

<tt:connection cid="con01" ... > ... </tt:connection> <tt:query id="balances" connectionId="con01"> SELECT account, balance FROM acct_table WHERE customer_number = ? <tt:param value="${requestScope.custNumber}" /> </tt:query> <tt:connection ... > <tt:query cid="balances"> SELECT account, balance FROM acct_table WHERE customer_number = ? <tt:param value="${requestScope.custNumber}" /> </tt:query> </tt:connection>

The TLD for the tag handler indicates that the connectionId attribute is optional with the following declaration:

<tag> ... <attribute> <name>connectionId</name> <required>false</required> </attribute> </tag>

Prev

Up

Next

http://java.boot.by/wcd-guide/ch10s03.html 2 / 3 2004/6/13 12:01:57

Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.

Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes.

Home

Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag.

http://java.boot.by/wcd-guide/ch10s03.html 3 / 3 2004/6/13 12:01:57

Describe the semantics of the "Simple" custom tag event model when th...lass; and explain the constraints on the JSP content within the tag.

Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag. Prev Chapter 10. Building a Custom Tag Library Next

Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag.
JSP 2.0 introduces a new type of tag extension called a Simple Tag Extension. Simple Tag Extensions can be written in one of two ways:

In Java, by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface. This class is intended for use by advanced page authors and tag library developers who need the flexibility of the Java language in order to write their tag handlers. The javax. servlet.jsp.tagext.SimpleTagSupport class provides a default implementation for all methods in SimpleTag. In JSP, using tag files. This method can be used by page authors who do not know Java. It can also be used by advanced page authors or tag library developers who know Java but are producing tag libraries that are presentation-centric or can take advantage of existing tag libraries.

In addition to being simpler to work with, Simple Tag Extensions do not directly rely on any servlet APIs, which allows for potential future integration with other technologies. This is facilitated by the JspContext class, which PageContext now extends. JspContext provides generic services such as storing the JspWriter and keeping track of scoped attributes, whereas PageContext has functionality specific to serving JSPs in the context of servlets. Whereas the Tag interface relies on PageContext, SimpleTag only relies on JspContext. Unlike classic tag handlers, SimpleTag does not extend Tag.

package javax.servlet.jsp.tagext; public interface SimpleTag extends JspTag { public void doTag()throws JspException, java.io.IOException; public void setParent(JspTag parent); public JspTag getParent(); public void setJspContext(JspContext pc); public void setJspBody(JspFragment jspBody); }

Most SimpleTag handlers should extend javax.servlet.jsp.tagext.SimpleTagSupport. This is the convenience class, similar to TagSupport or BodyTagSupport. There are also some helpful methods included in this class that include:
http://java.boot.by/wcd-guide/ch10s04.html 1 / 5 2004/6/13 12:02:00

Describe the semantics of the "Simple" custom tag event model when th...lass; and explain the constraints on the JSP content within the tag.

public JspFragment getJspBody() - returns the body passed in by the container via setJspBody. The JspFragment encapsulates the body of the tag. If the JspFragment is null, it indicates that tag has a body content type of empty. public static final JspTag findAncestorWithClass(JspTag from, java.lang.Class klass) - finds the instance of a given class type that is closest to a given instance. This method uses the getParent() method from the Tag and/or SimpleTag interfaces. This method is used for coordination among cooperating tags. While traversing the ancestors, for every instance of TagAdapter (used to allow collaboration between classic Tag handlers and SimpleTag handlers) encountered, the tag handler returned by TagAdapter.getAdaptee() is compared to klass. In a case where the tag handler matches this class, and not its TagAdapter, is returned.

The body of a Simple Tag, if present, is translated into a JSP Fragment and passed to the setJspBody method. The tag can then execute the fragment as many times as needed. Because JSP fragments do not support scriptlets, the <body-content> of a SimpleTag cannot be "JSP". A TLD is invalid if it specifies "JSP" as the value for <body-content> for a tag whose handler implements the SimpleTag interface. JSP containers are recommended to but not required to produce an error if "JSP" is specified in this case. During the translation phase, various pieces of the page are translated into implementations of the javax.servlet.jsp.tagext.JspFragment abstract class, before being passed to a tag handler. JSP fragments are pieces of JSP code. Written using standard JSP syntax, a fragment is translated into an implementation of the interface JspFragment for use by tag handlers. A JSP fragment is used to represent the body of a tag for use with a SimpleTag handler. The JspFragment interface declares only two methods: invoke and getJspContext.

package javax.servlet.jsp.tagext; public abstract class JspFragment { public abstract void invoke(java.io.Writer out) throws JspException, java.io.IOException; public abstract JspContext getJspContext(); }

invoke causes the fragment to be executed, writing the output produced to the Writer passed to it. You can invoke a fragment as many times as needed. invoke can throw a SkipPageException, which signals that the fragment has determined that the remainder of the page doesn't need to be evaluated. The following example shows the simple custom tag:

public class MySimpleTag extends SimpleTagSupport {


http://java.boot.by/wcd-guide/ch10s04.html 2 / 5 2004/6/13 12:02:00

Describe the semantics of the "Simple" custom tag event model when th...lass; and explain the constraints on the JSP content within the tag.

public void doTag() throws JspException, IOException { getJspContext().getOut().write("Hello, World !"); } }

The lifecycle of a Simple Tag Handler is straightforward and is not complicated by caching semantics. Once a Simple Tag Handler is instantiated by the Container, it is executed and then discarded. The same instance must not be cached and reused. The following lifecycle events take place for the simple tag handler (in the same order): 1. A new tag handler instance is created each time the tag is encountered by the container. This is done by calling the zero argument constructor on the corresponding implementation class. It is important to note that a new instance must be created for each tag invocation. 2. The setJspContext() and setParent() methods are invoked on the tag handler. If the value being passed is 'null', then the setParent() method need not be called. In the case of tag files, a JspContext wrapper is created so that the tag file can appear to have its own page scope. Calling getJspContext() must return the wrapped JspContext. 3. The container calls the setters for each attribute defined for this tag in the order in which they appear in the JSP page or Tag File. If the attribute value is an expression language expression or a runtime expression, it gets evaluated first and is then passed on to the setter. On the other hand if the attribute is a dynamic-attribute then setDynamicAttribute() is called. 4. The setJspBody() method is called by the container to set the body of this tag, as a JspFragment. A value of null is passed to setJspBody() if the tag is declared to have a <bodycontent> of empty. 5. The doTag() method is called by the container. All tag logic, iteration and body evaluations occur in this method. 6. All variables are synchronized after the doTag() method returns. The following example simply writes the body to the output stream. When the Writer given to invoke is null, the output from invoke goes to the JspWriter associated with the JspContext of the tag handler:

import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class MySimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspBody().invoke(null); } }
http://java.boot.by/wcd-guide/ch10s04.html 3 / 5 2004/6/13 12:02:00

Describe the semantics of the "Simple" custom tag event model when th...lass; and explain the constraints on the JSP content within the tag.

The invoke method directs all output to a supplied writer or to the JspWriter returned by the getOut method of the JspContext associated with the tag handler if the writer is null.

<%@ taglib uri="/mytag" prefix="mytag" %> <html> <body> <mytag:MySimpleTag> Hello, World ! </mytag:MySimpleTag> </body> </html>

SimpleTagSupport provides the convenience method getJspBody() to return the JspFragment generated for the body content. The following example demonstrates that a SimpleTag can obtain a copy of the body so that it can use or MANIPULATE it:

public class MySimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { StringWriter sw = new StringWriter(); getJspBody().invoke(sw); getJspContex().getOut().write(sw.toString()); } }

is equivalent to:

public class MySimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { StringWriter sw = new StringWriter(); jspBody().invoke(sw); getJspContex().getOut().write(sw.toString()); } }

http://java.boot.by/wcd-guide/ch10s04.html 4 / 5 2004/6/13 12:02:00

Describe the semantics of the "Simple" custom tag event model when th...lass; and explain the constraints on the JSP content within the tag.

Prev Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.

Up

Next Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag.

Home

http://java.boot.by/wcd-guide/ch10s04.html 5 / 5 2004/6/13 12:02:00

Describe the semantics of the Tag File model; describe the web applica...nd explain the constraints on the JSP content in the body of the tag.

Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag. Prev Chapter 10. Building a Custom Tag Library Next

Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag.
Writing a traditional custom tag requires two steps:

Writing and compiling a tag handler. Defining the tag that is associated with the tag handler.

Tag files simplify the process. First, tag files don't need to be compiled. They are compiled as they are invoked. Also, tag files allow tag extensions to be written using only JSP syntax. This means someone who does not know Java can also write tag extensions. Secondly, a tag element in a tag library descriptor describes the name to be used in a JSP page to reference the custom action. Using tag files, the name of a custom action is the same as the tag file representing the action. Therefore, you don't need a tag library descriptor at all. A tag file looks like a JSP page. It can have directives, scripts, EL expressions, and standard and custom tags. A tag file has the . tag or .tagx extension and can also include other files that contain a common resource. An include file for a tag file has a .tagf extension. To work, tag files must be placed in the WEB-INF/tags directory under your application directory OR a subdirectory under it. The container converts each tag file found in (or uder) WEB-INF/tags into a tag handler. A number of implicit objects are available from inside of a tag file. You can access these objects from a script or an EL expression: Table 10.2. The Tag Files implicit objects
Object request response out session application config Type javax.servlet.http.HttpServletRequest javax.servlet.http.HttpServletResponse javax.servlet.jsp.JspWriter javax.servlet.http.HttpSession javax.servlet.ServletContext javax.servlet.ServletConfig

http://java.boot.by/wcd-guide/ch10s05.html 1 / 4 2004/6/13 12:02:03

Describe the semantics of the Tag File model; describe the web applica...nd explain the constraints on the JSP content in the body of the tag.

jspContext

javax.servlet.jsp.JspContext

This is the example of a tag library in which the tag file simply writes a String to the implicit out object:

<% WEB-INF/tags/myExample.tld %> <% out.println("Hello, World !"); %>

In JSP you need the taglib directive as usual, with the prefix attribute to identify your tag library throughout the page. NOTE, instead of a uri attribute, you have a tagdir attribute. The tagdir attribute refers to the WEB-INF/tags directory OR ANY subdirectory below WEB-INF/tags:

<%@ taglib prefix="simpleTag" tagdir="/WEB-INF/tags" %> <simpleTag:myExample />

Combined with the expression language (EL), you can really build a scriptless JSP page very rapidly. The following example accepts an attribute from a calling JSP page and converts it to the upper case:

<% WEB-INF/tags/myExample2.tld %> <%@ attribute name="someAttribute" %> <% someAttribute = someAttribute.toUpperCase(); out.println(someAttribute); %>

The following JSP page that uses the tag file:

http://java.boot.by/wcd-guide/ch10s05.html 2 / 4 2004/6/13 12:02:03

Describe the semantics of the Tag File model; describe the web applica...nd explain the constraints on the JSP content in the body of the tag.

<%@ taglib prefix="simpleTag" tagdir="/WEB-INF/tags" %> <simpleTag:myExample2 someAttribute="hello" />

example, which is Java-code-free:

<% WEB-INF/tags/myExample3.tag %> <%@ variable name-given="myVar" scope="AT_BEGIN" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="myVar" value="3"/> After: ${myVar} <jsp:doBody/>

To use the tag file, use the following JSP page:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="sampleTag" tagdir="/WEB-INF/tags" %> <c:set var="myVar" value="1"/> Before: ${myVar} <br> <simpleTag:myExample3/>

Prev

Up

Next

http://java.boot.by/wcd-guide/ch10s05.html 3 / 4 2004/6/13 12:02:03

Describe the semantics of the Tag File model; describe the web applica...nd explain the constraints on the JSP content in the body of the tag.

Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag.

Chapter 11. J2EE Patterns Home

http://java.boot.by/wcd-guide/ch10s05.html 4 / 4 2004/6/13 12:02:03

Chapter 11. J2EE Patterns

Chapter 11. J2EE Patterns Prev Part I. Exam Objectives Next

Chapter 11. J2EE Patterns

Given a scenario description with a list of issues, select a pattern that would solve the issues. The list of patterns you must know are: Intercepting Filter, Model-ViewController, Front Controller, Service Locator, Business Delegate, and Transfer Object.

Intercepting Filter. Model-View-Controller. Front Controller. Service Locator. Business Delegate. Transfer Object.

see: http://java.sun.com/blueprints/corej2eepatterns/

Prev Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag.

Up

Next Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-View-Controller, Front Controller, Service Locator, Business Delegate, and Transfer Object.

Home

http://java.boot.by/wcd-guide/ch11.html2004/6/13 12:02:05

Match design patterns with statements describing potential benefits th... Controller, Service Locator, Business Delegate, and Transfer Object.

Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-View-Controller, Front Controller, Service Locator, Business Delegate, and Transfer Object. Prev Chapter 11. J2EE Patterns Next

Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-ViewController, Front Controller, Service Locator, Business Delegate, and Transfer Object.

Intercepting Filter. Model-View-Controller. Front Controller. Service Locator. Business Delegate. Transfer Object.

see: http://java.sun.com/blueprints/corej2eepatterns/

Prev Chapter 11. J2EE Patterns

Up Home

Next Part II. Appendixes

http://java.boot.by/wcd-guide/ch11s02.html2004/6/13 12:02:07

Part II. Appendixes

Part II. Appendixes Prev Next

Appendixes
Bibliography
[Servlet_2.4] Java Servlet Specification Version 2.4 (http://java.sun.com/products/servlet). [JSP_2.0] JavaServer Pages Specification Version 2.0 (http://java.sun.com/products/jsp). [JavaRanch] JavaRanch.com forum for SCWCD Certification. [HTTP-1.0] Internet RFC: HTTP/1.0 - RFC 1945 (ftp://ftp.isi.edu/in-notes/rfc1945.txt) . [HTTP-1.1] Internet RFC: HTTP/1.1 - RFC 2616 (ftp://ftp.isi.edu/in-notes/rfc2616.txt) .

Prev Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-View-Controller, Front Controller, Service Locator, Business Delegate, and Transfer Object.

Up

Next Appendix A. First Appendix

Home

http://java.boot.by/wcd-guide/pt02.html2004/6/13 12:02:09

Appendix A. First Appendix

Appendix A. First Appendix Prev Part II. Appendixes Next

Appendix A. First Appendix

First Section
sdsds

Prev Part II. Appendixes

Up Home

Next Second Section

http://java.boot.by/wcd-guide/apa.html2004/6/13 12:02:12

Second Section

Second Section Prev Appendix A. First Appendix Next

Second Section
sdsds

Prev Appendix A. First Appendix

Up Home

Next Third Section

http://java.boot.by/wcd-guide/apas02.html2004/6/13 12:02:14

Third Section

Third Section Prev Appendix A. First Appendix Next

Third Section
sdsds

Prev Second Section

Up Home

Next Bibliography

http://java.boot.by/wcd-guide/apas03.html2004/6/13 12:02:16

SCDJWS Study Guide

SCDJWS Study Guide Next

SCDJWS Study Guide


IBA USA, Inc. Mikalai Zaikin
<NZaikin[at]iba.by>

Copyright 2004 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. April 2004
Revision History Revision 0.1 Chapter 1 updates. Revision 0.0 initial release. 17 Mar 2004 MZ 7 Apr 2004 MZ

Abstract The purpose of this document is to help in preparation for exam CX-310-220 (Sun Certified Developer for Java Web Services). This document should not be used as the only study material for SCDJWS (Sun Certified Developer for Java Web Services) Test. It covers all objective topics, but it is not enough. I tried to make this document as much accurate as possible, but if you find any error, please let me know.

Table of Contents

http://java.boot.by/wsd-guide/ 1 / 5 2004/6/13 12:02:21

SCDJWS Study Guide

Foreword Preface I. Exam Objectives 1. XML Web Service Standards Given XML documents, schemas, and fragments determine whether their syntax and form are correct (according to W3C schema) and whether they conform to the WS-I Basic Profile 1.0a. Describe the use of XML schema in J2EE Web services. Describe the use of namespaces in an XML document. 2. SOAP 1.1 Web Service Standards List and describe the encoding types used in a SOAP message. Describe how SOAP message header blocks are used and processed. Describe the function of each element contained in a SOAP message, the SOAP binding to HTTP, and how to represent faults that occur when processing a SOAP message. Create a SOAP message that contains an attachment. Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a. Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages. 3. Describing and Publishing (WSDL and UDDI) Explain the use of WSDL in Web services, including a description of WSDL's basic elements, binding mechanisms and the basic WSDL operation types as limited by the WS-I Basic Profile 1.0a. Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1. Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a. Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry. 4. JAX-RPC Explain the service description model, client connection types, interaction modes, transport mechanisms/protocols, and endpoint types as they relate to JAX-RPC. Given a set of requirements for a Web service, such as transactional needs, and security requirements, design and develop Web service applications that use servlet-based endpoints and EJB based endpoints. Given an set of requirements, design and develop a Web sevice client, such as a J2EE client and a stand-alone Java client, using the appropriate JAX-RPC client connection style. Given a set of requirements, develop and configure a Web service client that accesses a stateful Web service. Explain the advantages and disadvantages of a WSDL to Java vs. a Java to WSDL development approach. Describe the advantages and disadvantages of web service applications that use either synchronous/request response, one-way RPC, or non-blocking RPC invocation modes.

http://java.boot.by/wsd-guide/ 2 / 5 2004/6/13 12:02:21

SCDJWS Study Guide

5.

6.

7.

8.

9.

Use the JAX-RPC Handler API to create a SOAP message handler, describe the function of a handler chain, and describe the role of SAAJ when creating a message handler. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ) Describe the functions and capabilities of the APIs included within JAXP. Given a scenario, select the proper mechanism for parsing and processing the information in an XML document. Describe the functions and capabilities of JAXB, including the JAXB process flow, such as XML-to-Java and Java-to-XML, and the binding and validation mechanisms provided by JAXB. Use the SAAJ APIs to create and manipulate a SOAP message. JAXR Describe the function of JAXR in Web service architectural model, the two basic levels of business registry functionality supported by JAXR, and the function of the basic JAXR business objects and how they map to the UDDI data structures. Use JAXR to connect to a UDDI business registry, execute queries to locate services that meet specific requirements, and publish or update information about a business service. J2EE Web Services Identify the characteristics of and the services and APIs included in the J2EE platform. Explain the benefits of using the J2EE platform for creating and deploying Web service applications. Describe the functions and capabilities of the JAXP, DOM, SAX, JAXR, JAX-RPC, and SAAJ in the J2EE platform. Describe the role of the WS-I Basic Profile when designing J2EE Web services. Security Explain basic security mechanisms including: transport level security, such as basic and mutual authentication and SSL, message level security, XML encryption, XML Digital Signature, and federated identity and trust. Identify the purpose and benefits of Web services security oriented initiatives and standards such as Username Token Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project. Given a scenario, implement J2EE based web service web-tier and/or EJB-tier basic security mechanisms, such as mutual authentication, SSL, and access control. Describe factors that impact the security requirements of a Web service, such as the relationship between the client and service provider, the type of data being exchanged, the message format, and the transport mechanism. Developing Web Services Describe the steps required to configure, package, and deploy J2EE Web services and service clients, including a description of the packaging formats, such as .ear, . war, .jar, deployment descriptor settings, the associated Web Services description file, RPC mapping files, and service reference elements used for EJB and servlet

http://java.boot.by/wsd-guide/ 3 / 5 2004/6/13 12:02:21

SCDJWS Study Guide

endpoints. Given a set of requirements, develop code to process XML files using the SAX, DOM, XSLT, and JAXB APIs. Given an XML schema for a document style Web service create a WSDL file that describes the service and generate a service implementation. Given a set of requirements, develop code to create an XML-based, document style, Web service using the JAX-RPC APIs. Implement a SOAP logging mechanism for testing and debugging a Web Service application using J2EE Web Service APIs. Given a set of requirements, develop code to handle system and service exceptions and faults received by a Web services client. 10. General Design and Architecture Describe the characteristics of a service oriented architecture and how Web Services fits to this model. Given a scenario, design a J2EE service using the Business Delegate, Service Locator, and/or Proxy client-side design patterns and the Adapter, Command, Web Service Broker, and/or Faade server-side patterns. Describe alternatives for dealing with issues that impact the quality of service provided by a Web service and methods to improve the system reliability, maintainability, security, and performance of a service. Describe how to handle the various types of return values, faults, errors, and exceptions that can occur during a Web service interaction. Describe the role that Web services play when integrating data, application functions, or business processes in a J2EE application. Describe how to design a stateless Web service that exposes the functionality of a stateful business process. 11. Endpoint Design and Architecture Given a scenario, design Web service applications using information models that are either procedure-style or document-style. Describe the function of the service interaction and processing layers in a Web service. Describe the tasks performed by each phase of an XML-based, document oriented, Web service application, including the consumption, business processing, and production phases. Design a Web service for an asynchronous, document-style process and describe how to refactor a Web service from a synchronous to an asynchronous model. Describe how the characteristics, such as resource utilization, conversational capabilities, and operational modes, of the various types of Web service clients impact the design of a Web service or determine the type of client that might interact with a particular service. II. Appendixes A. First Appendix SAAJ API Second Section

http://java.boot.by/wsd-guide/ 4 / 5 2004/6/13 12:02:21

SCDJWS Study Guide

Third Section Bibliography

Next Foreword

http://java.boot.by/wsd-guide/ 5 / 5 2004/6/13 12:02:21

Foreword

Foreword Prev Next

Foreword
A preface.

Prev SCDJWS Study Guide

Up Home

Next Preface

http://java.boot.by/wsd-guide/pr01.html2004/6/13 12:02:23

Preface

Preface Prev Next

Preface
This document is available in 2 formats: single page and chunked pages If you would like to have PDF (printable eBook for Adobe Acrobat Reader) version or CHM (single file copy of web-site to browse offline) version of SCDJWS Study Guide, please, contact me.

Prev Foreword

Up Home

Next Part I. Exam Objectives

http://java.boot.by/wsd-guide/pr02.html2004/6/13 12:02:28

Part I. Exam Objectives

Part I. Exam Objectives Prev Next

Exam Objectives
Prev Preface Up Home Next Chapter 1. XML Web Service Standards

http://java.boot.by/wsd-guide/pt01.html2004/6/13 12:02:30

Chapter 1. XML Web Service Standards

Chapter 1. XML Web Service Standards Prev Part I. Exam Objectives Next

Chapter 1. XML Web Service Standards

Given XML documents, schemas, and fragments determine whether their syntax and form are correct (according to W3C schema) and whether they conform to the WS-I Basic Profile 1.0a.
BP 1.0 - Service Description (WSDL) - Document Structure. A DESCRIPTION MUST only use the WSDL "import" statement to import another WSDL description. To import XML Schema Definitions, a DESCRIPTION MUST use the XML Schema "import" statement. A DESCRIPTION MUST use the XML Schema "import" statement only within the xsd:schema element of the types section. A DESCRIPTION MUST NOT use the XML Schema "import" statement to import a Schema from any document whose root element is not "schema" from the namespace "http://www.w3. org/2001/XMLSchema". An XML Schema directly or indirectly imported by a DESCRIPTION MUST use either UTF-8 or UTF-16 encoding. An XML Schema directly or indirectly imported by a DESCRIPTION MUST use version 1.0 of the eXtensible Markup Language W3C Recommendation. CORRECT:

<definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions"> <import namespace="http://example.com/stockquote/definitions" location="http://example.com/stockquote/stockquote.wsdl"/> <message name="GetLastTradePriceInput"> <part name="body" element="..."/> </message> ...
http://java.boot.by/wsd-guide/ch01.html 1 / 9 2004/6/13 12:02:35

Chapter 1. XML Web Service Standards

</definitions>

CORRECT:

<definitions name="StockQuote" targetNamespace="http://example.com/stockquote/" xmlns:xsd1="http://example.com/stockquote/schemas" ... xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/definitions" location="http://example.com/stockquote/stockquote.wsdl"/> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> ... </definitions>

INCORRECT (imports not "wsdl" document):

<definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions" xmlns:xsd1="http://example.com/stockquote/schemas"" ... xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/schemas" location="http://example.com/stockquote/stockquote.xsd"/> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> ... </definitions>

http://java.boot.by/wsd-guide/ch01.html 2 / 9 2004/6/13 12:02:35

Chapter 1. XML Web Service Standards

A DESCRIPTION MUST specify a non-empty location attribute on the wsdl:import element. When they appear in a DESCRIPTION, wsdl:import elements MUST precede all other elements from the WSDL namespace except wsdl:documentation. When they appear in a DESCRIPTION, wsdl:types elements MUST precede all other elements from the WSDL namespace except wsdl:documentation and wsdl:import. CORRECT:

<definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions"> <import namespace="http://example.com/stockquote/base" location="http://example.com/stockquote/stockquote.wsdl"/> <message name="GetLastTradePriceInput"> <part name="body" element="..."/> </message> ... </definitions>

CORRECT:

<definitions name="StockQuote" ... xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <schema targetNamespace="http://example.com/stockquote/schemas" xmlns="http://www.w3.org/2001/XMLSchema"> ....... </schema> </types> <message name="GetLastTradePriceInput"> <part name="body" element="tns:TradePriceRequest"/> </message> ...
http://java.boot.by/wsd-guide/ch01.html 3 / 9 2004/6/13 12:02:35

Chapter 1. XML Web Service Standards

<service name="StockQuoteService"> <port name="StockQuotePort" binding="tns:StockQuoteSoap"> .... </port> </service> </definitions>

INCORRECT:

<definitions name="StockQuote" ... xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/definitions" location="http://example.com/stockquote/stockquote.wsdl"/> <message name="GetLastTradePriceInput"> <part name="body" type="tns:TradePriceRequest"/> </message> ... <service name="StockQuoteService"> <port name="StockQuotePort" binding="tns:StockQuoteSoap"> .... </port> </service> <types> <schema targetNamespace="http://example.com/stockquote/schemas" xmlns="http://www.w3.org/2001/XMLSchema"> ....... </schema> </types> </definitions>

A DESCRIPTION MUST use version 1.0 of the eXtensible Markup Language W3C Recommendation. DESCRIPTION MUST use either UTF-8 or UTF-16 encoding.

http://java.boot.by/wsd-guide/ch01.html 4 / 9 2004/6/13 12:02:35

Chapter 1. XML Web Service Standards

The targetNamespace attribute on the wsdl:definitions element of a description that is being imported MUST have same the value as the namespace attribute on the wsdl:import element in the importing DESCRIPTION. A document-literal binding in a DESCRIPTION MUST, in each of its soapbind:body element(s), have at most one part listed in the parts attribute, if the parts attribute is specified. If a document-literal binding in a DESCRIPTION does not specify the parts attribute on a soapbind: body element, the corresponding abstract wsdl:message MUST define zero or one wsdl:parts. A wsdl:binding in a DESCRIPTION MAY contain soapbind:body element(s) that specify that zero parts form the soap:Body. An rpc-literal binding in a DESCRIPTION MUST refer, in its soapbind:body element(s), only to wsdl: part element(s) that have been defined using the type attribute. A MESSAGE described with an rpc-literal binding MUST NOT have the xsi:nil attribute with a value of "1" or "true" on the part accessors. A wsdl:message in a DESCRIPTION MAY contain wsdl:parts that use the elements attribute provided those wsdl:parts are not referred to by a soapbind:body in an rpc-literal binding. A document-literal binding in a DESCRIPTION MUST refer, in each of its soapbind:body element (s), only to wsdl:part element(s) that have been defined using the element attribute. A binding in a DESCRIPTION MAY contain soapbind:header element(s) that refer to wsdl:parts in the same wsdl:message that are referred to by its soapbind:body element(s). A wsdl:binding in a DESCRIPTION MUST refer, in each of its soapbind:header, soapbind:headerfault and soapbind:fault elements, only to wsdl:part element(s) that have been defined using the element attribute. A wsdl:binding in a DESCRIPTION SHOULD bind every wsdl:part of a wsdl:message in the wsdl: portType to which it refers to one of soapbind:body, soapbind:header, soapbind:fault or soapbind: headerfault. A wsdl:message in a DESCRIPTION containing a wsdl:part that uses the element attribute MUST refer, in that attribute, to a global element declaration CORRECT:

<message name="GetTradePriceInput"> <part name="body" element="tns:SubscribeToQuotes"/>

http://java.boot.by/wsd-guide/ch01.html 5 / 9 2004/6/13 12:02:35

Chapter 1. XML Web Service Standards

</message>

INCORRECT:

<message name="GetTradePriceInput"> <part name="tickerSymbol" element="xsd:string"/> <part name="time" element="xsd:timeInstant"/> </message>

INCORRECT:

<message name="GetTradePriceInput"> <part name="tickerSymbol" element="xsd:string"/> </message>

BP 1.0 - Service Description (WSDL) - Port Types. The order of the elements in the soap:body of a MESSAGE MUST be the same as that of the wsdl: parts in the wsdl:message that describes it. A DESCRIPTION MAY use the parameterOrder attribute of an wsdl:operation element to indicate the return value and method signatures as a hint to code generators. A DESCRIPTION MUST NOT use Solicit-Response and Notification type operations in a wsdl: portType definition. A wsdl:portType in a DESCRIPTION MUST have operations with distinct values for their name attributes. A wsdl:portType in a DESCRIPTION MUST be constructed so that the parameterOrder attribute, if present, omits at most 1 wsdl:part from the output message. A wsdl:message in a DESCRIPTION MUST NOT specify both type and element attributes on the same wsdl:part.

http://java.boot.by/wsd-guide/ch01.html 6 / 9 2004/6/13 12:02:35

Chapter 1. XML Web Service Standards

BP 1.0 - Service Description (WSDL) - SOAP Binding. The wsdl:binding element in a DESCRIPTION MUST be constructed so that its soapbind:binding child element specifies the transport attribute. A wsdl:binding element in a DESCRIPTION MUST specify the HTTP transport protocol with SOAP binding. Specifically, the transport attribute of its soapbind:binding child MUST have the value "http://schemas.xmlsoap.org/soap/http". A wsdl:binding in a DESCRIPTION MUST use either be a rpc-literal binding or a document-literal binding. A wsdl:binding in a DESCRIPTION MUST use the value of "literal" for the use attribute in all soapbind:body, soapbind:fault, soapbind:header and soapbind:headerfault elements. A wsdl:binding in a DESCRIPTION that contains one or more soapbind:body, soapbind:fault, soapbind: header or soapbind:headerfault elements that do not specify the use attribute MUST be interpreted as though the value "literal" had been specified in each case. A wsdl:portType in a DESCRIPTION MAY have zero or more wsdl:bindings that refer to it, defined in the same or other WSDL documents. The operations in a wsdl:binding in a DESCRIPTION MUST result in wire signatures that are different from one another. A DESCRIPTION SHOULD NOT have more than one wsdl:port with the same value for the location attribute of the soapbind:address element. A document-literal binding MUST be represented on the wire as a MESSAGE with a soap:Body whose child element is an instance of the global element declaration referenced by the corresponding wsdl:message part. For one-way operations, an INSTANCE MUST NOT return a HTTP response that contains a SOAP envelope. Specifically, the HTTP response entity-body must be empty. A CONSUMER MUST ignore a SOAP response carried in a response from a one-way operation. For one-way operations, a CONSUMER MUST NOT interpret a successful HTTP response status code (i.e., 2xx) to mean the message is valid or that the receiver would process it. A document-literal binding in a DESCRIPTION MUST NOT have the namespace attribute specified on contained soapbind:body, soapbind:header, soapbind:headerfault and soapbind:fault elements. An rpc-literal binding in a DESCRIPTION MUST have the namespace attribute specified, the value of which MUST be an absolute URI, on contained soapbind:body elements.
http://java.boot.by/wsd-guide/ch01.html 7 / 9 2004/6/13 12:02:35

Chapter 1. XML Web Service Standards

An rpc-literal binding in a DESCRIPTION MUST NOT have the namespace attribute specified on contained soapbind:header, soapbind:headerfault and soapbind:fault elements. A wsdl:binding in a DESCRIPTION MUST have the same set of wsdl:operations as the wsdl:portType to which it refers. A wsdl:binding in a DESCRIPTION MAY contain no soapbind:headerfault elements if there are no known header faults. A wsdl:binding in a DESCRIPTION SHOULD contain a soapbind:fault describing each known fault. A wsdl:binding in a DESCRIPTION SHOULD contain a soapbind:headerfault describing each known header fault. A MESSAGE MAY contain a fault detail entry in a SOAP fault that is not described by a wsdl:fault element in the corresponding WSDL description. A MESSAGE MAY contain the details of a header processing related fault in a SOAP header block that is not described by a wsdl:headerfault element in the corresponding WSDL description. A wsdl:binding in a DESCRIPTION MUST use the attribute named part with a schema type of "NMTOKEN" on all contained soapbind:header and soapbind:headerfault elements. A wsdl:binding in a DESCRIPTION MUST NOT use the attribute named parts on contained soapbind: header and soapbind:headerfault elements. CORRECT:

<binding name="StockQuoteSoap" type="tns:StockQuotePortType"> <soapbind:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="SubscribeToQuotes"> <input message="tns:SubscribeToQuotes"> <soapbind:body parts="body" use="literal"/> <soapbind:header message="tns:SubscribeToQuotes" part="subscribeheader" use="literal"/> </input> </operation> </binding>

A wsdl:binding in a DESCRIPTION MUST have the name attribute specified on all contained soapbind: fault elements.
http://java.boot.by/wsd-guide/ch01.html 8 / 9 2004/6/13 12:02:35

Chapter 1. XML Web Service Standards

In a DESCRIPTION, the value of the name attribute on a soapbind:fault element MUST match the value of the name attribute on its parent wsdl:fault element. ... ... ...

Prev Part I. Exam Objectives

Up Home

Next Describe the use of XML schema in J2EE Web services.

http://java.boot.by/wsd-guide/ch01.html 9 / 9 2004/6/13 12:02:35

Describe the use of XML schema in J2EE Web services.

Describe the use of XML schema in J2EE Web services. Prev Chapter 1. XML Web Service Standards Next

Describe the use of XML schema in J2EE Web services.


The W3C XML Schema Definition Language is a way of describing and constraining the content of XML documents. The XML Schema specification consists of three parts. One part defines a set of simple datatypes, which can be associated with XML element types and attributes; this allows XML software to do a better job of managing dates, numbers, and other special forms of information. The second part of the specification proposes methods for describing the structure and constraining the contents of XML documents, and defines the rules governing schema validation of documents. The third part is a primer that explains what schemas are, how they differ from DTDs, and how one builds a schema. XML Schema introduces new levels of flexibility that may accelerate the adoption of XML for significant industrial use. For example, a schema author can build a schema that borrows from a previous schema, but overrides it where new unique features are needed. XML Schema allows the author to determine which parts of a document may be validated, or identify parts of a document where a schema may apply. XML Schema also provides a way for users of ecommerce systems to choose which XML Schema they use to validate elements in a given namespace, thus providing better assurance in e-commerce transactions and greater security against unauthorized changes to validation rules. Further, as XML Schema are XML documents themselves, they may be managed by XML authoring tools, or through XSLT. Let's start from "Hello World !" example:

<?xml version="1.0" encoding="UTF-8" ?> <greeting> Hello World! </greeting>

<?xml version="1.0" encoding="UTF-8" ?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="greeting" type="xsd:string"/> </xsd:schema>

http://java.boot.by/wsd-guide/ch01s02.html 1 / 8 2004/6/13 12:02:40

Describe the use of XML schema in J2EE Web services.

Here is a simple data structure for a purchase order. The order example contains following elements: company name, product identifier, and price.

<?xml version="1.0" encoding="UTF-8" ?> <order_request> <company_name>IBA USA, Inc.</company_name> <product_id>C-0YST</product_id> <product_price>500.00</product_price> </order_request>

This example represents pricing data as a floating-point number and company name and product identifier as strings. Agreement among different programs about how to handle data is essential. XML solves data typing issues through the use of XML Schemas. The following example shows how each element in the order request can be designated a specific data type:

<?xml version="1.0" encoding="UTF-8" ?> <xsd:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xsd:element name="order_request"> <xsd:complexType> <xsd:sequence> <xsd:element name="company_name" type="xsd:string"/> <xsd:element name="product_id" type="xsd:string"/> <xsd:element name="product_price" type="xsd:double"/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>

it is equivalent to following XML Schema:

<?xml version="1.0" encoding="UTF-8"?>

http://java.boot.by/wsd-guide/ch01s02.html 2 / 8 2004/6/13 12:02:40

Describe the use of XML schema in J2EE Web services.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="company_name" type="xsd:string"/> <xsd:element name="order_request"> <xsd:complexType> <xsd:sequence> <xsd:element ref="company_name"/> <xsd:element ref="product_id"/> <xsd:element ref="product_price"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="product_id" type="xsd:string"/> <xsd:element name="product_price" type="xsd:double"/> </xsd:schema>

Another example of XML document for more complex purchase order:

<?xml version="1.0" encoding="UTF-8" ?> <purchase_order order_date="2004-04-07"> <shipping_address country="US"> <name>Mikalai Zaikin</name> <street>28th Street</street> <city>Boulder</city> <state>CO</state> <zip>80301</zip> </shipping_address> <items> <item part_number="008291"> <product_name>PRESARIO S5140</product_name> <quantity>1</quantity> <price>898.00</price> </item> <item part_number="005376"> <product_name>COMPAQ FP7317</product_name> <quantity>1</quantity> <price>398.00</price> </item> </items> </purchase_order>

http://java.boot.by/wsd-guide/ch01s02.html 3 / 8 2004/6/13 12:02:40

Describe the use of XML schema in J2EE Web services.

The XML Schema (one of many possible) for this document will be:

<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="city" type="xsd:string" /> <xsd:element name="item"> <xsd:complexType> <xsd:sequence> <xsd:element name="product_name" type="xsd:string" /> <xsd:element ref="quantity" /> <xsd:element ref="price" /> </xsd:sequence> <xsd:attribute name="part_number" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> <xsd:element name="items"> <xsd:complexType> <xsd:sequence> <xsd:element maxOccurs="unbounded" minOccurs="1" ref="item" /> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="name" type="xsd:string" /> <xsd:element name="price" type="xsd:decimal" /> <xsd:element name="purchase_order"> <xsd:complexType> <xsd:sequence> <xsd:element name="shipping_address" type="us_address" /> <xsd:element ref="items" /> </xsd:sequence> <xsd:attribute name="order_date" type="xsd:date" use="required" /> </xsd:complexType> </xsd:element> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction>
http://java.boot.by/wsd-guide/ch01s02.html 4 / 8 2004/6/13 12:02:40

Describe the use of XML schema in J2EE Web services.

</xsd:simpleType> </xsd:element> <xsd:complexType name="us_address"> <xsd:sequence> <xsd:element ref="name" /> <xsd:element ref="street" /> <xsd:element ref="city" /> <xsd:element ref="state" /> <xsd:element ref="zip" /> </xsd:sequence> <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US" /> </xsd:complexType> <xsd:element name="state" type="xsd:string" /> <xsd:element name="street" type="xsd:string" /> <xsd:element name="zip" type="xsd:string" /> </xsd:schema>

Default value of minOccurs is 1. Default value of maxOccurs is 1. XML Schema defines four main elements: 1. 2. 3. 4. xsd:element declares an element and assigns it a type. xsd:attribute declares an attribute and assigns it a type. xsd:complexType defines a new complex type. xsd:simpleType defines a new simple type.

Attribute values are always simple types. Attributes are unordered. It does not matter whether complex type is defined before or after the element declaration as long as it is present in the schema document. You can derive new simple types from existing types. An xsd:simpleType element defines the subtype. The name attribute of xsd:simpleType assigns a name to the new type, by which it can be referred to in xsd:element type attributes. An xsd:restriction child element derives by restricting the legal values of the base type. An xsd:list child element derives a type as a white space separated list of base type instances. An xsd:union child element derives by combining legal values from multiple base types. You can derive new simple types types from existing types by restricting the type to a subset of
http://java.boot.by/wsd-guide/ch01s02.html 5 / 8 2004/6/13 12:02:40

Describe the use of XML schema in J2EE Web services.

its normal values. An xsd:simpleType element defines the restricted type. The name attribute of xsd:simpleType assigns a name to the new type. An xsd:restriction child element specifies what type is being restricted via its base attribute. Facet children of xsd:restriction specify the constraints on the type. For example, this xsd:simpleType element defines a myYear as any year from 1974 on:

<xsd:simpleType name="myYear"> <xsd:restriction base="xsd:gYear"> <xsd:minInclusive value="1974"/> </xsd:restriction> </xsd:simpleType>

Then you declare the year element like this:

<xsd:element type="myYear" />

Facets include: length, minLength, maxLength, pattern, enumeration, whiteSpace, maxInclusive, maxExclusive, minInclusive, minExclusive, totalDigits, fractionDigits. Not all facets apply to all types. For example, new string type must contain between 1 and 255 characters:

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:simpleType name="Str255"> <xsd:restriction base="xsd:string"> <xsd:minLength value="1"/> <xsd:maxLength value="255"/> </xsd:restriction> </xsd:simpleType> </xsd:schema>

For example, the new year type must be between 1974 and 2100:

http://java.boot.by/wsd-guide/ch01s02.html 6 / 8 2004/6/13 12:02:40

Describe the use of XML schema in J2EE Web services.

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:simpleType name="myYear"> <xsd:restriction base="xsd:gYear"> <xsd:minInclusive value="1974"/> <xsd:maxInclusive value="2100"/> </xsd:restriction> </xsd:simpleType> </xsd:schema>

The enumeration facet lists all allowed values. Applies to all simple types except boolean. For example, the computer brand name must be one of the following : COMPAQ, DELL, HP.

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:simpleType name="computerBrandName"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="COMPAQ"/> <xsd:enumeration value="DELL"/> <xsd:enumeration value="HP"/> </xsd:restriction> </xsd:simpleType> </xsd:schema>

Each element in the xsd:all group must occur zero or once; that is minOccurs and maxOccurs must each be 0 or 1. The xsd:all group must be the top level element of its type. The xsd:all group may contain only individual element declarations; no choices or sequences. Example:

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:complexType name="personName"> <xsd:all> <xsd:element name="firstName" type="xsd:string"/> <xsd:element name="lastName" type="xsd:string"/>
http://java.boot.by/wsd-guide/ch01s02.html 7 / 8 2004/6/13 12:02:40

Describe the use of XML schema in J2EE Web services.

</xsd:all> </xsd:complexType> </xsd:schema>

xsd:choice requires exactly one of a group of specified elements to appear. The choice can have minOccurs and maxOccurs attributes that adjust this from zero to any given number. Example:

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:complexType name="coputer"> <xsd:sequence> <xsd:element name="name" type="xsd:string"/> <xsd:choice minOccurs="1" maxOccurs="1"> <xsd:element name="desktop" type="xsd:string"/> <xsd:element name="notebook" type="xsd:string"/> <xsd:element name="handheld" type="xsd:string"/> </xsd:choice> </xsd:sequence> </xsd:complexType> </xsd:schema>

xsd:sequence requires each child element it specifies to appear in the specified order. The sequence can have minOccurs and maxOccurs attributes that repeat each sequence zero to any given number of times.

Prev Chapter 1. XML Web Service Standards

Up Home

Next Describe the use of namespaces in an XML document.

http://java.boot.by/wsd-guide/ch01s02.html 8 / 8 2004/6/13 12:02:40

Describe the use of namespaces in an XML document.

Describe the use of namespaces in an XML document. Prev Chapter 1. XML Web Service Standards Next

Describe the use of namespaces in an XML document.


The XML namespaces recommendation defines a way to distinguish between duplicate element type and attribute names. Such duplication might occur, for example, in an XSLT stylesheet or in a document that contains element types and attributes from two different DTDs. An XML namespace is a collection of element type and attribute names. The namespace is identified by a unique name, which is a URI. Thus, any element type or attribute name in an XML namespace can be uniquely identified by a two-part name: the name of its XML namespace and its local name. This two-part naming system is the only thing defined by the XML namespaces recommendation. XML namespaces are declared with an xmlns attribute, which can associate a prefix with the namespace. You can declare an XML namespace on any element in an XML document. The declaration is in scope for the element containing the attribute and all its descendants (unless it is overridden or undeclared on one of those descendants). It is a common practice to declare all namespaces within the root element. For example:

<!-- Declares two XML namespaces. Their scope is the 'aaa' and 'bbb' elements. --> <aaa xmlns:foo="http://www.foo.org/" xmlns="http://www.bar.org/"> <bbb>abcd</bbb> </aaa>

If an XML namespace declaration contains a prefix, you refer to element type and attribute names in that namespace with the prefix. For example:

<!-- 'aaa' and 'bbb' are in the 'http://www.foo.org/' namespace, which is associated with the 'foo' prefix. --> <foo:aaa xmlns:foo="http://www.foo.org/"> <foo:bbb>abcd</foo:bbb> </foo:aaa>

http://java.boot.by/wsd-guide/ch01s03.html 1 / 5 2004/6/13 12:02:43

Describe the use of namespaces in an XML document.

If an XML namespace declaration does not contain a prefix, the namespace is the default XML namespace and you refer to element type names in that namespace without a prefix. For example:

<!-- This is equivalent to the previous example but uses a DEFAULT namespace instead of the 'foo' prefix. --> <aaa xmlns="http://www.foo.org/"> <bbb>abcd<bbb> </aaa>

The value (unique URI) of the xmlns attribute identifies the namespace, not the prefix. In this example, all elements belong to the same namespace although different prefixes are used.

<!-- 'aaa' and 'bbb' belong to the same 'http://www.foo.org/' namespace. --> <foo:aaa xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.foo.org/"> <bar:bbb>abcd</bar:bbb> </foo:aaa>

In this example, all elements belong to different namespaces although they have the same prefixes.

<!-- 'aaa' and 'bbb' belong to different namespaces. --> <foo:aaa xmlns:foo="http://www.foo.org/"> <foo:aaa /> </foo:aaa> <foo:bbb xmlns:foo="http://www.bar.org/"> <foo:bbb /> </foo:bbb>

You may override the prefix used in an XML namespace declaration, simply declare another XML namespace with the same prefix. For example, in the following, the foo prefix is associated with the http://www.foo.org/ namespace on the aaa element and the http://www.bar.org/ namespace on
http://java.boot.by/wsd-guide/ch01s03.html 2 / 5 2004/6/13 12:02:43

Describe the use of namespaces in an XML document.

the bbb element. That is, the name aaa is in the http://www.foo.org/ namespace and the name bbb is in the http://www.bar.org/ namespace.

<!-- 'bbb' belongs to overriden 'http://www.bar.org/' namespace. --> <foo:aaa xmlns:foo="http://www.foo.org/"> <foo:bbb xmlns:foo="http://www.bar.org/">abcd</foo:bbb> </foo:aaa>

This practice leads to documents that are confusing to read and should be avoided. When an XML namespace declaration goes out of scope, it simply no longer applies. For example, in the following, the declaration of the http://www.foo.org/ namespace does not apply to the bbb element because this is outside its scope.

<!-- 'bbb' does NOT belong to any namespace. --> <aaa xmlns="http://www.foo.org/">abcd</aaa> <bbb>abcd</bbb>

You may undeclare the default XML namespace - declare a default XML namespace with an empty (zero-length) name (URI). Within the scope of this declaration, unprefixed element type names do not belong to any XML namespace. For example, in the following, the default XML namespace is the http://www.foo.org/ for the aaa and there is no default XML namespace for the bbb elements. The name aaa is in the http://www.foo.org/ namespace and the name bbb is not in any XML namespace.

<!-- 'bbb' does NOT belong to any namespace. --> <aaa xmlns="http://www.foo.org/"> <aaa> <bbb xmlns=""> <bbb>abcd</bbb> </bbb> </aaa> </aaa>

http://java.boot.by/wsd-guide/ch01s03.html 3 / 5 2004/6/13 12:02:43

Describe the use of namespaces in an XML document.

You may NOT undeclare XML namespace prefix. It remains in scope until the end of the element on which it was declared unless it is overridden. Furthermore, trying to undeclare a prefix by redeclaring it with an empty (zero-length) name (URI) results in a namespace error. For example:

<!-- You may NOT undeclare XML namespace prefix. --> <foo:aaa xmlns:foo="http://www.foo.org/"> <foo:aaa> <foo"bbb xmlns:foo=""> <!-- ERROR --> <foo:bbb>abcd</foo:bbb> </foo:bbb> </foo:aaa> </foo:aaa>

Attributes can be also explicitly assigned to the given namespace. See the example:

<!-You may assign namespaces to attributes. 'bbb' element belongs to 'http://www.bar.org/' namespace. 'attr' attribute belongs to 'http://www.foo.org/' namespace. --> <foo:aaa xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org/"> <bar:bbb foo:attr="attribute">abcd</bar:bbb> </foo:aaa>

Attributes without a prefix never belongs to any namespace. The attributes do not belong to any namespace even if a default namespace is defined for the relevant element.

Prev Describe the use of XML schema in J2EE Web services.

Up Home

Next Chapter 2. SOAP 1.1 Web Service Standards

http://java.boot.by/wsd-guide/ch01s03.html 4 / 5 2004/6/13 12:02:43

Describe the use of namespaces in an XML document.

http://java.boot.by/wsd-guide/ch01s03.html 5 / 5 2004/6/13 12:02:43

Chapter 2. SOAP 1.1 Web Service Standards

Chapter 2. SOAP 1.1 Web Service Standards Prev Part I. Exam Objectives Next

Chapter 2. SOAP 1.1 Web Service Standards

List and describe the encoding types used in a SOAP message.


The SOAP encoding style is based on a simple type system that is a generalization of the common features found in type systems in programming languages, databases and semistructured data. A type either is a simple (scalar) type or is a compound type constructed as a composite of several parts, each with a type. This is described in more detail below. This section defines rules for serialization of a graph of typed objects. It operates on two levels. First, given a schema in any notation consistent with the type system described, a schema for an XML grammar may be constructed. Second, given a type-system schema and a particular graph of values conforming to that schema, an XML instance may be constructed. In reverse, given an XML instance produced in accordance with these rules, and given also the original schema, a copy of the original value graph may be constructed. There are following SOAP encoding types:

Simple Types
r r r

Strings Enumerations Array of Bytes

Compound Types
r r

Arrays Structures

Simple Types For simple types, SOAP adopts all the types found in the section "Built-in datatypes" of the "XML Schema Part 2: Datatypes" Specification, both the value and lexical spaces. Examples include: boolean (true, false, 0 or 1), byte, short, int, long, float, double, string (java.lang.String), decimal (java. math.BigDecimal), date (java.util.GregorianCalendar), dateTime (java.util.Date), SOAP-ENC:base64 (byte []). The following examples are a SOAP representation of these primitive data types:

http://java.boot.by/wsd-guide/ch02.html 1 / 8 2004/6/13 12:02:47

Chapter 2. SOAP 1.1 Web Service Standards

<element name="age" type="int"/> <element name="height" type="float"/> <element name="displacement" type="negativeInteger"/> <element name="color"> <simpleType base="xsd:string"> <enumeration value="Green"/> <enumeration value="Blue"/> </simpleType> </element> <age>45</age> <height>5.9</height> <displacement>-450</displacement> <color>Blue</color>

Strings The datatype "string" is defined in "XML Schema Part 2: Datatypes" Specification. Note that this is not identical to the type called "string" in many database or programming languages, and in particular may forbid some characters those languages would permit. (Those values must be represented by using some datatype other than xsd:string.) A string MAY be encoded as a singlereference or a multi-reference value. The containing element of the string value MAY have an "id" attribute. Additional accessor elements MAY then have matching "href" attributes. For example, two accessors to the same string could appear, as follows:

<greeting id="String-0">Hello</greeting> <salutation href="#String-0"/>

However, if the fact that both accessors reference the same instance of the string (or subtype of string) is immaterial, they may be encoded as two single-reference values as follows:

<greeting>Hello</greeting> <salutation>Hello</salutation>

Schema fragments for these examples could appear similar to the following:

http://java.boot.by/wsd-guide/ch02.html 2 / 8 2004/6/13 12:02:47

Chapter 2. SOAP 1.1 Web Service Standards

<element name="greeting" type="SOAP-ENC:string"/> <element name="salutation" type="SOAP-ENC:string"/>

(In this example, the type SOAP-ENC:string is used as the element's type as a convenient way to declare an element whose datatype is "xsd:string" and which also allows an "id" and "href" attribute. See the SOAP Encoding schema for the exact definition. Schemas MAY use these declarations from the SOAP Encoding schema but are not required to.) Enumerations Enumeration as a concept indicates a set of distinct names. A specific enumeration is a specific list of distinct values appropriate to the base type. For example the set of color names ("Green", "Blue", "Brown") could be defined as an enumeration based on the string built-in type. The values ("1", "3", "5") are a possible enumeration based on integer, and so on. "XML Schema Part 2: Datatypes" supports enumerations for all of the simple types except for boolean. The language of "XML Schema Part 1: Structures" Specification can be used to define enumeration types. If a schema is generated from another notation in which no specific base type is applicable, use "string". In the following schema example "EyeColor" is defined as a string with the possible values of "Green", "Blue", or "Brown" enumerated, and instance data is shown accordingly:

<element name="EyeColor" type="tns:EyeColor"/> <simpleType name="EyeColor" base="xsd:string"> <enumeration value="Green"/> <enumeration value="Blue"/> <enumeration value="Brown"/> </simpleType> <Person> <Name>Henry Ford</Name> <Age>32</Age> <EyeColor>Brown</EyeColor> </Person>

Array of Bytes An array of bytes MAY be encoded as a single-reference or a multi-reference value. The rules for an array of bytes are similar to those for a string. In particular, the containing element of the array of bytes value MAY have an "id" attribute. Additional accessor elements MAY then have
http://java.boot.by/wsd-guide/ch02.html 3 / 8 2004/6/13 12:02:47

Chapter 2. SOAP 1.1 Web Service Standards

matching "href" attributes. The recommended representation of an opaque array of bytes is the 'base64' encoding defined in XML Schemas, which uses the base64 encoding algorithm. However, the line length restrictions that normally apply to base64 data in MIME do not apply in SOAP. A "SOAP-ENC:base64" subtype is supplied for use with SOAP:

<picture xsi:type="SOAP-ENC:base64"> aG93IG5vDyBicm73biBjb3cNCg== </picture>

Polymorphic Accessor Many languages allow accessors that can polymorphically access values of several types, each type being available at run time. A polymorphic accessor instance MUST contain an "xsi:type" attribute that describes the type of the actual value. For example, a polymorphic accessor named "cost" with a value of type "xsd:float" would be encoded as follows:

<cost xsi:type="xsd:float">29.95</cost>

as contrasted with a cost accessor whose value's type is invariant, as follows:

<cost>29.95</cost>

Compound types A "struct" is a compound value in which accessor name is the only distinction among member values, and no accessor has the same name as any other. An "array" is a compound value in which ordinal position serves as the only distinction among member values. Structures The members of a Compound Value are encoded as accessor elements. When accessors are distinguished by their name (as for example in a struct), the accessor name is used as the
http://java.boot.by/wsd-guide/ch02.html 4 / 8 2004/6/13 12:02:47

Chapter 2. SOAP 1.1 Web Service Standards

element name. Accessors whose names are local to their containing types have unqualified element names; all others have qualified names. The following is an example of a struct of type "book":

<book> <author>Mikalai Zaikin</author> <title>SCDJWS Study Guide</title> <intro>This is a certification guide</intro> </book>

And this is a schema fragment describing the above structure:

<xsd:element name="book"> <xsd:complexType> <xsd:sequence> <xsd:element name="author" type="xsd:string" /> <xsd:element name="title" type="xsd:string" /> <xsd:element name="intro" type="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:element>

The structure also can contain both simple and complex data type values that can reference each other. Below is an example of a type with both simple and complex members. It shows two levels of referencing. Note that the "href" attribute of the "author" accessor element is a reference to the value whose "id" attribute matches. A similar construction appears for the "address" element:

<book> <title>SCDJWS Study Guide</title> <author href="#person-1" /> </book> <person id="person-1"> <name>Mikalai Zaikin</name> <address href="#address-1" /> </person>
http://java.boot.by/wsd-guide/ch02.html 5 / 8 2004/6/13 12:02:47

Chapter 2. SOAP 1.1 Web Service Standards

<inet_address id="address-1"> <email>mailto:nikolay_zaikin[at]mail.ru</email> <web>http://www.iba.by</web> </inet_address>

Arrays SOAP arrays are defined as having a type of "SOAP-ENC:Array" or a type derived there from. Arrays are represented as element values, with no specific constraint on the name of the containing element (just as values generally do not constrain the name of their containing element). Arrays can contain elements which themselves can be of any type, including nested arrays. New types formed by restrictions of SOAP-ENC:Array can also be created to represent, for example, arrays limited to integers or arrays of some user-defined enumeration. The representation of the value of an array is an ordered sequence of elements constituting the items of the array. Within an array value, element names are not significant for distinguishing accessors. Elements may have any name. In practice, elements will frequently be named so that their declaration in a schema suggests or determines their type. As with compound types generally, if the value of an item in the array is a single-reference value, the item contains its value. Otherwise, the item references its value via an "href" attribute. The following example is a schema fragment and an array containing integer array members:

<element name="myFavoriteNumbers" type="SOAP-ENC:Array"/> <myFavoriteNumbers SOAP-ENC:arrayType="xsd:int[3]"> <number>1</number> <number>2</number> <number>3</number> </myFavoriteNumbers>

In that example, the array "myFavoriteNumbers" contains several members each of which is a value of type SOAP-ENC:int. This can be determined by inspection of the SOAP-ENC:arrayType attribute. Note that the SOAP-ENC:Array type allows unqualified element names without restriction. These convey no type information, so when used they must either have an xsi:type attribute or the containing element must have a SOAP-ENC:arrayType attribute. Naturally, types derived from SOAP-ENC:Array may declare local elements, with type information. As previously noted, the SOAP-ENC schema contains declarations of elements with names corresponding to each simple type in the "XML Schema Part 2: Datatypes" Specification. It also contains a declaration for "Array". Using these, we might write:

http://java.boot.by/wsd-guide/ch02.html 6 / 8 2004/6/13 12:02:47

Chapter 2. SOAP 1.1 Web Service Standards

<SOAP-ENC:Array SOAP-ENC:arrayType="xsd:int[3]"> <SOAP-ENC:int>1</SOAP-ENC:int> <SOAP-ENC:int>2</SOAP-ENC:int> <SOAP-ENC:int>3</SOAP-ENC:int> </SOAP-ENC:Array>

Arrays can contain instances of any subtype of the specified arrayType. That is, the members may be of any type that is substitutable for the type specified in the arrayType attribute, according to whatever substitutability rules are expressed in the schema. So, for example, an array of integers can contain any type derived from integer (for example "int" or any userdefined derivation of integer). Similarly, an array of "address" might contain a restricted or extended type such as "internationalAddress". Because the supplied SOAP-ENC:Array type admits members of any type, arbitrary mixtures of types can be contained unless specifically limited by use of the arrayType attribute. Array values may be structs or other compound values. For example an array of "my:order" structs :

<SOAP-ENC:Array SOAP-ENC:arrayType="my:order[2]"> <order> <product>Melon</product> <price>0.99</price> </order> <order> <product>Apple</product> <price>1.49</price> </order> </SOAP-ENC:Array>

Arrays may have other arrays as member values. The following is an example of an array of two arrays, each of which is an array of strings:

<SOAP-ENC:Array SOAP-ENC:arrayType="xsd:string[][2]"> <item href="#array-1"/> <item href="#array-2"/> </SOAP-ENC:Array>

http://java.boot.by/wsd-guide/ch02.html 7 / 8 2004/6/13 12:02:47

Chapter 2. SOAP 1.1 Web Service Standards

<SOAP-ENC:Array id="array-1" SOAP-ENC:arrayType="xsd:string[3]"> <item>row1column1</item> <item>row1column2</item> <item>row1column3</item> </SOAP-ENC:Array> <SOAP-ENC:Array id="array-2" SOAP-ENC:arrayType="xsd:string[2]"> <item>row2column1</item> <item>row2column2</item> </SOAP-ENC:Array>

Arrays may be multi-dimensional. In this case, more than one size will appear within the asize part of the arrayType attribute:

<SOAP-ENC:Array SOAP-ENC:arrayType="xsd:string[2,3]"> <item>row1column1</item> <item>row1column2</item> <item>row1column3</item> <item>row2column1</item> <item>row2ccolumn2</item> <item>row2column3</item> </SOAP-ENC:Array>

Prev Describe the use of namespaces in an XML document.

Up Home

Next Describe how SOAP message header blocks are used and processed.

http://java.boot.by/wsd-guide/ch02.html 8 / 8 2004/6/13 12:02:47

Describe how SOAP message header blocks are used and processed.

Describe how SOAP message header blocks are used and processed. Prev Chapter 2. SOAP 1.1 Web Service Standards Next

Describe how SOAP message header blocks are used and processed.
SOAP provides a flexible mechanism for extending a message in a decentralized and modular way without prior knowledge between the communicating parties. Typical examples of extensions that can be implemented as header entries are authentication, transaction management, payment etc. The Header element is encoded as the first immediate child element of the SOAP Envelope XML element. NOTE: The Header element is OPTIONAL. All immediate child elements of the Header element are called header entries (Header element may contain multiple child elements - header entries). Header entries can have following attributes: actor, encodingStyle, mustUnderstand. The encoding rules for header entries are as follows: 1. A header entry is identified by its fully qualified element name, which consists of the namespace URI and the local name. All immediate child elements of the SOAP Header element MUST be namespace-qualified. 2. The SOAP encodingStyle attribute MAY be used to indicate the encoding style used for the header entries. 3. The SOAP mustUnderstand attribute and SOAP actor attribute MAY be used to indicate how to process the entry and by whom. The SOAP Header attributes defined in this section determine how a recipient of a SOAP message should process the message. A SOAP application generating a SOAP message SHOULD only use the SOAP Header attributes on immediate child elements of the SOAP Header element. The recipient of a SOAP message MUST ignore all SOAP Header attributes that are not applied to an immediate child element of the SOAP Header element. An example is a header with an element identifier of "Transaction", a "mustUnderstand" value of "1", and a value of 12345. This would be encoded as follows:

<SOAP-ENV:Header> <t:Transaction xmlns:t="some-URI" SOAP-ENV:mustUnderstand="1"> 12345 </t:Transaction> </SOAP-ENV:Header>

http://java.boot.by/wsd-guide/ch02s02.html 1 / 5 2004/6/13 12:02:52

Describe how SOAP message header blocks are used and processed.

or

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <t:Transaction xmlns:t="some-URI" soap:mustUnderstand="1"> 12345 </t:Transaction> </soap:Header> ... ... </soap:Envelope>

A SOAP message travels from the originator to the ultimate destination, potentially by passing through a set of SOAP intermediaries along the message path. A SOAP intermediary is an application that is capable of both receiving and forwarding SOAP messages. Both intermediaries as well as the ultimate destination are identified by a URI. Not all parts of a SOAP message may be intended for the ultimate destination of the SOAP message but, instead, may be intended for one or more of the intermediaries on the message path. The role of a recipient of a header element is similar to that of accepting a contract in that it cannot be extended beyond the recipient. That is, a recipient receiving a header element MUST NOT forward that header element to the next application in the SOAP message path. The recipient MAY insert a similar header element but in that case, the contract is between that application and the recipient of that header element. The SOAP actor global attribute can be used to indicate the recipient of a header element. The value of the SOAP actor attribute is a URI:

SOAP-ENV:actor="some-URI"

or

soap:actor="some-URI"

The special URI "http://schemas.xmlsoap.org/soap/actor/next" indicates that the header element is


http://java.boot.by/wsd-guide/ch02s02.html 2 / 5 2004/6/13 12:02:52

Describe how SOAP message header blocks are used and processed.

intended for the very first SOAP application that processes the message. This is similar to the hop-by-hop scope model represented by the Connection header field in HTTP. NOTE: Omitting the SOAP actor attribute indicates that the recipient is the ultimate destination of the SOAP message. This attribute MUST appear in the SOAP message instance in order to be effective. An example:

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <t:Transaction xmlns:t="some-URI" soap:actor="http://myserver.com/myactor"> 12345 </t:Transaction> </soap:Header> ... ... </soap:Envelope>

In this example header will be processed by first application:

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <t:Transaction xmlns:t="some-URI" soap:actor="http://schemas.xmlsoap.org/soap/actor/next"> 12345 </t:Transaction> </soap:Header> ... ... </soap:Envelope>

The SOAP mustUnderstand global attribute can be used to indicate whether a header entry is
http://java.boot.by/wsd-guide/ch02s02.html 3 / 5 2004/6/13 12:02:52

Describe how SOAP message header blocks are used and processed.

mandatory or optional for the recipient to process. The recipient of a header entry is defined by the SOAP actor attribute. The value of the mustUnderstand attribute is either "1" or "0".

SOAP-ENV:mustUnderstand="0|1"

or

soap:mustUnderstand="0|1"

The absence of the SOAP mustUnderstand attribute is semantically equivalent to its presence with the value "0". If a header element is tagged with a SOAP mustUnderstand attribute with a value of "1", the recipient of that header entry either MUST obey the semantics (as conveyed by the fully qualified name of the element) and process correctly to those semantics, or MUST fail processing the message. The SOAP mustUnderstand attribute allows for robust evolution. Elements tagged with the SOAP mustUnderstand attribute with a value of "1" MUST be presumed to somehow modify the semantics of their parent or peer elements. Tagging elements in this manner assures that this change in semantics will not be silently (and, presumably, erroneously) ignored by those who may not fully understand it. This attribute MUST appear in the instance in order to be effective. An example:

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <t:Transaction xmlns:t="some-URI" soap:actor="http://myserver.com/myactor" soap:mustUnderstand="1"> 12345 </t:Transaction> </soap:Header> ... ... </soap:Envelope>

http://java.boot.by/wsd-guide/ch02s02.html 4 / 5 2004/6/13 12:02:52

Describe how SOAP message header blocks are used and processed.

Prev Chapter 2. SOAP 1.1 Web Service Standards

Up

Next Describe the function of each element contained in a SOAP message, the SOAP binding to HTTP, and how to represent faults that occur when processing a SOAP message.

Home

http://java.boot.by/wsd-guide/ch02s02.html 5 / 5 2004/6/13 12:02:52

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

Describe the function of each element contained in a SOAP message, the SOAP binding to HTTP, and how to represent faults that occur when processing a SOAP message. Prev Chapter 2. SOAP 1.1 Web Service Standards Next

Describe the function of each element contained in a SOAP message, the SOAP binding to HTTP, and how to represent faults that occur when processing a SOAP message.
A SOAP message is an XML document that consists of a mandatory SOAP envelope, an optional SOAP header, and a mandatory SOAP body. The namespace identifier for the elements and attributes from SOAP message is "http://schemas.xmlsoap.org/soap/envelope/". A SOAP message contains the following:

The Envelope is the top element of the XML document representing the message. The Header is a generic mechanism for adding features to a SOAP message in a decentralized manner without prior agreement between the communicating parties. SOAP defines a few attributes that can be used to indicate who should deal with a feature and whether it is optional or mandatory. NOTE: Header element is OPTIONAL. The Body is a container for mandatory information intended for the ultimate recipient of the message. SOAP defines one element for the body, which is the Fault element used for reporting errors. NOTE: Body element is MANDATORY and MUST be exactly 1 per message.

The grammar rules are as follows: 1. Envelope


The element name is "Envelope". The element MUST be present in a SOAP message. The element MAY contain namespace declarations as well as additional attributes. If present, such additional attributes MUST be namespace-qualified. Similarly, the element MAY contain additional sub elements. If present these elements MUST be namespace-qualified and MUST follow the SOAP Body element.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> <xs:complexType name="Envelope"> <xs:sequence> <xs:element ref="tns:Header" minOccurs="0" /> <xs:element ref="tns:Body" minOccurs="1" /> <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax" />
http://java.boot.by/wsd-guide/ch02s03.html 1 / 12 2004/6/13 12:02:58

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

</xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax" /> </xs:complexType> .... </xs:schema>

2. Header

The element name is "Header". The element MAY be present in a SOAP message. If present, the element MUST be the first immediate child element of a SOAP Envelope element. The element MAY contain a set of header entries each being an immediate child element of the SOAP Header element. All immediate child elements of the SOAP Header element MUST be namespace-qualified.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> .... <xs:complexType name="Header"> <xs:sequence> <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax" /> </xs:complexType> .... </xs:schema>

3. Body

The element name is "Body". The element MUST be present in a SOAP message and MUST be an immediate child element of a SOAP Envelope element. It MUST directly follow the SOAP Header element if present. Otherwise it MUST be the first immediate child element of the SOAP Envelope element. The element MAY contain a set of body entries each being an immediate child element of the SOAP Body element. Immediate child elements of the SOAP Body element MAY be namespace-qualified. SOAP defines the SOAP Fault element, which is used to indicate error messages.

http://java.boot.by/wsd-guide/ch02s03.html 2 / 12 2004/6/13 12:02:58

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> .... <xs:complexType name="Body"> <xs:sequence> <xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> <xs:anyAttribute namespace="##any" processContents="lax"> <xs:annotation> <xs:documentation> Prose in the spec does not specify that attributes are allowed on the Body element </xs:documentation> </xs:annotation> </xs:anyAttribute> </xs:complexType> .... </xs:schema>

The SOAP Body element provides a simple mechanism for exchanging mandatory information intended for the ultimate recipient of the message. Typical uses of the Body element include marshalling RPC calls and error reporting. The Body element is encoded as an immediate child element of the SOAP Envelope XML element. If a Header element is present then the Body element MUST immediately follow the Header element, otherwise it MUST be the first immediate child element of the Envelope element. All immediate child elements of the Body element are called body entries and each body entry is encoded as an independent element within the SOAP Body element. The encoding rules for body entries are as follows: 1. A body entry is identified by its fully qualified element name, which consists of the namespace URI and the local name. Immediate child elements of the SOAP Body element MAY be namespace-qualified. 2. The SOAP encodingStyle attribute MAY be used to indicate the encoding style used for the body entries (this attribute MAY appear on any element, and is scoped to that element's contents and all child elements not themselves containing such an attribute, much as an XML namespace declaration is scoped). SOAP defines one body entry, which is the Fault entry used for reporting errors. Here is schema definition of Fault element:

http://java.boot.by/wsd-guide/ch02s03.html 3 / 12 2004/6/13 12:02:58

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> .... <xs:complexType name="Fault" final="extension"> <xs:annotation> <xs:documentation>Fault reporting structure</xs:documentation> </xs:annotation> <xs:sequence> <xs:element name="faultcode" type="xs:QName" /> <xs:element name="faultstring" type="xs:string" /> <xs:element name="faultactor" type="xs:anyURI" minOccurs="0" /> <xs:element name="detail" type="tns:detail" minOccurs="0" /> </xs:sequence> </xs:complexType> .... </xs:schema>

SOAP Fault The SOAP Fault element is used to carry error and/or status information within a SOAP message. If present, the SOAP Fault element MUST appear as a body entry and MUST NOT appear more than once within a Body element. The SOAP Fault element defines the following four subelements: 1. faultcode - The faultcode element is intended for use by software to provide an algorithmic mechanism for identifying the fault. The faultcode MUST be present in a SOAP Fault element and the faultcode value MUST be a qualified name. SOAP defines a small set of SOAP fault codes covering basic SOAP faults. 2. faultstring - The faultstring element is intended to provide a human readable explanation of the fault and is not intended for algorithmic processing. The faultstring element is similar to the 'Reason-Phrase' defined by HTTP. It MUST be present in a SOAP Fault element and SHOULD provide at least some information explaining the nature of the fault. 3. faultactor - The faultactor element is intended to provide information about who caused the fault to happen within the message path. It is similar to the SOAP actor attribute but instead of indicating the destination of the header entry, it indicates the source of the fault. The value of the faultactor attribute is a URI identifying the source. Applications that do not act as the ultimate destination of the SOAP message MUST include the faultactor element in a SOAP Fault element. The ultimate destination of a message MAY use the faultactor element to indicate explicitly that it generated the fault. 4. detail - The detail element is intended for carrying application specific error information related to the Body element. It MUST be present if the contents of the Body element could not be successfully processed. It MUST NOT be used to carry information about error

http://java.boot.by/wsd-guide/ch02s03.html 4 / 12 2004/6/13 12:02:58

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

information belonging to header entries. Detailed error information belonging to header entries MUST be carried within header entries. The absence of the detail element in the Fault element indicates that the fault is not related to processing of the Body element. This can be used to distinguish whether the Body element was processed or not in case of a fault situation. All immediate child elements of the detail element are called detail entries and each detail entry is encoded as an independent element within the detail element.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> .... <xs:complexType name="detail"> <xs:sequence> <xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> <xs:anyAttribute namespace="##any" processContents="lax" /> </xs:complexType> .... </xs:schema>

The encoding rules for detail entries are as follows: a. A detail entry is identified by its fully qualified element name, which consists of the namespace URI and the local name. Immediate child elements of the detail element MAY be namespace-qualified. b. The SOAP encodingStyle attribute MAY be used to indicate the encoding style used for the detail entries The faultcode values MUST be used in the faultcode element when describing faults. The namespace identifier for these faultcode values is "http://schemas.xmlsoap.org/soap/envelope/". The default SOAP faultcode values are defined in an extensible manner that allows for new SOAP faultcode values to be defined while maintaining backwards compatibility with existing faultcode values. The mechanism used is very similar to the 1xx, 2xx, 3xx etc basic status classes classes defined in HTTP. However, instead of integers, they are defined as XML qualified names. The character "." (dot) is used as a separator of faultcode values indicating that what is to the left of the dot is a more generic fault code value than the value to the right. Example:

Client.Authentication

The set of faultcode values is:


http://java.boot.by/wsd-guide/ch02s03.html 5 / 12 2004/6/13 12:02:58

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

Table 2.1. SOAP Fault Codes


Error VersionMismatch Description The processing party found an invalid namespace for the SOAP Envelope element. An immediate child element of the SOAP Header element that was either not understood or not obeyed by the processing party contained a SOAP mustUnderstand attribute with a value of "1". The Client class of errors indicate that the message was incorrectly formed or did not contain the appropriate information in order to succeed. For example, the message could lack the proper authentication or payment information. It is generally an indication that the message should not be resent without change. The Server class of errors indicate that the message could not be processed for reasons not directly attributable to the contents of the message itself but rather to the processing of the message. For example, processing could include communicating with an upstream processor, which didn't respond. The message may succeed at a later point in time.

MustUnderstand

Client

Server

Using SOAP in HTTP Binding SOAP to HTTP provides the advantage of being able to use the formalism and decentralized flexibility of SOAP with the rich feature set of HTTP. Carrying SOAP in HTTP does not mean that SOAP overrides existing semantics of HTTP but rather that the semantics of SOAP over HTTP maps naturally to HTTP semantics. SOAP naturally follows the HTTP request/response message model providing SOAP request parameters in a HTTP request and SOAP response parameters in a HTTP response. Note, however, that SOAP intermediaries are NOT the same as HTTP intermediaries. That is, an HTTP intermediary addressed with the HTTP Connection header field cannot be expected to inspect or process the SOAP entity body carried in the HTTP request. HTTP applications MUST use the media type "text/xml" when including SOAP entity bodies in HTTP messages. The SOAPAction HTTP request header field can be used to indicate the intent of the SOAP HTTP request. The value is a URI identifying the intent. SOAP places no restrictions on the format or specificity of the URI or that it is resolvable. An HTTP client MUST use this header field when issuing a SOAP HTTP Request. The presence and content of the SOAPAction header field can be used by servers such as firewalls to appropriately filter SOAP request messages in HTTP. The header field value of empty string ("") means that the intent of the SOAP message is provided by the HTTP Request-URI. No value means that there is no indication of the intent of the message. Examples:
http://java.boot.by/wsd-guide/ch02s03.html 6 / 12 2004/6/13 12:02:58

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

SOAPAction: "http://electrocommerce.org/abc#MyMessage"

SOAPAction: "myapp.sdl"

SOAPAction: ""

SOAPAction:

SOAP HTTP follows the semantics of the HTTP Status codes for communicating status information in HTTP. For example, a 2xx status code indicates that the client's request including the SOAP component was successfully received, understood, and accepted etc. In case of a SOAP error while processing the request, the SOAP HTTP server MUST issue an HTTP 500 "Internal Server Error" response and include a SOAP message in the response containing a SOAP Fault element indicating the SOAP processing error. Below is an example of HTTP request, successful response and fault response of simple Web Service for retrieving Quote information. Quote SOAP HTTP request:

POST /StockQuoteProj/servlet/rpcrouter HTTP/1.0 Host: localhost:9080 Content-Type: text/xml; charset=utf-8 Content-Length: 469 SOAPAction: "" <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"

http://java.boot.by/wsd-guide/ch02s03.html 7 / 12 2004/6/13 12:02:59

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getQuote xmlns:ns1="http://tempuri.org/StockQuoteService" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <symbol xsi:type="xsd:string">ibm</symbol> </ns1:getQuote> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Quote SOAP HTTP successful response:

HTTP/1.1 200 OK Server: WebSphere Application Server/5.1 Content-Type: text/xml; charset=utf-8 Content-Length: 488 Content-Language: ru-RU Connection: close <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getQuoteResponse xmlns:ns1="http://tempuri.org/StockQuoteService" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <return xsi:type="xsd:float">93.12</return> </ns1:getQuoteResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Quote SOAP HTTP fault response (exception is thrown by service endpoint object):

HTTP/1.1 500 Internal Server Error Server: WebSphere Application Server/5.1 Expires: Thu, 01 Dec 1994 16:00:00 GMT Set-Cookie: JSESSIONID=0000XEtXnz75hI--bFdY49XCHGU:-1;Path=/ Cache-Control: no-cache="set-cookie,set-cookie2"
http://java.boot.by/wsd-guide/ch02s03.html 8 / 12 2004/6/13 12:02:59

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

<?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Exception from service object: null</faultstring> <faultactor>/StockQuoteProj/servlet/rpcrouter</faultactor> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP request Using POST with a Mandatory Header:

POST /StockQuote HTTP/1.1 Host: www.stockquoteserver.com Content-Type: text/xml; charset="utf-8" Content-Length: nnnn SOAPAction: "Some-URI" <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Header> <t:Transaction xmlns:t="some-URI" SOAP-ENV:mustUnderstand="1"> 12345 </t:Transaction> </SOAP-ENV:Header> <SOAP-ENV:Body> <m:GetLastTradePrice xmlns:m="Some-URI"> <symbol>DEF</symbol> </m:GetLastTradePrice> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP request Using POST with multiple request parameters:

http://java.boot.by/wsd-guide/ch02s03.html 9 / 12 2004/6/13 12:02:59

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

POST /StockQuote HTTP/1.1 Host: www.stockquoteserver.com Content-Type: text/xml; charset="utf-8" Content-Length: nnnn SOAPAction: "Some-URI" <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <m:GetLastTradePriceDetailed xmlns:m="Some-URI"> <Symbol>DEF</Symbol> <Company>DEF Corp</Company> <Price>34.1</Price> </m:GetLastTradePriceDetailed> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP response with a Mandatory Header:

HTTP/1.1 200 OK Content-Type: text/xml; charset="utf-8" Content-Length: nnnn <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Header> <t:Transaction xmlns:t="some-URI" xsi:type="xsd:int" mustUnderstand="1"> 12345 </t:Transaction> </SOAP-ENV:Header> <SOAP-ENV:Body> <m:GetLastTradePriceResponse xmlns:m="Some-URI"> <Price>34.5</Price> </m:GetLastTradePriceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP response with a Struct:

http://java.boot.by/wsd-guide/ch02s03.html 10 / 12 2004/6/13 12:02:59

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

HTTP/1.1 200 OK Content-Type: text/xml; charset="utf-8" Content-Length: nnnn <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <m:GetLastTradePriceResponse xmlns:m="Some-URI"> <PriceAndVolume> <LastTradePrice> 34.5 </LastTradePrice> <DayVolume> 10000 </DayVolume> </PriceAndVolume> </m:GetLastTradePriceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP response Failing to honor Mandatory Header:

HTTP/1.1 500 Internal Server Error Content-Type: text/xml; charset="utf-8" Content-Length: nnnn <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>SOAP-ENV:MustUnderstand</faultcode> <faultstring>SOAP Must Understand Error</faultstring> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP response Failing to handle Body:

http://java.boot.by/wsd-guide/ch02s03.html 11 / 12 2004/6/13 12:02:59

Describe the function of each element contained in a SOAP message, t... how to represent faults that occur when processing a SOAP message.

HTTP/1.1 500 Internal Server Error Content-Type: text/xml; charset="utf-8" Content-Length: nnnn <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Server Error</faultstring> <detail> <e:myfaultdetails xmlns:e="Some-URI"> <message> My application didn't work </message> <errorcode> 1001 </errorcode> </e:myfaultdetails> </detail> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Prev Describe how SOAP message header blocks are used and processed.

Up Home

Next Create a SOAP message that contains an attachment.

http://java.boot.by/wsd-guide/ch02s03.html 12 / 12 2004/6/13 12:02:59

Create a SOAP message that contains an attachment.

Create a SOAP message that contains an attachment. Prev Chapter 2. SOAP 1.1 Web Service Standards Next

Create a SOAP message that contains an attachment.


The SOAP with Attachments API for Java (SAAJ) provides a standard way to send XML documents over the Internet from the Java platform. It is based on the SOAP 1.1 and SOAP with Attachments specifications, which define a basic framework for exchanging XML messages. The process of creation and sending SOAP message includes following steps:

Creating a SOAP connection Creating a SOAP message Populating the message Sending the message Retrieving the reply

A SAAJ client is a standalone client. That is, it sends point-to-point messages directly to a Web service that is implemented for request-response messaging. Request-response messaging is synchronous, meaning that a request is sent and its response is received in the same operation. A request-response message is sent over a SOAPConnection object via the method SOAPConnection.call, which sends the message and blocks until it receives a response. A standalone client can operate only in a client role, that is, it can only send requests and receive their responses. A SOAPMessage object represents an XML document that is a SOAP message. A SOAPMessage object always has a required SOAP part, and it may also have one or more attachment parts. The SOAP part must always have a SOAPEnvelope> object, which must in turn always contain a SOAPBody object. The SOAPEnvelope object may also contain a SOAPHeader object, to which one or more headers can be added. A SOAPMessage object represents an XML document that is a SOAP message. A SOAPMessage object always has a required SOAP part, and it may also have one or more attachment parts. The SOAP part must always have a SOAPEnvelope object, which must in turn always contain a SOAPBody> object. The SOAPEnvelope object may also contain a SOAPHeader> object, to which one or more headers can be added. The SOAPBody object can hold XML fragments as the content of the message being sent. If you want to send content that is not in XML format or that is an entire XML document, your message will need to contain an attachment part in addition to the SOAP part. There is no limitation on the content in the attachment part, so it can include images or any other kind of content, including XML fragments and documents. Common types of attachment include sound, picture, and movie data: .mp3, .jpg, and .mpg files. The first thing a SAAJ client needs to do is get a connection in the form of a SOAPConnection
http://java.boot.by/wsd-guide/ch02s04.html 1 / 4 2004/6/13 12:03:02

Create a SOAP message that contains an attachment.

object. A SOAPConnection object is a point-to-point connection that goes directly from the sender to the recipient. The connection is created by a SOAPConnectionFactory object. A client obtains the default implementation for SOAPConnectionFactory by calling the following line of code:

SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();

The client can use factory to create a SOAPConnection object.

SOAPConnection connection = factory.createConnection();

Messages, like connections, are created by a factory. To obtain a MessageFactory object, you get an instance of the default implementation for the MessageFactory class. This instance can then be used to create a SOAPMessage object:

MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage message = messageFactory.createMessage();

All of the SOAPMessage objects that messageFactory creates, including message in the previous line of code, will be SOAP messages. This means that they will have no pre-defined headers. The new SOAPMessage object message automatically contains the required elements SOAPPart, SOAPEnvelope, and SOAPBody, plus the optional element SOAPHeader (which is included for convenience). The SOAPHeader and SOAPBody objects are initially empty, and the following sections will illustrate some of the typical ways to add content. Content can be added to the SOAPPart object, to one or more AttachmentPart objects, or to both parts of a message. As stated earlier, all messages have a SOAPPart object, which has a SOAPEnvelope object containing a SOAPHeader object and a SOAPBody object. One way to add content to the SOAP part of a message is to create a SOAPHeaderElement object or a SOAPBodyElement object and add an XML fragment that you build with the method SOAPElement.addTextNode. The first three lines of the following code fragment access the SOAPBody object body, which is used to create a new SOAPBodyElement object and add it to body. The argument passed to the createName method is a Name object identifying the SOAPBodyElement being added. The last line adds the XML string passed to the method addTextNode:

SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getSOAPEnvelope(); SOAPBody body = envelope.getSOAPBody(); SOAPBodyElement bodyElement = body.addBodyElement( envelope.createName("text", "hotitems", "http://hotitems.com/products/gizmo");
http://java.boot.by/wsd-guide/ch02s04.html 2 / 4 2004/6/13 12:03:02

Create a SOAP message that contains an attachment.

bodyElement.addTextNode("some-xml-text");

Another way is to add content to the SOAPPart object by passing it a javax.xml.transform.Source object, which may be a SAXSource, DOMSource, or StreamSource object. The Source object contains content for the SOAP part of the message and also the information needed for it to act as source input. A StreamSource object will contain the content as an XML document; the SAXSource or DOMSource object will contain content and instructions for transforming it into an XML document. The following code fragments illustrates adding content as a DOMSource object. The first step is to get the SOAPPart object from the SOAPMessage object. Next the code uses methods from the JAXP API to build the XML document to be added. It uses a DocumentBuilderFactory object to get a DocumentBuilder object. Then it parses the given file to produce the document that will be used to initialize a new DOMSource object. Finally, the code passes the DOMSource object domSource to the method SOAPPart.setContent:

SOAPPart soapPart = message.getSOAPPart(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbFactory.newDocumentBuilder(); Document document = builder.parse("file:///foo.bar/soap.xml"); DOMSource domSource = new DOMSource(document); soapPart.setContent(domSource);

This code would work equally well with a SAXSource or a StreamSource object. You use the setContent method when you want to send an existing SOAP message. If you have an XML document that you want to send as the content of a SOAP message, you use the addDocument method on the body of the message:

SOAPBodyElement docElement = body.addDocument(document);

This allows you to keep your application data in a document that is separate from the SOAP envelope unless and until it is time to send that data as a message. A Message object may have no attachment parts, but if it is to contain anything that is not in XML format, that content must be contained in an attachment part. There may be any number of attachment parts, and they may contain anything from plain text to image files. In the following code fragment, the content is an image in a JPEG file, whose URL is used to initialize the javax. activation.DataHandler object handler. The Message object message creates the AttachmentPart object attachPart, which is initialized with the data handler containing the URL for the image. Finally, the message adds attachPart to itself:

http://java.boot.by/wsd-guide/ch02s04.html 3 / 4 2004/6/13 12:03:02

Create a SOAP message that contains an attachment.

URL url = new URL("http://foo.bar/img.jpg"); DataHandler handler = new DataHandler(url); AttachmentPart attachPart = message.createAttachmentPart(handler); message.addAttachmentPart(attachPart);

A SOAPMessage object can also give content to an AttachmentPart object by passing an Object and its content type to the method createAttachmentPart:

AttachmentPart attachPart = message.createAttachmentPart( "content-string", "text/plain"); message.addAttachmentPart(attachPart);

Once you have populated a SOAPMessage object, you are ready to send it. A client uses the SOAPConnection method call to send a message. This method sends the message and then blocks until it gets back a response. The arguments to the method call are the message being sent and a URL object that contains the URL specifying the endpoint of the receiver.

SOAPMessage response = soapConnection.call(message, endpoint);

Prev Describe the function of each element contained in a SOAP message, the SOAP binding to HTTP, and how to represent faults that occur when processing a SOAP message.

Up

Next Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.

Home

http://java.boot.by/wsd-guide/ch02s04.html 4 / 4 2004/6/13 12:03:02

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a. Prev Chapter 2. SOAP 1.1 Web Service Standards Next

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.
BP 1.0 - Messaging - XML Representation of SOAP Messages. When a MESSAGE contains a soap:Fault element, that element MUST NOT have element children other than faultcode, faultstring, faultactor and detail. CORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <faultcode>soap:Client</faultcode> <faultstring>Invalid message format</faultstring> <faultactor>http://example.org/someactor</faultactor> <detail> <m:msg xmlns:m='http://example.org/faults/exceptions'> There were <b>lots</b> of elements in the message that I did not understand </m:msg> <m:Exception xmlns:m='http://example.org/faults/exceptions'> <m:ExceptionType>Severe</m:ExceptionType> </m:Exception> </detail> </soap:Fault>

INCORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <faultcode>soap:Client</faultcode> <faultstring>Invalid message format</faultstring> <faultactor>http://example.org/someactor</faultactor> <detail>There were <b>lots</b> of elements in the message that I did not understand </detail> <m:Exception xmlns:m='http://example.org/faults/exceptions' > <m:ExceptionType>Severe</m:ExceptionType> </m:Exception>
http://java.boot.by/wsd-guide/ch02s05.html 1 / 6 2004/6/13 12:03:05

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.

</soap:Fault>

When a MESSAGE contains a soap:Fault element its element children MUST be unqualified. CORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns='' > <faultcode>soap:Client</faultcode> <faultstring>Invalid message format</faultstring> <faultactor>http://example.org/someactor</faultactor> <detail> <m:msg xmlns:m='http://example.org/faults/exceptions'> There were <b>lots</b> of elements in the message that I did not understand </m:msg> </detail> </soap:Fault>

INCORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <soap:faultcode>soap:Client</soap:faultcode> <soap:faultstring>Invalid message format</soap:faultstring> <soap:faultactor>http://example.org/someactor</soap:faultactor> <soap:detail> <m:msg xmlns:m='http://example.org/faults/exceptions'> There were <b>lots</b> of elements in the message that I did not understand </m:msg> </soap:detail> </soap:Fault>

A RECEIVER MUST accept fault messages that have any number of ELEMENTS, including zero, appearing as children of the detail element. Such children can be qualified or unqualified.
http://java.boot.by/wsd-guide/ch02s05.html 2 / 6 2004/6/13 12:03:05

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.

A RECEIVER MUST accept fault messages that have any number of qualified or unqualified ATTRIBUTES, including zero, appearing on the detail element. The namespace of qualified attributes can be anything other than "http://schemas.xmlsoap.org/soap/envelope/". A RECEIVER MUST accept fault messages that carry an xml:lang attribute on the faultstring element. When a MESSAGE contains a faultcode element the content of that element SHOULD be one of the fault codes defined in SOAP 1.1 or a namespace qualified fault code. The faultcode values defined below MUST be used in the faultcode element when describing faults. Table 2.2. SOAP Fault Codes
Error VersionMismatch Description The processing party found an invalid namespace for the SOAP Envelope element. An immediate child element of the SOAP Header element that was either not understood or not obeyed by the processing party contained a SOAP mustUnderstand attribute with a value of "1". The Client class of errors indicate that the message was incorrectly formed or did not contain the appropriate information in order to succeed. For example, the message could lack the proper authentication or payment information. It is generally an indication that the message should not be resent without change. The Server class of errors indicate that the message could not be processed for reasons not directly attributable to the contents of the message itself but rather to the processing of the message. For example, processing could include communicating with an upstream processor, which didn't respond. The message may succeed at a later point in time.

MustUnderstand

Client

Server

When a MESSAGE contains a faultcode element the content of that element SHOULD NOT use of the SOAP 1.1 "dot" notation to refine the meaning of the Fault. CORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:c='http://example.org/faultcodes' > <faultcode>c:ProcessingError</faultcode> <faultstring>An error occured while processing the message

http://java.boot.by/wsd-guide/ch02s05.html 3 / 6 2004/6/13 12:03:05

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.

</faultstring> </soap:Fault>

CORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <faultcode>soap:Server</faultcode> <faultstring>An error occured while processing the message </faultstring> </soap:Fault>

INCORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:c='http://example.org/faultcodes' > <faultcode>soap:Server.ProcessingError</faultcode> <faultstring>An error occurred while processing the message </faultstring> </soap:Fault>

A MESSAGE MUST NOT contain soap:encodingStyle attributes on any of the elements whose namespace name is "http://schemas.xmlsoap.org/soap/envelope/". A MESSAGE MUST NOT contain soap:encodingStyle attributes on any element that is a child of soap: Body. A MESSAGE described in an rpc-literal binding MUST NOT contain soap:encodingStyle attribute on any elements are grandchildren of soap:Body. A MESSAGE MUST NOT contain a Document Type Declaration (DTD). A MESSAGE MUST NOT contain Processing Instructions (PI). A RECEIVER MUST accept messages that contain an XML Declaration.

http://java.boot.by/wsd-guide/ch02s05.html 4 / 6 2004/6/13 12:03:05

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.

A MESSAGE MUST NOT have any element children of soap:Envelope following the soap:Body element. CORRECT:

<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <soap:Body> <p:Process xmlns:p='http://example.org/Operations' > <m:Data xmlns:m='http://example.org/information' > Here is some data with the message </m:Data> </p:Process> </soap:Body> </soap:Envelope>

INCORRECT:

<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <soap:Body> <p:Process xmlns:p='http://example.org/Operations' /> </soap:Body> <m:Data xmlns:m='http://example.org/information' > Here is some data with the message </m:Data> </soap:Envelope>

A MESSAGE MUST be serialized as either UTF-8 or UTF-16. The media type of a MESSAGE's envelope MUST indicate the correct character encoding, using the charset parameter. A MESSAGE containing a soap:mustUnderstand attribute MUST only use the lexical forms "0" and "1". The children of the soap:Body element in a MESSAGE MUST be namespace qualified. A RECEIVER MUST generate a fault if they encounter a message whose document element has a
http://java.boot.by/wsd-guide/ch02s05.html 5 / 6 2004/6/13 12:03:05

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.

local name of "Envelope" but a namespace name that is not "http://schemas.xmlsoap.org/soap/ envelope/". A RECEIVER MUST NOT mandate the use of the xsi:type attribute in messages except as required in order to indicate a derived type.

Prev Create a SOAP message that contains an attachment.

Up Home

Next Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages.

http://java.boot.by/wsd-guide/ch02s05.html 6 / 6 2004/6/13 12:03:05

Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages.

Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages. Prev Chapter 2. SOAP 1.1 Web Service Standards Next

Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages.
HTTP is a transport-level protocols and SOAP is a messaging-layer (communication) protocol. SOAP can be used in combination with a variety of transport protocols - including SMTP, JMS, and other protocols in addition to HTTP - and does not depend on any particular network protocol. Although HTTP is a widely used protocol for SOAP, SOAP toolkit vendors have also started providing support for other protocols, like SMTP. SOAP messages may travel across several different transport-layer protocols before they reach their ultimate destination SOAP advantages.

Platform independent. SOAP decouples the encoding and communications protocol from the runtime environment. Web service can receive a SOAP payload from a remote service, and the platform details of the source are entirely irrelevant. Language independent. Anything can generate XML, from Perl scripts to C++ code to J2EE app servers. So, as of the 1.1 version of the SOAP specification, anyone and anything can participate in a SOAP conversation, with a relatively low barrier to entry. Uses XML to send and receive messages. SOAP is also a simple way to accomplish remote object/component/service communications. It formalizes the vocabulary definition in a form that's now familiar, popular, and accessible (XML). If you know XML, you can figure out the basics of SOAP encoding pretty quickly. Uses standard internet HTTP protocol. SOAP runs over HTTP, which eliminates firewall problems. When using HTTP as the protocol binding, an RPC call maps naturally to an HTTP request and an RPC response maps to an HTTP response. SOAP is very simple compared to RMI, CORBA, and DCOM because it does not deal with certain ancillary but important aspects of remote object systems. A protocol for exchanging information in a decentralized and distributed environment. SOAP is, transport protocol-independent and can therefore potentially be used in combination with a variety of protocols. Vendor neutral.

SOAP disadvantages

http://java.boot.by/wsd-guide/ch02s06.html 1 / 2 2004/6/13 12:03:08

Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages.

The SOAP specification contains no mention of security facilities. SOAP 1.1 specification does not specify a default encoding for the message body. There is an encoding defined in the spec, but it is not required that you use this encoding to be compliant: Any custom encoding that you choose can be specified in the encodingStyle attribute of the message or of individual elements in the message. Because SOAP deals with objects serialized to plain text and not with stringified remote object references (interoperable object references, IORs, as defined in CORBA), distributed garbage collection has no meaning. SOAP clients do not hold any stateful references to remote objects.

Prev Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.

Up Home

Next Chapter 3. Describing and Publishing (WSDL and UDDI)

http://java.boot.by/wsd-guide/ch02s06.html 2 / 2 2004/6/13 12:03:08

Chapter 3. Describing and Publishing (WSDL and UDDI)

Chapter 3. Describing and Publishing (WSDL and UDDI) Prev Part I. Exam Objectives Next

Chapter 3. Describing and Publishing (WSDL and UDDI)

Explain the use of WSDL in Web services, including a description of WSDL's basic elements, binding mechanisms and the basic WSDL operation types as limited by the WSI Basic Profile 1.0a.
WSDL is an XML-based language that allows formal XML desriptions of the interfaces of Web services:

Interface information describing all publicly available functions. Data type information for all message requests and message responses. Binding information about the transport protocol to be used. Address information for locating the specified service.

WSDL benefits:

It is an interface description is a contract between the server developers and the client developers (like Java interface represents a contract between client code and the actual Java object). It has formal descriptions which allows tool support, e.g. code template generators, integrate new services with little or no manual code.

WSDL language can be described as having two layers: 1. The service definition layer describes abstract properties:

data types message types operations services

2. The binding layer describes concrete properties:


protocols data formats

The definitions element MUST be the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document. An actual WSDL document consists of a set of definitions of the following kinds:

http://java.boot.by/wsd-guide/ch03.html 1 / 8 2004/6/13 12:03:13

Chapter 3. Describing and Publishing (WSDL and UDDI)

types - Contains XML Schema element and type definitions. The types element describes all the data types used between the client and server. WSDL is not tied exclusively to a specific typing system, but it uses the W3C XML Schema specification as its default choice. If the service uses only XML Schema built-in simple types, such as strings and integers, the types element is not required. message - Consistes of either a number of named parts typed by XML Schema elements, or a single part typed by a XML Schema type. The message element describes a one-way message, whether it is a single message request or a single message response. It defines the name of the message and contains zero or more message part elements, which can refer to message parameters or message return values. portType - describing a set of operations, each being either:
r

one-way: The endpoint receives an input message. (NOTE: The WS-I BP 1.0 restricts the valid wsdl:operations to one-way and request-response operations).

<wsdl:definitions .... > <wsdl:portType .... > * <wsdl:operation name="nmtoken"> <wsdl:input name="nmtoken"? message="qname"/> </wsdl:operation> </wsdl:portType > </wsdl:definitions>

request-response: The endpoint receives an input message and then responds with an output message (like RPC - Remote Procedure Call). (NOTE: The WS-I BP 1.0 restricts the valid wsdl:operations to one-way and request-response operations).

<wsdl:definitions .... > <wsdl:portType .... > * <wsdl:operation name="nmtoken" parameterOrder="nmtokens"> <wsdl:input name="nmtoken"? message="qname"/> <wsdl:output name="nmtoken"? message="qname"/> <wsdl:fault name="nmtoken" message="qname"/>* </wsdl:operation> </wsdl:portType > </wsdl:definitions>

solicit-response: The endpoint sends an output message and then receives an input

http://java.boot.by/wsd-guide/ch03.html 2 / 8 2004/6/13 12:03:13

Chapter 3. Describing and Publishing (WSDL and UDDI)

message (NOTE: A DESCRIPTION MUST NOT use Solicit-Response and Notification type operations in a wsdl:portType definition - R2303 - BP 1.0).

<wsdl:definitions .... > <wsdl:portType .... > * <wsdl:operation name="nmtoken" parameterOrder="nmtokens"> <wsdl:output name="nmtoken"? message="qname"/> <wsdl:input name="nmtoken"? message="qname"/> <wsdl:fault name="nmtoken" message="qname"/>* </wsdl:operation> </wsdl:portType > </wsdl:definitions>

notification: The endpoint sends an output message (NOTE: A DESCRIPTION MUST NOT use Solicit-Response and Notification type operations in a wsdl:portType definition - R2303 - BP 1.0).

<wsdl:definitions .... > <wsdl:portType .... > * <wsdl:operation name="nmtoken" parameterOrder="nmtokens"> <wsdl:output name="nmtoken"? message="qname"/> </wsdl:operation> </wsdl:portType > </wsdl:definitions>

The portType element combines multiple message elements to form a complete one-way or round-trip operation. For example, a portType can combine one request and one response message into a single request/response operation, most commonly used in SOAP services. Note that a portType can (and frequently does) define multiple operations.

binding - Selects communication protocol and data formats for each operation and message. The binding element describes the concrete specifics of how the service will be implemented on the wire. WSDL includes built-in extensions for defining SOAP services, and SOAP-specific information therefore goes here. (NOTE: For interoperability the WS-I BP 1.0 requires that all messages must be sent using the SOAP 1.1 protocol over an HTTP transport as described in Section 3 of the WSDL 1.1 spec. The SOAP messages must be in either "document-literal" or "rpc-literal" form). The WS-I BP 1.0 requires that a wsdl: binding and its wsdl:portType have the same list of wsdl:operations. A perfect matching

http://java.boot.by/wsd-guide/ch03.html 3 / 8 2004/6/13 12:03:13

Chapter 3. Describing and Publishing (WSDL and UDDI)

between the two lists is established through a 1-1 and onto relation from the wsdl:binding to the wsdl:portType. The wsdl:binding should completely bind all operations within a wsdl: portType. service - Describes a collection of named ports, each associated with a binding and a network address. The service element defines the address for invoking the specified service. Most commonly, this includes a URL for invoking the SOAP service.

The simplified structure of a WSDL document is:

<definitions> <!-- root WSDL element --> <types> <!-- defines data types to be transmitted --> </types> <message> <!-- defines messages to be transmitted --> </message> <portType> <!-- defines operations (functions) to be supported --> </portType> <binding> <!-- defines how will the messages be transmitted on the wire --> </binding> <service> <!-- defines location of web service --> </service> </definitions>

WSDL document grammar:

<wsdl:definitions name="nmtoken"? targetNamespace="uri"?> <import namespace="uri" location="uri"/>* <wsdl:documentation .... /> ?


http://java.boot.by/wsd-guide/ch03.html 4 / 8 2004/6/13 12:03:13

Chapter 3. Describing and Publishing (WSDL and UDDI)

<wsdl:types> ? <wsdl:documentation .... />? <xsd:schema .... />* <-- extensibility element --> * </wsdl:types> <wsdl:message name="nmtoken"> * <wsdl:documentation .... />? <part name="nmtoken" element="qname"? type="qname"?/> * </wsdl:message> <wsdl:portType name="nmtoken">* <wsdl:documentation .... />? <wsdl:operation name="nmtoken">* <wsdl:documentation .... /> ? <wsdl:input name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:input> <wsdl:output name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:output> <wsdl:fault name="nmtoken" message="qname"> * <wsdl:documentation .... /> ? </wsdl:fault> </wsdl:operation> </wsdl:portType> <wsdl:binding name="nmtoken" type="qname">* <wsdl:documentation .... />? <-- extensibility element --> * <wsdl:operation name="nmtoken">* <wsdl:documentation .... /> ? <-- extensibility element --> * <wsdl:input> ? <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:input> <wsdl:output> ? <wsdl:documentation .... /> ? <-- extensibility element --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <wsdl:documentation .... /> ? <-- extensibility element --> * </wsdl:fault>
http://java.boot.by/wsd-guide/ch03.html 5 / 8 2004/6/13 12:03:13

Chapter 3. Describing and Publishing (WSDL and UDDI)

</wsdl:operation> </wsdl:binding> <wsdl:service name="nmtoken"> * <wsdl:documentation .... />? <wsdl:port name="nmtoken" binding="qname"> * <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:port> <-- extensibility element --> </wsdl:service> <-- extensibility element --> * </wsdl:definitions>

Example of simple WSDL (SOAP 1.1 Request-Response via HTTP):

<?xml version="1.0" encoding="UTF-8"?> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd1="http://example.com/stockquote.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <schema targetNamespace="http://example.com/stockquote.xsd" xmlns="http://www.w3.org/2000/10/XMLSchema"> <element name="TradePriceRequest"> <complexType> <all> <element name="tickerSymbol" type="string"/> </all> </complexType> </element> <element name="TradePrice"> <complexType> <all> <element name="price" type="float"/>
http://java.boot.by/wsd-guide/ch03.html 6 / 8 2004/6/13 12:03:13

Chapter 3. Describing and Publishing (WSDL and UDDI)

</all> </complexType> </element> </schema> </types> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> <message name="GetLastTradePriceOutput"> <part name="body" element="xsd1:TradePrice"/> </message> <portType name="StockQuotePortType"> <operation name="GetLastTradePrice"> <input message="tns:GetLastTradePriceInput"/> <output message="tns:GetLastTradePriceOutput"/> </operation> </portType> <binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetLastTradePrice"> <soap:operation soapAction="http://example.com/GetLastTradePrice"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>

http://java.boot.by/wsd-guide/ch03.html 7 / 8 2004/6/13 12:03:13

Chapter 3. Describing and Publishing (WSDL and UDDI)

Prev Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages.

Up Home

Next Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1.

http://java.boot.by/wsd-guide/ch03.html 8 / 8 2004/6/13 12:03:13

Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1.

Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1. Prev Chapter 3. Describing and Publishing (WSDL and UDDI) Next

Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1.
The types element encloses data type definitions that are relevant for the exchanged messages. For maximum interoperability and platform neutrality, WSDL prefers the use of XSD as the canonical type system, and treats it as the intrinsic type system.

<definitions .... > <types> <xsd:schema .... />* </types> </definitions>

The XSD type system can be used to define the types in a message regardless of whether or not the resulting wire format is actually XML, or whether the resulting XSD schema validates the particular wire format. This is especially interesting if there will be multiple bindings for the same message, or if there is only one binding but that binding type does not already have a type system in widespread use. A DESCRIPTION MUST NOT use QName references to elements in namespaces that have been neither imported, nor defined in the referring WSDL document. A QName reference to a Schema component in a DESCRIPTION MUST use the namespace defined in the targetNamespace attribute on the xsd:schema element, or to a namespace defined in the namespace attribute on an xsd:import element within the xsd:schema element. All xsd:schema elements contained in a wsdl:types element of a DESCRIPTION MUST have a targetNamespace attribute with a valid and non-null value, UNLESS the xsd:schema element has xsd: import and/or xsd:annotation as its only child element(s). In a DESCRIPTION, array declarations MUST NOT extend or restrict the soapenc:Array type. In a DESCRIPTION, array declarations MUST NOT use wsdl:arrayType attribute in the type declaration. In a DESCRIPTION, array declaration wrapper elements SHOULD NOT be named using the convention ArrayOfXXX.

http://java.boot.by/wsd-guide/ch03s02.html 1 / 3 2004/6/13 12:03:16

Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1.

A MESSAGE containing serialized arrays MUST NOT include the soapenc:arrayType attribute. CORRECT:

Given the WSDL Description: <xsd:element name="MyArray1" type="tns:MyArray1Type"/> <xsd:complexType name="MyArray1Type"> <xsd:sequence> <xsd:element name="x" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> The SOAP message would serialize as (omitting namespace declarations for clarity): <MyArray1> <x>abcd</x> <x>efgh</x> </MyArray1>

INCORRECT:

Given the WSDL Description: <xsd:element name="MyArray2" type="tns:MyArray2Type"/> <xsd:complexType name="MyArray2Type" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" > <xsd:complexContent> <xsd:restriction base="soapenc:Array"> <xsd:sequence> <xsd:element name="x" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> <xsd:attribute ref="soapenc:arrayType" wsdl:arrayType="tns:MyArray2Type[]"/> </xsd:restriction> </xsd:complexContent> </xsd:complexType>
http://java.boot.by/wsd-guide/ch03s02.html 2 / 3 2004/6/13 12:03:16

Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1.

The SOAP message would serialize as (omitting namespace declarations for clarity): <MyArray2 soapenc:arrayType="tns:MyArray2Type[]" > <x>abcd</x> <x>efgh</x> </MyArray2>

Prev Chapter 3. Describing and Publishing (WSDL and UDDI)

Up Home

Next Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

http://java.boot.by/wsd-guide/ch03s02.html 3 / 3 2004/6/13 12:03:16

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a. Prev Chapter 3. Describing and Publishing (WSDL and UDDI) Next

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.
UDDI supports the following five core data structures: 1. 2. 3. 4. 5. Business Entity Business Service Binding Template tModel Publisher Assertion

This division by information type provides simple partitions to assist in the rapid location and understanding of the different information that makes up a registration.

http://java.boot.by/wsd-guide/ch03s03.html 1 / 9 2004/6/13 12:03:21

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

The businessEntity structure The businessEntity structure represents all known information about a business or entity that publishes descriptive information about the entity as well as the services that it offers. From an XML standpoint, the businessEntity is the top-level data structure that accommodates holding descriptive information about a business or entity. Service descriptions and technical information are expressed within a businessEntity by a containment relationship. Structure Specification:
http://java.boot.by/wsd-guide/ch03s03.html 2 / 9 2004/6/13 12:03:21

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

<element name="businessEntity" type="uddi:businessEntity" /> <complexType name="businessEntity"> <sequence> <element ref="uddi:discoveryURLs" minOccurs="0" /> <element ref="uddi:name" maxOccurs="unbounded" /> <element ref="uddi:description" minOccurs="0" maxOccurs="unbounded" /> <element ref="uddi:contacts" minOccurs="0" /> <element ref="uddi:businessServices" minOccurs="0" /> <element ref="uddi:identifierBag" minOccurs="0" /> <element ref="uddi:categoryBag" minOccurs="0" /> </sequence> <attribute name="businessKey" type="uddi:businessKey" use="required" /> <attribute name="operator" type="string" use="optional" /> <attribute name="authorizedName" type="string" use="optional" /> </complexType>

The businessService structure The businessService structures each represent a logical service classification. The name of the element includes the term business in an attempt to describe the purpose of this level in the service description hierarchy. Each businessService structure is the logical child of a single businessEntity structure. The identity of the containing (parent) businessEntity is determined by examining the embedded businessKey value. If no businessKey value is present, the businessKey must be obtainable by searching for a businessKey value in any parent structure containing the businessService. Each businessService element contains descriptive information in business terms outlining the type of technical services found within each businessService element. In some cases, businesses would like to share or reuse services, e.g. when a large enterprise publishes separate businessEntity structures. This can be established by using the businessService structure as a projection to an already published businessService. Any businessService projected in this way is not managed as a part of the referencing businessEntity, but centrally as a part of the referenced businessEntity. This means that changes of the businessService by the referenced businessEntity are automatically valid for the service projections done by referencing businessEntity structures. In order to specify both referenced and referencing businessEntity structures correctly, service projections can only be published by a save_business message with the referencing businessKey present in the businessEntity structure and both the referenced businessKey and the referenced

http://java.boot.by/wsd-guide/ch03s03.html 3 / 9 2004/6/13 12:03:21

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

businessService present in the businessService structure. Structure Specification:

<element name="businessService" type="uddi:businessService" /> <complexType name="businessService"> <sequence> <element ref="uddi:name" minOccurs="0" maxOccurs="unbounded" /> <element ref="uddi:description" minOccurs="0" maxOccurs="unbounded" /> <element ref="uddi:bindingTemplates" minOccurs="0" /> <element ref="uddi:categoryBag" minOccurs="0" /> </sequence> <attribute name="serviceKey" type="uddi:serviceKey" use="required" /> <attribute name="businessKey" type="uddi:businessKey" use="optional" /> </complexType>

The bindingTemplate structure Technical descriptions of Web services are accommodated via individual contained instances of bindingTemplate structures. These structures provide support for determining a technical entry point or optionally support remotely hosted services, as well as a lightweight facility for describing unique technical characteristics of a given implementation. Support for technology and application specific parameters and settings files are also supported. Since UDDIs main purpose is to enable description and discovery of Web Service information, it is the bindingTemplate that provides the most interesting technical data. Each bindingTemplate structure has a single logical businessService parent, which in turn has a single logical businessEntity parent. Structure Specification:

<element name="bindingTemplate" type="uddi:bindingTemplate" /> <complexType name="bindingTemplate"> <sequence>


http://java.boot.by/wsd-guide/ch03s03.html 4 / 9 2004/6/13 12:03:21

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

<element ref="uddi:description" minOccurs="0" maxOccurs="unbounded" /> <choice> <element ref="uddi:accessPoint" /> <element ref="uddi:hostingRedirector" /> </choice> <element ref="uddi:tModelInstanceDetails" /> </sequence> <attribute name="serviceKey" type="uddi:serviceKey" use="optional" /> <attribute name="bindingKey" type="uddi:bindingKey" use="required" /> </complexType>

The tModel structure Being able to describe a Web service and then make the description meaningful enough to be useful during searches is an important UDDI goal. Another goal is to provide a facility to make these descriptions useful enough to learn about how to interact with a service that you dont know much about. In order to do this, there needs to be a way to mark a description with information that designates how it behaves, what conventions it follows, or what specifications or standards the service is compliant with. Providing the ability to describe compliance with a specification, concept, or even a shared design is one of the roles that the tModel structure fills. The tModel structure takes the form of keyed metadata (data about data). In a general sense, the purpose of a tModel within the UDDI registry is to provide a reference system based on abstraction. Thus, the kind of data that a tModel represents is pretty nebulous. In other words, a tModel registration can define just about anything, but in the current revision, two conventions have been applied for using tModels: as sources for determining compatibility and as keyed namespace references. The information that makes up a tModel is quite simple. Theres a key, a name, an optional description, and then a URL that points somewhere presumably somewhere where the curious can go to find out more about the actual concept represented by the metadata in the tModel itself. There are two places within a businessEntity registration that you'll find references to tModels. In this regard, tModels are special. Whereas the other data within the businessEntity (e.g. businessService and bindingTemplate data) exists uniquely with one uniquely keyed instance as a member of one unique parent businessEntity, tModels are used as references. This means that you'll find references to specific tModel instances in many businessEntity structures. Defining the technical fingerprint. The primary role that a tModel plays is to represent a technical specification. An example might be a specification that outlines wire protocols, interchange formats and interchange sequencing
http://java.boot.by/wsd-guide/ch03s03.html 5 / 9 2004/6/13 12:03:21

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

rules. Examples can be seen in the RosettaNet Partner Interface Processes specification, the Open Applications Group Integration Specification and various Electronic Document Interchange (EDI) efforts. Software that communicates with other software across some communication medium invariably adheres to some pre-agreed specifications. In situations where this is true, the designers of the specifications can establish a unique technical identity within a UDDI registry by registering information about the specification in a tModel. Once registered in this way, other parties can express the availability of Web services that are compliant with a specification by simply including a reference to the tModel identifier (called a tModelKey) in their technical service descriptions bindingTemplate data. This approach facilitates searching for registered Web services that are compatible with a particular specification. Once you know the proper tModelKey value, you can find out whether a particular business or entity has registered a Web service that references that tModel key. In this way, the tModelKey becomes a technical fingerprint that is unique to a given specification. Defining an abstract namespace reference. The other place where tModel references are used is within the identifierBag, categoryBag, address and publisherAssertion structures that are used to define organizational identity and various classifications. Used in this context, the tModel reference represents a relationship between the keyed name-value pairs to the super-name, or namespace within which the name-value pairs are meaningful. An example of this can be seen in the way a business or entity can express the fact that their US tax code identifier (which they are sure they are known by to their partners and customers) is a particular value. To do this, let's assume that we find a tModel that is named US Tax Codes, with a description United States business tax code numbers as defined by the United States Internal Revenue Service. In this regard, the tModel still represents a specific concept but instead of being a technical specification, it represents a unique area within which tax code IDs have a particular meaning. Once this meaning is established, a business can use the tModelKey for the tax code tModel as a unique reference that qualifies the remainder of the data that makes up an entry in the identifierBag data. To get things started, the UDDI Operator Sites have registered a number of useful tModels, including NAICS (an industry code taxonomy), UNSPC (a product and service category code taxonomy), and ISO 3166 (a geographical region code taxonomy). Structure Specification:

<element name="tModel" type="uddi:tModel" />


http://java.boot.by/wsd-guide/ch03s03.html 6 / 9 2004/6/13 12:03:21

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

<complexType name="tModel"> <sequence> <element ref="uddi:name" /> <element ref="uddi:description" minOccurs="0" maxOccurs="unbounded" /> <element ref="uddi:overviewDoc" minOccurs="0" /> <element ref="uddi:identifierBag" minOccurs="0" /> <element ref="uddi:categoryBag" minOccurs="0" /> </sequence> <attribute name="tModelKey" type="uddi:tModelKey" use="required" /> <attribute name="operator" type="string" use="optional" /> <attribute name="authorizedName" type="string" use="optional" /> </complexType>

The publisherAssertion structure Many businesses, like large enterprises or marketplaces, are not effectively represented by a single businessEntity, since their description and discovery are likely to be diverse. As a consequence, several businessEntity structures can be published, representing individual subsidiaries of a large enterprise or individual participants of a marketplace. Nevertheless, they still represent a more or less coupled community and would like to make some of their relationships visible in their UDDI registrations. Therefore, two related businesses use the xx_publisherAssertion messages, publishing assertions of business relationships. In order to eliminate the possibility that one publisher claims a relationship between both businesses that is in fact not reciprocally recognized, both publishers have to agree that the relationship is valid by publishing their own publisherAssertion. Therefore, both publishers have to publish exactly the same information. When this happens, the relationship becomes visible. In the case that a publisher is responsible for both businesses, the relationship automatically becomes visible after publishing just one of both assertions that make up the relationship. The publisherAssertion structure consists of the three elements fromKey (the first businessKey), toKey (the second businessKey) and keyedReference. The keyedReference designates the asserted relationship type in terms of a keyName keyValue pair within a tModel, uniquely referenced by a tModelKey. All three parts of the keyedReference the tModelKey, the keyName, and the keyValue are mandatory in this context. Empty (zero length) keyName and keyValue elements are permitted.

<element name="publisherAssertion" type="uddi:publisherAssertion" />

http://java.boot.by/wsd-guide/ch03s03.html 7 / 9 2004/6/13 12:03:21

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

<complexType name="publisherAssertion"> <sequence> <element ref="uddi:fromKey" /> <element ref="uddi:toKey" /> <element ref="uddi:keyedReference" /> </sequence> </complexType>

BP 1.0 Requirements - Service Publication and Discovery REGDATA of type uddi:bindingTemplate representing a conformant INSTANCE MUST contain the uddi:accessPoint element. CORRECT:

<bindingTemplate bindingKey="..."> <description xml:lang="EN">BarSOAPPort</description> <accessPoint>http://example.org/myBarSOAPPort</accessPoint> <tModelInstanceDetails> ... </tModelInstanceDetails> </bindingTemplate>

INCORRECT:

<bindingTemplate bindingKey="..."> <description xml:lang="EN">BarSOAPPort</description> <hostingRedirector bindingKey="..."/> <tModelInstanceDetails> ... </tModelInstanceDetails> </bindingTemplate>

REGDATA of type uddi:tModel representing a conformant Web service type MUST use WSDL as the description language.

http://java.boot.by/wsd-guide/ch03s03.html 8 / 9 2004/6/13 12:03:21

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

REGDATA of type uddi:tModel representing a conformant Web service type MUST be categorized using the uddi:types taxonomy and a categorization of "wsdlSpec". The wsdl:binding that is referenced by REGDATA of type uddi:tModel MUST itself conform to the Profile.

Prev Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1.

Up Home

Next Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry.

http://java.boot.by/wsd-guide/ch03s03.html 9 / 9 2004/6/13 12:03:21

Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry.

Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry. Prev Chapter 3. Describing and Publishing (WSDL and UDDI) Next

Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry.
Publish API functions The messages in this section represent commands that require authenticated access to an UDDI Operator Site, and are used to publish and update information contained in a UDDI compatible registry. Each business should initially select one Operator Site to host their information. Once chosen, information can only be updated at the site originally selected. UDDI provides no automated means to reconcile multiple or duplicate registrations. The messages defined in this section all behave synchronously and are callable via HTTP-POST only. HTTPS is used exclusively for all of the calls defined in this publisher's API. The publishing API calls defined that UDDI operators support are:

add_publisherAssertions: Used to add relationship assertions to the existing set of assertions. delete_binding: Used to remove an existing bindingTemplate from the bindingTemplates collection that is part of a specified businessService structure. delete_business: Used to delete registered businessEntity information from the registry. delete_publisherAssertions: Used to delete specific publisher assertions from the assertion collection controlled by a particular publisher account. Deleting assertions from the assertion collection will affect the visibility of business relationships. Deleting an assertion will cause any relationships based on that assertion to be invalidated. delete_service: Used to delete an existing businessService from the businessServices collection that is part of a specified businessEntity. delete_tModel: Used to hide registered information about a tModel. Any tModel hidden in this way is still usable for reference purposes and accessible via the get_tModelDetail> message, but is simply hidden from find_tModel> result sets. There is no way to actually cause a tModel to be deleted, except by administrative petition. discard_authToken: Used to inform an Operator Site that a previously provided authentication token is no longer valid and should be considered invalid if used after this message is received and until such time as an authToken value is recycled or reactivated at an operator's discretion. See get_authToken. get_assertionStatusReport: Used to get a status report containing publisher assertions and status information. This report is useful to help an administrator manage active and tentative publisher assertions. Publisher assertions are used in UDDI to manage publicly visible relationships between businessEntity structures. Relationships are a feature introduced in generic 2.0 that help manage complex business structures that require more than one businessEntity or more than one publisher account to manage parts of a businessEntity. Returns an assertionStatusReport that includes the status of all assertions made involving any businessEntity controlled by the requesting publisher account. get_authToken: Used to request an authentication token from an Operator Site.

http://java.boot.by/wsd-guide/ch03s04.html 1 / 3 2004/6/13 12:03:24

Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry.

Authentication tokens are required when using all other APIs defined in the publishers API. This function serves as the program's equivalent of a login request. get_publisherAssertions: Used to get a list of active publisher assertions that are controlled by an individual publisher account. Returns a publisherAssertions message containing all publisher assertions associated with a specific publisher account. Publisher assertions are used to control publicly visible business relationships. get_registeredInfo: Used to request an abbreviated synopsis of all information currently managed by a given individual. save_binding: Used to register new bindingTemplate information or update existing bindingTemplate information. Use this to control information about technical capabilities exposed by a registered business. save_business: Used to register new businessEntity information or update existing businessEntity information. Use this to control the overall information about the entire business. Of the save_xx APIs this one has the broadest effect. In UDDI V2, a feature is introduced where save_business can be used to reference a businessService that is parented by another businessEntity. save_service: Used to register or update complete information about a businessService exposed by a specified businessEntity. save_tModel: Used to register or update complete information about a tModel. set_publisherAssertions: used to save the complete set of publisher assertions for an individual publisher account. Replaces any existing assertions, and causes any old assertions that are not reasserted to be removed from the registry. Publisher assertions are used to control publicly visible business relationships.

Inquiry API functions The messages in this section represent inquiries that anyone can make of any UDDI Operator Site at any time. These messages all behave synchronously and are required to be exposed via HTTP-POST only. Other synchronous or asynchronous mechanisms may be provided at the discretion of the individual UDDI Operator Site or UDDI compatible registry. The publicly accessible queries are:

find_binding: Used to locate specific bindings within a registered businessService. Returns a bindingDetail message. find_business: Used to locate information about one or more businesses. Returns a businessList message. find_relatedBusinesses: Used to locate information about businessEntity registrations that are related to a specific business entity whose key is passed in the inquiry. The Related Businesses feature is used to manage registration of business units and subsequently relate them based on organizational hierarchies or business partner relationships. Returns a relatedBusinessesList message. find_service: Used to locate specific services within a registered businessEntity. Returns a serviceList message. find_tModel: Used to locate one or more tModel information structures. Returns a tModelList structure. get_bindingDetail: Used to get full bindingTemplate information suitable for making one or more service requests. Returns a bindingDetail message. get_businessDetail: Used to get the full businessEntity information for one or more

http://java.boot.by/wsd-guide/ch03s04.html 2 / 3 2004/6/13 12:03:24

Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry.

businesses or organizations. Returns a businessDetail message. get_businessDetailExt: Used to get extended businessEntity information. Returns a businessDetailExt message. get_serviceDetail: Used to get full details for a given set of registered businessService data. Returns a serviceDetail message. get_tModelDetail>: Used to get full details for a given set of registered tModel data. Returns a tModelDetail message.

Prev Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.

Up Home

Next Chapter 4. JAX-RPC

http://java.boot.by/wsd-guide/ch03s04.html 3 / 3 2004/6/13 12:03:24

Chapter 4. JAX-RPC

Chapter 4. JAX-RPC Prev Part I. Exam Objectives Next

Chapter 4. JAX-RPC

Explain the service description model, client connection types, interaction modes, transport mechanisms/protocols, and endpoint types as they relate to JAX-RPC.
JAX-RPC is for Web services interoperability across heterogeneous platforms and languages. This makes JAX-RPC a key technology for Web services integration. You can use the standard JAX-RPC programming model to develop Web service clients and endpoints based on SOAP. A Web service endpoint is described using a Web Services Description Language (WSDL) document. JAX-RPC enables JAX-RPC clients to invoke Web services developed across heterogeneous platforms. In a similar manner, JAX-RPC Web service endpoints can be invoked by heterogeneous clients. JAX-RPC requires SOAP and WSDL standards for this cross-platform interoperability. JAX-RPC provides an easy to develop programming model for development of SOAP based Web services. You can use the RPC programming model to develop Web service clients and endpoints. For typical scenarios, you are not exposed to the complexity of the underlying runtime mechanisms (for example, SOAP protocol level mechanisms, marshalling and unmarshalling). A JAX-RPC runtime system (a library) abstracts these runtime mechanisms for the Web services programming model. This simplifies Web service development. JAX-RPC provides support for WSDL-to-Java and Java-to-WSDL mapping as part of the development of Web service clients and endpoints. In a typical development environment, tools provide these mapping functionality. This further simplifies the application development. JAX-RPC enables a Web service endpoint to be developed using either a Java Servlet or Enterprise JavaBeans (EJB) component model. A Web service endpoint is deployed on either the Web container or EJB container based on the corresponding component model. These endpoints are described using a WSDL document. This WSDL document can be published in public or private registry, though this is not required. A client uses this WSDL document and invokes the Web service endpoint. A JAX-RPC client can use stubs-based, dynamic proxy or dynamic invocation interface (DII) programming models to invoke a heterogeneous Web service endpoint. JAX-RPC requires SOAP over HTTP for interoperability. JAX-RPC provides support for SOAP message processing model through the SOAP message handler functionality. This enables developers to build SOAP specific extensions to support security, logging and any other facility based on the SOAP messaging. JAX-RPC uses SAAJ API for SOAP message handlers. SAAJ provides a standard Java API for constructing and manipulating SOAP messages with attachments.
http://java.boot.by/wsd-guide/ch04.html 1 / 4 2004/6/13 12:03:27

Chapter 4. JAX-RPC

JAX-RPC provides support for document-based messaging. Using JAX-RPC, any MIME-encoded content can be carried as part of a SOAP message with attachments. This enables exchange of XML documents, images and other MIME types across Web services. JAX-RPC supports HTTP level session management and SSL based security mechanisms. This enables you to develop secure Web services. More advanced SOAP message-level security will be addressed in the evolution of JAX-RPC technology. Steps for Implementing a Service: 1. Define Web Service Endpoint Interface 2. Implement Web Service class and methods 3. Package and deploy Endpoint Interface example: package com.example; import java.rmi.Remote; import java.rmi. RemoteException; public interface HelloIF extends Remote { public String sayHello(String s) throws RemoteException; } Service endpoint interface may be: 1. Java java.rmi.Remote Interface 2. Generated from WSDL Web Service can be implemented in form: 1. Java class (for servlet-based endpoint) package com.example; public class HelloImpl implements HelloIF { public String message = "Hello "; public String sayHello(String s) { return message + s; } } NOTE: Your implementation class does not throw RemoteException. This is the responsibility of the container as this implementation will be deployed in a managed J2EE container. 2. Stateless session bean (for EJB-based endpoint) Endpoint interface:

package com.example; public interface Greeting extends Remote { public String sayHello(String name) throws RemoteException; }

Stateless Session Bean Class:

http://java.boot.by/wsd-guide/ch04.html 2 / 4 2004/6/13 12:03:27

Chapter 4. JAX-RPC

package com.example; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import java.rmi.RemoteException; public class GreetingBean implements SessionBean { public String sayHello(String name) throws RemoteException { return "Hello" + name; } public void ejbCreate() { } // Standard callback methods public void ejbActivate() { } public void ejbPassivate() { } public void ejbRemove() { } public void setSessionContext(SessionContext ctx) { } }

Deployment Descriptor:

<?xml version='1.0' encoding='UTF-8'?> <ejb-jar version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"> <enterprise-beans> <session> <ejb-name>GreetingBeen</ejb-name> <service-endpoint>com.example.Greeting</service-endpoint> <ejb-class>com.example.GreetingBeen</ejb-class>
http://java.boot.by/wsd-guide/ch04.html 3 / 4 2004/6/13 12:03:27

Chapter 4. JAX-RPC

<session-type>Stateless</session-type> <transaction-type>Container</transaction-type> <security-identity> <use-caller-identity/> </security-identity> </session> </enterprise-beans> </ejb-jar>

Prev Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry.

Up

Next Given a set of requirements for a Web service, such as transactional needs, and security requirements, design and develop Web service applications that use servlet-based endpoints and EJB based endpoints.

Home

http://java.boot.by/wsd-guide/ch04.html 4 / 4 2004/6/13 12:03:27

Given a set of requirements for a Web service, such as transactional n...pplications that use servlet-based endpoints and EJB based endpoints.

Given a set of requirements for a Web service, such as transactional needs, and security requirements, design and develop Web service applications that use servlet-based endpoints and EJB based endpoints. Prev Chapter 4. JAX-RPC Next

Given a set of requirements for a Web service, such as transactional needs, and security requirements, design and develop Web service applications that use servlet-based endpoints and EJB based endpoints.
EJB based endpoint JSR 109 standardizes webservice in J2EE 1.4 using JAX-RPC. EJB 2.1 exposes Stateless Session bean as a web service endpoint using JAX-RPC interface and any webservice client can access the EJB webservice using SOAP 1.1 over HTTP. The developer can choose a web service endpoint interface for a stateless session bean whenever he wants to expose the functionality of the bean as a web service endpoint through WSDL. The clients for ejb webservice endpoint may be Java clients and/or clients written in a programming language other than Java. A Java client that accesses the ejb web service has to use JAX-RPC client APIs. This is an example shows how can you expose your existing EJB applications as a webservice endpoint and how a pure Java client accesses the ejb webservice. We will use a simple Stateless Session bean TimeBean that displays the current time and locale information. For exposing the webservice endpoint you do not need to have home or remote interfaces for the EJBs, only the end-point interface that extends java.rmi.Remote and bean implementation class is required. Following the code for the service-endpoint for the EJB:

package time; import java.rmi.RemoteException; import java.rmi.Remote; public interface TimeService extends Remote { public String getDateTime (String name) throws RemoteException; }

Then we have to define the end-point interface in ejb-jar.xml as follows:

<session> <display-name>TimeServiceEJB</display-name>
http://java.boot.by/wsd-guide/ch04s02.html 1 / 5 2004/6/13 12:03:32

Given a set of requirements for a Web service, such as transactional n...pplications that use servlet-based endpoints and EJB based endpoints.

<ejb-name>TimeServiceEJB</ejb-name> <service-endpoint>time.TimeService</service-endpoint> <ejb-class>time.TimeServiceBean</ejb-class> <session-type>Stateless</session-type> ... </session>

The WSDL file defines the web services e.g. the following MyTimeService.wsdl describes the Time ejb webservice:

<?xml version="1.0" encoding="UTF-8"?> <definitions name="MyTimeService" targetNamespace="urn:oracle-ws" xmlns:tns="urn:oracle-ws" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/ XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"> <types/> <message name="TimeService_getDateTime"> <part name="String_1" type="xsd:string"/> </message> <message name="TimeService_getDateTimeResponse"> <part name="result" type="xsd:string"/> </message> <portType name="TimeService"> <operation name="getDateTime" parameterOrder="String_1"> <input message="tns:TimeService_getDateTime"/> <output message="tns:TimeService_getDateTimeResponse"/> </operation> </portType> <binding name="TimeServiceBinding" type="tns:TimeService"> <operation name="getDateTime"> <input> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" use="encoded" namespace="urn:oracle-ws"/> </input> <output> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"

http://java.boot.by/wsd-guide/ch04s02.html 2 / 5 2004/6/13 12:03:32

Given a set of requirements for a Web service, such as transactional n...pplications that use servlet-based endpoints and EJB based endpoints.

use="encoded" namespace="urn:oracle-ws"/> </output> <soap:operation soapAction=""/> </operation> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/> </binding> <service name="MyTimeService"> <port name="TimeServicePort" binding="tns:TimeServiceBinding"> <soap:address location="REPLACE_WITH_ACTUAL_URL"/></port> </service> </definitions>

The mapping.xml file specifies the Java to WSDL mapping i.e. it contains the mapping between package names and XML namespaces, WSDL root types and Java artifacts, and the set of mappings for services. For example we will have the following contents for our mapping.xml:

<package-mapping> <package-type>time</package-type> <namespaceURI>urn:oracle-ws</namespaceURI> </package-mapping>

Deployment of webservices requires a deployment descriptor named webservices.xml in META-INF of the ejb-jar file. This descriptor specifies the set of web service descriptions that are to be deployed into the J2EE Application Server and the dependencies they have on container resources and services:

<webservice-description> <webservice-description-name>TimeServiceEJB</webservice-description-name> <wsdl-file>META-INF/MyTimeService.wsdl</wsdl-file> <jaxrpc-mapping-file>META-INF/mapping.xml</jaxrpc-mapping-file> <port-component> <description>port component description</description> <port-component-name>TimeServicePort</port-component-name> <wsdl-port> <namespaceURI>urn:oracle-ws</namespaceURI>
http://java.boot.by/wsd-guide/ch04s02.html 3 / 5 2004/6/13 12:03:33

Given a set of requirements for a Web service, such as transactional n...pplications that use servlet-based endpoints and EJB based endpoints.

<localpart>TimeServicePort</localpart> </wsdl-port> <service-endpoint-interface>time.TimeService</service-endpoint-interface> <service-impl-bean> <ejb-link>TimeServiceEJB</ejb-link> </service-impl-bean> </port-component> </webservice-description>

Servlet based endpoint During the deployment of a service endpoint component on a servlet container based JAX-RPC runtime system, a service endpoint class is associated with a servlet. The associated servlet class is provided by the JAX-RPC runtime system (not by service endpoint developer) during the deployment. This association is configured in a manner specific to a JAX-RPC runtime system and its deployment tool. For example, a JAX-RPC deployment tool may configure a 1-1 association between a servlet class and service endpoint class. The associated servlet class corresponds to the configured transport binding for the service endpoint. For example, the servlet class javax.servlet.http.HttpServlet is used for the HTTP transport. The associated servlet typically takes the responsibility of handling transport specific processing of an RPC request and for initiating dispatch to the target service endpoint instance. Each Servlet. service(...) method maps to a single remote method invocation on the target service endpoint instance. The thread model (whether single threaded or concurrent) for the remote method invocation on the service endpoint instance depends on the runtime system specific servlet associated with the corresponding endpoint class. The Servlet specification provides facility for both concurrent and single threaded model (the latter through the SingleThreadModel interface) for the service(...) method on a servlet. When processing an incoming SOAP request for a one-way operation, the associated servlet is required to send back an HTTP response code of 200 or 202 as soon as it has identified the incoming request as being one-way and before it dispatches it to the target service endpoint instance.

Prev Chapter 4. JAX-RPC

Up

Next Given an set of requirements, design and develop a Web sevice client, such as a J2EE client and a stand-alone Java client, using the appropriate JAX-RPC client connection style.

Home

http://java.boot.by/wsd-guide/ch04s02.html 4 / 5 2004/6/13 12:03:33

Given a set of requirements for a Web service, such as transactional n...pplications that use servlet-based endpoints and EJB based endpoints.

http://java.boot.by/wsd-guide/ch04s02.html 5 / 5 2004/6/13 12:03:33

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

Given an set of requirements, design and develop a Web sevice client, such as a J2EE client and a stand-alone Java client, using the appropriate JAX-RPC client connection style. Prev Chapter 4. JAX-RPC Next

Given an set of requirements, design and develop a Web sevice client, such as a J2EE client and a stand-alone Java client, using the appropriate JAX-RPC client connection style.
JAX-RPC Client Environment:

Service endpoint can be implemented using any platform or language. May generate client code from WSDL:
r r

Static stub (compile time) Dynamic proxy (runtime)

May call Web Service directly:


r

Dynamic invocation interface (DII)

Can use either J2SE or J2EE programming model.

There are three Web Service Client programming models: 1. Stub-based (least dynamic) Both interface (WSDL) and implementation (stub) created at compile time. 2. Dynamic proxy Interface (WSDL) created at compile time. Implementation (dynamic proxy) created at runtime. 3. Dynamic invocation interface (DII) Both interface (WSDL) and implementation created at runtime. Stub-based Invocation Model

Stub class gets generated at compile time Instantiated using vendor-generated Service implementation class Best performance Stub class implements javax.xml.rpc.Stub interface and Web Service definition interface (com.example.HelloIF)

http://java.boot.by/wsd-guide/ch04s03.html 1 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

package javax.xml.rpc; import java.util.Iterator; public interface Stub { /** * Standard property: User name for authentication. */ public static final String USERNAME_PROPERTY = Call.USERNAME_PROPERTY; /** * Standard property: Password for authentication. */ public static final String PASSWORD_PROPERTY = Call.PASSWORD_PROPERTY; /** * Standard property: Target service endpoint address. The * URI scheme for the endpoint address specification must * correspond to the protocol/transport binding for this * stub class. */ public static final String ENDPOINT_ADDRESS_PROPERTY = "javax.xml.rpc.service. endpoint.address"; /** * Standard property: This boolean property is used by a service * client to indicate whether or not it wants to participate in * a session with a service endpoint. If this property is set to * true, the service client indicates that it wants the session * to be maintained. If set to false, the session is not maintained. * The default value for this property is false. */ public static final String SESSION_MAINTAIN_PROPERTY = Call. SESSION_MAINTAIN_PROPERTY; public void _setProperty(String name, Object value); public Object _getProperty(String name); public Iterator _getPropertyNames(); }

http://java.boot.by/wsd-guide/ch04s03.html 2 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

Steps for Stub-Based Invocation Client: 1. 2. 3. 4. Generate Stubs Create Client code Compile the Client code with remote interface and stubs in CLASSPATH Run the Client with JAX-RPC generated code and runtime

Stand-alone Stub-based Client example:

package com.example; import javax.xml.rpc.Stub; public class HelloClient { public static void main(String[] args) { try { Stub stub = (Stub) (new MyHelloService_Impl().getHelloIFPort()); stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]); HelloIF hello = (HelloIF) stub; println(hello.sayHello("Duke!")); } catch (Exception ex) { ex.printStackTrace(); } } }

J2EE Stub-based Client example:

http://java.boot.by/wsd-guide/ch04s03.html 3 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

package com.example; import javax.xml.rpc.Stub; public class HelloClient { public void callSayHello { try { Context ic = new InitialContext(); Service service = (Service) ic.lookup("java:comp/env/service/HelloService"); HelloIF hello = (HelloIF) service.getHelloServiceProviderPort(); println(hello.sayHello("Duke!")); } catch (Exception ex) { ex.printStackTrace(); } } }

Dynamic Proxy-based Invocation Model


At Runtime Application provides the WSDL Dynamic proxy is generated on the fly by JAX-RPC runtime system Slower than stub-based: proxy created and casted More portable than stub-based: does not depend on vendor generated service class before runtime

Dynamic Proxy Client example:

package com.example; import java.net.URL; import javax.xml.rpc.Service; import javax.xml.rpc.JAXRPCException; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceFactory; public class HelloClient { public static void main(String[] args) { try { String UrlString = "http://localhost:8080/ProxyHelloWorld.wsdl"; String nameSpaceUri = "http://sample.proxy.org/wsdl"; String serviceName = "HelloWorld"; // maps to service name in WSDL String portName = "HelloIFPort"; // maps to port name in WSDL URL helloWsdlUrl = new URL(UrlString);
http://java.boot.by/wsd-guide/ch04s03.html 4 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

ServiceFactory serviceFactory = ServiceFactory.newInstance(); // Create a Service object named helloService Service helloService = serviceFactory.createService(helloWsdlUrl, new QName (nameSpaceUri, serviceName)); // Destination for service endpoint retrieval QName qn = new QName(nameSpaceUri, portName); // Create a proxy with type of interface 'com.example.HelloIF' HelloIF myProxy = (HelloIF) helloService.getPort(qn, com.example.HelloIF.class); System.out.println(myProxy.sayHello("Duke")); } catch (Exception ex) { ex.printStackTrace(); } } }

WSDL:

... <service name="HelloWorld"> <port name="HelloIFPort" binding="tns:HelloWorldBinding"> <soap:address location="http://example.com/HelloWorld"/> </port> </service> ...

The javax.xml.rpc.Service interface :

package javax.xml.rpc; import javax.xml.namespace.QName; import javax.xml.rpc.encoding.TypeMappingRegistry; import javax.xml.rpc.handler.HandlerRegistry;

http://java.boot.by/wsd-guide/ch04s03.html 5 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

public interface Service { /** * The getPort method returns either an instance of a generated * stub implementation class or a dynamic proxy. A service client * uses this dynamic proxy to invoke operations on the target * service endpoint. The <code>serviceEndpointInterface</code> * specifies the service endpoint interface that is supported by * the created dynamic proxy or stub instance. */ public java.rmi.Remote getPort(QName portName, Class serviceEndpointInterface) throws ServiceException; /** * The getPort method returns either an instance of a generated * stub implementation class or a dynamic proxy. The parameter * <code>serviceEndpointInterface</code> specifies the service * endpoint interface that is supported by the returned stub or * proxy. In the implementation of this method, the JAX-RPC * runtime system takes the responsibility of selecting a protocol * binding (and a port) and configuring the stub accordingly. * The returned <code>Stub</code> instance should not be * reconfigured by the client. */ public java.rmi.Remote getPort(Class serviceEndpointInterface) throws ServiceException; public Call[] getCalls(QName portName) throws ServiceException; public Call createCall(QName portName) throws ServiceException; public Call createCall(QName portName, QName operationName) throws ServiceException; public Call createCall(QName portName, String operationName) throws ServiceException; public Call createCall() throws ServiceException; public QName getServiceName(); public java.util.Iterator getPorts() throws ServiceException; public java.net.URL getWSDLDocumentLocation(); public TypeMappingRegistry getTypeMappingRegistry(); public HandlerRegistry getHandlerRegistry(); }

Dynamic Invocation Interface (DII) Model

http://java.boot.by/wsd-guide/ch04s03.html 6 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

Gives complete control to client programmer Most dynamic but complex programming Create JAX-RPC javax.xml.rpc.Call object first, set operation and parameters during runtime Could combine with UDDI lookup and WSDL parsing for dynamic lookup and discovery Used when service definition interface is NOT known until runtime

Dynamic Invocation Interface (DII) Client example:

package com.example; import javax.xml.rpc.Call; import javax.xml.rpc.Service; import javax.xml.rpc.JAXRPCException; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceFactory; import javax.xml.rpc.ParameterMode; public class HelloClient { private static String endpoint = "http://localhost:8080/dynamic-jaxrpc/dynamic"; private static String qnameService = "Hello"; private static String qnamePort = "HelloIF"; private static String BODY_NAMESPACE_VALUE = "http://dynamic.org/wsdl"; private static String ENCODING_STYLE_PROPERTY = "javax.xml.rpc.encodingstyle. namespace.uri"; private static String NS_XSD = "http://www.w3.org/2001/XMLSchema"; private static String URI_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"; public static void main(String[] args) { try { ServiceFactory factory = ServiceFactory.newInstance(); Service service = factory.createService(new QName(qnameService)); QName port = new QName(qnamePort); //create JAX-RPC Call using JAX-RPC Service's createCall() method. Call call = service.createCall(port); // Configure your Call instance with its setter methods call.setTargetEndpointAddress(endpoint); call.setProperty(Call.SOAPACTION_USE_PROPERTY, new Boolean(true)); call.setProperty(Call.SOAPACTION_URI_PROPERTY, ""); call.setProperty(ENCODING_STYLE_PROPERTY, URI_ENCODING); QName QNAME_TYPE_STRING = new QName(NS_XSD, "string"); call.setReturnType(QNAME_TYPE_STRING); call.setOperationName(new QName(BODY_NAMESPACE_VALUE "sayHello"));
http://java.boot.by/wsd-guide/ch04s03.html 7 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

call.addParameter("String_1", QNAME_TYPE_STRING, ParameterMode.IN); String[] params = { "Duke!" }; // Invoke the WS operation using the JAX-RPC Call's invoke method String result = (String) call.invoke(params); System.out.println(result); } catch (Exception ex) { ex.printStackTrace(); } } }

The javax.xml.rpc.Call interface:

package javax.xml.rpc; import javax.xml.namespace.QName; import java.util.Iterator; import java.util.List; import java.util.Map; /** * The <code>javax.xml.rpc.Call</code> interface provides support * for the dynamic invocation of a service endpoint. The * <code>javax.xml.rpc.Service</code> interface acts as a factory * for the creation of <code>Call</code> instances. */ public interface Call { /** * Standard property: User name for authentication */ public static final String USERNAME_PROPERTY = "javax.xml.rpc.security.auth.username"; /** * Standard property: Password for authentication */ public static final String PASSWORD_PROPERTY = "javax.xml.rpc.security.auth.password"; /** * Standard property for operation style. This property is * set to "rpc" if the operation style is rpc; "document"
http://java.boot.by/wsd-guide/ch04s03.html 8 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

* if the operation style is document. */ public static final String OPERATION_STYLE_PROPERTY = "javax.xml.rpc.soap.operation. style"; /** * Standard property for SOAPAction. This boolean property * indicates whether or not SOAPAction is to be used. The * default value of this property is false indicating that * the SOAPAction is not used. */ public static final String SOAPACTION_USE_PROPERTY = "javax.xml.rpc.soap.http. soapaction.use"; /** * Standard property for SOAPAction. Indicates the SOAPAction * URI if the <code>javax.xml.rpc.soap.http.soapaction.use</code> * property is set to <code>true</code>. */ public static final String SOAPACTION_URI_PROPERTY = "javax.xml.rpc.soap.http. soapaction.uri"; /** * Standard property for encoding Style: Encoding style specified * as a namespace URI. The default value is the SOAP 1.1 encoding * <code>http://schemas.xmlsoap.org/soap/encoding/</code> */ public static final String ENCODINGSTYLE_URI_PROPERTY = "javax.xml.rpc.encodingstyle. namespace.uri"; /** * Standard property: This boolean property is used by a service * client to indicate whether or not it wants to participate in * a session with a service endpoint. If this property is set to * true, the service client indicates that it wants the session * to be maintained. If set to false, the session is not maintained. * The default value for this property is <code>false</code>. */ public static final String SESSION_MAINTAIN_PROPERTY = "javax.xml.rpc.session. maintain"; /** * Indicates whether <code>addParameter</code> and * <code>setReturnType</code> methods * are to be invoked to specify the parameter and return type * specification for a specific operation.
http://java.boot.by/wsd-guide/ch04s03.html 9 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

*/ public boolean isParameterAndReturnSpecRequired(QName operationName); /** * Adds a parameter type and mode for a specific operation. * Note that the client code may not call any * <code>addParameter</code> and <code>setReturnType</code> * methods before calling the <code>invoke</code> method. In * this case, the Call implementation class determines the * parameter types by using reflection on parameters, using * the WSDL description and configured type mapping registry. */ public void addParameter(String paramName, QName xmlType, ParameterMode parameterMode); /** * Adds a parameter type and mode for a specific operation. * This method is used to specify the Java type for either * OUT or INOUT parameters. * * @param paramName Name of the parameter * @param xmlType XML datatype of the parameter * @param javaType The Java class of the parameter * @param parameterMode Mode of the parameter-whether * ParameterMode.IN, OUT or INOUT */ public void addParameter(String paramName, QName xmlType, Class javaType, ParameterMode parameterMode); /** * Gets the XML type of a parameter by name. */ public QName getParameterTypeByName(String paramName); /** * Sets the return type for a specific operation. Invoking * <code>setReturnType(null)</code> removes the return * type for this Call object. */ public void setReturnType(QName xmlType); /** * Sets the return type for a specific operation. */ public void setReturnType(QName xmlType, Class javaType); /**
http://java.boot.by/wsd-guide/ch04s03.html 10 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

* Gets the return type for a specific operation. */ public QName getReturnType(); /** * Removes all specified parameters from this <code>Call</code> instance. * Note that this method removes only the parameters and not * the return type. The <code>setReturnType(null)</code> is * used to remove the return type. */ public void removeAllParameters(); /** * Gets the name of the operation to be invoked using this Call instance. */ public QName getOperationName(); /** * Sets the name of the operation to be invoked using this * <code>Call</code> instance. */ public void setOperationName(QName operationName); /** * Gets the qualified name of the port type. */ public QName getPortTypeName(); /** * Sets the qualified name of the port type. */ public void setPortTypeName(QName portType); /** * Sets the address of the target service endpoint. * This address must correspond to the transport specified * in the binding for this <code>Call</code> instance. */ public void setTargetEndpointAddress(String address); /** * Gets the address of a target service endpoint. */ public String getTargetEndpointAddress(); /**
http://java.boot.by/wsd-guide/ch04s03.html 11 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

* Sets the value for a named property. JAX-RPC specification * specifies a standard set of properties that may be passed * to the <code>Call.setProperty</code> method. */ public void setProperty(String name, Object value); /** * Gets the value of a named property. */ public Object getProperty(String name); /** * Removes a named property. */ public void removeProperty(String name); /** * Gets the names of configurable properties supported by * this <code>Call</code> object. */ public Iterator getPropertyNames(); // Remote Method Invocation methods /** * Invokes a specific operation using a synchronous request-response * interaction mode. */ public Object invoke(Object[] inputParams) throws java.rmi.RemoteException; /** * Invokes a specific operation using a synchronous request-response * interaction mode. */ public Object invoke(QName operationName, Object[] inputParams) throws java.rmi.RemoteException; /** * Invokes a remote method using the one-way interaction mode. The * client thread does not block waiting for the completion of the * server processing for this remote method invocation. This method * must not throw any remote exceptions. This method may throw a * <code>JAXRPCException</code> during the processing of the one-way * remote call. */ public void invokeOneWay(Object[] params);
http://java.boot.by/wsd-guide/ch04s03.html 12 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

/** * Returns a <code>Map</code> of {name, value} for the output parameters of * the last invoked operation. The parameter names in the * returned Map are of type <code>java.lang.String</code>. */ public Map getOutputParams(); /** * Returns a <code>List</code> values for the output parameters * of the last invoked operation. */ public List getOutputValues(); }

Table 4.1. Usage scenarios of the three Web Service service client styles.
Dynamic Invocation Interface (DII) Considerable changes to the Web service expected, such as: Web service not expected to change Some changes to the Web Service expected, such as the location of the service

Static stub

Dynamic proxy

Location of the service Request/response format Data types

Most common scenario You can generate a stub class either from WSDL (using WSDL2Java) or from a service endpoint interface. A generated stub class is required to implement both javax.xml.rpc.Stub and the service endpoint interface. This stub interface provides APIs to configure stubs by setting properties like endpoint address, session, user name, password, etc.

Less common

Less common

The client at runtime creates dynamic proxy stubs using the javax.xml. rpc.Service interface. The client has a priori knowledge of the WSDL and the service it is going to invoke. It uses the javax. xml.rpc.ServiceFactory classes to create the service and get the proxy.

This software pattern eliminates the need for clients to know in advance a service's exact name and parameters. A DII client can discover this information at runtime using a service broker that can look up the service's information. This flexibility in service discovery enables the run-time system to use service brokers, which can adopt varying service discovery mechanisms - ebXML registries, UDDI, etc.

http://java.boot.by/wsd-guide/ch04s03.html 13 / 14 2004/6/13 12:03:42

Given an set of requirements, design and develop a Web sevice client, ...e Java client, using the appropriate JAX-RPC client connection style.

Prev Given a set of requirements for a Web service, such as transactional needs, and security requirements, design and develop Web service applications that use servlet-based endpoints and EJB based endpoints.

Up

Next Given a set of requirements, develop and configure a Web service client that accesses a stateful Web service.

Home

http://java.boot.by/wsd-guide/ch04s03.html 14 / 14 2004/6/13 12:03:42

Given a set of requirements, develop and configure a Web service client that accesses a stateful Web service.

Given a set of requirements, develop and configure a Web service client that accesses a stateful Web service. Prev Chapter 4. JAX-RPC Next

Given a set of requirements, develop and configure a Web service client that accesses a stateful Web service.
1212

Prev Given an set of requirements, design and develop a Web sevice client, such as a J2EE client and a stand-alone Java client, using the appropriate JAX-RPC client connection style.

Up

Next Explain the advantages and disadvantages of a WSDL to Java vs. a Java to WSDL development approach.

Home

http://java.boot.by/wsd-guide/ch04s04.html2004/6/13 12:03:44

Explain the advantages and disadvantages of a WSDL to Java vs. a Java to WSDL development approach.

Explain the advantages and disadvantages of a WSDL to Java vs. a Java to WSDL development approach. Prev Chapter 4. JAX-RPC Next

Explain the advantages and disadvantages of a WSDL to Java vs. a Java to WSDL development approach.
WSDL to Java: 1. 2. 3. 4. Convenient when WSDL document already exists More powerful Requires WSDL and XML Schema knowledge Easy to stray outside of WS-I BP 1.0, harming interoperability

Java to WSDL: 1. Easier to use 2. No need to learn WSDL or XML Schema 3. Less control over published service contract

Prev Given a set of requirements, develop and configure a Web service client that accesses a stateful Web service.

Up

Next Describe the advantages and disadvantages of web service applications that use either synchronous/ request response, one-way RPC, or nonblocking RPC invocation modes.

Home

http://java.boot.by/wsd-guide/ch04s05.html2004/6/13 12:03:47

Describe the advantages and disadvantages of web service applicatio...quest response, one-way RPC, or non-blocking RPC invocation modes.

Describe the advantages and disadvantages of web service applications that use either synchronous/request response, one-way RPC, or non-blocking RPC invocation modes. Prev Chapter 4. JAX-RPC Next

Describe the advantages and disadvantages of web service applications that use either synchronous/request response, one-way RPC, or non-blocking RPC invocation modes.
Synchrous request-response mode:

Client's thread blocks until a return value or exception is returned

One-way RPC mode:


Client's thread continues processing No return value or exception is expected

Example:

... <portType name="HelloOneWayIF"> <operation name="oneWayValueType"> <input message="tns:HelloOneWayIF_oneWayValueType"/> </operation> </portType> <binding name="HelloOneWayIFBinding" type="tns:HelloOneWayIF"> <operation name="oneWayValueType"> <input> <soap:body use="literal"/> </input> <soap:operation soapAction=""/> </operation> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/> </binding> ...

Non-blocking RPC invocation mode:

http://java.boot.by/wsd-guide/ch04s06.html 1 / 2 2004/6/13 12:03:49

Describe the advantages and disadvantages of web service applicatio...quest response, one-way RPC, or non-blocking RPC invocation modes.

A client invokes a remote procedure and continues in its thread without blocking Later, the client processes the remote method return by performing a blocked receive call or by polling for the return value

Prev Explain the advantages and disadvantages of a WSDL to Java vs. a Java to WSDL development approach.

Up

Next Use the JAX-RPC Handler API to create a SOAP message handler, describe the function of a handler chain, and describe the role of SAAJ when creating a message handler.

Home

http://java.boot.by/wsd-guide/ch04s06.html 2 / 2 2004/6/13 12:03:49

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

Use the JAX-RPC Handler API to create a SOAP message handler, describe the function of a handler chain, and describe the role of SAAJ when creating a message handler. Prev Chapter 4. JAX-RPC Next

Use the JAX-RPC Handler API to create a SOAP message handler, describe the function of a handler chain, and describe the role of SAAJ when creating a message handler.
JAX-RPC handlers allow you to intercept a SOAP message at various times during a service invocation. Handlers can exist on both the client and the server side. If you use JAX-RPC on the client side, you can have a handler process a SOAP request message right before it goes on the network, and you can process the response message before it is returned to the client. Similarly, you can intercept an incoming SOAP request message on the server before invoking the service implementation, as well as the outgoing response. Several handlers can be combined into what is called a "handler chain". Each handler processes the SOAP message, which is then passed on to the next handler in the chain. The exact sequence in which this happens is configurable. To develop a JAX-RPC handler, you simply create a class that implements the javax.xml.rpc.handler. Handler interface. It has three methods to handle SOAP requests, responses and faults, respectively. Handlers are defined in the JAX-RPC specification. However, the "Enterprise Web Services" (JSR109) specification describes how they are used in a J2EE environment and adds some clarification to the way handlers are managed by the application server. We will assume that your Web service runs on a J2EE application server and hence we will follow the definitions of JSR109 as well as JAX-RPC. Handlers are shared across multiple service invocations. In other words, they can store information that is only valid for a particular client or server instance. You can compare this to the way servlets are handled. When a new instance of a handler is created, its init(...) method is called. That allows you to set up things that you can use for multiple invocations. Before the handler is removed, the destroy() method is called, so that you can do cleanup in there. As a rule of thumb, however, you should avoid storing any state in a handler altogether. Handlers can be configured either programmatically or, in case you are running a J2EE application server, they are configured in the Web service deployment descriptor. Handlers and handler chains are defined on a per service basis. They can be defined in both the server and client side deployment descriptors. Listing below shows the deployment descriptor for our sample service, showing how a handler class called handler.PerformanceHandler is registered for the HelloWorld service:

<webservices> <webservice-description>
http://java.boot.by/wsd-guide/ch04s07.html 1 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

<webservice-description-name>HelloWorldService</webservice-description-name> <wsdl-file>WEB-INF/wsdl/HelloWorld.wsdl</wsdl-file> <jaxrpc-mapping-file>WEB-INF/HelloWorld_mapping.xml</jaxrpc-mapping-file> <port-component> <port-component-name>HelloWorld</port-component-name> <wsdl-port> <namespaceURI>http://pack</namespaceURI> <localpart>HelloWorld</localpart> </wsdl-port> <service-endpoint-interface>pack.HelloWorld</service-endpoint-interface> <service-impl-bean> <servlet-link>pack_HelloWorld</servlet-link> </service-impl-bean> <handler> <handler-name>handler.PerformanceHandler</handler-name> <handler-class>handler.PerformanceHandler</handler-class> </handler> </port-component> </webservice-description> </webservices>

Multiple handlers would be defined here to form a chain as mentioned above. If multiple handlers that are involved in one service invocation need to share information, they can do so by adding properties to the message context as it is passed from handler to handler. This message context will be available from the request to the response. In other words, we can use it to store information on an incoming request that we can reuse when the response comes back. Now let's look at how you can create a handler that measures the response time of your service implementation. We will assume that you have created a HelloWorld web service, which simply returns a String message. Listing below shows the code for the service implementation bean:

public class HelloWorld { public String helloWorld(String message) { return "Hello " + message; } }

The handler will be configured for the server that hosts the Web service. It will be invoked on both the request and the response message, so that we can measure the elapsed time.

http://java.boot.by/wsd-guide/ch04s07.html 2 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

Each handler must implement the javax.xml.rpc.handler.Handler interface. Or, you can make your life a bit easier by simply inheriting the javax.xml.rpc.handler.GenericHandler class, which provides default implementations for all the methods. For storing performance results, we use a class called Logger, which we set up in the init() method. Moreover, the application server passes a javax.xml.rpc.handler.HandlerInfo object into this method, which we need to cache as well:

public class PerformanceHandler extends GenericHandler { protected HandlerInfo info = null; protected Logger logger = null; public void init(HandlerInfo arg) { info = arg; logger = Logger.getLogger("c://temp//HelloWorldServiceLog"); } public void destroy() { try { logger.close(); } catch (Exception x) {} } ... }

Note that we close the Logger object when the handler instance is destroyed. Each handler implements the handleRequest method, which is invoked when a request message arrives:

public boolean handleRequest(MessageContext context) { try { Date startTime = new Date(); context.setProperty("startTime", startTime); } catch (Exception x) { x.printStackTrace(); } return true; }

Here you can see that we store the current time in the message context as a property called "startTime". The application server will guarantee that the same message context object is
http://java.boot.by/wsd-guide/ch04s07.html 3 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

passed into the handleResponse method, so that we can measure the elapsed time there:

public boolean handleResponse(MessageContext context) { try { Date startTime = (Date)context.getProperty("startTime"); Date endTime = new Date(); long elapsedTime = endTime.getTime() - startTime.getTime(); logger.write("Elapsed time is " + elapsedTime+"\n"); } catch (Exception x) { x.printStackTrace(); } return true; }

JAX-RPC defines a mechanism with which you can manage service invocations by intercepting request and response messages without having to change the actual service consumer or provider. In J2EE, you can configure handlers in a deployment descriptor, without writing any code, providing you with a powerful way of controlling SOAP messages as they pass through your system. Handlers let you access/modify SOAP request and response messages, but typically used to process service contexts in SOAP header blocks. Possible example handlers: encryption, decryption, authentication, authorization, logging, auditing, caching. Handlers are pluggable and chainable through standardized programming API, portable across implementations. Handler has its own lifecycle: JAX-RPC runtime system calls init(...), destroy() of a handler. Handler instances can be pooled (stateless). MessageContext is used to share properties among handlers in a handler chain. On the service client side: a request handler is invoked before an RPC request is communicated to the target service endpoint, a response or fault handler is invoked before an RPC response is returned to the client. On a service endpoint: a request handler is invoked before an RPC request is dispatched to the target service endpoint, a response or fault handler is invoked before communication back to the service client from the target service endpoint. javax.xml.rpc.handler.Handler interface is required to be implemented by a SOAP message handler:

package javax.xml.rpc.handler; import javax.xml.namespace.QName;


http://java.boot.by/wsd-guide/ch04s07.html 4 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

public interface Handler { public boolean handleRequest(MessageContext context); // 'false' will block the HandlerChain public boolean handleResponse(MessageContext context); // 'false' will block the HandlerChain public boolean handleFault(MessageContext context); // 'false' will block the HandlerChain public abstract void init(HandlerInfo config); public abstract void destroy(); public QName[] getHeaders(); }

or extend GenericHandler abstract class:

package javax.xml.rpc.handler; import javax.xml.namespace.QName; public abstract class GenericHandler implements Handler { protected GenericHandler() {} public boolean handleRequest(MessageContext context) { return true; } public boolean handleResponse(MessageContext context) { return true; } public boolean handleFault(MessageContext context) { return true; } public void init(HandlerInfo config) {} public void destroy() {} public abstract QName[] getHeaders(); }

Sample handler which extends GenericHandler:

public class SampleSOAPHeaderHandler extends GenericHandler{


http://java.boot.by/wsd-guide/ch04s07.html 5 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

public boolean handleRequest(MessageContext ctx){ try{ SOAPMessageContext mc = (SOAPMessageContext)ctx; SOAPMessage msg = mc.getMessage(); SOAPPart sp = msg.getSOAPPart(); SOAPEnvelop se = sp.getEnvelop(); SOAPHeader header= se.getHeader(); // now we can process the header if (everything is fine) { return true; // with 'true' handler chain continues processing } else { return false; // return 'false' results in chaining to stop } } catch(Exception ex){} } }

Configurable on both client and endpoint side:


Server side in jaxrpc-ri.xml file Client side in config.xml file

jaxrpc-ri.xml (server side config): <?xml version="1.0" encoding="UTF-8" ?> <webServices xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/dd" version="1.0" targetNamespaceBase="http://com.test/wsdl" typeNamespaceBase="http://com.test/types" urlPatternBase="/test"> <endpoint name="MyHandlerApp" interface="service.HandlerTest" implementation="service. HandlerTestImpl"> <handlerChains> <chain runAt="server"> <!-- this handler declares that it understands the "loginfo" header --> <handler className="service.ServerHandler1" headers="ns1:loginfo" xmlns: ns1="http://example.com/headerprops"> <property name="name" value="server1" /> </handler>

http://java.boot.by/wsd-guide/ch04s07.html 6 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

<handler className="service.ServerHandler2"> <property name="name" value="server2" /> </handler> </chain> </handlerChains> </endpoint> <endpointMapping endpointName="MyHandlerApp" urlPattern="/test" /> </webServices>

Example of generic SOAP message handler:

package com.example; public class MySOAPMessageHandler implements javax.xml.rpc.handler.Handler { public MySOAPMessageHandler() { ... } public boolean handleRequest(MessageContext context){ try { SOAPMessageContext smc = (SOAPMessageContext)context; SOAPMessage msg = smc.getMessage(); SOAPPart sp = msg.getSOAPPart(); SOAPEnvelope se = sp.getEnvelope(); SOAPHeader sh = se.getHeader(); // Process one or more header blocks // ... // Next step based on the processing model for this handler } catch(Exception ex) { // throw exception } } ... }

Server side handler:


http://java.boot.by/wsd-guide/ch04s07.html 7 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

package service; import javax.xml.namespace.QName; import javax.xml.rpc.handler.soap.SOAPMessageContext; import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.handler.*; import javax.xml.soap.*; /** * This class implements a handler by extending the abstract * class javax.xml.rpc.handler.GenericHandler. */ public class ServerHandler1 extends GenericHandler { private HandlerInfo handlerInfo; private String name; public void init(HandlerInfo info) { handlerInfo = info; // this parameter was configured in jaxrpc-ri.xml name = (String) info.getHandlerConfig().get("name"); System.out.println("ServerHandler1: name = " + name); } /* * This method is declared abstract in GenericHandler and must * be defined here. See ServerHandler2 for another way to implement. */ public QName[] getHeaders() { return handlerInfo.getHeaders(); } /* * This handler will check incoming messages for the header * specified in jaxrpc-ri.xml. It doesn't do anything with the * information besides output it, but it could be used to determine * what type of processing should be performed on this message * before passing on to the ultimate recipient. */ public boolean handleRequest(MessageContext context) { // ... } }

http://java.boot.by/wsd-guide/ch04s07.html 8 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

config.xml (client side config):

<?xml version="1.0" encoding="UTF-8"?> <configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> <wsdl location="http://localhost:8080/handler/test?WSDL" packageName="handlersample"> <handlerChains> <chain runAt="client"> <handler className="client.ClientHandler1"> <!-- Send a property to this handler --> <property name="name" value="My Client Handler" /> </handler> </chain> </handlerChains> </wsdl> </configuration>

Client side handler:

package client; import javax.xml.namespace.QName; import javax.xml.rpc.handler.soap.SOAPMessageContext; import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.handler.*; import javax.xml.soap.*; /** * This class implements a handler by extending the abstract * class javax.xml.rpc.handler.GenericHandler. */ public class ClientHandler1 extends GenericHandler { HandlerInfo handlerInfo; String name; public void init(HandlerInfo info) { handlerInfo = info; // this parameter was configured in config.xml name = (String) info.getHandlerConfig().get("name"); System.out.println("ClientHandler1: name = " + name); }
http://java.boot.by/wsd-guide/ch04s07.html 9 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

/* * This method is declared abstract in GenericHandler and must * be defined here. Another way to implement is to keep an array * of QNames and set them in the init() method to info.getHeaders(). */ public QName[] getHeaders() { return handlerInfo.getHeaders(); } public boolean handleRequest(MessageContext context) { try { // get the soap header SOAPMessageContext smc = (SOAPMessageContext) context; SOAPMessage message = smc.getMessage(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPHeader header = message.getSOAPHeader(); if (header == null) { header = envelope.addHeader(); } // Add logger element with musUnderstand=1. // Will use the default actor "next" for this example, otherwise // use loggerElement.setActor(String actorURI). // The element will contain a ficticuous log level for // this example. System.out.println("ClientHandler1: adding loggerElement"); SOAPHeaderElement loggerElement = header.addHeaderElement( envelope.createName("loginfo", "ns1", "http://example.com/headerprops")); loggerElement.setMustUnderstand(true); loggerElement.setValue("10"); // Add simple element describing the client making the request. System.out.println("ClientHandler1: adding nameElement"); SOAPHeaderElement nameElement = header.addHeaderElement( envelope.createName("clientname", "ns1", "http://example.com/headerprops")); nameElement.addTextNode("Duke"); } catch (Exception e) { throw new JAXRPCException(e); } // return true to continue message processing return true; } }
http://java.boot.by/wsd-guide/ch04s07.html 10 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

A handler chain represents an ordered list of handlers. This grouping helps you define policies that you want associated with the handler invocation model. Examples of such policies include order of invocation, style of invocation (for example, a one-way call invokes only handleRequest(); no handleResponse()), etc. Another possible policy you can set on the handler chain: A handler chain can invoke a handler based on the qname of the outermost element of a SOAP header. This association can be configured to the handler through the Handler.init(...) method passing a HandlerInfo object. The handler chain continues processing the handlers only if the current processing handler returns true. You can associate a handler chain with SOAP actors (or roles) by specifying the URIs of the actors. By default, a handler chain is always associated with the special SOAP actor http://schemas.xmlsoap.org/soap/actor/next. A handler chain is registered on a per service endpoint basis, as indicated by the qualified name of the WSDL port.

package javax.xml.rpc.handler; import java.util.List; import java.util.Map; public interface HandlerChain extends List { public boolean handleRequest(MessageContext context); public boolean handleResponse(MessageContext context); public boolean handleFault(MessageContext context); public void init(Map config); public void destroy(); public void setRoles(String[] soapActorNames); public java.lang.String[] getRoles(); }

Prev Describe the advantages and disadvantages of web service applications that use either synchronous/ request response, one-way RPC, or nonblocking RPC invocation modes.

Up

Next Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

Home

http://java.boot.by/wsd-guide/ch04s07.html 11 / 12 2004/6/13 12:03:56

Use the JAX-RPC Handler API to create a SOAP message handler, descr...in, and describe the role of SAAJ when creating a message handler.

http://java.boot.by/wsd-guide/ch04s07.html 12 / 12 2004/6/13 12:03:56

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ) Prev Part I. Exam Objectives Next

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

Describe the functions and capabilities of the APIs included within JAXP.
SAX 1212 DOM 1212 TrAX (Transformation API for XML) TrAX is an API for transforming XML documents using XSLT style sheets. TrAX is a Java API and has been defined to provide common access to different XSLT Processors. TrAX is part of the JAXP API, which combines a number of Java APIs. The TrAX API extends the original JAXP mission to include XML transformations: provide a vendor and implementation agnostic standard Java API for specifying and executing XML transformations. This is important to note, because TrAX is more than just a standard interface for XSLT engines - it is designed to be used as a general-purpose transformation interface for XML documents. TrAX isn't a competitor to the existing DOM and SAX APIs used to represent and process XML, but a common Java API to bridge the various XML transformation methods (a la JDBC, JNDI, etc.) including SAX Events and XSLT Templates. In fact, TrAX relies upon a SAX2- and DOMlevel-2-compliant XML parser/XSLT engine. JAXP 1.0 allows the developer to change XML parsers by setting a property, and TrAX provides the same functionality for XSLT engines. Here is a sample of how to apply an XSLT stylesheet to an XML document and write the results out to a file. In this example, both the stylesheet and the XML document exist as files, but they could just as easily have come from any Java InputStream or Reader class. The same follows for the results of the transformation; I could've just as easily written the results out to any Java OutputStream or Writer class.

// 1. create the XML content input source: // can be a DOM node, SAX stream, or any Java input stream/reader String xmlInputFile = "myXMLinput.xml";
http://java.boot.by/wsd-guide/ch05.html 1 / 6 2004/6/13 12:04:01

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

Source xmlSource = new StreamSource(new FileInputStream(xmlInputFile)); // 2. create the XSLT Stylesheet input source // can be a DOM node, SAX stream, or a java input stream/reader String xsltInputFile = "myXsltStylesheet.xsl"; Source xsltSource = new StreamSource(new FileInputStream(xsltInputFile)); // 3. create the result target of the transformation // can be a DOM node, SAX stream, or a java out stream/reader String xmlOutputFile = "result.html"; Result transResult = new StreamResult(new FileOutputStream(xmlOutputFile)); // 4. create the transformerfactory and transformer instance TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(xsltSource); // 5. execute transformation and fill result target object t.transform(xmlSource, transResult);

The first three stanzas simply establish our inputs and result targets, and aren't that interesting, with one exception. Notice that the XSLT stylesheet isn't handled via a different class in TrAX. It's treated just like any other XML source document, because that's exactly what it is. We use the stream implementations of the Source and Result interfaces from the javax.xml.transform.stream package to handle reading the data from our file streams. In the fourth stanza, we use the TransformerFactory to get an instance of a Transformer, and then use the Source instance for the XSLT stylesheet we created in the second stanza to define the transformation that this transformer will perform. A Transformer actually executes the transformation and assembles the result. A single Transformer instance can be reused, but it is not thread-safe. In this example, the XSLT stylesheet is reprocessed for each successive transformation. A very common case is that the same transformation is applied multiple times to different Sources, perhaps in different threads. A more efficient approach in this case is to process the transformation stylesheet once, and save this object for successive transformations. This is achieved through the use of the TrAX Templates interface:

// we've already set up our content Source instance, // XSLT Source instance, TransformerFactory, and // Result target from the previous example // process the XSLT stylesheet into a Templates instance // with our TransformerFactory instance Templates t = tf.newTemplates(xsltSource);

http://java.boot.by/wsd-guide/ch05.html 2 / 6 2004/6/13 12:04:01

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

// whenever you need to execute this transformation, create // a new Transformer instance from the Templates instace Transformer trans = t.newTransformer(); // execute transformation and fill result target object trans.transform(xmlSource, transResult);

While the Transformer performs the transformation, a Templates instance is the actual run-time representation of the processed transformation instructions. Templates instances may be reused to increase performance, and they are thread-safe. It might seem odd that an interface has a plural name, but it stems from the fact that an XSLT stylesheet consists of a collection of one or more xsl:template elements. Each template element defines a transformation in that stylesheet, so it follows that the simplest name for a representation of a collection of template elements is Templates. One of the main reasons the TrAX API is so clean and simple is the Interface-driven approach to design. The highest-level interfaces define the essential entities that are being modeled, and the interactions are left to the implementations. The interfaces themselves aren't very interesting. They are essentially marker interfaces. Source The Source interface is a generic container for existing XML documents that will be used in a transformation as either the input document or the stylesheet. Serve as a single vendor-neutral object for multiple types of input. Implementations of the Source interface provide access to the XML document to be processed. TrAX defines Source implementations for DOM trees (DOMSource); SAX 2.0 InputSources (SAXSource); and Java InputStreams, Readers and any of their derived classes (StreamSource).

package javax.xml.transform; public interface Source { public void setSystemId(String systemId); public String getSystemId(); }

Result The Result interface is a generic container for an XML document that will be produced by a transformation. Serve as a single object for multiple types of output, so there can be simple process method signatures. Implementations of the Result interface provide access to the transformed XML document. TrAX defines Result implementations for DOM trees (DOMResult);
http://java.boot.by/wsd-guide/ch05.html 3 / 6 2004/6/13 12:04:01

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

SAX 2.0 ContentHandlers (SAXResult); and Java OutputStreams, Writers and any of their derived classes (StreamResult).

package javax.xml.transform; public interface Result { public static final String PI_DISABLE_OUTPUT_ESCAPING; public static final String PI_ENABLE_OUTPUT_ESCAPING; public void setSystemId(String url); public String getSystemId(); }

Templates Templates is a thread-safe interface that represents a compiled stylesheet. It can quickly create new Transformer objects without having to reread and reparse the original stylesheet. Its particularly useful when you want to use the same stylesheet in multiple threads. The runtime representation of the transformation instructions. A template implementation is the optimized, in-memory representation of an XML transformation that is processed and ready to be executed. Templates objects are safe to use in concurrent threads. To reuse a single Template instance in multiple concurrent threads, multiple Transformer instances would have to be created via the Templates.newTransformer() factory method. Each Transformer instance may be used completely independently in concurrent threads, and both the Templates and the Transformer instances can be reused for subsequent transformations.

package javax.xml.transform; public interface Templates { public Transformer newTransformer() throws TransformerConfigurationException; public Properties getOutputProperties(); }

Transformer Transformer is the abstract class that represents a compiled stylesheet. It transforms Source objects into Result objects. A single Transformer can transform multiple input documents in sequence but not in parallel. Act as a per-thread execution context for transformations, act as

http://java.boot.by/wsd-guide/ch05.html 4 / 6 2004/6/13 12:04:01

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

an interface for performing the transformation. A Transformer is the object that actually applies the transformation to the source document and creates the result document. However, it is not responsible for outputting, or serializing, the result of the transformation. This is the responsibility of the transformation engine's serializer and this behavior can be modified via the setOutputProperty(java.lang.String name, java.lang.String value) method. The configurable OutputProperties are defined in the OutputKeys class, and are described in the XSLT 1.0 Specification. Transformers are immutable, they cannot change which Templates instance gets applied to the Source.

package javax.xml.transform; public abstract class Transformer { protected Transformer(); public void transform(Source input, Result output) throws TransformerException; public void setParameter(String name, Object value); public Object getParameter(String name); public void clearParameters(); public void setURIResolver(URIResolver resolver); public URIResolver getURIResolver(); public void setOutputProperties(Properties serialization) throws IllegalArgumentException; public Properties getOutputProperties(); public void setOutputProperty(String name, String value) throws IllegalArgumentException; public String getOutputProperty(String name) throws IllegalArgumentException; public void setErrorListener(ErrorListener listener) throws IllegalArgumentException; public ErrorListener getErrorListener(); }

TransformerFactory TransformerFactory is an abstract factory that creates new Transformer and Templates objects. The concrete subclass that newInstance() instantiates is specified by the javax.xml.transform. TransformerFactory Java system property. If this class is not set, a platform dependent default class is chosen. Serve as a vendor-neutral Processor interface for XSLT and similar processors. The TransformerFactory is primarily responsible for creating new Transformer>s and Templates objects. New instances of Transformer are created via the static newTransformer() method. Processing Source instances into Templates objects is handled by the newTemplates(Source source) method.

package javax.xml.transform; public abstract class TransformerFactory {


http://java.boot.by/wsd-guide/ch05.html 5 / 6 2004/6/13 12:04:01

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

protected TransformerFactory(); public static TransformerFactory newInstance() throws TransformerFactoryConfigurationError; public Transformer newTransformer(Source source) throws TransformerConfigurationException; public Transformer newTransformer() throws TransformerConfigurationException; public Templates newTemplates(Source source) throws TransformerConfigurationException; public Source getAssociatedStylesheet(Source source, String media, String title, String charset) throws TransformerConfigurationException; public void setURIResolver(URIResolver resolver); public URIResolver getURIResolver(); public boolean getFeature(String name); public void setAttribute(String name, Object value) throws IllegalArgumentException; public Object getAttribute(String name) throws IllegalArgumentException; public void setErrorListener(ErrorListener listener) throws IllegalArgumentException; public ErrorListener getErrorListener(); }

Prev Use the JAX-RPC Handler API to create a SOAP message handler, describe the function of a handler chain, and describe the role of SAAJ when creating a message handler.

Up

Next Given a scenario, select the proper mechanism for parsing and processing the information in an XML document.

Home

http://java.boot.by/wsd-guide/ch05.html 6 / 6 2004/6/13 12:04:01

Given a scenario, select the proper mechanism for parsing and processing the information in an XML document.

Given a scenario, select the proper mechanism for parsing and processing the information in an XML document. Prev Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ) Next

Given a scenario, select the proper mechanism for parsing and processing the information in an XML document.
SAX:

SAX is an event-driven XML parser that is appropriate for high-speed processing of XML because it does not produce a representation of the data in memory. SAX automatically perform structure validation. Event-based parsers (SAX) provide a data-centric view of XML. When an element is encountered, the idea is to process it and then forget about it. The event-based parser returns the element, its list of attributes, and the content. This is more efficient for many types of applications, especially searches. It requires less code and less memory since there is no need to build a large tree in memory as you are scanning for a particular element, attribute, and/or content sequence in an XML document.

DOM:

DOM produces an in-memory data representation, which allows an application to manipulate the contents in memory DOM automatically perform structure validation. Tree-based parsers (DOM) provide a document-centric view of XML. In tree-based parsing, an in-memory tree is created for the entire document, which is extremely memory-intensive for large documents. All elements and attributes are available at once, but not until the entire document has been parsed. This technique is useful if you need to navigate around the document and perhaps change various document chunks, which is precisely why it is useful for the Document Object Model (DOM), the aim of which is to manipulate documents via scripting languages or Java.

JAXB:

JAXB application can perform structure and content validation with Java classes that it generates from a schema. A JAXB application builds an in-memory data structure, like a DOM, by marshalling an XML document to build a content tree, which contains objects that are instances of the derived classes. However, unlike a DOM tree, a content tree is specific to one source schema, does not contain extra tree-manipulation functionality, allows access to its data with the derived classes' accessor methods, and is not built dynamically. For these reasons, a JAXB application uses memory more efficiently than a DOM application does. If the content of a document is more dynamic and not wellconstrained, DOM and SAX are more appropriate than JAXB for processing XML content that does not have a well-known schema prior to processing the content. Build object trees representing XML data that is valid against the XML Schema by either

http://java.boot.by/wsd-guide/ch05s02.html 1 / 2 2004/6/13 12:04:03

Given a scenario, select the proper mechanism for parsing and processing the information in an XML document.

unmarshalling the data from a document or instantiating the classes you created. Access and modify the data. Optionally validate the modifications to the data relative to the constraints expressed in the XML Schema. Marshal the data to new XML documents.

Prev Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

Up

Next Describe the functions and capabilities of JAXB, including the JAXB process flow, such as XML-to-Java and Java-toXML, and the binding and validation mechanisms provided by JAXB.

Home

http://java.boot.by/wsd-guide/ch05s02.html 2 / 2 2004/6/13 12:04:03

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

Describe the functions and capabilities of JAXB, including the JAXB process flow, such as XML-to-Java and Javato-XML, and the binding and validation mechanisms provided by JAXB. Prev Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ) Next

Describe the functions and capabilities of JAXB, including the JAXB process flow, such as XML-to-Java and Java-to-XML, and the binding and validation mechanisms provided by JAXB.
JAXB defines an architecture for binding XML schemata to Java objects. These bindings allow you to unmarshal XML documents into a hierarchy of Java objects and marshal the Java objects into XML with minimal effort. If you work a lot with XML, you know how tedious it can be to write Simple API for XML (SAX) or Document Object Model (DOM) code to convert XML into Java objects that mean something to your program. JAXB generates code automatically so you can go about the business of processing data instead of parsing it.

http://java.boot.by/wsd-guide/ch05s03.html 1 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

Latest version of JAXB supports XML schema definitions and allows additional binding declarations to be defined inside of the schema using XML schema annotations. The JAXB API, defined in the javax.xml.bind package, is a set of interfaces through which client applications communicate with code generated from a schema. The center of the JAXB API is JAXBContext, the client' s entry point. It provides an abstraction for managing the XML-Java binding information necessary to implement the JAXB binding framework operations: unmarshal, marshal and validate. These three aspects of JAXB are covered by three separate interfaces. Instances of those interfaces can be created from a JAXBContext object:

javax.xml.bind.Unmarshaller - governs the process of deserializing XML data into Java content trees, optionally validating the XML data as it is unmarshalled.

package javax.xml.bind; import java.io.File; import java.io.InputStream; import java.net.URL; import javax.xml.bind.JAXBException; import javax.xml.bind.PropertyException; import javax.xml.bind.UnmarshallerHandler; import javax.xml.bind.ValidationEventHandler; import javax.xml.transform.Source; import org.w3c.dom.Node; import org.xml.sax.InputSource; public interface Unmarshaller { public Object unmarshal(File f) throws JAXBException; public Object unmarshal(InputStream is) throws JAXBException; public Object unmarshal(URL url) throws JAXBException; public Object unmarshal(InputSource source) throws JAXBException; public Object unmarshal(Node node) throws JAXBException; public Object unmarshal(Source source) throws JAXBException; public UnmarshallerHandler getUnmarshallerHandler(); public void setValidating(boolean validating) throws JAXBException; public boolean isValidating() throws JAXBException; public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; public void setProperty(String name, Object value) throws PropertyException; public Object getProperty(String name) throws PropertyException; }
http://java.boot.by/wsd-guide/ch05s03.html 2 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

javax.xml.bind.Marshaller - governs the process of serializing Java content trees back into XML data.

package javax.xml.bind; import java.io.OutputStream; import java.io.Writer; import javax.xml.bind.JAXBException; import javax.xml.bind.PropertyException; import javax.xml.bind.ValidationEventHandler; import javax.xml.transform.Result; import org.w3c.dom.Node; import org.xml.sax.ContentHandler; public interface Marshaller { public static final String JAXB_ENCODING = "jaxb.encoding"; public static final String JAXB_FORMATTED_OUTPUT = "jaxb.formatted.output"; public static final String JAXB_SCHEMA_LOCATION = "jaxb.schemaLocation"; public static final String JAXB_NO_NAMESPACE_SCHEMA_LOCATION = "jaxb. noNamespaceSchemaLocation"; public void marshal(Object obj, Result result) throws JAXBException; public void marshal(Object obj, OutputStream os) throws JAXBException; public void marshal(Object obj, Writer writer) throws JAXBException; public void marshal(Object obj, ContentHandler handler) throws JAXBException; public void marshal(Object obj, Node node) throws JAXBException; public org.w3c.dom.Node getNode(Object contentTree) throws JAXBException; public void setProperty(String name, Object value) throws PropertyException; public Object getProperty(String name) throws PropertyException; public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; }

javax.xml.bind.Validator - performs the validation on an in-memory object graph.

package javax.xml.bind; import javax.xml.bind.JAXBException; import javax.xml.bind.PropertyException; import javax.xml.bind.ValidationEventHandler; public interface Validator { public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; public boolean validate(Object subrootObj) throws JAXBException; public boolean validateRoot(Object rootObj) throws JAXBException; public void setProperty(String name, Object value) throws PropertyException;
http://java.boot.by/wsd-guide/ch05s03.html 3 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

public Object getProperty(String name) throws PropertyException; }

JAXBContext is an abstract class defined in the API, so its actual implementation is vendor-dependent. To create a new instance of JAXBContext, you use the static newInstance(contextPath) method.

JAXBContext context = JAXBContext.newInstance("org.acme.foo:org.acme.bar");

The contextPath contains a list of Java package names that contain schema derived interfaces. The value of this parameter initializes the JAXBContext object so that it is capable of managing the schema derived interfaces. The client application must supply a context path which is a list of colon (':') separated java package names that contain schema derived classes. In this way, the unmarshaller will look at a document and figure out which package to use. This makes it easy to read in different types of documents without knowing their type in advance. Unmarshalling (XML-to-Java) An unmarshaller is used to read XML and build an object tree from classes generated by the compiler. To read an XML file, you would simply do:

... JAXBContext jaxbContext = JAXBContext.newInstance(packageName); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setValidating(true); Item item = (Item) unmarshaller.unmarshal(new File("item.xml")); ...

There are other overloaded versions that take different types of input, such as InputStream or InputSource. You can even unmarshal a javax.xml.transform.Source object. All in all, it's similar to the way DOM trees are parsed. Here are some more examples of unmarshalling: Unmarshalling from a File:

JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); Object o = u.unmarshal( new File( "xmlFile.xml" ) );

Unmarshalling from an java.io.InputStream:

InputStream is = new FileInputStream( "xmlFile.xml" ); JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); Object o = u.unmarshal( is );

Unmarshalling from a java.net.URL:

http://java.boot.by/wsd-guide/ch05s03.html 4 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); URL url = new URL( "http://server.com/xmlFile.xml" ); Object o = u.unmarshal( url );

Unmarshalling from a StringBuffer using a javax.xml.transform.stream.StreamSource:

JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); StringBuffer xmlStr = new StringBuffer( "<?xml version='1.0'?> ..." ); Object o = u.unmarshal( new StreamSource( new StringReader( xmlStr.toString() ) ) );

Unmarshalling from a org.w3c.dom.Node:

JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File( "xmlFile.xml")); Object o = u.unmarshal( doc );

By default, Unmarshaller is very forgiving. Even if a document is invalid, it tries to recover from errors. If the document is so broken that it cannot be read, an javax.xml.bind.UnmarshalException (child of javax.xml.bind. JAXBException) will be thrown. It's often desirable to get more information about errors or reject documents with errors. The first step to do this is to set ValidationEventHandler to the Unmarshaller. A ValidationEventHandler can explicitly tell a JAXB implementation whether it should reject a document or try to recover from errors. It also gives you more information, such as line numbers, about errors. An Unmarshaller can validate a document with the schema while unmarshalling. With this option turned on, it rejects anything short of a valid document. However, W3C XML Schema validation can be very costly. Another possibility is to set up a SAX pipeline in such a way that your XML parser does the validation; alternately, you could install a standalone validator in the pipeline. In this way, for example, you can change your schema to change what you get from the compiler, while maintaining the scrutiny of the original schema. Marshalling (Java-to-XML) A Marshaller is used to write an object graph into XML. To write an object o to a file, you would do:

... JAXBContext jaxbContext = JAXBContext.newInstance(packageName); Marshaller marshaller = jaxbContext.createMarshaller(); ObjectFactory itemMaker = new ObjectFactory(); Item item = itemMaker.createItem(); marshaller.marshal(item, new FileOutputStream("newIem.xml"));
http://java.boot.by/wsd-guide/ch05s03.html 5 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

...

There are other overloaded versions which allow you to produce XML as a a DOM tree or as SAX events. For example, by using StringWriter, you can marshal an object into a string. You can also marshal an object graph to a javax.xml.transform.Result object. Here are some more examples of marshalling: Marshalling to a File:

OutputStream os = new FileOutputStream( "xmlFile.xml" ); m.marshal( obj, os );

Marshalling to a SAX ContentHandler:

// assume MyContentHandler instanceof ContentHandler m.marshal( obj, new MyContentHandler() );

Marshalling to a DOM Node:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); m.marshal( obj, doc );

Marshalling to a java.io.OutputStream:

m.marshal( obj, System.out );

Marshalling to a java.io.Writer:

m.marshal( obj, new PrintWriter( System.out ) );

Marshalling to a javax.xml.transform.SAXResult:

// assume MyContentHandler instanceof ContentHandler SAXResult result = new SAXResult( new MyContentHandler() ); m.marshal( obj, result );

http://java.boot.by/wsd-guide/ch05s03.html 6 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

Marshalling to a javax.xml.transform.DOMResult:

DOMResult result = new DOMResult(); m.marshal( obj, result );

Although each of the marshal methods accepts a java.lang.Object as its first parameter, JAXB Providers are not required to be able to marshal any arbitrary java.lang.Object. If the JAXBContext object that was used to create this Marshaller does not have enough information to know how to marshal the object parameter (or any objects reachable from it), then the marshal operation will throw a MarshalException>. By default, the Marshaller will use UTF-8 encoding when generating XML data to a java.io.OutputStream, or a java.io. Writer. Use the setProperty API to change the ouput encoding used during these marshal operations. You can control the behavior of marshalling by setting Marshaller properties. For example, you can toggle indentation of the XML:

... Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true)); ...

JAXB can produce XML as SAX events. That is, you can pass ContentHandler and have it receive SAX events from a JAXB object. This gives client apps plenty of chances to modify XML. For example, you can add and remove elements or attributes, use one of the freely available serializers for better output, or write your own XML serializer that prints XML in your preferred way. Finally, you can ask a Marshaller to marshal an invalid object graph by setting a ValidationEventHandler. If a provider supports error recovery, you can tell it to write XML even if it's incomplete. If the boolean ValidationEventHandler.handleEvent(ValidationEvent event) method throws an unchecked runtime exception, the JAXB Provider must treat that as if the method returned false, effectively terminating whatever operation was in progress at the time (unmarshal, validate, or marshal). The method returns: true if the JAXB Provider should attempt to continue the current unmarshal, validate, or marshal operation after handling this warning/error, false if the provider should terminate the current operation with the appropriate UnmarshalException, ValidationException, or MarshalException. Validation There are three forms of Validation in JAXB: 1. Unmarshal-Time Validation This form of validation enables a client application to receive information about validation errors and warnings detected while unmarshalling XML data into a Java content tree and is completely orthogonal to the other types of validation. To enable or disable it use method Unmarhaller.setValidating(...). All JAXB Providers are REQUIRED to support this operation. 2. On-Demand Validation This form of validation enables a client application to receive information about validation errors and warnings detected in the Java content tree. At any point, client applications can call the Validator.validate(...) method on the Java content tree (or any sub-tree of it). All JAXB Providers are REQUIRED to support this operation.
http://java.boot.by/wsd-guide/ch05s03.html 7 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

3. Fail-Fast Validation This form of validation enables a client application to receive immediate feedback about modifications to the Java content tree that violate type constraints on Java Properties as defined in the specification. JAXB Providers are NOT REQUIRED support this type of validation. Of the JAXB Providers that do support this type of validation, some may require you to decide at schema compile time whether or not a client application will be allowed to request fail-fast validation at runtime. The Validator class is responsible for managing On-Demand Validation. The Unmarshaller class is responsible for managing Unmarshal-Time Validation during the unmarshal operations. Although there is no formal method of enabling validation during the marshal operations, the Marshaller may detect errors, which will be reported to the ValidationEventHandler registered on it. JAXB has the capability to validate an object graph in memory without actually writing it to XML. This allows client apps to check if a graph is okay and ready to process; if not, validation will identify objects that contain errors so that, for example, client apps can ask users to fix those. The following code validates the object "item":

... JAXBContext jaxbContext = JAXBContext.newInstance(packageName); ObjectFactory itemMaker = new ObjectFactory(); Item item = itemMaker.createItem(); Validator validator = jaxbContext.createValidator(); if(! validator.validate(item)) { System.err.println("Not valid !!!"); } ...

To receive detailed information about errors, you need to register ValidationEventHandler with the Validator, just like you did in Unmarshaller and Marshaller. This is analogous to registering an ErrorHandler for a SAX parser. You can also first marshal an object graph and then validate XML (for example by Java API for validators). But doing so makes it much harder to associate errors with their sources, which makes debugging harder for humans. Validation after marshalling will give you errors like "missing <foo> element," but you can hardly know what is actually wrong in the object graph. Validity is not enforced while you are modifying an object graph; you ALWAYS have to explicitly validate it. To edit a valid object graph into another valid object graph, you may need to go through invalid intermediate states. If validity is enforced on every step of mutation, this becomes impossible. Customization Through the Schema The binding language is an XML based language which defines constructs referred to as binding declarations. A binding declaration can be used to customize the default binding between an XML schema component and its Java representation. The schema for binding declarations is defined in the namespace http://java.sun.com/xml/ns/jaxb. This specification uses the namespace prefix "jaxb" to refer to the namespace of binding declarations. For example:

<jaxb: binding declaration >

http://java.boot.by/wsd-guide/ch05s03.html 8 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

A binding compiler interprets the binding declaration relative to the source schema and a set of default bindings for that schema. Therefore a source schema need not contain a binding declarations for every schema component. This makes the job of a JAXB application developer easier. There are two ways to associate a binding declaration with a schema element:

as part of the source schema (inline annotated schema). external to the source schema in an external binding declaration.

The syntax and semantics of the binding declaration is the same regardless of which of the above two methods is used for customization. Inline Annotated Schema This method of customization utilizes on the appinfo element specified by the XML Schema. A binding declaration is embedded within the appinfo element as illustrated below:

<xs:annotation> <xs:appinfo> <binding declaration> </xs:appinfo> </xs:annotation>

The inline annotation where the binding declaration is used identifies the schema component. Here are the changes you must make to the schema to make JAXB generate java.util.Vector rather than java.util. ArrayList, its default collection (the collecionType value must be either "indexed" or any fully qualified class name that implements java.util.List). Note that the top-level schema tag needs to be changed too:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="1.0"> ... <xs:annotation> <xs:appinfo> <jxb:globalBindings collectionType="java.util.Vector" /> </xs:appinfo> </xs:annotation> ...

The annotation tag introduces a part of the schema that is usually intended for schema processing software. The appinfo tag introduces instructions for a particular processing application (in this case, JAXB's xjc code-generation tool). Usually, each application uses its own namespace, as JAXB has done here. Before customization:
http://java.boot.by/wsd-guide/ch05s03.html 9 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="todolist"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" minOccurs="0" name="item" type="entry"/> </xs:sequence> </xs:complexType> </xs:element> ... </xs:schema>

public class TodolistTypeImpl implements ... { protected com.sun.xml.bind.util.ListImpl _Item = new com.sun.xml.bind.util.ListImpl(new java.util.ArrayList()); ... }

After customization:

<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="1.0"> <xs:annotation> <xs:appinfo> <jxb:globalBindings collectionType="java.util.Vector" /> </xs:appinfo> </xs:annotation> <xs:element name="todolist"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" minOccurs="0" name="item" type="entry"/> </xs:sequence> </xs:complexType> </xs:element> ... </xs:schema>

http://java.boot.by/wsd-guide/ch05s03.html 10 / 11 2004/6/13 12:04:11

Describe the functions and capabilities of JAXB, including the JAXB...o-XML, and the binding and validation mechanisms provided by JAXB.

public class TodolistTypeImpl implements ... { protected com.sun.xml.bind.util.ListImpl _Item = new com.sun.xml.bind.util.ListImpl(new java.util.Vector()); ... }

External Binding Declaration> The external binding declaration format enables customized binding without requiring modification of the source schema. Unlike inline annotation, the remote schema component to which the binding declaration applies must be identified explicitly. The jaxb:bindings element enables the specification of a remote schema context to associate its binding declaration(s) with. Minimally, an external binding declaration follows the following format:

<jaxb:bindings schemaLocation = "xs:anyURI"> <jaxb:bindings node = "xs:string">* <binding declaration> <jaxb:bindings> </jaxb:bindings>

The attributes schemaLocation and node are used to construct a reference to a node in a remote schema. The binding declaration is applied to this node by the binding compiler as if the binding declaration was embedded in the nodes xs:appinfo element. The attribute values are interpreted as follows:

schemaLocation - It is a URI reference to a remote schema. node - It is an XPath 1.0 expression that identifies the schema node within schemaLocation to associate binding declarations with.

Prev Given a scenario, select the proper mechanism for parsing and processing the information in an XML document.

Up Home

Next Use the SAAJ APIs to create and manipulate a SOAP message.

http://java.boot.by/wsd-guide/ch05s03.html 11 / 11 2004/6/13 12:04:11

Use the SAAJ APIs to create and manipulate a SOAP message.

Use the SAAJ APIs to create and manipulate a SOAP message. Prev Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ) Next

Use the SAAJ APIs to create and manipulate a SOAP message.


SAAJ - SOAP with Attachments API for Java - contains APIs for creating and populating SOAP messages which might or might not contain attachments. It also contains APIs for sending point to point, non-provider-based, request and response SOAP messages. SOAP message is made of SOAP Envelope and zero or more attachments. The SOAP Envelope is then made of SOAP Header and SOAP Body. SOAP attachment allows the SOAP message to contain not only the XML data but also nonXML data such as JPG file. And it uses the MIME multipart as container for these non-XML data. The SAAJ API provides the SOAPMessage class to represent a SOAP message, the SOAPPart class to represent the SOAP part, the SOAPEnvelope interface to represent the SOAP envelope, and so on. When you create a new SOAPMessage object, it will automatically have the parts that are required to be in a SOAP message. In other words, a new SOAPMessage object has a SOAPPart object that contains a SOAPEnvelope object. The SOAPEnvelope object in turn automatically contains an empty SOAPHeader object followed by an empty SOAPBody object. If you do not need the SOAPHeader object, which is optional, you can delete it. The rationale for having it automatically included is that more often than not you will need it, so it is more convenient to have it provided. The SOAPHeader object may contain one or more headers with information about the sending and receiving parties. The SOAPBody object, which always follows the SOAPHeader object if there is one, provides a simple way to send information intended for the ultimate recipient. For example, if there is a SOAPFault object, it must be in the SOAPBody object. A SOAP message may include one or more attachment parts in addition to the SOAP part. The SOAP part may contain only XML content; as a result, if any of the content of a message is not in XML format, it must occur in an attachment part. So, if for example, you want your message to contain a binary file, your message must have an attachment part for it. Note that an attachment part can contain any kind of content, so it can contain data in XML format as well. The SAAJ API provides the AttachmentPart class to represent the attachment part of a SOAP message. A SOAPMessage object automatically has a SOAPPart object and its required subelements, but because AttachmentPart objects are optional, you have to create and add them yourself. SAAJ API belongs to javax.xml.soap.* package. SOAPConnection provides request/response SOAP message exchange. SOAPMessage creates and populates SOAP message (consists of SOAPPart and AttachmentPart).

http://java.boot.by/wsd-guide/ch05s04.html 1 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

javax.xml.soap.MessageFactory is a factory for creating SOAP 1.1-based messages.

public abstract class MessageFactory { public static MessageFactory newInstance() throws SOAPException { ... } public abstract SOAPMessage createMessage() throws SOAPException; ... }

javax.xml.soap.SOAPMessage is a Java technology abstraction for a SOAP 1.1 message. Contains EXACTLY ONE SOAPPart and ZERO OR MORE AttachmentParts.

public abstract class SOAPMessage { public abstract SOAPPart getSOAPPart();


http://java.boot.by/wsd-guide/ch05s04.html 2 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

public abstract Iterator getAttachments(); public abstract Iterator getAttachments(MimeHeaders headers); ... }

javax.xml.soap.SOAPPart is the first part of a multi-part message when there are attachments.

public abstract class SOAPPart implements org.w3c.dom.Document { public abstract SOAPEnvelope getEnvelope() throws SOAPException; ... }

javax.xml.soap.AttachmentPart can contain any data (for example: JPEG images, XML business documents, etc.) If a SOAPMessage object has one or more attachments, each AttachmentPart object must have a MIME header to indicate the type of data it contains. It may also have additional MIME headers to identify it or to give its location, which are optional but can be useful when there are multiple attachments. When a SOAPMessage object has one or more AttachmentPart objects, its SOAPPart object may or may not contain message content. Steps of SAAJ Programming 1. Creating a message (SOAPMessage) Use MessageFactory to as a factory of messages. SOAPMessage object has the following:

SOAPPart object
r

SOAPEnvelope object

empty SOAPHeader object empty SOAPBody object

Example:

MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage();

Result:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body/> </SOAP-ENV:Envelope>

2. Accessing elements of a message Approach 1: from SOAPEnvelope object:

http://java.boot.by/wsd-guide/ch05s04.html 3 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody();

Approach 2: from SOAPMessage object:

SOAPHeader header = message.getSOAPHeader(); SOAPBody body = message.getSOAPBody();

3. Adding contents to the body Example:

SOAPBody body = message.getSOAPBody(); SOAPFactory soapFactory = SOAPFactory.newInstance(); Name bodyName = soapFactory.createName("GetLastTradePrice", "m", "http://wombat.ztrade.com"); SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

Will produce following XML:

<m:GetLastTradePrice xmlns:m="http://wombat.ztrade.com"> ... </m:GetLastTradePrice>

Example:

Name name = soapFactory.createName("symbol"); SOAPElement symbol = bodyElement.addChildElement(name); symbol.addTextNode("SUNW");

Generates XML fragment like following:

<symbol>SUNW</symbol>

4. Getting a SOAPConnection object

SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();


http://java.boot.by/wsd-guide/ch05s04.html 4 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

All SOAP messages are sent and received over a connection. With the SAAJ API, the connection is represented by a SOAPConnection object, which goes from the sender directly to its destination. This kind of connection is called a point-to-point connection because it goes from one endpoint to another endpoint. Messages sent using the SAAJ API are called request-response messages. They are sent over a SOAPConnection object with the method call, which sends a message (a request) and then blocks until it receives the reply (a response). 5. Sending a message

// Create an endpint point which is either URL or String type java.net.URL endpoint = new URL("http://wombat.ztrade.com/quotes"); // Send a SOAPMessage (request) and then wait for SOAPMessage (response) SOAPMessage response = connection.call(message, endpoint);

A SAAJ client calls the SOAPConnection method call on a SOAPConnection object to send a message. The call method takes two arguments, the message being sent and the destination to which the message should go. This message is going to the stock quote service indicated by the URL object endpoint. 6. Getting the content of a message

SOAPBody soapBody = response.getSOAPBody(); java.util.Iterator iterator = soapBody.getChildElements(bodyName); SOAPBodyElement bodyElement = (SOAPBodyElement)iterator.next(); String lastPrice = bodyElement.getValue(); System.out.print("The last price for SUNW is "); System.out.println(lastPrice);

In order to access bodyElement, you need to call the method getChildElements on soapBody. Passing bodyName to getChildElements returns a java.util.Iterator object that contains all of the child elements identified by the Name object bodyName. You already know that there is only one, so just calling the method next on it will return the SOAPBodyElement you want. Note that the method Iterator.next() returns a Java Object, so it is necessary to cast the Object it returns to a SOAPBodyElement object before assigning it to the variable bodyElement. Adding content to SOAPHeader To add content to the header, you need to create a SOAPHeaderElement object. As with all new elements, it must have an associated Name object, which you can create using the message's SOAPEnvelope object or a SOAPFactory object. For example, suppose you want to add a conformance claim header to the message to state that your message conforms to the WS-I Basic Profile. The following code fragment retrieves the SOAPHeader object from message and adds a new SOAPHeaderElement object to it. This SOAPHeaderElement object contains the correct qualified name and attribute for a WS-I conformance claim header:

SOAPHeader header = message.getSOAPHeader(); Name headerName = soapFactory.createName("Claim", "wsi", "http://ws-i.org/schemas/conformanceClaim/"); SOAPHeaderElement headerElement = header.addHeaderElement(headerName); headerElement.addAttribute(soapFactory.createName("conformsTo"), "http://ws-i.org/profiles/ basic1.0/");

At this point, header contains the SOAPHeaderElement object headerElement identified by the Name object headerName.
http://java.boot.by/wsd-guide/ch05s04.html 5 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

Note that the addHeaderElement method both creates headerElement and adds it to header. XML fragment generated:

<SOAP-ENV:Header> <wsi:Claim conformsTo="http://ws-i.org/profiles/basic1.0/" xmlns:wsi="http://ws-i.org/schemas/conformanceClaim/"/> </SOAP-ENV:Header>

A conformance claim header has no content. For a different kind of header, you might want to add content to headerElement. The following line of code uses the method addTextNode to do this:

headerElement.addTextNode("order");

Now you have the SOAPHeader object header that contains a SOAPHeaderElement object whose content is "order". Adding content to SOAPBody The process for adding content to the SOAPBody object is the same as the process for adding content to the SOAPHeader object. You access the SOAPBody object, add a SOAPBodyElement object to it, and add text to the SOAPBodyElement object. It is possible to add additional SOAPBodyElement objects, and it is possible to add subelements to the SOAPBodyElement objects with the method addChildElement. For each element or child element, you add content with the method addTextNode. The following example shows adding multiple SOAPElement objects and adding text to each of them:

SOAPBody body = soapFactory.getSOAPBody(); Name bodyName = soapFactory.createName("PurchaseLineItems", "PO", "http://sonata.fruitsgalore.com"); SOAPBodyElement purchaseLineItems = body.addBodyElement(bodyName); Name childName = soapFactory.createName("Order"); SOAPElement order = purchaseLineItems.addChildElement(childName); childName = soapFactory.createName("Product"); SOAPElement product = order.addChildElement(childName); product.addTextNode("Apple"); childName = soapFactory.createName("Price"); SOAPElement price = order.addChildElement(childName); price.addTextNode("1.56");

The code first creates the SOAPBodyElement object purchaseLineItems, which has a fully qualified name associated with it. That is, the Name object for it has a local name, a namespace prefix, and a namespace URI. As you saw earlier, a SOAPBodyElement object is required to have a fully qualified name, but child elements added to it, such as SOAPElement objects, may have Name objects with only the local name.

http://java.boot.by/wsd-guide/ch05s04.html 6 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

The SAAJ code in the preceding example produces the following XML in the SOAP body:

<PO:PurchaseLineItems xmlns:PO="http://www.sonata.fruitsgalore/order"> <Order> <Product>Apple</Product> <Price>1.56</Price> </Order> </PO:PurchaseLineItems>

Adding and accessing attachments Create from AttachmentPart object:

AttachmentPart attachment = message.createAttachmentPart();

AttachmentPart is made of two parts: application-specific content and associated MIME headers (Content-Type):

attachment.setMimeHeader("Content-Type", "application/xml");

> Adding contents to attachment (Option 1: Setting 'Content' and 'ContentId'):

String stringContent = "Update address for Sunny Skies " stringContent += "Inc., to 10 Upbeat Street, Pleasant Grove, CA 95439"; attachment.setContent(stringContent, "text/plain"); attachment.setContentId("update_address"); message.addAttachmentPart(attachment);

The code fragment above shows one of the ways to use the method setContent. This method takes two parameters, the first being a Java Object containing the content and the second being a String giving the content type. The Java Object may be a String, a stream, a javax.xml.transform.Source object, or a javax.activation.DataHandler object. The Java Object being added in the following code fragment is a String, which is plain text, so the second argument must be "text/ plain". The code also sets a content identifier, which can be used to identify this AttachmentPart object. After you have added content to attachment, you need to add it to the SOAPMessage object, which is done in the last line. As with AttachmentPart.setContent(...), the Object may be a String, a stream, a javax.xml.transform.Source object, or a javax. activation.DataHandler object. Adding Contents to Attachment (Option 2: Using DataHandler):

// Create DataHandler object URL url = new URL ("http://greatproducts.com/gizmos/img.jpg"); DataHandler dataHandler = new DataHandler(url); AttachmentPart attachment = message.createAttachmentPart(dataHandler);
http://java.boot.by/wsd-guide/ch05s04.html 7 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

// Note that there is no need to set Content Type attachment.setContentId("attached_image"); message.addAttachmentPart(attachment);

The other method for creating an AttachmentPart object with content takes a DataHandler object, which is part of the JavaBeans Activation Framework (JAF). Using a DataHandler object is fairly straightforward. First you create a java.net. URL object for the file you want to add as content. Then you create a DataHandler object initialized with the URL object: You might note two things about the previous code fragment. First, it sets a header for Content-ID with the method setContentId(...). This method takes a String that can be whatever you like to identify the attachment. Second, unlike the other methods for setting content, this one does not take a String for Content-Type. This method takes care of setting the Content-Type header for you, which is possible because one of the things a DataHandler object does is determine the data type of the file it contains. Accessing attachments:

java.util.Iterator iterator = message.getAttachments(); while (iterator.hasNext()) { AttachmentPart attachment = (AttachmentPart)iterator.next(); String id = attachment.getContentId(); String type = attachment.getContentType(); System.out.print("Attachment " + id + " has content type " + type); if (type == "text/plain") { Object content = attachment.getContent(); System.out.println("Attachment " + "contains:\n" + content); } }

Adding attributes to SOAPHeaderElement SOAP Header attributes: actor and mustUnderstand The attribute actor is optional, but if it is used, it must appear in a SOAPHeaderElement object. Its purpose is to indicate the recipient of a header element. The default actor is the message's ultimate recipient; that is, if no actor attribute is supplied, the message goes directly to the ultimate recipient. An actor is an application that can both receive SOAP messages and forward them to the next actor. The ability to specify one or more actors as intermediate recipients makes it possible to route a message to multiple recipients and to supply header information that applies specifically to each of the recipients. For example, suppose that a message is an incoming purchase order. Its SOAPHeader object might have SOAPHeaderElement objects with actor attributes that route the message to applications that function as the order desk, the shipping desk, the confirmation desk, and the billing department. Each of these applications will take the appropriate action, remove the SOAPHeaderElement objects relevant to it, and send the message on to the next actor. An actor is identified by its URI. For example, the following line of code, in which orderHeader is a SOAPHeaderElement object, sets the actor to the given URI:

orderHeader.setActor("http://gizmos.com/orders");

Additional actors may be set in their own SOAPHeaderElement objects. The following code fragment first uses the
http://java.boot.by/wsd-guide/ch05s04.html 8 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

SOAPMessage object message to get its SOAPHeader object header. Then header creates two SOAPHeaderElement objects, each of which sets its actor attribute:

SOAPHeader header = message.getSOAPHeader(); SOAPFactory soapFactory = SOAPFactory.newInstance(); String nameSpace = "ns"; String nameSpaceURI = "http://gizmos.com/NSURI"; Name order = soapFactory.createName("orderDesk", nameSpace, nameSpaceURI); SOAPHeaderElement orderHeader = header.addHeaderElement(order); orderHeader.setActor("http://gizmos.com/orders"); Name shipping = soapFactory.createName("shippingDesk", nameSpace, nameSpaceURI); SOAPHeaderElement shippingHeader = header.addHeaderElement(shipping); shippingHeader.setActor("http://gizmos.com/shipping");

Retrieving all SOAPHeaderElements with a particular Actor The SOAPHeader interface provides two methods that return a java.util.Iterator object over all of the SOAPHeaderElement objects with an actor that matches the specified actor. The first method, examineHeaderElements, returns an iterator over all of the elements with the specified actor:

// Note that an Actor is identified by an URL Iterator headerElements = header.examineHeaderElements("http://gizmos.com/orders");

The second method, extractHeaderElements, not only returns an iterator over all of the SOAPHeaderElement objects with the specified actor attribute but also detaches them from the SOAPHeader object. So, for example, after the order desk application has done its work, it would call extractHeaderElements to remove all of the SOAPHeaderElement> objects that applied to it:

// Actors are detached from the SOAPHeader object Iterator headerElements = header.extractHeaderElements("http://gizmos.com/orders");

Creating SOAPHeaderElement with mustUnderstand attribute The Java code:

SOAPHeader header = message.getSOAPHeader(); Name name = soapFactory.createName("Transaction", "t", "http://gizmos.com/orders"); SOAPHeaderElement transaction = header.addHeaderElement(name); transaction.setMustUnderstand(true); transaction.addTextNode("5");

The XML fragment:

http://java.boot.by/wsd-guide/ch05s04.html 9 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

<SOAP-ENV:Header> <t:Transaction xmlns:t="http://gizmos.com/orders" SOAP-ENV:mustUnderstand="1"> 5 </t:Transaction> </SOAP-ENV:Header>

SOAPFault object Represents SOAP Fault element in SOAP body. Parties that can generate SOAPFault (for example):

Recipient of a message in point-to-point messaging (Indicates missing address information in purchase order SOAP message) Messaging provider in messaging provider-based messaging (Messaging provider cannot deliver the message due to server failure)

SOAPFault Object Contains: 1. fault code (mandatory) Required in SOAPFault Object (VersionMismatch, MustUnderstand, Client, Server). 2. fault string (mandatory) Human readable explanation of the fault 3. fault actor (conditional) Required if SOAPHeader object has one or more actor attributes 4. Detail object (conditional) Required if the fault is error related to the SOAPBody object. If not present in Client fault, SOAPBody is assumed to be OK. SOAPFault with no Detail object:

// Create SOAPBody object SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope(); SOAPBody body = envelope.getBody(); // Create and fill up SOAPFault object. // Note that Detail object is not being set here since the fault has // nothing to do with SOAPBody SOAPFault fault = body.addFault(); fault.setFaultCode("Server"); fault.setFaultActor("http://gizmos.com/orders"); fault.setFaultString("Server not responding");

SOAPFault with Detail object:

// Create SOAPFault object SOAPFault fault = body.addFault();

http://java.boot.by/wsd-guide/ch05s04.html 10 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

// Set fault code and fault string fault.setFaultCode("Client"); fault.setFaultString("Message does not have necessary info"); // Detail object contains two DetailEntry's Detail detail = fault.addDetail(); Name entryName = envelope.createName("order", "PO", "http://gizmos.com/orders/"); DetailEntry entry = detail.addDetailEntry(entryName); entry.addTextNode("quantity element does not have a value"); Name entryName2 = envelope.createName("confirmation", "PO", "http://gizmos.com/confirm"); DetailEntry entry2 = detail.addDetailEntry(entryName2); entry2.addTextNode("Incomplete address: no zip code");

Retrieving SOAPFault:

// Get SOAPBody object SOAPBody body = newmsg.getSOAPPart().getEnvelope().getBody(); // Check if SOAPFault is present in the message if ( body.hasFault() ) { SOAPFault newFault = body.getFault(); String code = newFault.getFaultCode(); String string = newFault.getFaultString(); String actor = newFault.getFaultActor(); if ( actor != null ) { System.out.println(" fault actor = " + actor); } }

Retrieving Detail Object:

// Get Detail object Detail newDetail = newFault.getDetail(); // Get the list of DetailEntry's if ( newDetail != null) { Iterator it = newDetail.getDetailEntries(); while ( it.hasNext() ) { DetailEntry entry = (DetailEntry)it.next(); String value = entry.getValue(); System.out.println(" Detail entry = " + value); } }

Prev Describe the functions and capabilities of JAXB, including the JAXB process flow, such as XML-toJava and Java-to-XML, and the binding and validation mechanisms provided by JAXB.

Up Home

Next Chapter 6. JAXR

http://java.boot.by/wsd-guide/ch05s04.html 11 / 12 2004/6/13 12:04:19

Use the SAAJ APIs to create and manipulate a SOAP message.

http://java.boot.by/wsd-guide/ch05s04.html 12 / 12 2004/6/13 12:04:19

Chapter 6. JAXR

Chapter 6. JAXR Prev Part I. Exam Objectives Next

Chapter 6. JAXR

Describe the function of JAXR in Web service architectural model, the two basic levels of business registry functionality supported by JAXR, and the function of the basic JAXR business objects and how they map to the UDDI data structures.
1212

Prev Use the SAAJ APIs to create and manipulate a SOAP message.

Up

Next Use JAXR to connect to a UDDI business registry, execute queries to locate services that meet specific requirements, and publish or update information about a business service.

Home

http://java.boot.by/wsd-guide/ch06.html2004/6/13 12:04:21

Use JAXR to connect to a UDDI business registry, execute queries to lo...irements, and publish or update information about a business service.

Use JAXR to connect to a UDDI business registry, execute queries to locate services that meet specific requirements, and publish or update information about a business service. Prev Chapter 6. JAXR Next

Use JAXR to connect to a UDDI business registry, execute queries to locate services that meet specific requirements, and publish or update information about a business service.
1212

Prev Chapter 6. JAXR

Up Home

Next Chapter 7. J2EE Web Services

http://java.boot.by/wsd-guide/ch06s02.html2004/6/13 12:04:23

Chapter 7. J2EE Web Services

Chapter 7. J2EE Web Services Prev Part I. Exam Objectives Next

Chapter 7. J2EE Web Services

Identify the characteristics of and the services and APIs included in the J2EE platform.
1212

Prev Use JAXR to connect to a UDDI business registry, execute queries to locate services that meet specific requirements, and publish or update information about a business service.

Up

Next Explain the benefits of using the J2EE platform for creating and deploying Web service applications.

Home

http://java.boot.by/wsd-guide/ch07.html2004/6/13 12:04:25

Explain the benefits of using the J2EE platform for creating and deploying Web service applications.

Explain the benefits of using the J2EE platform for creating and deploying Web service applications. Prev Chapter 7. J2EE Web Services Next

Explain the benefits of using the J2EE platform for creating and deploying Web service applications.
1212

Prev Chapter 7. J2EE Web Services

Up Home

Next Describe the functions and capabilities of the JAXP, DOM, SAX, JAXR, JAX-RPC, and SAAJ in the J2EE platform.

http://java.boot.by/wsd-guide/ch07s02.html2004/6/13 12:04:27

Describe the functions and capabilities of the JAXP, DOM, SAX, JAXR, JAX-RPC, and SAAJ in the J2EE platform.

Describe the functions and capabilities of the JAXP, DOM, SAX, JAXR, JAX-RPC, and SAAJ in the J2EE platform. Prev Chapter 7. J2EE Web Services Next

Describe the functions and capabilities of the JAXP, DOM, SAX, JAXR, JAX-RPC, and SAAJ in the J2EE platform.
1212

Prev Explain the benefits of using the J2EE platform for creating and deploying Web service applications.

Up Home

Next Describe the role of the WS-I Basic Profile when designing J2EE Web services.

http://java.boot.by/wsd-guide/ch07s03.html2004/6/13 12:04:30

Describe the role of the WS-I Basic Profile when designing J2EE Web services.

Describe the role of the WS-I Basic Profile when designing J2EE Web services. Prev Chapter 7. J2EE Web Services Next

Describe the role of the WS-I Basic Profile when designing J2EE Web services.
1212

Prev Describe the functions and capabilities of the JAXP, DOM, SAX, JAXR, JAX-RPC, and SAAJ in the J2EE platform.

Up Home

Next Chapter 8. Security

http://java.boot.by/wsd-guide/ch07s04.html2004/6/13 12:04:32

Chapter 8. Security

Chapter 8. Security Prev Part I. Exam Objectives Next

Chapter 8. Security

Explain basic security mechanisms including: transport level security, such as basic and mutual authentication and SSL, message level security, XML encryption, XML Digital Signature, and federated identity and trust.
There are two ways with which we can ensure security with Web Services. They are: 1. Security at Transport level 2. Security at XML level Security at Transport level Transport level security is based on Secure Sockets Layer (SSL) or Transport Layer Security (TLS) that runs beneath HTTP. SSL and TLS provide security features including authentication, data protection, and cryptographic token support for secure HTTP connections. To run with HTTPS, the service endpoint address must be in the form https://. The integrity and confidentiality of transport data, including SOAP messages and HTTP basic authentication, is confirmed when you use SSL and TLS. Web services applications can also use Federal Information Processing Standard (FIPS) approved ciphers for more secure TLS connections. Implementing security at the transport level means, securing the network protocol, a Web Service uses for communication. SSL is the Industry accepted standard protocol for secured encrypted communications over TCP/IP. In this model, a Web Service client will use SSL to open a secure socket to a Web Service. The client then sends and receives SOAP messages over this secured socket using HTTPS. The SSL implementation takes care of ensuring privacy by encrypting all the network traffic on the socket. SSL can also authenticate the Web Service to the client using the PKI infrastructure. HTTPS provides encryption, which ensures privacy and message integrity. HTTPS also authenticates through the use of certificates, which can be used on the server side, the client side, or both. HTTPS with server-side certificates is the most common configuration on the Web today. In this configuration, clients can authenticate servers, but servers cannot authenticate clients. However, HTTPS can also be used in conjunction with basic or digest authentication, which provides a weaker form of authentication for clients. HTTP basic authentication uses a user name and password to authenticate a service client to a secure endpoint. A simple way to provide authentication data for the service client is to authenticate to the protected service endpoint to the HTTP basic authentication. The basic authentication is located in the HTTP header that carries the SOAP request. When the application server receives the HTTP request, the user name and password are retrieved and verified using the authentication mechanism specific to the server. Although the basic authentication data is base64-encoded, sending data over HTTPS is recommended. The integrity and confidentiality of the data can be protected by the Secure Sockets Layer (SSL) protocol. Security at XML level There are some standards available for securing Web Services at XML level. They are:

XML Encryption The W3C is coordinating XML Encryption. Its goal is to develop XML syntax for representing encrypted data and to establish procedures for encrypting and decrypting such data. Unlike SSL, with XML Encryption, you can encrypt only the data that needs to be encrypted, for example, only the credit card information in a purchase order XML document:

<purchaseOrder> <name>Alice Smith</name> <address> ... </address> <EncryptedData xmlns='http://www.w3.org/2000/11/temp-xmlenc'> <EncryptionMethod Algorithm="urn:nist-gov:tripledes-ede-cbc"> <s0:IV xmlns:s0='http://somens'>ABCD</s0:IV> </EncryptionMethod> <KeyInfo xmlns='http://www.w3.org/2000/09/xmldsig#'> <KeyName>SharedKey</KeyName> </KeyInfo>
http://java.boot.by/wsd-guide/ch08.html 1 / 12 2004/6/13 12:04:41

Chapter 8. Security

<CipherData>A23B45C56</CipherData> </EncryptedData> <prodNumber>8a32gh19908</prodNumber> <quantity>1</quantity> </purchaseOrder>

In XML Encryption, your plaintext is either an element or that element's content (that's the finest granularity you getyou can't encrypt, say, half an element's content). After encryption, you get an XML element called EncryptedData, containing the ciphertext in Base64-encoded format. That EncryptedData element replaces your plaintext. That is, if you encrypt element bar in this snippet below:

<foo> <bar>secret text</bar> </foo>

you'll get back something like this:

<foo> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns=...> <!-- some info, including the ciphertext --> </EncryptedData> </foo>

Whereas if you encrypt element bar's content, the result will look similar to this:

http://java.boot.by/wsd-guide/ch08.html 2 / 12 2004/6/13 12:04:41

Chapter 8. Security

<foo> <bar> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns=...> <!-- some info, including the ciphertext --> </EncryptedData> </bar> </foo>

Note the difference between the Type attributes in the two examples. From looking at this attribute, we can tell immediately whether the plaintext is an element of just its content. EncryptedData is shown below. In this structure "?" denotes zero or one occurrence; "+" denotes one or more occurrences; "*" denotes zero or more occurrences; and the empty element tag means the element must be empty:

<EncryptedData Id? Type? MimeType? Encoding?> <EncryptionMethod/>? <ds:KeyInfo> <EncryptedKey>? <AgreementMethod>? <ds:KeyName>? <ds:RetrievalMethod>? <ds:*>? </ds:KeyInfo>? <CipherData> <CipherValue>? <CipherReference URI?>? </CipherData> <EncryptionProperties>? </EncryptedData>

EncryptedData's most important element, CipherData, either directly contains the ciphertext in CipherValue, or, if CipherReference> is used, a reference to it. The other elements are optional because usually the receiving party already has the information they contain. For instance, EncryptionMethod lets you specify the algorithm and key size, but usually you and the other party will agree on those beforehand. The same goes for KeyInfo: it gives you the flexibility to give the other party the material to decrypt your message, but you'd probably want to sent it through some out-of-band mechanism. EncryptionProperties> serves as another optional element used for, optional information, such as a date/time stamp. Consider the following fictitious payment information, which includes identification information and information appropriate to a payment method (e.g., credit card, money transfer, or electronic check):

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <CreditCard Limit='5,000' Currency='USD'> <Number>4019 2445 0277 5567</Number> <Issuer>Example Bank</Issuer> <Expiration>04/02</Expiration> </CreditCard> </PaymentInfo>

Credit card number is sensitive information. If the application wishes to keep that information confidential, it can encrypt the CreditCard element:

http://java.boot.by/wsd-guide/ch08.html 3 / 12 2004/6/13 12:04:41

Chapter 8. Security

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <EncryptedData Type='http://www.w3.org/2001/04/xmlenc#Element' xmlns='http://www.w3.org/2001/04/xmlenc#'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </PaymentInfo>

By encrypting the entire CreditCard element from its start to end tags, the identity of the element itself is hidden. The CipherData element contains the encrypted serialization of the CreditCard element. Encrypting XML Element Content (Elements) As an alternative scenario, it may be useful for intermediate agents to know that John used a credit card with a particular limit, but not the card's number, issuer, and expiration date. In this case, the content (character data or children elements) of the CreditCard element is encrypted:

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <CreditCard Limit='5,000' Currency='USD'> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Content'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </CreditCard> </PaymentInfo>

Encrypting XML Element Content (Character Data) We can consider the scenario in which all the information except the actual credit card number can be in the clear, including the fact that the Number element exists:

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <CreditCard Limit='5,000' Currency='USD'> <Number> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Content'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </Number> <Issuer>Example Bank</Issuer> <Expiration>04/02</Expiration> </CreditCard> </PaymentInfo>

http://java.boot.by/wsd-guide/ch08.html 4 / 12 2004/6/13 12:04:41

Chapter 8. Security

Both CreditCard and Number are in the clear, but the character data content of Number is encrypted. Encrypting Arbitrary Data and XML Documents> If the application scenario requires all of the information to be encrypted, the whole document is encrypted as an octet sequence. This applies to arbitrary data including XML documents:

<?xml version='1.0'?> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' MimeType='text/xml'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData>

Super-Encryption: Encrypting EncryptedData An XML document may contain zero or more EncryptedData elements. EncryptedData cannot be the parent or child of another EncryptedData element. However, the actual data encrypted can be anything, including EncryptedData and EncryptedKey elements (i. e., super-encryption). During super-encryption of an EncryptedData or EncryptedKey element, one must encrypt the entire element. Encrypting only the content of these elements, or encrypting selected child elements is an invalid instance under the provided schema. For example, consider the following:

<pay:PaymentInfo xmlns:pay='http://example.org/paymentv2'> <EncryptedData Id='ED1' xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Element'> <CipherData> <CipherValue>originalEncryptedData</CipherValue> </CipherData> </EncryptedData> </pay:PaymentInfo>

A valid super-encryption of "//xenc:EncryptedData[@Id='ED1']" would be:

<pay:PaymentInfo xmlns:pay='http://example.org/paymentv2'> <EncryptedData Id='ED2' xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Element'> <CipherData> <CipherValue>newEncryptedData</CipherValue> </CipherData> </EncryptedData> </pay:PaymentInfo>

where the CipherValue content of 'newEncryptedData' is the base64 encoding of the encrypted octet sequence resulting from encrypting the EncryptedData element with Id='ED1'.

XML Digital Signature XML Digital Signature, like any other digital signing technology, provides authentication, data integrity (tamper-proofing), and nonrepudiation. Of all the XML-based security initiatives, the XML digital signature effort is the furthest along. The W3C (World

http://java.boot.by/wsd-guide/ch08.html 5 / 12 2004/6/13 12:04:41

Chapter 8. Security

Wide Web Consortium) and the IETF (Internet Engineering Task Force) jointly coordinate this effort. The project aims to develop XML syntax for representing digital signatures over any data type. The XML digital signature specification also defines procedures for computing and verifying such signatures. Another important area that XML digital signature addresses is the canonicalization of XML documents. Canonicalization enables the generation of the identical message digest and thus identical digital signatures for XML documents that are syntactically equivalent but different in appearance due to, for example, a different number of white spaces present in the documents. So why XML Digital Signature? XML Digital Signature provides a flexible means of signing and supports diverse sets of Internet transaction models. For example, you can sign individual items or multiple items of an XML document. The document you sign can be local or even a remote object, as long as those objects can be referenced through a URI (Uniform Resource Identifier). You can sign not only XML data, but also non-XML data. A signature can be either enveloped or enveloping, which means the signature can be either embedded in a document being signed or reside outside the document. XML digital signature also allows multiple signing levels for the same content, thus allowing flexible signing semantics. For example, the same content can be semantically signed, cosigned, witnessed, and notarized by different people. The XML signature specification is an extremely flexible tool for generating digitally signed XML documents. It supports signing complete XML documents, parts of XML documents and even non-XML documents. The resulting signature is a well-formed XML fragment that can either be used on its own (a standalone XML document) or embedded within a more complex XML document.

XML Signature Forms: 1. Enveloped An enveloped signature is useful when you have a simple XML document which you to guarantee the integrity of. For example, XKMS messages can use enveloped signatures to convey "trustable" answers from a server back to a client. The signature is over the XML content that contains the signature as an element. The content provides the root XML document element. Obviously, enveloped signatures must take care not to include their own value in the calculation of the SignatureValue. Signature is enveloped within the content been signed:

<doc Id="myID"> <myElement> ...


http://java.boot.by/wsd-guide/ch08.html 6 / 12 2004/6/13 12:04:41

Chapter 8. Security

</myElement> <Signature> ... <Reference URI="#myID"/> ... </Signature> </doc>

2. Enveloping An enveloping signature is useful when the signing facility wants to add its own metadata (such as a timestamp) to a signature - it doesn't have to modify the source document, but can include additional data covered by the signature within the signature document it generates. (An XML Digital Signature can sign multiple objects at once, so enveloping is usually combined with another format). The signature is over content found within an Object element of the signature itself. The Object (or its content) is identified via a Reference (via a URI fragment identifier or transform). Signature envelopes the contents to be signed:

<Signature> ... <Reference URI="#myRefObjectID"> ... </Reference> <Object Id="myRefObjectID"> <doc> <myElement> ... </myElement> ... </doc> </Object> </Signature>

3. Detached A detached signature is useful when you can't modify the source; the downside is that it requires two XML documents - the source and its signature - to be carried together. In other words, it requires a packaging format - enter SOAP headers. The signature is over content external to the Signature element, and can be identified via a URI or transform. Consequently, the signature is "detached" from the content it signs. This definition typically applies to separate data objects, but it also includes the instance where the Signature and data object reside within the same XML document but are sibling elements. Signature is external to the content that is signed:

<Signature> ... <Reference URI="http://www.buy.com/books/purchaseWS"/> ... </Signature>

XML Signatures are applied to arbitrary digital content (data objects) via an indirection. Data objects are digested, the resulting
http://java.boot.by/wsd-guide/ch08.html 7 / 12 2004/6/13 12:04:41

Chapter 8. Security

value is placed in an element (with other information) and that element is then digested and cryptographically signed. XML digital signatures are represented by the Signature element which has the following structure (where "?" denotes zero or one occurrence; "+" denotes one or more occurrences; and "*" denotes zero or more occurrences):

<Signature ID?> <SignedInfo> <CanonicalizationMethod/> <SignatureMethod/> (<Reference URI? > (<Transforms>)? <DigestMethod> <DigestValue> </Reference>)+ </SignedInfo> <SignatureValue> (<KeyInfo>)? (<Object ID?>)* </Signature>

Signatures are related to data objects via URIs. Within an XML document, signatures are related to local data objects via fragment identifiers. Such local data can be included within an enveloping signature or can enclose an enveloped signature. Detached signatures are over external network resources or local data objects that reside within the same XML document as sibling elements; in this case, the signature is neither enveloping (signature is parent) nor enveloped (signature is child). Since a Signature element (and its Id attribute value/name) may co-exist or be combined with other elements (and their IDs) within a single XML document, care should be taken in choosing names such that there are no subsequent collisions that violate the ID uniqueness validity constraint. Simple example:

<Signature Id="MyFirstSignature" xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/> <Reference URI="http://www.w3.org/TR/2000/REC-xhtml1-20000126/"> <Transforms> <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> </SignedInfo> <SignatureValue>MC0CFFrVLtRlk=...</SignatureValue> <KeyInfo> <KeyValue> <DSAKeyValue> <P>...</P><Q>...</Q><G>...</G><Y>...</Y> </DSAKeyValue> </KeyValue> </KeyInfo> </Signature>

The required SignedInfo element is the information that is actually signed. Core validation of SignedInfo consists of two mandatory processes: validation of the signature over SignedInfo and validation of each Reference digest within SignedInfo. Note that the algorithms used in calculating the SignatureValue are also included in the signed information while the SignatureValue element is outside SignedInfo.

http://java.boot.by/wsd-guide/ch08.html 8 / 12 2004/6/13 12:04:41

Chapter 8. Security

The CanonicalizationMethod is the algorithm that is used to canonicalize the SignedInfo element before it is digested as part of the signature operation. Note that this example is not in canonical form. The SignatureMethod is the algorithm that is used to convert the canonicalized SignedInfo into the SignatureValue. It is a combination of a digest algorithm and a key dependent algorithm and possibly other algorithms such as padding, for example RSA-SHA1. The algorithm names are signed to resist attacks based on substituting a weaker algorithm. To promote application interoperability we specify a set of signature algorithms that MUST be implemented, though their use is at the discretion of the signature creator. We specify additional algorithms as RECOMMENDED or OPTIONAL for implementation; the design also permits arbitrary user specified algorithms. Each Reference element includes the digest method and resulting digest value calculated over the identified data object. It also may include transformations that produced the input to the digest operation. A data object is signed by computing its digest value and a signature over that value. The signature is later checked via reference and signature validation. KeyInfo indicates the key to be used to validate the signature. Possible forms for identification include certificates, key names, and key agreement algorithms and information - we define only a few. KeyInfo is optional for two reasons. First, the signer may not wish to reveal key information to all document processing parties. Second, the information may be known within the application's context and need not be represented explicitly. Since KeyInfo is outside of SignedInfo, if the signer wishes to bind the keying information to the signature, a Reference can easily identify and include the KeyInfo as part of the signature. How to Create an XML Signature: 1. Determine which resources are to be signed. This will take the form of identifying the resources through a Uniform Resource Identifier (URI).

"http://www.abccompany.com/index.html" would reference an HTML page on the Web "http://www.abccompany.com/logo.gif" would reference a GIF image on the Web "http://www.abccompany.com/xml/po.xml" would reference an XML file on the Web "http://www.abccompany.com/xml/po.xml#sender1" would reference a specific element in an XML file on the Web

2. Calculate the digest of each resource. In XML signatures, each referenced resource is specified through a Reference element and its digest (calculated on the identified resource and not the Filename>Reference element itself) is placed in a DigestValue child element like:

<Reference URI="http://www.abccompany.com/news/2000/03_27_00.htm"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> <Reference URI="http://www.w3.org/TR/2000/WD-xmldsig-core-20000228/signature-example.xml"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>UrXLDLBIta6skoV5/A8Q38GEw44=</DigestValue> </Reference>

The DigestMethod element identifies the algorithm used to calculate the digest. 3. Collect the Reference elements Collect the Reference elements (with their associated digests) within a SignedInfo element like:

<SignedInfo Id="foobar"> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1" />


http://java.boot.by/wsd-guide/ch08.html 9 / 12 2004/6/13 12:04:41

Chapter 8. Security

<Reference URI="http://www.abccompany.com/news/2000/03_27_00.htm"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> <Reference URI="http://www.w3.org/TR/2000/WD-xmldsig-core-20000228/signature-example.xml"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>UrXLDLBIta6skoV5/A8Q38GEw44=</DigestValue> </Reference> </SignedInfo>

The CanonicalizationMethod element indicates the algorithm was used to canonize the SignedInfo element. Different data streams with the same XML information set may have different textual representations, e.g. differing as to whitespace. To help prevent inaccurate verification results, XML information sets must first be canonized before extracting their bit representation for signature processing. The SignatureMethod element identifies the algorithm used to produce the signature value. 4. Signing Calculate the digest of the SignedInfo element, sign that digest and put the signature value in a SignatureValue element:

<SignatureValue>MC0E LE=</SignatureValue>

5. Add key information If keying information is to be included, place it in a KeyInfo element. Here the keying information contains the X.509 certificate for the sender, which would include the public key needed for signature verification:

<KeyInfo> <X509Data> <X509SubjectName>CN=Ed Simon,O=XMLSec Inc.,ST=OTTAWA,C=CA</X509SubjectName> <X509Certificate>MIID5jCCA0+gA...lVN</X509Certificate> </X509Data> </KeyInfo>

6. Enclose in a Signature element Place the SignedInfo, SignatureValue, and KeyInfo elements into a Signature element. The Signature element comprises the XML signature:

<?xml version="1.0" encoding="UTF-8"?> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo Id="foobar"> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1" /> <Reference URI="http://www.abccompany.com/news/2000/03_27_00.htm"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> <Reference URI="http://www.w3.org/TR/2000/WD-xmldsig-core-20000228/signature-example.xml">
http://java.boot.by/wsd-guide/ch08.html 10 / 12 2004/6/13 12:04:41

Chapter 8. Security

<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>UrXLDLBIta6skoV5/A8Q38GEw44=</DigestValue> </Reference> </SignedInfo> <SignatureValue>MC0E~LE=</SignatureValue> <KeyInfo> <X509Data> <X509SubjectName>CN=Ed Simon,O=XMLSec Inc.,ST=OTTAWA,C=CA</X509SubjectName> <X509Certificate> MIID5jCCA0+gA...lVN </X509Certificate> </X509Data> </KeyInfo> </Signature>

Verifying an XML Signature. A brief description of how to verify an XML signature: 1. Verify the signature of the SignedInfo element. To do so, recalculate the digest of the SignedInfo element (using the digest algorithm specified in the SignatureMethod element) and use the public verification key to verify that the value of the SignatureValue element is correct for the digest of the SignedInfo element. 2. If this step passes, recalculate the digests of the references contained within the SignedInfo element and compare them to the digest values expressed in each Reference element's corresponding DigestValue element.

XKMS (XML Key Management Specification) [see next section] SAML (Security Assertion Markup Language) [see next section]

Federated identity and trust There are two possible identity management architectures, one based on a centralized model and the other, on a federated model. In the centralized model, a single operator performs authentication and authorization by owning and controlling all the identity information. In the federated model, both authentication and authorization tasks are distributed among federated communities. One advantage of the centralized model is that, because a single operator owns and controls everything, constructing and managing the identity network could be easier than with the federated model. However, the centralized model has serious downsides. The most serious one is the dangerous potential for the single operator becoming a tollgate for all transactions over the Internet. For example, the operator might charge a fee for every transaction you make. You might have to pay a few cents or dollars whenever you perform a transaction on eBay. The centralized model has another serious problem: the single operator could represent a single point of security failure or hacker attack. One more reason why the centralized model has not garnered any support, especially from the business community, is because a single operator can take away the most important business assetthat is, customer identity and profile informationfrom an organization. That results in a serious threat to businesses such as banks and brokerage houses whose success depends on their customer information. This information represents one of the most critical assets to a business, one it is not willing to give up to a third party. The federated model, driven by the Liberty Alliance Project, is designed to correct the centralized model's problems. The goal of the Liberty Alliance Project is to create an open standard for identity, authentication, and authorization, which will lower e-commerce costs and accelerate organizations' commercial opportunities, while at the same time increasing customer satisfaction. In a Liberty architecture, organizations can maintain their own customer/employee data while sharing identity data with partners based on their business objectives and customer preferences. In the federated identity management architecture scheme, three roles could exist. The first is the role of a consumer. As a consumer, you can have multiple identity profiles, and you can ask different identity providers to maintain these profiles. For example, you might want your HMO to manage your healthcare profile and your brokerage house to maintain your brokerage profile. In fact, as a consumer, you can pick and choose which identity provider to maintain your profile based on price, credibility, service, and so on. In this model, consumers have a final say in terms of who can access what information. Consumers can be a person, a business, or a software entity. In this case, the HMO and brokerage house play the role of identity provider. Identity providers maintain user profile information and
http://java.boot.by/wsd-guide/ch08.html 11 / 12 2004/6/13 12:04:41

Chapter 8. Security

can interoperate among themselves as long as they have permission to do so from the profile's owner, the consumer. Identity providers are expected to compete for your business in the future in the same way HMOs, banks, and brokerage houses compete for your business today. The third role is that of the service provider, the merchant who has services to offer consumers. Service providers can customize their services to each consumer by retrieving relevant identity profiles from the identity providers. For example, your travel agent might discover your travel and dining preferences from the identity provider you designated to maintain your travel preference. In the phase with no federation (separate login for each site), a consumer must log in separately to each site. This phase will then evolve into an environment where multiple identity networks exist. Within a single identity network, single sign-on can be achieved. However, no network-to-network identity propagation is available at this stage. Eventually, these individually constructed and operating identity networks will work together by exchanging their consumers' identity information, thus providing a truly seamless, global-scale identity network, the Liberty Alliance Project's ultimate goal. The ATM network serves as an analogy for the federated network. Initially, individual banks issued their own ATM cards, and different banks did not interoperate. At this stage, you could not use your ATM card in an ATM machine owned and operated by another bank. These days, you can use your credit card or ATM card in any ATM machine, as long as the bank that owns the machine and your bank are members of the same affiliation network. In the not too distant future, it is not a stretch to think about a single global network to which all banks directly or indirectly belong. The identity network should evolve similarly. One possible challenge of the federated identity network model is that because there are many parties involved, the standard has to be defined in an unambiguous manner. The Liberty Alliance Project addresses that challenge. Federated Identity allows users to link identity information between accounts without centrally storing personal information. Also, the user can control when and how their accounts and attributes are linked and shared between domains and Service Providers, allowing for greater control over their personal data. In practice, this means that users can be authenticated by one company or website and be recognized and delivered personalized content and services in other locations without having to re-authenticate or sign on with a separate username and password. "Circle of Trust" is enabled through federated identity and is defined as a group of service providers that share linked identities and have pertinent business agreements in place regarding how to do business and interact with identities. Once a user has been authenticated by a Circle of Trust identity provider, that individual can be easily recognized and take part in targeted services from other service providers within that Circle of Trust. It should be noted that this concept of trust-based relationships between organizations and their individual or joint customers has existed in the offline business world for years; two common examples would include travel alliances and affiliate business partnerships.

Prev Describe the role of the WS-I Basic Profile when designing J2EE Web services.

Up Home

Next Identify the purpose and benefits of Web services security oriented initiatives and standards such as Username Token Profile, SAML, XACML, XKMS, WSSecurity, and the Liberty Project.

http://java.boot.by/wsd-guide/ch08.html 12 / 12 2004/6/13 12:04:41

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

Identify the purpose and benefits of Web services security oriented initiatives and standards such as Username Token Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project. Prev Chapter 8. Security Next

Identify the purpose and benefits of Web services security oriented initiatives and standards such as Username Token Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.
SAML Security Assertions Markup Language effort, or SAML, which is being defined by the OASIS (Organization for the Advancement of Structured Information) security services technical committee. The committee aims to outline a standard XML framework for exchanging authentication and authorization information. In a nutshell, SAML is an XML-based framework for exchanging security information. As a framework, it deals with three things. First, it defines syntax and semantics of XML-encoded assertion messages. Second, it defines request and response protocols between requesting and asserting parties for exchanging security information. Third, it defines rules for using assertions with standard transport and message frameworks. For example, it defines how SAML assertion messages can transport using SOAP over HTTP. The security information for exchanging is expressed in the form of assertions about subjects, where a subject is an entity (either human or computer) that has an identity in some security domain. A typical example of a subject is a person, identified by his or her email address in a particular Internet DNS domain. Assertions can convey information about authentication acts performed by subjects, attributes of subjects, and authorization decisions about whether subjects are allowed to access certain resources. Assertions are represented as XML constructs and have a nested structure, whereby a single assertion might contain several different internal statements about authentication, authorization, and attributes. Note that assertions containing authentication statements merely describe acts of authentication that happened previously. Assertions are issued by SAML authorities, namely, authentication authorities, attribute authorities, and policy decision points. SAML defines a protocol by which clients can request assertions from SAML authorities and get a response from them. This protocol, consisting of XML-based request and response message formats, can be bound to many different underlying communications and transport protocols; SAML currently defines one binding, to SOAP over HTTP. SAML authorities can use various sources of information, such as external policy stores and assertions that were received as input in requests, in creating their responses. Thus, while clients always consume assertions, SAML authorities can be both producers and consumers of assertions.

http://java.boot.by/wsd-guide/ch08s02.html 1 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

One major design goal for SAML is Single Sign-On (SSO), the ability of a user to authenticate in one domain and use resources in other domains without re-authenticating. However, SAML can be used in various configurations to support additional scenarios as well. Several profiles of SAML are currently being defined that support different styles of SSO and the securing of SOAP payloads. XACML XACML stands for Extensible Access Control Markup Language, and its primary goal is to standardize access control language in XML syntax. A standard access control language results in lower costs because there is no need to develop an application-specific access control language or write the access control policy in multiple languages. Plus, system administrators need to understand only one language. With XACML, it is also possible to compose access control policies from the ones created by different parties. In a nutshell, XACML is a general-purpose access control policy language. This means that it provides a syntax (defined in XML) for managing access to resources. XACML is an OASIS standard that describes both a policy language and an access control decision request/response language (both written in XML). The policy language is used to describe general access control requirements, and has standard extension points for defining new functions, data types, combining logic, etc. The request/response language lets you form a query to ask whether or not a given action should be allowed, and interpret the result. The response always includes an answer about whether the request should be allowed using one of four values: Permit, Deny, Indeterminate (an error occurred or some required value was missing, so a decision cannot be made) or Not Applicable (the request can't be answered by this service). The typical setup is that someone wants to take some action on a resource. They will make a request to whatever actually protects that resource (like a filesystem or a web server), which is called a Policy Enforcement Point (PEP). The PEP will form a request based on the requester's attributes, the resource in question, the action, and other information pertaining to the request. The PEP will then send this request to a Policy Decision Point (PDP), which will look at the request and some policy that applies to the request, and come up with an answer about whether access should be granted. That answer is returned to the PEP, which can then allow or deny access to the requester. Note that the PEP and PDP might both be contained within a single application, or might be distributed across several servers. In addition to providing request/ response and policy languages, XACML also provides the other pieces of this relationship, namely finding a policy that applies to a given request and evaluating the request against that policy to come up with a yes or no answer. There are many existing proprietary and application-specific languages for doing this kind of thing but XACML has several points in its favor:

It's standard. By using a standard language, you're using something that has been reviewed by a large community of experts and users, you don't need to roll your own system each time, and you don't need to think about all the tricky issues involved in designing a new language. Plus, as XACML becomes more widely deployed, it will be

http://java.boot.by/wsd-guide/ch08s02.html 2 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

easier to interoperate with other applications using the same standard language. It's generic. This means that rather than trying to provide access control for a particular environment or a specific kind of resource, it can be used in any environment. One policy can be written which can then be used by many different kinds of applications, and when one common language is used, policy management becomes much easier. It's distributed. This means that a policy can be written which in turn refers to other policies kept in arbitrary locations. The result is that rather than having to manage a single monolithic policy, different people or groups can manage sub-pieces of policies as appropriate, and XACML knows how to correctly combine the results from these different policies into one decision. It's powerful. While there are many ways the base language can be extended, many environments will not need to do so. The standard language already supports a wide variety of data types, functions, and rules about combining the results of different policies. In addition to this, there are already standards groups working on extensions and profiles that will hook XACML into other standards like SAML and LDAP, which will increase the number of ways that XACML can be used.

Every enterprise has a need to secure resources accessed by employees, partners, and customers. For example, browser based access to portals which aggregate resources (web pages, applications, services, etc.) are typical in today's enterprises. Clients send requests to servers for resources, but before a server can return that resource it must determine if the requester is authorized to use the resource. This is where XACML fits in. XACML provides a policy language which allows administrators to define the access control requirements for their application resources. The language and schema support include data types, functions, and combining logic which allow complex (or simple) rules to be defined. XACML also includes an access decision language used to represent the runtime request for a resource. When a policy is located which protects a resource, functions compare attributes in the request against attributes contained in the policy rules ultimately yielding a permit or deny decision. When a client makes a resource request upon a server, the entity charged with access control by enforcing authorization is called the Policy Enforcement Point. In order to enforce policy, this entity will formalize attributes describing the requester at the Policy Information Point and delegate the authorization decision to the Policy Decision Point. Applicable policies are located in a policy store and evaluated at the Policy Decision Point, which then returns the authorization decision. Using this information, the Policy Enforcement Point can deliver the appropriate response to the client. An administrator creates policies in the XACML language. The key top-level element is the PolicySet which aggregates other PolicySet elements or Policy elements. The Policy element is composed principally of Target, Rule and Obligation elements and is evaluated at the Policy Decision Point to yield and access decision. Since multiple policies may be found applicable to an access decision, (and since a single policy can contain multiple Rules) Combining Algorithms are used to reconcile multiple outcomes into a single decision. Standard Combining Algorithms are defined for Deny-Overrides, Permit-Overrides, First Applicable, and Only-One Applicable outcomes. The Target element is used to associate a requested resource to an applicable Policy. It contains conditions that the requesting Subject, Resource, or Action must meet for a Policy Set, Policy, or Rule to be applicable to the resource. The Target includes a build-in scheme for efficient indexing/lookup of Policies. Rules provide the conditions which test the relevant attributes within a Policy. Any number of Rule elements may be used each of which generates a

http://java.boot.by/wsd-guide/ch08s02.html 3 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

true or false outcome. Combining these outcomes yields a single decision for the Policy, which may be "Permit", "Deny", "Indeterminate", or a "NotApplicable" decision. Attributes provide the typed values that represent both a resource requester and the Policy's condition predicates. When describing the requester, attributes may include an issue date and time, issuer identification, and optionally are contained in the Subject, Environment, Resource and Action elements of the access request. The Attribute Designator element is used to retrieve attribute values from a request by specifying the name, type, and issuer of attributes. The SubjectAttributeDesignator, ResourceAttributeDesignator, ActionAttributeDesignator, and EnvironmentAttributeDesignator each retrieves attributes from the respective elements in the request. An AttributeSelector element is used to locate request attributes using XPATH queries. Since queries can return collections of attributes (all of the same primitive type) they are placed in a Bag. Functions are then used to compare attributes contained within a Bag. XKMS (XML Key Management Specification) XKMS stands for the XML Key Management Specification and consists of two parts: XKISS (XML Key Information Service Specification) and XKRSS (XML Key Registration Service Specification). XKISS defines a protocol for resolving or validating public keys contained in signed and encrypted XML documents, while XKRSS defines a protocol for public key registration, revocation, and recovery. The key aspect of XKMS is that it serves as a protocol specification between an XKMS client and an XKMS server in which the XKMS server provides trust services to its clients (in the form of Web services) by performing various PKI (public key infrastructure) operations, such as public key validation, registration, recovery, and revocation on behalf of the clients. Now let's talk about why we need XKMS. To explain it, I must discuss PKI first. PKI proves important for e-commerce and Web services. However, one of the obstacles to PKI's wide adoption is that PKI operations such as public key validation, registration, recovery, and revocation are complex and require large amounts of computing resources, which prevents some applications and small devices such as cell phones from participating in PKI-based ecommerce or Web services transactions. XKMS enables an XKMS server to perform these PKI operations. In other words, applications and small devices, by sending XKMS messages over SOAP (Simple Object Access Protocol), can ask the XKMS server to perform the PKI operations. In this regard, the XKMS server provides trust services to its clients in the form of Web services. [PKI refers to a set of security services for authentication, encryption and digital certificate management under which documents are encrypted with a private key and decrypted using a publicly available key accessible to the recipient via a network. PKI differs from private key technology, like Kerberos, in which a single key that is shared by the sender and receiver is used to encrypt and decrypt a message or document.] XKMS defines a Web services interface to a public key infrastructure. This makes it easy for applications to interface with key-related services, like registration and revocation, and location and validation. Most developers will only ever need to worry about implementing XKMS clients. XKMS server components are mostly implemented by providers of public key infrasructure (PKI) providers, such as Entrust, Baltimore and VeriSign. VeriSign, for example, provides an XKMS responder that can be used to register and query VeriSign's certificate store. Even SSL server ID's can be validated in real-time using the XKMS interface.

http://java.boot.by/wsd-guide/ch08s02.html 4 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

XKMS is a foundational specification for secure Web services, enabling Web services to register and manage cryptographic keys used for digital signatures and encryption. When combined with WS-Security, XKMS makes it easier than ever for developers to deploy enterprise applications in the form of secure Web services available to business partners beyond the firewall. With XKMS, developers can integrate authentication, digital signature, and encryption services, such as certificate processing and revocation status checking, into applications in a matter of hours - without the constraints and complications associated with proprietary PKI software toolkits. XKMS Functions An XKMS-compliant service supports the following operations:

Register: XKMS services can be used to register key pairs for escrow services. Generation of the public key pair may be performed by either the client or the registration service. Once keys are registered, the XKMS-compliant service manages the revocation and recovery of registered keys, whether client- or server-generated. Additional functions are reissue, revoke, and recover. Locate: The Locate service is used to retrieve a public key registered with an XKMScompliant service. The public key can in turn be used to encrypt a document or verify a signature. Validate: The Validate service is used to ensure that a public key registered with an XKMScompliant service is valid, and has not expired or been revoked. The validation service can also be used to check attributes against a public key.

These services can be complimented by having cryptographic capabilities on the client, but client crypto is not required. For example, if a client must generate keys, then some crypto code, resident on the client, performs the key generation. However, the client can just as easily have the XKMS service generate the keys that are subsequently managed through the service. For security, however, most client applications generate a keypair, and then register the public key with the CA. The Benefits of XKMS XKMS provides many benefits. The most important benefits are that XKMS is:

Easy to use: The developer-friendly syntax used in XKMS eliminates the necessity for PKI toolkits and proprietary plug-ins. The XKMS specification allows developers to rapidly implement trust features, incorporating cryptographic support for XML digital signatures and XML encryption using standard XML toolkits. Quick to deploy: By simplifying application development, XKMS removes the need to delay PKI deployment because of , and instead, moves the complexity of PKI to server side components. Developers can now focus on their core competency of developing applications rather than the complexities surrounding a PKI deployment.

http://java.boot.by/wsd-guide/ch08s02.html 5 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

Open: The common XML vocabulary used to describe authentication, authorization, and profile information in XML documents makes XKMS services completely platform, vendor, and transport-protocol-neutral. The XKMS specification has been submitted to the World Wide Web Consortium (W3C) as an open standard for distribution and registration of keys. Ideal for mobile devices: XKMS allow mobile devices to access full-featured PKI through ultra-minimal-footprint client device interfaces. Future-proof: Supports new and emerging PKI developments since the impact of future PKI developments is restricted to server-side components. By restricting the impact of future PKI developments and advancements to the server-side components, XKMS protects developers and applications from becoming incompatible with the latest developments in PKI.

WS-Security The goal of WS-Security is to enable applications to construct secure SOAP message exchanges. The WS-Security (Web Services Security) specification defines a set of SOAP header extensions for end-to-end SOAP messaging security. It supports message integrity and confidentiality by allowing communicating partners to exchange signed and encrypted messages in a Web services environment. Because it is based on XML digital signature and XML Encryption standards, you can digitally sign and encrypt any combination of message parts. WS-Security supports multiple security models, such as username/password-based and certificate-based models. It also supports multiple security technologies, including Kerberos, PKI, SAML, and so on. In addition, it supports multiple security tokens; for example, tokens that contain Kerberos tickets, X.509 certificates, or SAML assertions. The following example illustrates a message with a username security token:

(001) <?xml version="1.0" encoding="utf-8"?> (002) <S:Envelope xmlns:S="http://www.w3.org/2001/12/soap-envelope" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> (003) <S:Header> (004) <m:path xmlns:m="http://schemas.xmlsoap.org/rp/"> (005) <m:action>http://fabrikam123.com/getQuote</m:action> (006) <m:to>http://fabrikam123.com/stocks</m:to> (007) <m:id>uuid:84b9f5d0-33fb-4a81-b02b-5b760641c1d6</m:id> (008) </m:path> (009) <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext"> (010) wsse:UsernameToken Id="MyID"> (011) <wsse:Username>Zoe</wsse:Username> (012) </wsse:UsernameToken> (013) <ds:Signature> (014) <ds:SignedInfo> (015) <ds:CanonicalizationMethod Algorithm="..."/> (016) <ds:SignatureMethod Algorithm="..."/>
http://java.boot.by/wsd-guide/ch08s02.html 6 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

(017) <ds:Reference URI="#MsgBody"> (018) <ds:DigestMethod Algorithm="..."/> (019) <ds:DigestValue>LyLsF0Pi4wPU...</ds:DigestValue> (020) </ds:Reference> (021) </ds:SignedInfo> (022) <ds:SignatureValue>DJbchm5gK...</ds:SignatureValue> (023) <ds:KeyInfo> (024) <wsse:SecurityTokenReference> (025) <wsse:Reference URI="#MyID"/> (026) </wsse:SecurityTokenReference> (027) </ds:KeyInfo> (028) </ds:Signature> (029) </wsse:Security> (030) </S:Header> (031) <S:Body Id="MsgBody"> (032) <tru:StockSymbol xmlns:tru="http://fabrikam123.com/payloads"> QQQ </tru:StockSymbol> (033) </S:Body> (034) </S:Envelope>

The first two lines start the SOAP envelope. Line (003) begins the headers that are associated with this SOAP message. Lines (004) to (008) specify how to route this message (as defined in WS-Routing). Line (009) starts the Security header that we define in WS-Security specification. This header contains security information for an intended receiver. This element continues until line (029). Lines (010) to (012) specify a security token that is associated with the message. In this case, it defines username of the client using the UsernameToken. Note that here we assume the service knows the password - in other words, it is a shared secret. Lines (013) to (028) specify a digital signature. This signature ensures the integrity of the signed elements (that they aren't modified). The signature uses the XML Signature specification. In this example, the signature is based on a key generated from the users' password; typically stronger signing mechanisms would be used. Lines (014) to (021) describe the digital signature. Line (015) specifies how to canonicalize (normalize) the data that is being signed. Lines (017) to (020) select the elements that are signed. Specifically, line (017) indicates that the S:Body element is signed. In this example only the message body is signed; typically additional elements of the message, such as parts of the routing header, should be included in
http://java.boot.by/wsd-guide/ch08s02.html 7 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

the signature. Line (022) specifies the signature value of the canonicalized form of the data that is being signed as defined in the XML Signature specification. Lines (023) to (027) provide a hint as to where to find the security token associated with this signature. Specifically, lines (024) to (025) indicate that the security token can be found at (pulled from) the specified URL. Lines (031) to (033) contain the body (payload) of the SOAP message. Protecting the message content from being intercepted (confidentiality) or illegally modified (integrity) are primary security concerns. WS-Security specification provides a means to protect a message by encrypting and/or digitally signing a body, a header, an attachment, or any combination of them (or parts of them). Message integrity is provided by leveraging XML Signature in conjunction with security tokens to ensure that messages are transmitted without modifications. The integrity mechanisms are designed to support multiple signatures, potentially by multiple actors, and to be extensible to support additional signature formats. Message confidentiality leverages XML Encryption in conjunction with security tokens to keep portions of a SOAP message confidential. The encryption mechanisms are designed to support additional encryption processes and operations by multiple actors. The Security header block provides a mechanism for attaching security-related information targeted at a specific receiver (SOAP actor). This MAY be either the ultimate receiver of the message or an intermediary. Consequently, this header block MAY be present multiple times in a SOAP message. An intermediary on the message path MAY add one or more new sub-elements to an existing Security header block if they are targeted for the same SOAP node or it MAY add one or more new headers for additional targets. As stated, a message MAY have multiple Security header blocks if they are targeted for separate receivers. However, only one Security header block can omit the S:actor attribute and no two Security header blocks can have the same value for S:actor. Message security information targeted for different receivers MUST appear in different Security header blocks. The Security header block without a specified S:actor can be consumed by anyone, but MUST NOT be removed prior to the final destination as determined by WS-Routing. As elements are added to the Security header block, they should be prepended to the existing elements. As such, the Security header block represents the signing and encryption steps the message sender took to create the message. This prepending rule ensures that the receiving application MAY process sub-elements in the order they appear in the Security header block, because there will be no forward dependency among the sub-elements. Note that WSSecurity specification does not impose any specific order of processing the sub-elements. The receiving application can use whatever policy is needed. When a sub-element refers to a key carried in another sub-element (for example, a signature sub-element that refers to a binary security token sub-element that contains the X.509 certificate used for the signature), the keybearing security token SHOULD be prepended subsequent to the key-using sub-element being added, so that the key material appears before the key-using sub-element. The following illustrates the syntax of this header:

http://java.boot.by/wsd-guide/ch08s02.html 8 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

<S:Envelope> <S:Header> ... <Security S:actor="..." S:mustUnderstand="..."> <!-actor attribute is optional, however no two instances of the header block may omit an actor or specify the same actor --> ... </Security> ... </S:Header> ... </S:Envelope>

The following sample message illustrates the use of security tokens, signatures, and encryption. For this example, we use a fictitious "RoutingTransform" that selects the immutable routing headers along with the message body:

(001) <?xml version="1.0" encoding="utf-8"?> (002) <S:Envelope xmlns:S="http://www.w3.org/2001/12/soap-envelope" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"> (003) <S:Header> (004) <m:path xmlns:m="http://schemas.xmlsoap.org/rp/"> (005) <m:action>http://fabrikam123.com/getQuote</m:action> (006) <m:to>http://fabrikam123.com/stocks</m:to> (007) <m:from>mailto:johnsmith@fabrikam123.com</m:from> (008) <m:id>uuid:84b9f5d0-33fb-4a81-b02b-5b760641c1d6</m:id> (009) </m:path> (010) <wsse:Security> (011) <wsse:BinarySecurityToken ValueType="wsse:X509v3" Id="X509Token" EncodingType="wsse:Base64Binary"> (012) MIIEZzCCA9CgAwIBAgIQEmtJZc0rqrKh5i... (013) </wsse:BinarySecurityToken> (014) <xenc:EncryptedKey> (015) <xenc:EncryptionMethod Algorithm= "http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> (016) <ds:KeyInfo>
http://java.boot.by/wsd-guide/ch08s02.html 9 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

(017) (018) (019) (020) (021) (022) (023) (024) (025) (026) (027) (028) (029) (030) (031) (032) (033) (034) (035) (036) (037) (038) (039) (040) (041) (042) (043) (044) (045) (046) (047) (048) (049) (050) (051) (052) (053)

(054)

<ds:KeyName>CN=Hiroshi Maruyama, C=JP</ds:KeyName> </ds:KeyInfo> <xenc:CipherData> <xenc:CipherValue>d2FpbmdvbGRfE0lm4byV0... </xenc:CipherValue> </xenc:CipherData> <xenc:ReferenceList> <xenc:DataReference URI="#enc1"/> </xenc:ReferenceList> </xenc:EncryptedKey> <ds:Signature> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <ds:Reference> <ds:Transforms> <ds:Transform Algorithm="http://...#RoutingTransform"/> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <ds:DigestValue>LyLsF094hPi4wPU... </ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue> Hp1ZkmFZ/2kQLXDJbchm5gK... </ds:SignatureValue> <ds:KeyInfo> <wsse:SecurityTokenReference> <wsse:Reference URI="#X509Token"/> </wsse:SecurityTokenReference> </ds:KeyInfo> </ds:Signature> </wsse:Security> </S:Header> <S:Body> <xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" Id="enc1"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#3des-cbc"/>

http://java.boot.by/wsd-guide/ch08s02.html 10 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

(055) <xenc:CipherData> (056) <xenc:CipherValue>d2FpbmdvbGRfE0lm4byV0... (057) </xenc:CipherValue> (058) </xenc:CipherData> (059) </xenc:EncryptedData> (060) </S:Body> (061) </S:Envelope>

Lines (003)-(051) contain the SOAP message headers. Lines (004)-(009) specify the message routing information (as define in WS-Routing). In this case we are sending the message to the http://fabrikam123.com/stocks service requesting the "getQuote" action. Lines (010)-(050) represent the Security header block. This contains the security-related information for the message. Lines (011)-(013) specify a security token that is associated with the message. In this case, it specifies an X.509 certificate that is encoded as Base64. Line (012) specifies the actual Base64 encoding of the certificate. Lines (014)-(026) specify the key that is used to encrypt the body of the message. Since this is a symmetric key, it is passed in an encrypted form. Line (015) defines the algorithm used to encrypt the key. Lines (016)-(018) specify the name of the key that was used to encrypt the symmetric key. Lines (019)-(022) specify the actual encrypted form of the symmetric key. Lines (023)-(025) identify the encryption block in the message that uses this symmetric key. In this case it is only used to encrypt the body (Id="enc1"). Lines (027)-(049) specify the digital signature. In this example, the signature is based on the X.509 certificate. Lines (028)-(040) indicate what is being signed. Specifically, Line (029) indicates the canonicalization algorithm (exclusive in this example). Line (030) indicate the signature algorithm (rsa over sha1 in this case). Lines (031)-(039) identify the parts of the message that are being signed. Specifically, Line (033) identifies a "transform". This fictitious transforms selects the immutable portions of the routing header and the message body. Line (034) specifies the canonicalization algorithm to use on the selected message parts from line (033). Line (036) indicates the digest algorithm use on the canonicalized data. Line (037) specifies the digest value resulting from the specified algorithm on the canonicalized data. Lines (041)-(043) indicate the actual signature value - specified in Line (042). Lines (044)-(048) indicate the key that was used for the signature. In this case, it is the X.509 certificate included in the message. Line (046) provides a URI link to the Lines (011)-(013).
http://java.boot.by/wsd-guide/ch08s02.html 11 / 12 2004/6/13 12:04:46

Identify the purpose and benefits of Web services security oriented... Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.

The body of the message is represented by Lines (052)-(060). Lines (053)-(059) represent the encrypted metadata and form of the body using XML Encryption. Line (053) indicates that the "element value" is being replaced and identifies this encryption. Line (054) specifies the encryption algorithm - Triple-DES in this case. Lines (055)(058) contain the actual cipher text (i.e., the result of the encryption). Note that we don't include a reference to the key as the key references this encryption - Line (024). Liberty Project

Create an open standard for identity, authentication and authorization. Objective: lower costs, accelerate commercial opportunities, and increase customer satisfaction Federated standard will enable every business to:
r r r

Maintain their own customer/employee/device data. Tie data to an individuals or businesss identity. Share data with partners according to its business objectives, and customers preferences.

Prev Chapter 8. Security

Up

Next Given a scenario, implement J2EE based web service web-tier and/or EJBtier basic security mechanisms, such as mutual authentication, SSL, and access control.

Home

http://java.boot.by/wsd-guide/ch08s02.html 12 / 12 2004/6/13 12:04:47

Given a scenario, implement J2EE based web service web-tier and/or E...mechanisms, such as mutual authentication, SSL, and access control.

Given a scenario, implement J2EE based web service web-tier and/or EJB-tier basic security mechanisms, such as mutual authentication, SSL, and access control. Prev Chapter 8. Security Next

Given a scenario, implement J2EE based web service web-tier and/or EJB-tier basic security mechanisms, such as mutual authentication, SSL, and access control.
JAX-RPC implementation has to support HTTP Basic authentication. JAX-RPC specifciation does not require JAX-RPC implementation to support certificate based mutual authentication using HTTP/S (HTTP over SSL). HTTP Basic Authentication 1. Add the appropriate security elements to the web.xml deployment descriptor:

<?xml version="1.0"?> <web-app version="2.4" ...> <display-name>Basic Authentication Security Example</display-name> <security-constraint> <web-resource-collection> <web-resource-name>SecureHello</web-resource-name> <url-pattern>/hello</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> </login-config> <security-role>
http://java.boot.by/wsd-guide/ch08s03.html 1 / 3 2004/6/13 12:04:50

Given a scenario, implement J2EE based web service web-tier and/or E...mechanisms, such as mutual authentication, SSL, and access control.

<role-name>admin</role-name> </security-role> </web-app>

2. Set security properties in the client code:

try { Stub stub = createProxy(); stub._setProperty(javax.xml.rpc.Stub.USERNAME_PROPERTY, username); stub._setProperty(javax.xml.rpc.Stub.PASSWORD_PROPERTY, password); stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, endpointAddress); HelloIF hello = (HelloIF)stub; System.out.println(hello.sayHello(" Duke (secure)" )); } catch (Exception ex) { ex.printStackTrace(); }

Mutual Authentication 1. Configure SSL connector 2. Add the appropriate security elements to the web.xml deployment descriptor:

<?xml version="1.0"?> <web-app version="2.4" ...> <display-name>Secure Mutual Authentication Example</display-name> <security-constraint> <web-resource-collection> <web-resource-name>SecureHello</web-resource-name> <url-pattern>/hello</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint>
http://java.boot.by/wsd-guide/ch08s03.html 2 / 3 2004/6/13 12:04:50

Given a scenario, implement J2EE based web service web-tier and/or E...mechanisms, such as mutual authentication, SSL, and access control.

<login-config> <auth-method>CLIENT-CERT</auth-method> </login-config> </web-app>

3. Set Security Properties in client code:

try { Stub stub = createProxy(); System.setProperty("javax.net.ssl.keyStore", keyStore); System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword); System.setProperty("javax.net.ssl.trustStore", trustStore); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, endpointAddress); HelloIF hello = (HelloIF)stub; System.out.println(hello.sayHello(" Duke! secure!")); } catch (Exception ex) { ex.printStackTrace(); }

Prev Identify the purpose and benefits of Web services security oriented initiatives and standards such as Username Token Profile, SAML, XACML, XKMS, WSSecurity, and the Liberty Project.

Up

Next Describe factors that impact the security requirements of a Web service, such as the relationship between the client and service provider, the type of data being exchanged, the message format, and the transport mechanism.

Home

http://java.boot.by/wsd-guide/ch08s03.html 3 / 3 2004/6/13 12:04:50

Describe factors that impact the security requirements of a Web servi...ta being exchanged, the message format, and the transport mechanism.

Describe factors that impact the security requirements of a Web service, such as the relationship between the client and service provider, the type of data being exchanged, the message format, and the transport mechanism. Prev Chapter 8. Security Next

Describe factors that impact the security requirements of a Web service, such as the relationship between the client and service provider, the type of data being exchanged, the message format, and the transport mechanism.
1212

Prev Given a scenario, implement J2EE based web service web-tier and/or EJB-tier basic security mechanisms, such as mutual authentication, SSL, and access control.

Up

Next Chapter 9. Developing Web Services

Home

http://java.boot.by/wsd-guide/ch08s04.html2004/6/13 12:04:54

Chapter 9. Developing Web Services

Chapter 9. Developing Web Services Prev Part I. Exam Objectives Next

Chapter 9. Developing Web Services

Describe the steps required to configure, package, and deploy J2EE Web services and service clients, including a description of the packaging formats, such as .ear, .war, .jar, deployment descriptor settings, the associated Web Services description file, RPC mapping files, and service reference elements used for EJB and servlet endpoints.
1212

Prev Describe factors that impact the security requirements of a Web service, such as the relationship between the client and service provider, the type of data being exchanged, the message format, and the transport mechanism.

Up

Next Given a set of requirements, develop code to process XML files using the SAX, DOM, XSLT, and JAXB APIs.

Home

http://java.boot.by/wsd-guide/ch09.html2004/6/13 12:04:58

Given a set of requirements, develop code to process XML files using the SAX, DOM, XSLT, and JAXB APIs.

Given a set of requirements, develop code to process XML files using the SAX, DOM, XSLT, and JAXB APIs. Prev Chapter 9. Developing Web Services Next

Given a set of requirements, develop code to process XML files using the SAX, DOM, XSLT, and JAXB APIs.
1212

Prev Chapter 9. Developing Web Services

Up Home

Next Given an XML schema for a document style Web service create a WSDL file that describes the service and generate a service implementation.

http://java.boot.by/wsd-guide/ch09s02.html2004/6/13 12:05:00

Given an XML schema for a document style Web service create a WSDL file that describes the service and generate a service implementation.

Given an XML schema for a document style Web service create a WSDL file that describes the service and generate a service implementation. Prev Chapter 9. Developing Web Services Next

Given an XML schema for a document style Web service create a WSDL file that describes the service and generate a service implementation.
1212

Prev Given a set of requirements, develop code to process XML files using the SAX, DOM, XSLT, and JAXB APIs.

Up Home

Next Given a set of requirements, develop code to create an XML-based, document style, Web service using the JAX-RPC APIs.

http://java.boot.by/wsd-guide/ch09s03.html2004/6/13 12:05:02

Given a set of requirements, develop code to create an XML-based, document style, Web service using the JAX-RPC APIs.

Given a set of requirements, develop code to create an XML-based, document style, Web service using the JAX-RPC APIs. Prev Chapter 9. Developing Web Services Next

Given a set of requirements, develop code to create an XML-based, document style, Web service using the JAX-RPC APIs.
1212

Prev Given an XML schema for a document style Web service create a WSDL file that describes the service and generate a service implementation.

Up Home

Next Implement a SOAP logging mechanism for testing and debugging a Web Service application using J2EE Web Service APIs.

http://java.boot.by/wsd-guide/ch09s04.html2004/6/13 12:05:05

Implement a SOAP logging mechanism for testing and debugging a Web Service application using J2EE Web Service APIs.

Implement a SOAP logging mechanism for testing and debugging a Web Service application using J2EE Web Service APIs. Prev Chapter 9. Developing Web Services Next

Implement a SOAP logging mechanism for testing and debugging a Web Service application using J2EE Web Service APIs.
1212

Prev Given a set of requirements, develop code to create an XML-based, document style, Web service using the JAX-RPC APIs.

Up Home

Next Given a set of requirements, develop code to handle system and service exceptions and faults received by a Web services client.

http://java.boot.by/wsd-guide/ch09s05.html2004/6/13 12:05:07

Given a set of requirements, develop code to handle system and service exceptions and faults received by a Web services client.

Given a set of requirements, develop code to handle system and service exceptions and faults received by a Web services client. Prev Chapter 9. Developing Web Services Next

Given a set of requirements, develop code to handle system and service exceptions and faults received by a Web services client.
1212

Prev Implement a SOAP logging mechanism for testing and debugging a Web Service application using J2EE Web Service APIs.

Up Home

Next Chapter 10. General Design and Architecture

http://java.boot.by/wsd-guide/ch09s06.html2004/6/13 12:05:10

Chapter 10. General Design and Architecture

Chapter 10. General Design and Architecture Prev Part I. Exam Objectives Next

Chapter 10. General Design and Architecture

Describe the characteristics of a service oriented architecture and how Web Services fits to this model.
1212

Prev Given a set of requirements, develop code to handle system and service exceptions and faults received by a Web services client.

Up

Next Given a scenario, design a J2EE service using the Business Delegate, Service Locator, and/or Proxy client-side design patterns and the Adapter, Command, Web Service Broker, and/or Faade server-side patterns.

Home

http://java.boot.by/wsd-guide/ch10.html2004/6/13 12:05:13

Given a scenario, design a J2EE service using the Business Delegate, ...er, Command, Web Service Broker, and/or Faade server-side patterns.

Given a scenario, design a J2EE service using the Business Delegate, Service Locator, and/or Proxy client-side design patterns and the Adapter, Command, Web Service Broker, and/or Faade server-side patterns. Prev Chapter 10. General Design and Architecture Next

Given a scenario, design a J2EE service using the Business Delegate, Service Locator, and/or Proxy client-side design patterns and the Adapter, Command, Web Service Broker, and/or Faade server-side patterns.
Business Delegate Problem:

You want to hide clients from the complexity of remote communication with business service components. Business components are exposed to clients leading to coupling and fine-grained access.

Forces:

Clients need access to business services. Complexity of remote objects. You want to avoid unnecessary invocation of remote services. Clients and business components become tightly coupled. You want to minimize coupling between clients and the business services, thus hiding the underlying implementation details of the service, such as lookup and access. Business services APIs may change. You want to hide the details of service creation, reconfiguration, and invocation retries from the clients.

Solution:

Use a Business Delegate to encapsulate access to a business service. The Business Delegate hides the implementation details of the business service, such as lookup and access mechanisms. Use a Business Delegate to reduce coupling between presentation-tier clients and business services:

Consequences:

Reduces coupling, increases maintainability. Implements failure recovery: Retry or Synchronize.

http://java.boot.by/wsd-guide/ch10s02.html 1 / 7 2004/6/13 12:05:19

Given a scenario, design a J2EE service using the Business Delegate, ...er, Command, Web Service Broker, and/or Faade server-side patterns.

Translates network (System) Exceptions to Business service Exceptions. Exposes simpler, uniform Interface to the business tier. Performance enhancing cache. Hides complexities of remote services.

Service Locator Problem:

Clients want to transparently locate business components and services in a uniform manner.

Forces:

Vendor dependencies are exposed to the clients, we want to encapsulate vendor dependencies for registry implementations, and hide the dependency and complexity from the clients. Complexity and duplication of lookup and creation. Clients want to centralize and reuse the implementation of lookup mechanisms. Clients may need to reestablish connection to a previously accessed business object. Clients want to avoid performance overhead related to initial context creation and service lookups.

Solution:

Use a Service Locator to implement and encapsulate service and component lookup. A Service Locator hides the complexities of Initial Context creation, lookup, and object re-creation:

Consequences:

Abstracts complexity of lookups. Uniform lookup for all clients. Improves network performance. Improves client performance by caching.

Proxy

http://java.boot.by/wsd-guide/ch10s02.html 2 / 7 2004/6/13 12:05:19

Given a scenario, design a J2EE service using the Business Delegate, ...er, Command, Web Service Broker, and/or Faade server-side patterns.

Problem:

Provide a stand-in or placeholder to another object, in order to control access to it.

Forces:

The The The You

desired object may be inaccessible (if it exists in a different address space). desired object may be expensive to instantiate and you want to delay its creation until absolutely necessary. desired object may need to be protected from unauthorized access. may need to perform special actions upon accessing the desired object.

Solution:

Use a Proxy to provide a separate implementation of interface and working code for location transparency:

Consequences:

Decouples interface and implementation by providing two objects. Proxy handles all incoming requests to the object, it knows how to contact the object if it is remotely located. Proxy passes along all authorized communication to the object (and prevents unauthorized communication). If the Implementation class changes, the Proxy remains the same. An example is the EJB's Remote Interface.

Session Faade Problem:

Tight coupling between clients and business tier; fine-grained access.

Forces:

You want to avoid giving clients direct access to business-tier components, to prevent tight coupling with the clients. Numerous business objects are exposed over the network. No uniform access to business tier. You want to centralize and aggregate all business logic that needs to be exposed to remote clients. Clients are exposed to complex interactions and interdependencies of business objects. You want to hide the complex interactions and interdependencies between business components and services to improve manageability, centralize logic, increase flexibility, and improve ability to cope with changes.

Solution:

Use a Session Faade to encapsulate business-tier components and expose a coarse-grained service to remote clients. Clients access a Session Faade instead of accessing business components directly. Use a Session Faade to encapsulate the complexity of interactions:

http://java.boot.by/wsd-guide/ch10s02.html 3 / 7 2004/6/13 12:05:19

Given a scenario, design a J2EE service using the Business Delegate, ...er, Command, Web Service Broker, and/or Faade server-side patterns.

Consequences:

Controller layer for business tier. Uniform exposure of business components. Reduces coupling between the tiers. Provides a uniform coarse-grained access. Centralizes business logic. Centralizes security management. Centralizes transaction control. Exposes fewer remote interfaces to clients. Improves performance, reduces fine-grained remote methods.

Adapter (Wrapper) Problem:

Convert the interface of a class into another interface clients expect.

Forces:

A potentially reusable class may not have the appropriate interface required by the particular application domain.

Solution:

Adapter lets classes work together that could not otherwise because of incompatible interfaces. Use an Adapter pattern to adapt one interface to another:

http://java.boot.by/wsd-guide/ch10s02.html 4 / 7 2004/6/13 12:05:19

Given a scenario, design a J2EE service using the Business Delegate, ...er, Command, Web Service Broker, and/or Faade server-side patterns.

Consequences:

Adapter pattern may come from Adapter pattern Adapter pattern

maps the interface of one class onto another so that they can work together. These incompatible classes different libraries or frameworks. can be used to expose existing component as Web Service. helps resolve integration issues.

Command Problem:

There are a lot of similar methods, and the interface to implement that kind of object is becoming heavy.

Forces:

Too many public methods for other objects to call. An interface that is unworkable and always changing. You feel that a method name must include prose describing the exact action, and this is preventing layering your code.

Solution:

Encapsulate a request as a Command object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

http://java.boot.by/wsd-guide/ch10s02.html 5 / 7 2004/6/13 12:05:19

Given a scenario, design a J2EE service using the Business Delegate, ...er, Command, Web Service Broker, and/or Faade server-side patterns.

Consequences:

Command pattern is an example of pluggable behavior that enforce client access to Web Services. The Command pattern is commonly used for gathering requests from client objects and packaging them into a single object for processing. The Command pattern allows for having well defined command interfaces that are implemented by the object that provides the processing for the client requests packaged as commands. Command design pattern provides a convenient way to store and execute an "Undo" function. Command decouples the object that invokes the operation from the one that knows how to perform it. Commands can be manipulated and extended like any other object. Commands can be made into a composite command. Commands can be stored. Since a command encapsulates all the data for a given request, it can be created and initialized at one point and applied at another.

Web Service Broker Problem:

You want to provide access to one or more services using XML and web protocols.

Forces:

You want to reuse and expose existing services to clients. You want to monitor and potentially limit the usage of exposed services, based on your business requirements and system resource usage. Your services must be exposed using open standards to enable integration of heterogeneous applications. You want to bridge the gap between business requirements and existing service capabilities.

Solution:

Use a Web Service Broker to expose and broker one or more services in your application to external clients as a Web Service using XML and standard web protocols:

http://java.boot.by/wsd-guide/ch10s02.html 6 / 7 2004/6/13 12:05:19

Given a scenario, design a J2EE service using the Business Delegate, ...er, Command, Web Service Broker, and/or Faade server-side patterns.

Consequences:

Introduces a layer between client and service. Existing remote Session Faades need be refactored to support local access. Network performance may be impacted due to web protocols. Coordinates interactions among one or more services, aggregates responses and may demarcate and compensate transactions.

Prev Chapter 10. General Design and Architecture

Up

Next Describe alternatives for dealing with issues that impact the quality of service provided by a Web service and methods to improve the system reliability, maintainability, security, and performance of a service.

Home

http://java.boot.by/wsd-guide/ch10s02.html 7 / 7 2004/6/13 12:05:19

Describe alternatives for dealing with issues that impact the quality of...m reliability, maintainability, security, and performance of a service.

Describe alternatives for dealing with issues that impact the quality of service provided by a Web service and methods to improve the system reliability, maintainability, security, and performance of a service. Prev Chapter 10. General Design and Architecture Next

Describe alternatives for dealing with issues that impact the quality of service provided by a Web service and methods to improve the system reliability, maintainability, security, and performance of a service.
1212

Prev Given a scenario, design a J2EE service using the Business Delegate, Service Locator, and/or Proxy client-side design patterns and the Adapter, Command, Web Service Broker, and/or Faade server-side patterns.

Up

Next Describe how to handle the various types of return values, faults, errors, and exceptions that can occur during a Web service interaction.

Home

http://java.boot.by/wsd-guide/ch10s03.html2004/6/13 12:05:21

Describe how to handle the various types of return values, faults, errors, and exceptions that can occur during a Web service interaction.

Describe how to handle the various types of return values, faults, errors, and exceptions that can occur during a Web service interaction. Prev Chapter 10. General Design and Architecture Next

Describe how to handle the various types of return values, faults, errors, and exceptions that can occur during a Web service interaction.
1212

Prev Describe alternatives for dealing with issues that impact the quality of service provided by a Web service and methods to improve the system reliability, maintainability, security, and performance of a service.

Up

Next Describe the role that Web services play when integrating data, application functions, or business processes in a J2EE application.

Home

http://java.boot.by/wsd-guide/ch10s04.html2004/6/13 12:05:24

Describe the role that Web services play when integrating data, application functions, or business processes in a J2EE application.

Describe the role that Web services play when integrating data, application functions, or business processes in a J2EE application. Prev Chapter 10. General Design and Architecture Next

Describe the role that Web services play when integrating data, application functions, or business processes in a J2EE application.
1212

Prev Describe how to handle the various types of return values, faults, errors, and exceptions that can occur during a Web service interaction.

Up Home

Next Describe how to design a stateless Web service that exposes the functionality of a stateful business process.

http://java.boot.by/wsd-guide/ch10s05.html2004/6/13 12:05:25

Describe how to design a stateless Web service that exposes the functionality of a stateful business process.

Describe how to design a stateless Web service that exposes the functionality of a stateful business process. Prev Chapter 10. General Design and Architecture Next

Describe how to design a stateless Web service that exposes the functionality of a stateful business process.
1212

Prev Describe the role that Web services play when integrating data, application functions, or business processes in a J2EE application.

Up Home

Next Chapter 11. Endpoint Design and Architecture

http://java.boot.by/wsd-guide/ch10s06.html2004/6/13 12:05:28

Chapter 11. Endpoint Design and Architecture

Chapter 11. Endpoint Design and Architecture Prev Part I. Exam Objectives Next

Chapter 11. Endpoint Design and Architecture

Given a scenario, design Web service applications using information models that are either procedure-style or document-style.
Choosing Between an RPC-Style (remote procedure call) and a Message-Style (document-style) Web Service. RPC-style Web services are interface driven, which means that the business methods of the underlying stateless session EJB determine how the Web service works. When clients invoke the Web service, they send parameter values to the Web service, which executes the corresponding methods and sends back the return values. The relationship is synchronous, which means that the client waits for a response from the Web service before it continues with the remainder of its application. Create an RPC-style Web service if your application has the following characteristics:

The The The The

client invoking the Web service needs an immediate response. client and Web service work in a back-and-forth, conversational way. behavior of the Web service can be expressed as an interface. Web service is process-oriented rather than data-oriented.

Examples of RPC-style Web services include providing the current weather conditions in a particular location; returning the current price for a given stock; or checking the credit rating of a potential trading partner prior to the completion of a business transaction. In each case the information is returned immediately, implying a synchronous relationship between the client and the Web service. RPC is essentially a Remote Procedure call in which the client sends a SOAP request to execute an operation on the Web Service. The SOAP request contains the name of method to be executed and the parameter it takes. The server running the Web Service converts this request to appropriate objects (java method call, EJB method call etc with parameters of defined type), executes the operation and sends the response as SOAP message to client. At the client side, this response is used to form appropriate objects and return the required information (output) to the client. RPC-style Web Services are tightly coupled because the sending parameters and return values are as described in WSDL (Web Service Description Language ) file and are wrapped in the SOAP body. Following is an example SOAP Body of RPC-style Web Service, which invokes GetStockQuote method with input parameter "ORCL":

<SOAP-ENV:Envelope...> <SOAP-ENV:Body>
http://java.boot.by/wsd-guide/ch11.html 1 / 9 2004/6/13 12:05:32

Chapter 11. Endpoint Design and Architecture

<m:GetStockQuote xmlns:m="urn:xmethods:example"> <m:Symbol>ORCL</m:Symbol> </m:GetStockQuote> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

RPC-style Web Services follow call/response semantics, and hence they are synchronous, which means that the client sends the request and waits for the response till the request is processed completely. You should create a message-style (document-style) Web service if your application has the following characteristics:

The client has an asynchronous relationship with the Web service, or in other words, the client does not expect an immediate response. The Web service is data-oriented rather than process-oriented.

Examples of message-style Web services include processing a purchase order; accepting a request for new DSL home service; or responding to a request for quote order from a customer. In each case, the client sends an entire document, such as purchase order, to the Web service and assumes that the Web service is processing it in some way, but the client does not require an answer right away or even at all. If your Web service will work in this asynchronous, document-driven manner, then you should consider designing it as a message-style Web service. NOTE: Document-Style web servives can use both one-way (non-blocking) calls and two-way (request-response) calls, but preferrable choice will be one-way calls. Document-Style Web Service are loosely coupled and the request/response are in the form of XML documents. The client sends the parameter to the Web Service as XML document, instead of discrete set of parameter values. The Web Service processes the document, executes the operation and constructs & sends the response to the client as an XML document. There is no direct mapping between the server objects (parameters, method calls etc) and the values in XML documents. The application has to take care of mapping the XML data values. The SOAP Body of a Document-Style carries one or more XML documents, within its body. The protocol places no constraint on how that document needs to be structured, which is totally handled at the application level. Document-Style Web Service follows asynchronous processing. Following is an example SOAP body for Document-Style Web Service:

<SOAP-ENV:Envelope ...> <SOAP-ENV:Body> <StockQuoteRequest symbol="ORCL"/> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

http://java.boot.by/wsd-guide/ch11.html 2 / 9 2004/6/13 12:05:32

Chapter 11. Endpoint Design and Architecture

The parameters of the methods which are to be exposed by the document style Web Service should be of type XML element only. The return type of the method can be either an XML element or void. The Simple Object Access Protocol (SOAP) offers two messaging styles: RPC (Remote Procedure Call) and document style. One is for creating tightly coupled, inter-object style interfaces for Web services components; the other is for developing loosely coupled, application-to-application and system-to-system interfaces. RPC-Style An RPC is a way for an application running in one execution thread on a system to call a procedure belonging to another application running in a different execution thread on the same or a different system. RPC interfaces are based on a request-response model where one program calls, or requests a service of, another across a tightly coupled interface. In Web services applications, one service acts as a client, requesting a service; the other as a server, responding to that request. RPC interfaces have two parts: the call-level interface seen by the two applications, and the underlying protocol for moving data from one application to the other. NOTE, it may be not only request-response (two-way) RPC call, but also one-way RPC call (but more often it is used with two-way calls). The call-level interface to an RPC procedure looks just like any other method call in the programming language being used. It consists of a method name and a parameter list. The parameter list is made up of the variables passed to the called procedure and those returned as part of its response. For Web services, SOAP defines the wiring between the calling and called procedures. At the SOAP level, the RPC interface appears as a series of highly structured XML messages moving between the client and the server where the Body of each SOAP message contains an XML representation of the call or return stack:

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <sm:someMethod xmlns:sm="http://www.xyz.com/sm"> <someParams> <item>100</item> <item>200</item> </someParams> </sm:someMethod> </env:Body> </env:Envelope>

http://java.boot.by/wsd-guide/ch11.html 3 / 9 2004/6/13 12:05:32

Chapter 11. Endpoint Design and Architecture

The transformation from call-level interface to XML and back occurs through the magic of two processes: marshaling and serialization. 1. The process begins with the client calling a method implemented as a remote procedure. The client actually calls a proxy stub that acts as a surrogate for the real procedure. The proxy stub presents the same external interface to the caller as would the real procedure, but instead of implementing the procedure's functionality, implements the processes necessary for preparing and transporting data across the interface. 2. The proxy stub gathers the parameters it receives through its parameter list into a standard form, in this case, into a SOAP message, through a process called marshaling. 3. The proxy stub encodes the parameters as appropriate during the marshaling process to ensure the recipient can correctly interpret their values. Encoding may be as simple as identifying the correct structure and data type as attributes on the XML tag enclosing the parameter's value or as complex as converting the content to a standard format such as Base64. The final product of the marshaling process is a SOAP message representation of the call stack. 4. The proxy stub serializes the SOAP message across the transport layer to the server. Serialization involves converting the SOAP message into a TCP/IP buffer stream and transporting that buffer stream between the client and the server. The server goes through the reverse process to extract the information it needs. A listener service on the server deserializes the transport stream and calls a proxy stub on the server that unmarshals the parameters, decodes and binds them to internal variables and data structures, and invokes the called procedure. The listener process may be, for example, a J2EE servlet, JSP (JavaServer Page), or Microsoft ASP (Active Server Page). The client and server reverse roles and the inverse process occurs to return the server's response to the client. Document-Style The difference between RPC-Style and Document-Style is primarily in the control you have over the marshaling process. With RPC-style messaging, standards govern that process. With document-style messaging, you make the decisions: you convert data from internal variables into XML; you place the XML into the Body element of the encapsulating SOAP document; you determine the schema(s), if any, for validating the document's structure; and you determine the encoding scheme, if any, for interpreting data item values. The SOAP document simply becomes a wrapper containing whatever content you decide. For example, the SOAP document shown in following example contains an XML namespace reference, http://www.xyz.com/genealogy, that presumably includes all the information a receiving program needs for validating the message's structure and content, and for correctly interpreting data values:

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <xyz:family xmlns:xyz="http://www.xyz.com/genealogy"> <parents> <father age="29">Mikalai</father>


http://java.boot.by/wsd-guide/ch11.html 4 / 9 2004/6/13 12:05:32

Chapter 11. Endpoint Design and Architecture

<mother age="29">Volha</mother> </parents> <children> ... </children> </xyz:family> </env:Body> </env:Envelope>

If you compare the steps involved in typical document-style message exchange process with those involved in processing an RPC-style message, you will notice they are essentially parallel processes: 1. The SOAP client uses an Extensible Stylesheet Language Transformation (XSLT) and the DOM parser, or some other means, to create an XML document. 2. The SOAP client places this XML document into the Body of a SOAP message. 3. The SOAP client optionally includes a namespace reference in the message that other applications can use for validating the encapsulated document's format and content. The namespace reference may be included as an attribute either on one of the SOAP elements or on the XML document's root element. If the document does not include a namespace reference, the client and server must agree on some other scheme for validating and interpreting the document's contents. 4. The SOAP client serializes the message to the SOAP server across either an HTTP or SMTP bound interface. The SOAP server reverses the process, potentially using a different XSLT, to validate, extract, and bind the information it needs from the XML document to its own internal variables. The roles reverse and the two follow inverse processes for returning and accessing any response values. The rules guiding the marshaling process are the primary difference between this process and that for RPC-style messages. With document-style, you as the SOAP client's author create those rules. RPC-style messaging maps to the object-oriented, component-technology space. It is an alternative to other component technologies such as DCOM and CORBA where component models are built around programmable interfaces and languages such as Java and C#. RPCstyle messaging's strength in this space lies in its platform independence. It offers a standardsbased, platform-independent component technology, implemented over standard Internet protocols. One of the benefits of this style's XML layer is that clients and servers can use different programming languages, or technologies, to implement their respective side of the interface, which means one side can choose one set of technologies, such as J2EE's JAX-RPC, while the other chooses a completely different set, such as .NET's C#. RPC-style messaging's standards heritage can be an important consideration in hybrid environments (one using multiple technologies such as J2EE and .NET) and can provide a transition path between different technologies.

http://java.boot.by/wsd-guide/ch11.html 5 / 9 2004/6/13 12:05:32

Chapter 11. Endpoint Design and Architecture

RPC-Style messaging's weaknesses

Strong coupling If you change the number, order, or data types of the parameters to the call-level interface, you must make the change on both sides of the interface. Synchronicity Most programming languages assume synchronous method calls: the calling program normally waits for the called program to execute and return any results before continuing. Web services are asynchronous by nature and, in comparison to technologies such as DCOM and CORBA, long running. You may want to take advantage of Web services' asynchronous nature to avoid the user having to wait for calls to complete by developing asynchronous RPC calls, but that adds another level of complexity to your application. Some tools hide this complexity using callbacks, or other techniques, to enable processing overlap between the request and the response. Check to see if the tools you' re using let you choose between synchronous and asynchronous RPC calls. Marshaling and serialization overhead Marshaling and serializing XML is more expensive than marshaling and serializing a binary data stream. With XML, at least one side of the interface, and possibly both, involves some parsing in order to move data between internal variables and the XML document. There is also the cost of moving encoded text, which can be larger in size than its binary equivalent, across the interface.

The coupling and synchronicity issues are common to RPC-based component technologies. So they are really not discriminators when making comparisons between these technologies. The marshaling and serialization overhead is greater for RPC-style messaging and places this messaging style at a relative disadvantage. However, with today's high-speed processors and networks, performance is generally not an issue. Document-style messaging is clearly an option in any situation where an XML document is one of the interface parameters. It is ideal for passing complex business documents, such as invoices, receipts, customer orders, or shipping manifests. Documentstyle messaging uses an XML document and a stylesheet to specify the content and structure of the information exchanged across the interface, making it an obvious choice in situations where a document's workflow involves a series of services where each service processes a subset of the information within the document. Each service can use an XSLT to validate, extract, and transform only the elements it needs from the larger XML document; with the exception of those elements, the service is insensitive to changes in other parts of the document. The XSLT insulates the service from changes in the number, order, or type of data elements being exchanged. As long as the service creating the document maintains backwards compatibility, it can add or rearrange the elements it places into a document without affecting other services. Those services can simply ignore any additional data. Document-style messaging is also agnostic on the synchronicity of the interface; it works equally well for both synchronous and asynchronous interfaces. Document-style messaging's weaknesses

http://java.boot.by/wsd-guide/ch11.html 6 / 9 2004/6/13 12:05:32

Chapter 11. Endpoint Design and Architecture

No standard service identification mechanism With document-style messaging, the client and server must agree on a service identification mechanism: a way for a document's recipient to determine which service(s) need to process that document. SOAP header entries offer one option; you can include information in the document's header that helps identify the service(s) needed. WSRouting makes just such a proposal. Another option is to name elements in the Body of the message for the services that need to process the payload the elements contain. You might ask how that differs from schema-based RPC-style messaging. You would be right in assuming there is little or no difference except possibly in terms of the number of "calls" that can be made per message. A third option is to perform either structure or content analysis as part of a service selection process in order to identify the services needed to process the document. Marshaling and serialization overhead Document-style messaging suffers from the same drawbacks as RPC-style messaging in this area. However, the problem may be more severe with document-style messaging. Document-style messaging incurs overhead in three areas: in using DOM, or another technique, to build XML documents; in using DOM, or SAX, to parse those documents in order to extract data values; and in mapping between extracted data values and internal program variables. Tools generating equivalent RPC-style interfaces optimize these transformations. You may have trouble achieving the same level of efficiency in your applications using standard tools.

There are two compelling reasons to use document-style messaging. One is to gain the independence it provides. Its strength lies in decoupling interfaces between services to the point that they can change completely independently of one another. The other is that document-style messaging puts the full power of XML for structuring and encoding information at your disposal. The latter is one reason many consider document-style superior to RPC-style messaging. RPC-style messaging's strength is as a bridging component technology. It is a good option for creating new components and for creating interfaces between Web services and existing components - you simply wrap existing components with RPC-style Web services interfaces. RPCstyle messaging is also an excellent component standard in situations where you are using multiple technologies, such as J2EE and .NET, and want to develop sharable components. Document-style messaging's strengths are in situations where an XML document is part of the data being passed across the interface, where you want to leverage the full power of XML and XSL, and in instances where you want to minimize coupling between services forming an interface, such as in application-to-application and system-to-system interfaces. WSDL Example for RPC-Style:

... <message name="myMethodRequest"> <part name="x" type="xsd:int"/>


http://java.boot.by/wsd-guide/ch11.html 7 / 9 2004/6/13 12:05:32

Chapter 11. Endpoint Design and Architecture

</message> <portType name="PT"> <operation name="myMethod"> <input message="myMethodRequest"/> </operation> </portType> ...

RPC-Literal SOAP message for this request:

<soap:Envelope> <soap:Body> <myMethod> <x>5</x> </myMethod> </soap:Body> </soap:Envelope>

WSDL Example for Document-Style:

<types> <schema> <element name="xElement" type="xsd:int"/> </schema> </types> <message name="myMethodRequest"> <part name="x" element="xElement"/> </message> <portType name="PT"> <operation name="myMethod"> <input message="myMethodRequest"/> </operation> </portType>

http://java.boot.by/wsd-guide/ch11.html 8 / 9 2004/6/13 12:05:32

Chapter 11. Endpoint Design and Architecture

Document-Literal SOAP message:

<soap:Envelope> <soap:Body> <xElement>5</xElement> </soap:Body> </soap:Envelope>

Prev Describe how to design a stateless Web service that exposes the functionality of a stateful business process.

Up Home

Next Describe the function of the service interaction and processing layers in a Web service.

http://java.boot.by/wsd-guide/ch11.html 9 / 9 2004/6/13 12:05:32

Describe the function of the service interaction and processing layers in a Web service.

Describe the function of the service interaction and processing layers in a Web service. Prev Chapter 11. Endpoint Design and Architecture Next

Describe the function of the service interaction and processing layers in a Web service.
1212

Prev Chapter 11. Endpoint Design and Architecture

Up

Next Describe the tasks performed by each phase of an XML-based, document oriented, Web service application, including the consumption, business processing, and production phases.

Home

http://java.boot.by/wsd-guide/ch11s02.html2004/6/13 12:05:36

Describe the tasks performed by each phase of an XML-based, documen...uding the consumption, business processing, and production phases.

Describe the tasks performed by each phase of an XML-based, document oriented, Web service application, including the consumption, business processing, and production phases. Prev Chapter 11. Endpoint Design and Architecture Next

Describe the tasks performed by each phase of an XML-based, document oriented, Web service application, including the consumption, business processing, and production phases.
1212

Prev Describe the function of the service interaction and processing layers in a Web service.

Up

Next Design a Web service for an asynchronous, document-style process and describe how to refactor a Web service from a synchronous to an asynchronous model.

Home

http://java.boot.by/wsd-guide/ch11s03.html2004/6/13 12:05:38

Design a Web service for an asynchronous, document-style process an...efactor a Web service from a synchronous to an asynchronous model.

Design a Web service for an asynchronous, document-style process and describe how to refactor a Web service from a synchronous to an asynchronous model. Prev Chapter 11. Endpoint Design and Architecture Next

Design a Web service for an asynchronous, document-style process and describe how to refactor a Web service from a synchronous to an asynchronous model.
1212

Prev Describe the tasks performed by each phase of an XML-based, document oriented, Web service application, including the consumption, business processing, and production phases.

Up

Next Describe how the characteristics, such as resource utilization, conversational capabilities, and operational modes, of the various types of Web service clients impact the design of a Web service or determine the type of client that might interact with a particular service.

Home

http://java.boot.by/wsd-guide/ch11s04.html2004/6/13 12:05:40

Describe how the characteristics, such as resource utilization, conversa...rmine the type of client that might interact with a particular service.

Describe how the characteristics, such as resource utilization, conversational capabilities, and operational modes, of the various types of Web service clients impact the design of a Web service or determine the type of client that might interact with a particular service. Prev Chapter 11. Endpoint Design and Architecture Next

Describe how the characteristics, such as resource utilization, conversational capabilities, and operational modes, of the various types of Web service clients impact the design of a Web service or determine the type of client that might interact with a particular service.
1212

Prev Design a Web service for an asynchronous, document-style process and describe how to refactor a Web service from a synchronous to an asynchronous model.

Up

Next Part II. Appendixes

Home

http://java.boot.by/wsd-guide/ch11s05.html2004/6/13 12:05:42

Part II. Appendixes

Part II. Appendixes Prev Next

Appendixes
Bibliography
[BP-1.0] Basic Profile Version 1.0a - Final Specification (http://www.ws-i.org/Profiles/ Basic/2003-08/BasicProfile-1.0a.html). [SOAP-1.1] Simple Object Access Protocol (SOAP) 1.1 (http://www.w3.org/TR/2000/NOTESOAP-20000508). [WSDL-1.1] Web Services Description Language (WSDL) 1.1 (http://www.w3.org/TR/wsdl). [UDDI-2.0-DS] UDDI Version 2.03 Data Structure Reference (http://uddi.org/pubs/ DataStructure-V2.03-Published-20020719.htm). [UDDI-2.0-API] UDDI Version 2.04 API Specification (http://uddi.org/pubs/ProgrammersAPIV2.04-Published-20020719.htm). [XML-DSIG] XML Digital Signature (http://www.w3.org/Signature). [XML-SIG] XML-Signature Syntax and Processing (http://www.w3.org/TR/2002/REC-xmldsigcore-20020212). [XML-ENCR] XML Encryption Syntax and Processing (http://www.w3.org/TR/2002/REC-xmlenccore-20021210). [SAML] SAML (http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=security). [XACML] XACML (http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=xacml). [WS-SEC] Web Services Security (WS-Security) (http://www-106.ibm.com/developerworks/ webservices/library/ws-secure/).

Prev

Up

Next

http://java.boot.by/wsd-guide/pt02.html 1 / 2 2004/6/13 12:05:45

Part II. Appendixes

Describe how the characteristics, such as resource utilization, conversational capabilities, and operational modes, of the various types of Web service clients impact the design of a Web service or determine the type of client that might interact with a particular service.

Appendix A. First Appendix Home

http://java.boot.by/wsd-guide/pt02.html 2 / 2 2004/6/13 12:05:45

Appendix A. First Appendix

Appendix A. First Appendix Prev Part II. Appendixes Next

Appendix A. First Appendix

SAAJ API
SAAJ Interfaces

package javax.xml.soap; public interface Node extends org.w3c.dom.Node { public abstract String getValue(); public abstract void setParentElement(SOAPElement parent) throws SOAPException; public abstract SOAPElement getParentElement(); public abstract void detachNode(); public abstract void recycleNode(); public abstract void setValue(String value); }

package javax.xml.soap; public interface Text extends Node, org.w3c.dom.Text { public abstract boolean isComment(); }

package javax.xml.soap; import java.util.Iterator;

http://java.boot.by/wsd-guide/apa.html 1 / 8 2004/6/13 12:05:51

Appendix A. First Appendix

public interface SOAPElement extends Node, org.w3c.dom.Element { public abstract SOAPElement addChildElement(Name name) throws SOAPException; public abstract SOAPElement addChildElement(String localName) throws SOAPException; public abstract SOAPElement addChildElement(String localName, String prefix) throws SOAPException; public abstract SOAPElement addChildElement( String localName, String prefix, String uri) throws SOAPException; public abstract SOAPElement addChildElement(SOAPElement element) throws SOAPException; public abstract SOAPElement addTextNode(String text) throws SOAPException; public abstract SOAPElement addAttribute(Name name, String value) throws SOAPException; public abstract SOAPElement addNamespaceDeclaration( String prefix, String uri) throws SOAPException; public abstract String getAttributeValue(Name name); public abstract Iterator getAllAttributes(); public abstract String getNamespaceURI(String prefix); public abstract Iterator getNamespacePrefixes(); public abstract Name getElementName(); public abstract boolean removeAttribute(Name name); public abstract boolean removeNamespaceDeclaration(String prefix); public abstract Iterator getChildElements(); public abstract Iterator getChildElements(Name name); public abstract void setEncodingStyle(String encodingStyle) throws SOAPException; public abstract String getEncodingStyle();
http://java.boot.by/wsd-guide/apa.html 2 / 8 2004/6/13 12:05:51

Appendix A. First Appendix

public abstract void removeContents(); public abstract Iterator getVisibleNamespacePrefixes(); }

package javax.xml.soap; import org.w3c.dom.Document; import java.util.Locale; public interface SOAPBody extends SOAPElement { public abstract SOAPFault addFault() throws SOAPException; public abstract boolean hasFault(); public abstract SOAPFault getFault(); public abstract SOAPBodyElement addBodyElement(Name name) throws SOAPException; public abstract SOAPFault addFault(Name faultCode, String faultString, Locale locale) throws SOAPException; public abstract SOAPFault addFault(Name faultCode, String faultString) throws SOAPException; public abstract SOAPBodyElement addDocument(Document document) throws SOAPException; }

package javax.xml.soap; public interface SOAPBodyElement extends SOAPElement {}

package javax.xml.soap; import java.util.Locale;

http://java.boot.by/wsd-guide/apa.html 3 / 8 2004/6/13 12:05:51

Appendix A. First Appendix

public interface SOAPFault extends SOAPBodyElement { public abstract void setFaultCode(String faultCode) throws SOAPException; public abstract String getFaultCode(); public abstract void setFaultActor(String faultActor) throws SOAPException; public abstract String getFaultActor(); public abstract void setFaultString(String faultString) throws SOAPException; public abstract String getFaultString(); public abstract Detail getDetail(); public abstract Detail addDetail() throws SOAPException; public abstract void setFaultCode(Name name) throws SOAPException; public abstract Name getFaultCodeAsName(); public abstract void setFaultString(String faultString, Locale locale) throws SOAPException; public abstract Locale getFaultStringLocale(); }

package javax.xml.soap; public interface SOAPEnvelope extends SOAPElement { public abstract Name createName(String localName, String prefix, String uri) throws SOAPException; public abstract Name createName(String localName) throws SOAPException; public abstract SOAPHeader getHeader() throws SOAPException; public abstract SOAPBody getBody() throws SOAPException; public abstract SOAPHeader addHeader() throws SOAPException;

http://java.boot.by/wsd-guide/apa.html 4 / 8 2004/6/13 12:05:51

Appendix A. First Appendix

public abstract SOAPBody addBody() throws SOAPException; }

package javax.xml.soap; import java.util.Iterator; public interface SOAPHeader extends SOAPElement { public abstract SOAPHeaderElement addHeaderElement(Name name) throws SOAPException; // does not detach headers public abstract Iterator examineHeaderElements(String actor); // detaches headers public abstract Iterator extractHeaderElements(String actor); public abstract Iterator examineMustUnderstandHeaderElements(String actor); public abstract Iterator examineAllHeaderElements(); public abstract Iterator extractAllHeaderElements(); }

package javax.xml.soap; public interface SOAPHeaderElement extends SOAPElement { public abstract void setActor(String actorURI); public abstract String getActor(); public abstract void setMustUnderstand(boolean mustUnderstand); public abstract boolean getMustUnderstand(); }

SAAJ API Classes.

http://java.boot.by/wsd-guide/apa.html 5 / 8 2004/6/13 12:05:51

Appendix A. First Appendix

package javax.xml.soap; import java.io.IOException; import java.io.InputStream; public abstract class MessageFactory { protected MessageFactory() {} public static MessageFactory newInstance() throws SOAPException { ... } public abstract SOAPMessage createMessage() throws SOAPException; public abstract SOAPMessage createMessage( MimeHeaders mimeheaders, InputStream inputstream) throws IOException, SOAPException; ... }

package javax.xml.soap; import javax.activation.DataHandler; import java.io.IOException; import java.io.OutputStream; import java.util.Iterator; public abstract class SOAPMessage { public SOAPMessage() {} public abstract String getContentDescription(); public abstract void setContentDescription(String description); public abstract SOAPPart getSOAPPart(); public abstract void removeAllAttachments(); public abstract int countAttachments(); public abstract Iterator getAttachments(); public abstract Iterator getAttachments(MimeHeaders headers); public abstract void addAttachmentPart(AttachmentPart attachmentpart); public abstract AttachmentPart createAttachmentPart(); public AttachmentPart createAttachmentPart(DataHandler datahandler) { ... } public abstract MimeHeaders getMimeHeaders(); public AttachmentPart createAttachmentPart(Object content, String contentType) {

http://java.boot.by/wsd-guide/apa.html 6 / 8 2004/6/13 12:05:51

Appendix A. First Appendix

... } public abstract void saveChanges() throws SOAPException; public abstract boolean saveRequired(); public abstract void writeTo(OutputStream out) throws SOAPException, IOException; public SOAPBody getSOAPBody() throws SOAPException { ... } public SOAPHeader getSOAPHeader() throws SOAPException { ... } public void setProperty(String property, Object value) throws SOAPException { ... } public Object getProperty(String property) throws SOAPException { ... } }

package javax.xml.soap; import javax.xml.transform.Source; import java.util.Iterator; public abstract class SOAPPart implements org.w3c.dom.Document { public SOAPPart() {} public abstract SOAPEnvelope getEnvelope() throws SOAPException; public String getContentId() { ... } public String getContentLocation() { ... } public void setContentId(String contentId) { ... } public void setContentLocation(String contentLocation) { ... } public abstract void removeMimeHeader(String header); public abstract void removeAllMimeHeaders(); public abstract String[] getMimeHeader(String name); public abstract void setMimeHeader(String name, String value);
http://java.boot.by/wsd-guide/apa.html 7 / 8 2004/6/13 12:05:51

Appendix A. First Appendix

public abstract void addMimeHeader(String name, String value); public abstract Iterator getAllMimeHeaders(); public abstract Iterator getMatchingMimeHeaders(String names[]); public abstract Iterator getNonMatchingMimeHeaders(String names[]); public abstract void setContent(Source source) throws SOAPException; public abstract Source getContent() throws SOAPException; }

package javax.xml.soap; import java.util.Locale; public interface SOAPFault extends SOAPBodyElement { public abstract void setFaultCode(String faultCode) throws SOAPException; public abstract String getFaultCode(); public abstract void setFaultActor(String faultActor) throws SOAPException; public abstract String getFaultActor(); public abstract void setFaultString(String faultString) public abstract String getFaultString(); public abstract Detail getDetail(); public abstract Detail addDetail() throws SOAPException; public abstract void setFaultCode(Name name) throws SOAPException; public abstract Name getFaultCodeAsName(); public abstract void setFaultString(String faultString, Locale locale) throws SOAPException; public abstract Locale getFaultStringLocale(); }

Prev Part II. Appendixes

Up Home

Next Second Section

http://java.boot.by/wsd-guide/apa.html 8 / 8 2004/6/13 12:05:51

Second Section

Second Section Prev Appendix A. First Appendix Next

Second Section
sdsds

Prev Appendix A. First Appendix

Up Home

Next Third Section

http://java.boot.by/wsd-guide/apas02.html2004/6/13 12:05:53

Third Section

Third Section Prev Appendix A. First Appendix Next

Third Section
sdsds

Prev Second Section

Up Home

Next Bibliography

http://java.boot.by/wsd-guide/apas03.html2004/6/13 12:05:55

SCDJWS Study Guide

SCDJWS Study Guide


IBA USA, Inc. Mikalai Zaikin
<NZaikin[at]iba.by>

Copyright 2004 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. April 2004
Revision History Revision 0.1 Chapter 1 updates. Revision 0.0 initial release. 17 Mar 2004 MZ 7 Apr 2004 MZ

Abstract The purpose of this document is to help in preparation for exam CX-310-220 (Sun Certified Developer for Java Web Services). This document should not be used as the only study material for SCDJWS (Sun Certified Developer for Java Web Services) Test. It covers all objective topics, but it is not enough. I tried to make this document as much accurate as possible, but if you find any error, please let me know.

Table of Contents Foreword Preface I. Exam Objectives 1. XML Web Service Standards Given XML documents, schemas, and fragments determine whether their syntax and form are correct (according to W3C schema) and whether they conform to the WS-I Basic Profile 1.0a. Describe the use of XML schema in J2EE Web services. Describe the use of namespaces in an XML document. 2. SOAP 1.1 Web Service Standards List and describe the encoding types used in a SOAP message. Describe how SOAP message header blocks are used and processed. Describe the function of each element contained in a SOAP message, the SOAP binding to HTTP, and how to represent faults that occur when processing a SOAP message. Create a SOAP message that contains an attachment. Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a. Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages. 3. Describing and Publishing (WSDL and UDDI) Explain the use of WSDL in Web services, including a description of WSDL's basic elements, binding mechanisms and the basic WSDL operation types as limited by the WS-I Basic Profile 1.0a. Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1. Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a. Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry.

http://java.boot.by/wsd-guide/wsd-guide.html 1 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

4. JAX-RPC Explain the service description model, client connection types, interaction modes, transport mechanisms/protocols, and endpoint types as they relate to JAX-RPC. Given a set of requirements for a Web service, such as transactional needs, and security requirements, design and develop Web service applications that use servlet-based endpoints and EJB based endpoints. Given an set of requirements, design and develop a Web sevice client, such as a J2EE client and a stand-alone Java client, using the appropriate JAX-RPC client connection style. Given a set of requirements, develop and configure a Web service client that accesses a stateful Web service. Explain the advantages and disadvantages of a WSDL to Java vs. a Java to WSDL development approach. Describe the advantages and disadvantages of web service applications that use either synchronous/request response, one-way RPC, or non-blocking RPC invocation modes. Use the JAX-RPC Handler API to create a SOAP message handler, describe the function of a handler chain, and describe the role of SAAJ when creating a message handler. 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ) Describe the functions and capabilities of the APIs included within JAXP. Given a scenario, select the proper mechanism for parsing and processing the information in an XML document. Describe the functions and capabilities of JAXB, including the JAXB process flow, such as XML-to-Java and Java-to-XML, and the binding and validation mechanisms provided by JAXB. Use the SAAJ APIs to create and manipulate a SOAP message. 6. JAXR Describe the function of JAXR in Web service architectural model, the two basic levels of business registry functionality supported by JAXR, and the function of the basic JAXR business objects and how they map to the UDDI data structures. Use JAXR to connect to a UDDI business registry, execute queries to locate services that meet specific requirements, and publish or update information about a business service. 7. J2EE Web Services Identify the characteristics of and the services and APIs included in the J2EE platform. Explain the benefits of using the J2EE platform for creating and deploying Web service applications. Describe the functions and capabilities of the JAXP, DOM, SAX, JAXR, JAX-RPC, and SAAJ in the J2EE platform. Describe the role of the WS-I Basic Profile when designing J2EE Web services. 8. Security Explain basic security mechanisms including: transport level security, such as basic and mutual authentication and SSL, message level security, XML encryption, XML Digital Signature, and federated identity and trust. Identify the purpose and benefits of Web services security oriented initiatives and standards such as Username Token Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project. Given a scenario, implement J2EE based web service web-tier and/or EJB-tier basic security mechanisms, such as mutual authentication, SSL, and access control. Describe factors that impact the security requirements of a Web service, such as the relationship between the client and service provider, the type of data being exchanged, the message format, and the transport mechanism. 9. Developing Web Services Describe the steps required to configure, package, and deploy J2EE Web services and service clients, including a description of the packaging formats, such as .ear, .war, .jar, deployment descriptor settings, the associated Web Services description file, RPC mapping files, and service reference elements used for EJB and servlet endpoints. Given a set of requirements, develop code to process XML files using the SAX, DOM, XSLT, and JAXB APIs. Given an XML schema for a document style Web service create a WSDL file that describes the service and generate a service implementation. Given a set of requirements, develop code to create an XML-based, document style, Web service using the JAX-RPC APIs. Implement a SOAP logging mechanism for testing and debugging a Web Service application using J2EE Web Service APIs. Given a set of requirements, develop code to handle system and service exceptions and faults received by a Web services client. 10. General Design and Architecture Describe the characteristics of a service oriented architecture and how Web Services fits to this model. Given a scenario, design a J2EE service using the Business Delegate, Service Locator, and/or Proxy client-side design patterns and the Adapter, Command, Web Service Broker, and/or Faade server-side patterns. Describe alternatives for dealing with issues that impact the quality of service provided by a Web service and methods to improve the system reliability, maintainability, security, and performance of a service. Describe how to handle the various types of return values, faults, errors, and exceptions that can occur during a Web service interaction. Describe the role that Web services play when integrating data, application functions, or business processes in a J2EE application. Describe how to design a stateless Web service that exposes the functionality of a stateful business process. 11. Endpoint Design and Architecture Given a scenario, design Web service applications using information models that are either procedure-style or document-

http://java.boot.by/wsd-guide/wsd-guide.html 2 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

style. Describe the function of the service interaction and processing layers in a Web service. Describe the tasks performed by each phase of an XML-based, document oriented, Web service application, including the consumption, business processing, and production phases. Design a Web service for an asynchronous, document-style process and describe how to refactor a Web service from a synchronous to an asynchronous model. Describe how the characteristics, such as resource utilization, conversational capabilities, and operational modes, of the various types of Web service clients impact the design of a Web service or determine the type of client that might interact with a particular service. II. Appendixes A. First Appendix SAAJ API Second Section Third Section Bibliography

Foreword
A preface.

Preface
This document is available in 2 formats: single page and chunked pages If you would like to have PDF (printable eBook for Adobe Acrobat Reader) version or CHM (single file copy of web-site to browse offline) version of SCDJWS Study Guide, please, contact me.

Exam Objectives
Chapter 1. XML Web Service Standards

Given XML documents, schemas, and fragments determine whether their syntax and form are correct (according to W3C schema) and whether they conform to the WS-I Basic Profile 1.0a.
BP 1.0 - Service Description (WSDL) - Document Structure. A DESCRIPTION MUST only use the WSDL "import" statement to import another WSDL description. To import XML Schema Definitions, a DESCRIPTION MUST use the XML Schema "import" statement. A DESCRIPTION MUST use the XML Schema "import" statement only within the xsd:schema element of the types section. A DESCRIPTION MUST NOT use the XML Schema "import" statement to import a Schema from any document whose root element is not "schema" from the namespace "http://www.w3.org/2001/XMLSchema". An XML Schema directly or indirectly imported by a DESCRIPTION MUST use either UTF-8 or UTF-16 encoding. An XML Schema directly or indirectly imported by a DESCRIPTION MUST use version 1.0 of the eXtensible Markup Language W3C Recommendation. CORRECT:

<definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions"> <import namespace="http://example.com/stockquote/definitions" location="http://example.com/stockquote/stockquote.wsdl"/>


http://java.boot.by/wsd-guide/wsd-guide.html 3 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<message name="GetLastTradePriceInput"> <part name="body" element="..."/> </message> ... </definitions>

CORRECT:

<definitions name="StockQuote" targetNamespace="http://example.com/stockquote/" xmlns:xsd1="http://example.com/stockquote/schemas" ... xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/definitions" location="http://example.com/stockquote/stockquote.wsdl"/> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> ... </definitions>

INCORRECT (imports not "wsdl" document):

<definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions" xmlns:xsd1="http://example.com/stockquote/schemas"" ... xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/schemas" location="http://example.com/stockquote/stockquote.xsd"/> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> ... </definitions>

A DESCRIPTION MUST specify a non-empty location attribute on the wsdl:import element. When they appear in a DESCRIPTION, wsdl:import elements MUST precede all other elements from the WSDL namespace except wsdl: documentation. When they appear in a DESCRIPTION, wsdl:types elements MUST precede all other elements from the WSDL namespace except wsdl: documentation and wsdl:import. CORRECT:

<definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions">


http://java.boot.by/wsd-guide/wsd-guide.html 4 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<import namespace="http://example.com/stockquote/base" location="http://example.com/stockquote/stockquote.wsdl"/> <message name="GetLastTradePriceInput"> <part name="body" element="..."/> </message> ... </definitions>

CORRECT:

<definitions name="StockQuote" ... xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <schema targetNamespace="http://example.com/stockquote/schemas" xmlns="http://www.w3.org/2001/XMLSchema"> ....... </schema> </types> <message name="GetLastTradePriceInput"> <part name="body" element="tns:TradePriceRequest"/> </message> ... <service name="StockQuoteService"> <port name="StockQuotePort" binding="tns:StockQuoteSoap"> .... </port> </service> </definitions>

INCORRECT:

<definitions name="StockQuote" ... xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/definitions" location="http://example.com/stockquote/stockquote.wsdl"/> <message name="GetLastTradePriceInput"> <part name="body" type="tns:TradePriceRequest"/> </message> ... <service name="StockQuoteService"> <port name="StockQuotePort" binding="tns:StockQuoteSoap"> .... </port> </service> <types> <schema targetNamespace="http://example.com/stockquote/schemas" xmlns="http://www.w3.org/2001/XMLSchema">
http://java.boot.by/wsd-guide/wsd-guide.html 5 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

....... </schema> </types> </definitions>

A DESCRIPTION MUST use version 1.0 of the eXtensible Markup Language W3C Recommendation. DESCRIPTION MUST use either UTF-8 or UTF-16 encoding. The targetNamespace attribute on the wsdl:definitions element of a description that is being imported MUST have same the value as the namespace attribute on the wsdl:import element in the importing DESCRIPTION. A document-literal binding in a DESCRIPTION MUST, in each of its soapbind:body element(s), have at most one part listed in the parts attribute, if the parts attribute is specified. If a document-literal binding in a DESCRIPTION does not specify the parts attribute on a soapbind:body element, the corresponding abstract wsdl:message MUST define zero or one wsdl:parts. A wsdl:binding in a DESCRIPTION MAY contain soapbind:body element(s) that specify that zero parts form the soap:Body. An rpc-literal binding in a DESCRIPTION MUST refer, in its soapbind:body element(s), only to wsdl:part element(s) that have been defined using the type attribute. A MESSAGE described with an rpc-literal binding MUST NOT have the xsi:nil attribute with a value of "1" or "true" on the part accessors. A wsdl:message in a DESCRIPTION MAY contain wsdl:parts that use the elements attribute provided those wsdl:parts are not referred to by a soapbind:body in an rpc-literal binding. A document-literal binding in a DESCRIPTION MUST refer, in each of its soapbind:body element(s), only to wsdl:part element(s) that have been defined using the element attribute. A binding in a DESCRIPTION MAY contain soapbind:header element(s) that refer to wsdl:parts in the same wsdl:message that are referred to by its soapbind:body element(s). A wsdl:binding in a DESCRIPTION MUST refer, in each of its soapbind:header, soapbind:headerfault and soapbind:fault elements, only to wsdl: part element(s) that have been defined using the element attribute. A wsdl:binding in a DESCRIPTION SHOULD bind every wsdl:part of a wsdl:message in the wsdl:portType to which it refers to one of soapbind: body, soapbind:header, soapbind:fault or soapbind:headerfault. A wsdl:message in a DESCRIPTION containing a wsdl:part that uses the element attribute MUST refer, in that attribute, to a global element declaration CORRECT:

<message name="GetTradePriceInput"> <part name="body" element="tns:SubscribeToQuotes"/> </message>

INCORRECT:

<message name="GetTradePriceInput"> <part name="tickerSymbol" element="xsd:string"/> <part name="time" element="xsd:timeInstant"/> </message>


http://java.boot.by/wsd-guide/wsd-guide.html 6 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

INCORRECT:

<message name="GetTradePriceInput"> <part name="tickerSymbol" element="xsd:string"/> </message>

BP 1.0 - Service Description (WSDL) - Port Types. The order of the elements in the soap:body of a MESSAGE MUST be the same as that of the wsdl:parts in the wsdl:message that describes it. A DESCRIPTION MAY use the parameterOrder attribute of an wsdl:operation element to indicate the return value and method signatures as a hint to code generators. A DESCRIPTION MUST NOT use Solicit-Response and Notification type operations in a wsdl:portType definition. A wsdl:portType in a DESCRIPTION MUST have operations with distinct values for their name attributes. A wsdl:portType in a DESCRIPTION MUST be constructed so that the parameterOrder attribute, if present, omits at most 1 wsdl:part from the output message. A wsdl:message in a DESCRIPTION MUST NOT specify both type and element attributes on the same wsdl:part. BP 1.0 - Service Description (WSDL) - SOAP Binding. The wsdl:binding element in a DESCRIPTION MUST be constructed so that its soapbind:binding child element specifies the transport attribute. A wsdl:binding element in a DESCRIPTION MUST specify the HTTP transport protocol with SOAP binding. Specifically, the transport attribute of its soapbind:binding child MUST have the value "http://schemas.xmlsoap.org/soap/http". A wsdl:binding in a DESCRIPTION MUST use either be a rpc-literal binding or a document-literal binding. A wsdl:binding in a DESCRIPTION MUST use the value of "literal" for the use attribute in all soapbind:body, soapbind:fault, soapbind:header and soapbind:headerfault elements. A wsdl:binding in a DESCRIPTION that contains one or more soapbind:body, soapbind:fault, soapbind:header or soapbind:headerfault elements that do not specify the use attribute MUST be interpreted as though the value "literal" had been specified in each case. A wsdl:portType in a DESCRIPTION MAY have zero or more wsdl:bindings that refer to it, defined in the same or other WSDL documents. The operations in a wsdl:binding in a DESCRIPTION MUST result in wire signatures that are different from one another. A DESCRIPTION SHOULD NOT have more than one wsdl:port with the same value for the location attribute of the soapbind:address element. A document-literal binding MUST be represented on the wire as a MESSAGE with a soap:Body whose child element is an instance of the global element declaration referenced by the corresponding wsdl:message part. For one-way operations, an INSTANCE MUST NOT return a HTTP response that contains a SOAP envelope. Specifically, the HTTP response entity-body must be empty. A CONSUMER MUST ignore a SOAP response carried in a response from a one-way operation. For one-way operations, a CONSUMER MUST NOT interpret a successful HTTP response status code (i.e., 2xx) to mean the message is valid or that the receiver would process it.
http://java.boot.by/wsd-guide/wsd-guide.html 7 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

A document-literal binding in a DESCRIPTION MUST NOT have the namespace attribute specified on contained soapbind:body, soapbind:header, soapbind:headerfault and soapbind:fault elements. An rpc-literal binding in a DESCRIPTION MUST have the namespace attribute specified, the value of which MUST be an absolute URI, on contained soapbind:body elements. An rpc-literal binding in a DESCRIPTION MUST NOT have the namespace attribute specified on contained soapbind:header, soapbind: headerfault and soapbind:fault elements. A wsdl:binding in a DESCRIPTION MUST have the same set of wsdl:operations as the wsdl:portType to which it refers. A wsdl:binding in a DESCRIPTION MAY contain no soapbind:headerfault elements if there are no known header faults. A wsdl:binding in a DESCRIPTION SHOULD contain a soapbind:fault describing each known fault. A wsdl:binding in a DESCRIPTION SHOULD contain a soapbind:headerfault describing each known header fault. A MESSAGE MAY contain a fault detail entry in a SOAP fault that is not described by a wsdl:fault element in the corresponding WSDL description. A MESSAGE MAY contain the details of a header processing related fault in a SOAP header block that is not described by a wsdl: headerfault element in the corresponding WSDL description. A wsdl:binding in a DESCRIPTION MUST use the attribute named part with a schema type of "NMTOKEN" on all contained soapbind:header and soapbind:headerfault elements. A wsdl:binding in a DESCRIPTION MUST NOT use the attribute named parts on contained soapbind:header and soapbind:headerfault elements. CORRECT:

<binding name="StockQuoteSoap" type="tns:StockQuotePortType"> <soapbind:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="SubscribeToQuotes"> <input message="tns:SubscribeToQuotes"> <soapbind:body parts="body" use="literal"/> <soapbind:header message="tns:SubscribeToQuotes" part="subscribeheader" use="literal"/> </input> </operation> </binding>

A wsdl:binding in a DESCRIPTION MUST have the name attribute specified on all contained soapbind:fault elements. In a DESCRIPTION, the value of the name attribute on a soapbind:fault element MUST match the value of the name attribute on its parent wsdl:fault element. ... ... ...

Describe the use of XML schema in J2EE Web services.


The W3C XML Schema Definition Language is a way of describing and constraining the content of XML documents. The XML Schema specification consists of three parts. One part defines a set of simple datatypes, which can be associated with XML

http://java.boot.by/wsd-guide/wsd-guide.html 8 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

element types and attributes; this allows XML software to do a better job of managing dates, numbers, and other special forms of information. The second part of the specification proposes methods for describing the structure and constraining the contents of XML documents, and defines the rules governing schema validation of documents. The third part is a primer that explains what schemas are, how they differ from DTDs, and how one builds a schema. XML Schema introduces new levels of flexibility that may accelerate the adoption of XML for significant industrial use. For example, a schema author can build a schema that borrows from a previous schema, but overrides it where new unique features are needed. XML Schema allows the author to determine which parts of a document may be validated, or identify parts of a document where a schema may apply. XML Schema also provides a way for users of e-commerce systems to choose which XML Schema they use to validate elements in a given namespace, thus providing better assurance in e-commerce transactions and greater security against unauthorized changes to validation rules. Further, as XML Schema are XML documents themselves, they may be managed by XML authoring tools, or through XSLT. Let's start from "Hello World !" example:

<?xml version="1.0" encoding="UTF-8" ?> <greeting> Hello World! </greeting>

<?xml version="1.0" encoding="UTF-8" ?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="greeting" type="xsd:string"/> </xsd:schema>

Here is a simple data structure for a purchase order. The order example contains following elements: company name, product identifier, and price.

<?xml version="1.0" encoding="UTF-8" ?> <order_request> <company_name>IBA USA, Inc.</company_name> <product_id>C-0YST</product_id> <product_price>500.00</product_price> </order_request>

This example represents pricing data as a floating-point number and company name and product identifier as strings. Agreement among different programs about how to handle data is essential. XML solves data typing issues through the use of XML Schemas. The following example shows how each element in the order request can be designated a specific data type:

<?xml version="1.0" encoding="UTF-8" ?> <xsd:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xsd:element name="order_request"> <xsd:complexType> <xsd:sequence> <xsd:element name="company_name" type="xsd:string"/> <xsd:element name="product_id" type="xsd:string"/> <xsd:element name="product_price" type="xsd:double"/> </xsd:sequence>

http://java.boot.by/wsd-guide/wsd-guide.html 9 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

</xsd:complexType> </xsd:element> </xsd:schema>

it is equivalent to following XML Schema:

<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="company_name" type="xsd:string"/> <xsd:element name="order_request"> <xsd:complexType> <xsd:sequence> <xsd:element ref="company_name"/> <xsd:element ref="product_id"/> <xsd:element ref="product_price"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="product_id" type="xsd:string"/> <xsd:element name="product_price" type="xsd:double"/> </xsd:schema>

Another example of XML document for more complex purchase order:

<?xml version="1.0" encoding="UTF-8" ?> <purchase_order order_date="2004-04-07"> <shipping_address country="US"> <name>Mikalai Zaikin</name> <street>28th Street</street> <city>Boulder</city> <state>CO</state> <zip>80301</zip> </shipping_address> <items> <item part_number="008291"> <product_name>PRESARIO S5140</product_name> <quantity>1</quantity> <price>898.00</price> </item> <item part_number="005376"> <product_name>COMPAQ FP7317</product_name> <quantity>1</quantity> <price>398.00</price> </item> </items> </purchase_order>

The XML Schema (one of many possible) for this document will be:

<?xml version="1.0" encoding="UTF-8"?>

http://java.boot.by/wsd-guide/wsd-guide.html 10 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="city" type="xsd:string" /> <xsd:element name="item"> <xsd:complexType> <xsd:sequence> <xsd:element name="product_name" type="xsd:string" /> <xsd:element ref="quantity" /> <xsd:element ref="price" /> </xsd:sequence> <xsd:attribute name="part_number" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> <xsd:element name="items"> <xsd:complexType> <xsd:sequence> <xsd:element maxOccurs="unbounded" minOccurs="1" ref="item" /> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="name" type="xsd:string" /> <xsd:element name="price" type="xsd:decimal" /> <xsd:element name="purchase_order"> <xsd:complexType> <xsd:sequence> <xsd:element name="shipping_address" type="us_address" /> <xsd:element ref="items" /> </xsd:sequence> <xsd:attribute name="order_date" type="xsd:date" use="required" /> </xsd:complexType> </xsd:element> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction> </xsd:simpleType> </xsd:element> <xsd:complexType name="us_address"> <xsd:sequence> <xsd:element ref="name" /> <xsd:element ref="street" /> <xsd:element ref="city" /> <xsd:element ref="state" /> <xsd:element ref="zip" /> </xsd:sequence> <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US" /> </xsd:complexType> <xsd:element name="state" type="xsd:string" /> <xsd:element name="street" type="xsd:string" /> <xsd:element name="zip" type="xsd:string" /> </xsd:schema>

Default value of minOccurs is 1. Default value of maxOccurs is 1.

http://java.boot.by/wsd-guide/wsd-guide.html 11 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

XML Schema defines four main elements: 1. 2. 3. 4. xsd:element declares an element and assigns it a type. xsd:attribute declares an attribute and assigns it a type. xsd:complexType defines a new complex type. xsd:simpleType defines a new simple type.

Attribute values are always simple types. Attributes are unordered. It does not matter whether complex type is defined before or after the element declaration as long as it is present in the schema document. You can derive new simple types from existing types. An xsd:simpleType element defines the subtype. The name attribute of xsd: simpleType assigns a name to the new type, by which it can be referred to in xsd:element type attributes. An xsd:restriction child element derives by restricting the legal values of the base type. An xsd:list child element derives a type as a white space separated list of base type instances. An xsd:union child element derives by combining legal values from multiple base types. You can derive new simple types types from existing types by restricting the type to a subset of its normal values. An xsd:simpleType element defines the restricted type. The name attribute of xsd:simpleType assigns a name to the new type. An xsd:restriction child element specifies what type is being restricted via its base attribute. Facet children of xsd:restriction specify the constraints on the type. For example, this xsd:simpleType element defines a myYear as any year from 1974 on:

<xsd:simpleType name="myYear"> <xsd:restriction base="xsd:gYear"> <xsd:minInclusive value="1974"/> </xsd:restriction> </xsd:simpleType>

Then you declare the year element like this:

<xsd:element type="myYear" />

Facets include: length, minLength, maxLength, pattern, enumeration, whiteSpace, maxInclusive, maxExclusive, minInclusive, minExclusive, totalDigits, fractionDigits. Not all facets apply to all types. For example, new string type must contain between 1 and 255 characters:

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:simpleType name="Str255"> <xsd:restriction base="xsd:string"> <xsd:minLength value="1"/> <xsd:maxLength value="255"/> </xsd:restriction> </xsd:simpleType> </xsd:schema>

For example, the new year type must be between 1974 and 2100:

<?xml version="1.0"?>
http://java.boot.by/wsd-guide/wsd-guide.html 12 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:simpleType name="myYear"> <xsd:restriction base="xsd:gYear"> <xsd:minInclusive value="1974"/> <xsd:maxInclusive value="2100"/> </xsd:restriction> </xsd:simpleType> </xsd:schema>

The enumeration facet lists all allowed values. Applies to all simple types except boolean. For example, the computer brand name must be one of the following : COMPAQ, DELL, HP.

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:simpleType name="computerBrandName"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="COMPAQ"/> <xsd:enumeration value="DELL"/> <xsd:enumeration value="HP"/> </xsd:restriction> </xsd:simpleType> </xsd:schema>

Each element in the xsd:all group must occur zero or once; that is minOccurs and maxOccurs must each be 0 or 1. The xsd:all group must be the top level element of its type. The xsd:all group may contain only individual element declarations; no choices or sequences. Example:

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:complexType name="personName"> <xsd:all> <xsd:element name="firstName" type="xsd:string"/> <xsd:element name="lastName" type="xsd:string"/> </xsd:all> </xsd:complexType> </xsd:schema>

xsd:choice requires exactly one of a group of specified elements to appear. The choice can have minOccurs and maxOccurs attributes that adjust this from zero to any given number. Example:

<?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:complexType name="coputer"> <xsd:sequence> <xsd:element name="name" type="xsd:string"/> <xsd:choice minOccurs="1" maxOccurs="1"> <xsd:element name="desktop" type="xsd:string"/> <xsd:element name="notebook" type="xsd:string"/> <xsd:element name="handheld" type="xsd:string"/>
http://java.boot.by/wsd-guide/wsd-guide.html 13 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

</xsd:choice> </xsd:sequence> </xsd:complexType> </xsd:schema>

xsd:sequence requires each child element it specifies to appear in the specified order. The sequence can have minOccurs and maxOccurs attributes that repeat each sequence zero to any given number of times.

Describe the use of namespaces in an XML document.


The XML namespaces recommendation defines a way to distinguish between duplicate element type and attribute names. Such duplication might occur, for example, in an XSLT stylesheet or in a document that contains element types and attributes from two different DTDs. An XML namespace is a collection of element type and attribute names. The namespace is identified by a unique name, which is a URI. Thus, any element type or attribute name in an XML namespace can be uniquely identified by a two-part name: the name of its XML namespace and its local name. This two-part naming system is the only thing defined by the XML namespaces recommendation. XML namespaces are declared with an xmlns attribute, which can associate a prefix with the namespace. You can declare an XML namespace on any element in an XML document. The declaration is in scope for the element containing the attribute and all its descendants (unless it is overridden or undeclared on one of those descendants). It is a common practice to declare all namespaces within the root element. For example:

<!-- Declares two XML namespaces. Their scope is the 'aaa' and 'bbb' elements. --> <aaa xmlns:foo="http://www.foo.org/" xmlns="http://www.bar.org/"> <bbb>abcd</bbb> </aaa>

If an XML namespace declaration contains a prefix, you refer to element type and attribute names in that namespace with the prefix. For example:

<!-- 'aaa' and 'bbb' are in the 'http://www.foo.org/' namespace, which is associated with the 'foo' prefix. --> <foo:aaa xmlns:foo="http://www.foo.org/"> <foo:bbb>abcd</foo:bbb> </foo:aaa>

If an XML namespace declaration does not contain a prefix, the namespace is the default XML namespace and you refer to element type names in that namespace without a prefix. For example:

<!-- This is equivalent to the previous example but uses a DEFAULT namespace instead of the 'foo' prefix. --> <aaa xmlns="http://www.foo.org/"> <bbb>abcd<bbb> </aaa>

The value (unique URI) of the xmlns attribute identifies the namespace, not the prefix. In this example, all elements belong to the same namespace although different prefixes are used.

http://java.boot.by/wsd-guide/wsd-guide.html 14 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<!-- 'aaa' and 'bbb' belong to the same 'http://www.foo.org/' namespace. --> <foo:aaa xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.foo.org/"> <bar:bbb>abcd</bar:bbb> </foo:aaa>

In this example, all elements belong to different namespaces although they have the same prefixes.

<!-- 'aaa' and 'bbb' belong to different namespaces. --> <foo:aaa xmlns:foo="http://www.foo.org/"> <foo:aaa /> </foo:aaa> <foo:bbb xmlns:foo="http://www.bar.org/"> <foo:bbb /> </foo:bbb>

You may override the prefix used in an XML namespace declaration, simply declare another XML namespace with the same prefix. For example, in the following, the foo prefix is associated with the http://www.foo.org/ namespace on the aaa element and the http://www.bar. org/ namespace on the bbb element. That is, the name aaa is in the http://www.foo.org/ namespace and the name bbb is in the http://www. bar.org/ namespace.

<!-- 'bbb' belongs to overriden 'http://www.bar.org/' namespace. --> <foo:aaa xmlns:foo="http://www.foo.org/"> <foo:bbb xmlns:foo="http://www.bar.org/">abcd</foo:bbb> </foo:aaa>

This practice leads to documents that are confusing to read and should be avoided. When an XML namespace declaration goes out of scope, it simply no longer applies. For example, in the following, the declaration of the http://www.foo.org/ namespace does not apply to the bbb element because this is outside its scope.

<!-- 'bbb' does NOT belong to any namespace. --> <aaa xmlns="http://www.foo.org/">abcd</aaa> <bbb>abcd</bbb>

You may undeclare the default XML namespace - declare a default XML namespace with an empty (zero-length) name (URI). Within the scope of this declaration, unprefixed element type names do not belong to any XML namespace. For example, in the following, the default XML namespace is the http://www.foo.org/ for the aaa and there is no default XML namespace for the bbb elements. The name aaa is in the http://www.foo.org/ namespace and the name bbb is not in any XML namespace.

<!-- 'bbb' does NOT belong to any namespace. --> <aaa xmlns="http://www.foo.org/"> <aaa>

http://java.boot.by/wsd-guide/wsd-guide.html 15 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<bbb xmlns=""> <bbb>abcd</bbb> </bbb> </aaa> </aaa>

You may NOT undeclare XML namespace prefix. It remains in scope until the end of the element on which it was declared unless it is overridden. Furthermore, trying to undeclare a prefix by redeclaring it with an empty (zero-length) name (URI) results in a namespace error. For example:

<!-- You may NOT undeclare XML namespace prefix. --> <foo:aaa xmlns:foo="http://www.foo.org/"> <foo:aaa> <foo"bbb xmlns:foo=""> <!-- ERROR --> <foo:bbb>abcd</foo:bbb> </foo:bbb> </foo:aaa> </foo:aaa>

Attributes can be also explicitly assigned to the given namespace. See the example:

<!-You may assign namespaces to attributes. 'bbb' element belongs to 'http://www.bar.org/' namespace. 'attr' attribute belongs to 'http://www.foo.org/' namespace. --> <foo:aaa xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org/"> <bar:bbb foo:attr="attribute">abcd</bar:bbb> </foo:aaa>

Attributes without a prefix never belongs to any namespace. The attributes do not belong to any namespace even if a default namespace is defined for the relevant element.

Chapter 2. SOAP 1.1 Web Service Standards

List and describe the encoding types used in a SOAP message.


The SOAP encoding style is based on a simple type system that is a generalization of the common features found in type systems in programming languages, databases and semi-structured data. A type either is a simple (scalar) type or is a compound type constructed as a composite of several parts, each with a type. This is described in more detail below. This section defines rules for serialization of a graph of typed objects. It operates on two levels. First, given a schema in any notation consistent with the type system described, a schema for an XML grammar may be constructed. Second, given a type-system schema and a particular graph of values conforming to that schema, an XML instance may be constructed. In reverse, given an XML instance produced in accordance with these rules, and given also the original schema, a copy of the original value graph may be constructed. There are following SOAP encoding types:

Simple Types
r r

Strings Enumerations

http://java.boot.by/wsd-guide/wsd-guide.html 16 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

Array of Bytes

Compound Types
r r

Arrays Structures

Simple Types For simple types, SOAP adopts all the types found in the section "Built-in datatypes" of the "XML Schema Part 2: Datatypes" Specification, both the value and lexical spaces. Examples include: boolean (true, false, 0 or 1), byte, short, int, long, float, double, string (java.lang.String), decimal (java.math.BigDecimal), date (java.util.GregorianCalendar), dateTime (java.util.Date), SOAP-ENC:base64 (byte []). The following examples are a SOAP representation of these primitive data types:

<element name="age" type="int"/> <element name="height" type="float"/> <element name="displacement" type="negativeInteger"/> <element name="color"> <simpleType base="xsd:string"> <enumeration value="Green"/> <enumeration value="Blue"/> </simpleType> </element> <age>45</age> <height>5.9</height> <displacement>-450</displacement> <color>Blue</color>

Strings The datatype "string" is defined in "XML Schema Part 2: Datatypes" Specification. Note that this is not identical to the type called "string" in many database or programming languages, and in particular may forbid some characters those languages would permit. (Those values must be represented by using some datatype other than xsd:string.) A string MAY be encoded as a single-reference or a multireference value. The containing element of the string value MAY have an "id" attribute. Additional accessor elements MAY then have matching "href" attributes. For example, two accessors to the same string could appear, as follows:

<greeting id="String-0">Hello</greeting> <salutation href="#String-0"/>

However, if the fact that both accessors reference the same instance of the string (or subtype of string) is immaterial, they may be encoded as two single-reference values as follows:

<greeting>Hello</greeting> <salutation>Hello</salutation>

Schema fragments for these examples could appear similar to the following:

<element name="greeting" type="SOAP-ENC:string"/> <element name="salutation" type="SOAP-ENC:string"/>


http://java.boot.by/wsd-guide/wsd-guide.html 17 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

(In this example, the type SOAP-ENC:string is used as the element's type as a convenient way to declare an element whose datatype is "xsd:string" and which also allows an "id" and "href" attribute. See the SOAP Encoding schema for the exact definition. Schemas MAY use these declarations from the SOAP Encoding schema but are not required to.) Enumerations Enumeration as a concept indicates a set of distinct names. A specific enumeration is a specific list of distinct values appropriate to the base type. For example the set of color names ("Green", "Blue", "Brown") could be defined as an enumeration based on the string built-in type. The values ("1", "3", "5") are a possible enumeration based on integer, and so on. "XML Schema Part 2: Datatypes" supports enumerations for all of the simple types except for boolean. The language of "XML Schema Part 1: Structures" Specification can be used to define enumeration types. If a schema is generated from another notation in which no specific base type is applicable, use "string". In the following schema example "EyeColor" is defined as a string with the possible values of "Green", "Blue", or "Brown" enumerated, and instance data is shown accordingly:

<element name="EyeColor" type="tns:EyeColor"/> <simpleType name="EyeColor" base="xsd:string"> <enumeration value="Green"/> <enumeration value="Blue"/> <enumeration value="Brown"/> </simpleType> <Person> <Name>Henry Ford</Name> <Age>32</Age> <EyeColor>Brown</EyeColor> </Person>

Array of Bytes An array of bytes MAY be encoded as a single-reference or a multi-reference value. The rules for an array of bytes are similar to those for a string. In particular, the containing element of the array of bytes value MAY have an "id" attribute. Additional accessor elements MAY then have matching "href" attributes. The recommended representation of an opaque array of bytes is the 'base64' encoding defined in XML Schemas, which uses the base64 encoding algorithm. However, the line length restrictions that normally apply to base64 data in MIME do not apply in SOAP. A "SOAP-ENC:base64" subtype is supplied for use with SOAP:

<picture xsi:type="SOAP-ENC:base64"> aG93IG5vDyBicm73biBjb3cNCg== </picture>

Polymorphic Accessor Many languages allow accessors that can polymorphically access values of several types, each type being available at run time. A polymorphic accessor instance MUST contain an "xsi:type" attribute that describes the type of the actual value. For example, a polymorphic accessor named "cost" with a value of type "xsd:float" would be encoded as follows:

<cost xsi:type="xsd:float">29.95</cost>

as contrasted with a cost accessor whose value's type is invariant, as follows:

http://java.boot.by/wsd-guide/wsd-guide.html 18 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<cost>29.95</cost>

Compound types A "struct" is a compound value in which accessor name is the only distinction among member values, and no accessor has the same name as any other. An "array" is a compound value in which ordinal position serves as the only distinction among member values. Structures The members of a Compound Value are encoded as accessor elements. When accessors are distinguished by their name (as for example in a struct), the accessor name is used as the element name. Accessors whose names are local to their containing types have unqualified element names; all others have qualified names. The following is an example of a struct of type "book":

<book> <author>Mikalai Zaikin</author> <title>SCDJWS Study Guide</title> <intro>This is a certification guide</intro> </book>

And this is a schema fragment describing the above structure:

<xsd:element name="book"> <xsd:complexType> <xsd:sequence> <xsd:element name="author" type="xsd:string" /> <xsd:element name="title" type="xsd:string" /> <xsd:element name="intro" type="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:element>

The structure also can contain both simple and complex data type values that can reference each other. Below is an example of a type with both simple and complex members. It shows two levels of referencing. Note that the "href" attribute of the "author" accessor element is a reference to the value whose "id" attribute matches. A similar construction appears for the "address" element:

<book> <title>SCDJWS Study Guide</title> <author href="#person-1" /> </book> <person id="person-1"> <name>Mikalai Zaikin</name> <address href="#address-1" /> </person> <inet_address id="address-1"> <email>mailto:nikolay_zaikin[at]mail.ru</email> <web>http://www.iba.by</web> </inet_address>
http://java.boot.by/wsd-guide/wsd-guide.html 19 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

Arrays SOAP arrays are defined as having a type of "SOAP-ENC:Array" or a type derived there from. Arrays are represented as element values, with no specific constraint on the name of the containing element (just as values generally do not constrain the name of their containing element). Arrays can contain elements which themselves can be of any type, including nested arrays. New types formed by restrictions of SOAP-ENC:Array can also be created to represent, for example, arrays limited to integers or arrays of some user-defined enumeration. The representation of the value of an array is an ordered sequence of elements constituting the items of the array. Within an array value, element names are not significant for distinguishing accessors. Elements may have any name. In practice, elements will frequently be named so that their declaration in a schema suggests or determines their type. As with compound types generally, if the value of an item in the array is a single-reference value, the item contains its value. Otherwise, the item references its value via an "href" attribute. The following example is a schema fragment and an array containing integer array members:

<element name="myFavoriteNumbers" type="SOAP-ENC:Array"/> <myFavoriteNumbers SOAP-ENC:arrayType="xsd:int[3]"> <number>1</number> <number>2</number> <number>3</number> </myFavoriteNumbers>

In that example, the array "myFavoriteNumbers" contains several members each of which is a value of type SOAP-ENC:int. This can be determined by inspection of the SOAP-ENC:arrayType attribute. Note that the SOAP-ENC:Array type allows unqualified element names without restriction. These convey no type information, so when used they must either have an xsi:type attribute or the containing element must have a SOAP-ENC:arrayType attribute. Naturally, types derived from SOAP-ENC:Array may declare local elements, with type information. As previously noted, the SOAP-ENC schema contains declarations of elements with names corresponding to each simple type in the "XML Schema Part 2: Datatypes" Specification. It also contains a declaration for "Array". Using these, we might write:

<SOAP-ENC:Array SOAP-ENC:arrayType="xsd:int[3]"> <SOAP-ENC:int>1</SOAP-ENC:int> <SOAP-ENC:int>2</SOAP-ENC:int> <SOAP-ENC:int>3</SOAP-ENC:int> </SOAP-ENC:Array>

Arrays can contain instances of any subtype of the specified arrayType. That is, the members may be of any type that is substitutable for the type specified in the arrayType attribute, according to whatever substitutability rules are expressed in the schema. So, for example, an array of integers can contain any type derived from integer (for example "int" or any user-defined derivation of integer). Similarly, an array of "address" might contain a restricted or extended type such as "internationalAddress". Because the supplied SOAP-ENC:Array type admits members of any type, arbitrary mixtures of types can be contained unless specifically limited by use of the arrayType attribute. Array values may be structs or other compound values. For example an array of "my:order" structs :

<SOAP-ENC:Array SOAP-ENC:arrayType="my:order[2]"> <order> <product>Melon</product> <price>0.99</price> </order> <order> <product>Apple</product> <price>1.49</price> </order> </SOAP-ENC:Array>

http://java.boot.by/wsd-guide/wsd-guide.html 20 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

Arrays may have other arrays as member values. The following is an example of an array of two arrays, each of which is an array of strings:

<SOAP-ENC:Array SOAP-ENC:arrayType="xsd:string[][2]"> <item href="#array-1"/> <item href="#array-2"/> </SOAP-ENC:Array> <SOAP-ENC:Array id="array-1" SOAP-ENC:arrayType="xsd:string[3]"> <item>row1column1</item> <item>row1column2</item> <item>row1column3</item> </SOAP-ENC:Array> <SOAP-ENC:Array id="array-2" SOAP-ENC:arrayType="xsd:string[2]"> <item>row2column1</item> <item>row2column2</item> </SOAP-ENC:Array>

Arrays may be multi-dimensional. In this case, more than one size will appear within the asize part of the arrayType attribute:

<SOAP-ENC:Array SOAP-ENC:arrayType="xsd:string[2,3]"> <item>row1column1</item> <item>row1column2</item> <item>row1column3</item> <item>row2column1</item> <item>row2ccolumn2</item> <item>row2column3</item> </SOAP-ENC:Array>

Describe how SOAP message header blocks are used and processed.
SOAP provides a flexible mechanism for extending a message in a decentralized and modular way without prior knowledge between the communicating parties. Typical examples of extensions that can be implemented as header entries are authentication, transaction management, payment etc. The Header element is encoded as the first immediate child element of the SOAP Envelope XML element. NOTE: The Header element is OPTIONAL. All immediate child elements of the Header element are called header entries (Header element may contain multiple child elements - header entries). Header entries can have following attributes: actor, encodingStyle, mustUnderstand. The encoding rules for header entries are as follows: 1. A header entry is identified by its fully qualified element name, which consists of the namespace URI and the local name. All immediate child elements of the SOAP Header element MUST be namespace-qualified. 2. The SOAP encodingStyle attribute MAY be used to indicate the encoding style used for the header entries. 3. The SOAP mustUnderstand attribute and SOAP actor attribute MAY be used to indicate how to process the entry and by whom. The SOAP Header attributes defined in this section determine how a recipient of a SOAP message should process the message. A SOAP application generating a SOAP message SHOULD only use the SOAP Header attributes on immediate child elements of the SOAP Header element. The recipient of a SOAP message MUST ignore all SOAP Header attributes that are not applied to an immediate child element of the SOAP Header element.
http://java.boot.by/wsd-guide/wsd-guide.html 21 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

An example is a header with an element identifier of "Transaction", a "mustUnderstand" value of "1", and a value of 12345. This would be encoded as follows:

<SOAP-ENV:Header> <t:Transaction xmlns:t="some-URI" SOAP-ENV:mustUnderstand="1"> 12345 </t:Transaction> </SOAP-ENV:Header>

or

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <t:Transaction xmlns:t="some-URI" soap:mustUnderstand="1"> 12345 </t:Transaction> </soap:Header> ... ... </soap:Envelope>

A SOAP message travels from the originator to the ultimate destination, potentially by passing through a set of SOAP intermediaries along the message path. A SOAP intermediary is an application that is capable of both receiving and forwarding SOAP messages. Both intermediaries as well as the ultimate destination are identified by a URI. Not all parts of a SOAP message may be intended for the ultimate destination of the SOAP message but, instead, may be intended for one or more of the intermediaries on the message path. The role of a recipient of a header element is similar to that of accepting a contract in that it cannot be extended beyond the recipient. That is, a recipient receiving a header element MUST NOT forward that header element to the next application in the SOAP message path. The recipient MAY insert a similar header element but in that case, the contract is between that application and the recipient of that header element. The SOAP actor global attribute can be used to indicate the recipient of a header element. The value of the SOAP actor attribute is a URI:

SOAP-ENV:actor="some-URI"

or

soap:actor="some-URI"

The special URI "http://schemas.xmlsoap.org/soap/actor/next" indicates that the header element is intended for the very first SOAP application that processes the message. This is similar to the hop-by-hop scope model represented by the Connection header field in HTTP. NOTE: Omitting the SOAP actor attribute indicates that the recipient is the ultimate destination of the SOAP message. This attribute MUST appear in the SOAP message instance in order to be effective. An example:

http://java.boot.by/wsd-guide/wsd-guide.html 22 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <t:Transaction xmlns:t="some-URI" soap:actor="http://myserver.com/myactor"> 12345 </t:Transaction> </soap:Header> ... ... </soap:Envelope>

In this example header will be processed by first application:

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <t:Transaction xmlns:t="some-URI" soap:actor="http://schemas.xmlsoap.org/soap/actor/next"> 12345 </t:Transaction> </soap:Header> ... ... </soap:Envelope>

The SOAP mustUnderstand global attribute can be used to indicate whether a header entry is mandatory or optional for the recipient to process. The recipient of a header entry is defined by the SOAP actor attribute. The value of the mustUnderstand attribute is either "1" or "0".

SOAP-ENV:mustUnderstand="0|1"

or

soap:mustUnderstand="0|1"

The absence of the SOAP mustUnderstand attribute is semantically equivalent to its presence with the value "0". If a header element is tagged with a SOAP mustUnderstand attribute with a value of "1", the recipient of that header entry either MUST obey the semantics (as conveyed by the fully qualified name of the element) and process correctly to those semantics, or MUST fail processing the message. The SOAP mustUnderstand attribute allows for robust evolution. Elements tagged with the SOAP mustUnderstand attribute with a value of "1" MUST be presumed to somehow modify the semantics of their parent or peer elements. Tagging elements in this manner assures that this change in semantics will not be silently (and, presumably, erroneously) ignored by those who may not fully understand it. This attribute MUST appear in the instance in order to be effective. An example:

http://java.boot.by/wsd-guide/wsd-guide.html 23 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <t:Transaction xmlns:t="some-URI" soap:actor="http://myserver.com/myactor" soap:mustUnderstand="1"> 12345 </t:Transaction> </soap:Header> ... ... </soap:Envelope>

Describe the function of each element contained in a SOAP message, the SOAP binding to HTTP, and how to represent faults that occur when processing a SOAP message.
A SOAP message is an XML document that consists of a mandatory SOAP envelope, an optional SOAP header, and a mandatory SOAP body. The namespace identifier for the elements and attributes from SOAP message is "http://schemas.xmlsoap.org/soap/envelope/". A SOAP message contains the following:

The Envelope is the top element of the XML document representing the message. The Header is a generic mechanism for adding features to a SOAP message in a decentralized manner without prior agreement between the communicating parties. SOAP defines a few attributes that can be used to indicate who should deal with a feature and whether it is optional or mandatory. NOTE: Header element is OPTIONAL. The Body is a container for mandatory information intended for the ultimate recipient of the message. SOAP defines one element for the body, which is the Fault element used for reporting errors. NOTE: Body element is MANDATORY and MUST be exactly 1 per message.

The grammar rules are as follows: 1. Envelope


The element name is "Envelope". The element MUST be present in a SOAP message. The element MAY contain namespace declarations as well as additional attributes. If present, such additional attributes MUST be namespace-qualified. Similarly, the element MAY contain additional sub elements. If present these elements MUST be namespace-qualified and MUST follow the SOAP Body element.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> <xs:complexType name="Envelope"> <xs:sequence> <xs:element ref="tns:Header" minOccurs="0" /> <xs:element ref="tns:Body" minOccurs="1" /> <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax" /> </xs:complexType> .... </xs:schema>

2. Header
http://java.boot.by/wsd-guide/wsd-guide.html 24 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

The element name is "Header". The element MAY be present in a SOAP message. If present, the element MUST be the first immediate child element of a SOAP Envelope element. The element MAY contain a set of header entries each being an immediate child element of the SOAP Header element. All immediate child elements of the SOAP Header element MUST be namespace-qualified.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> .... <xs:complexType name="Header"> <xs:sequence> <xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> <xs:anyAttribute namespace="##other" processContents="lax" /> </xs:complexType> .... </xs:schema>

3. Body

The element name is "Body". The element MUST be present in a SOAP message and MUST be an immediate child element of a SOAP Envelope element. It MUST directly follow the SOAP Header element if present. Otherwise it MUST be the first immediate child element of the SOAP Envelope element. The element MAY contain a set of body entries each being an immediate child element of the SOAP Body element. Immediate child elements of the SOAP Body element MAY be namespace-qualified. SOAP defines the SOAP Fault element, which is used to indicate error messages.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> .... <xs:complexType name="Body"> <xs:sequence> <xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> <xs:anyAttribute namespace="##any" processContents="lax"> <xs:annotation> <xs:documentation> Prose in the spec does not specify that attributes are allowed on the Body element </xs:documentation> </xs:annotation> </xs:anyAttribute> </xs:complexType> .... </xs:schema>

The SOAP Body element provides a simple mechanism for exchanging mandatory information intended for the ultimate recipient of the message. Typical uses of the Body element include marshalling RPC calls and error reporting. The Body element is encoded as an immediate child element of the SOAP Envelope XML element. If a Header element is present then the Body element MUST immediately follow the Header element, otherwise it MUST be the first immediate child element of the Envelope element. All immediate child elements of the Body element are called body entries and each body entry is encoded as an independent element within the SOAP Body element. The encoding rules for body entries are as follows:

http://java.boot.by/wsd-guide/wsd-guide.html 25 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

1. A body entry is identified by its fully qualified element name, which consists of the namespace URI and the local name. Immediate child elements of the SOAP Body element MAY be namespace-qualified. 2. The SOAP encodingStyle attribute MAY be used to indicate the encoding style used for the body entries (this attribute MAY appear on any element, and is scoped to that element's contents and all child elements not themselves containing such an attribute, much as an XML namespace declaration is scoped). SOAP defines one body entry, which is the Fault entry used for reporting errors. Here is schema definition of Fault element:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> .... <xs:complexType name="Fault" final="extension"> <xs:annotation> <xs:documentation>Fault reporting structure</xs:documentation> </xs:annotation> <xs:sequence> <xs:element name="faultcode" type="xs:QName" /> <xs:element name="faultstring" type="xs:string" /> <xs:element name="faultactor" type="xs:anyURI" minOccurs="0" /> <xs:element name="detail" type="tns:detail" minOccurs="0" /> </xs:sequence> </xs:complexType> .... </xs:schema>

SOAP Fault The SOAP Fault element is used to carry error and/or status information within a SOAP message. If present, the SOAP Fault element MUST appear as a body entry and MUST NOT appear more than once within a Body element. The SOAP Fault element defines the following four subelements: 1. faultcode - The faultcode element is intended for use by software to provide an algorithmic mechanism for identifying the fault. The faultcode MUST be present in a SOAP Fault element and the faultcode value MUST be a qualified name. SOAP defines a small set of SOAP fault codes covering basic SOAP faults. 2. faultstring - The faultstring element is intended to provide a human readable explanation of the fault and is not intended for algorithmic processing. The faultstring element is similar to the 'Reason-Phrase' defined by HTTP. It MUST be present in a SOAP Fault element and SHOULD provide at least some information explaining the nature of the fault. 3. faultactor - The faultactor element is intended to provide information about who caused the fault to happen within the message path. It is similar to the SOAP actor attribute but instead of indicating the destination of the header entry, it indicates the source of the fault. The value of the faultactor attribute is a URI identifying the source. Applications that do not act as the ultimate destination of the SOAP message MUST include the faultactor element in a SOAP Fault element. The ultimate destination of a message MAY use the faultactor element to indicate explicitly that it generated the fault. 4. detail - The detail element is intended for carrying application specific error information related to the Body element. It MUST be present if the contents of the Body element could not be successfully processed. It MUST NOT be used to carry information about error information belonging to header entries. Detailed error information belonging to header entries MUST be carried within header entries. The absence of the detail element in the Fault element indicates that the fault is not related to processing of the Body element. This can be used to distinguish whether the Body element was processed or not in case of a fault situation. All immediate child elements of the detail element are called detail entries and each detail entry is encoded as an independent element within the detail element.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.xmlsoap.org/soap/envelope/" targetNamespace="http://schemas.xmlsoap.org/soap/envelope/"> .... <xs:complexType name="detail"> <xs:sequence> <xs:any namespace="##any" minOccurs="0" maxOccurs="unbounded" processContents="lax" /> </xs:sequence> <xs:anyAttribute namespace="##any" processContents="lax" />
http://java.boot.by/wsd-guide/wsd-guide.html 26 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

</xs:complexType> .... </xs:schema>

The encoding rules for detail entries are as follows: a. A detail entry is identified by its fully qualified element name, which consists of the namespace URI and the local name. Immediate child elements of the detail element MAY be namespace-qualified. b. The SOAP encodingStyle attribute MAY be used to indicate the encoding style used for the detail entries The faultcode values MUST be used in the faultcode element when describing faults. The namespace identifier for these faultcode values is "http://schemas.xmlsoap.org/soap/envelope/". The default SOAP faultcode values are defined in an extensible manner that allows for new SOAP faultcode values to be defined while maintaining backwards compatibility with existing faultcode values. The mechanism used is very similar to the 1xx, 2xx, 3xx etc basic status classes classes defined in HTTP. However, instead of integers, they are defined as XML qualified names. The character "." (dot) is used as a separator of faultcode values indicating that what is to the left of the dot is a more generic fault code value than the value to the right. Example:

Client.Authentication

The set of faultcode values is: Table 2.1. SOAP Fault Codes
Error VersionMismatch MustUnderstand Description The processing party found an invalid namespace for the SOAP Envelope element. An immediate child element of the SOAP Header element that was either not understood or not obeyed by the processing party contained a SOAP mustUnderstand attribute with a value of "1". The Client class of errors indicate that the message was incorrectly formed or did not contain the appropriate information in order to succeed. For example, the message could lack the proper authentication or payment information. It is generally an indication that the message should not be resent without change. The Server class of errors indicate that the message could not be processed for reasons not directly attributable to the contents of the message itself but rather to the processing of the message. For example, processing could include communicating with an upstream processor, which didn't respond. The message may succeed at a later point in time.

Client

Server

Using SOAP in HTTP Binding SOAP to HTTP provides the advantage of being able to use the formalism and decentralized flexibility of SOAP with the rich feature set of HTTP. Carrying SOAP in HTTP does not mean that SOAP overrides existing semantics of HTTP but rather that the semantics of SOAP over HTTP maps naturally to HTTP semantics. SOAP naturally follows the HTTP request/response message model providing SOAP request parameters in a HTTP request and SOAP response parameters in a HTTP response. Note, however, that SOAP intermediaries are NOT the same as HTTP intermediaries. That is, an HTTP intermediary addressed with the HTTP Connection header field cannot be expected to inspect or process the SOAP entity body carried in the HTTP request. HTTP applications MUST use the media type "text/xml" when including SOAP entity bodies in HTTP messages. The SOAPAction HTTP request header field can be used to indicate the intent of the SOAP HTTP request. The value is a URI identifying the intent. SOAP places no restrictions on the format or specificity of the URI or that it is resolvable. An HTTP client MUST use this header field when issuing a SOAP HTTP Request. The presence and content of the SOAPAction header field can be used by servers such as firewalls to appropriately filter SOAP request messages in HTTP. The header field value of empty string ("") means that the intent of the SOAP message is provided by the HTTP Request-URI. No value means that there is no indication of the intent of the message. Examples:

SOAPAction: "http://electrocommerce.org/abc#MyMessage"

http://java.boot.by/wsd-guide/wsd-guide.html 27 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

SOAPAction: "myapp.sdl"

SOAPAction: ""

SOAPAction:

SOAP HTTP follows the semantics of the HTTP Status codes for communicating status information in HTTP. For example, a 2xx status code indicates that the client's request including the SOAP component was successfully received, understood, and accepted etc. In case of a SOAP error while processing the request, the SOAP HTTP server MUST issue an HTTP 500 "Internal Server Error" response and include a SOAP message in the response containing a SOAP Fault element indicating the SOAP processing error. Below is an example of HTTP request, successful response and fault response of simple Web Service for retrieving Quote information. Quote SOAP HTTP request:

POST /StockQuoteProj/servlet/rpcrouter HTTP/1.0 Host: localhost:9080 Content-Type: text/xml; charset=utf-8 Content-Length: 469 SOAPAction: "" <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getQuote xmlns:ns1="http://tempuri.org/StockQuoteService" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <symbol xsi:type="xsd:string">ibm</symbol> </ns1:getQuote> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Quote SOAP HTTP successful response:

HTTP/1.1 200 OK Server: WebSphere Application Server/5.1 Content-Type: text/xml; charset=utf-8 Content-Length: 488 Content-Language: ru-RU Connection: close <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"

http://java.boot.by/wsd-guide/wsd-guide.html 28 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getQuoteResponse xmlns:ns1="http://tempuri.org/StockQuoteService" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <return xsi:type="xsd:float">93.12</return> </ns1:getQuoteResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Quote SOAP HTTP fault response (exception is thrown by service endpoint object):

HTTP/1.1 500 Internal Server Error Server: WebSphere Application Server/5.1 Expires: Thu, 01 Dec 1994 16:00:00 GMT Set-Cookie: JSESSIONID=0000XEtXnz75hI--bFdY49XCHGU:-1;Path=/ Cache-Control: no-cache="set-cookie,set-cookie2" <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Exception from service object: null</faultstring> <faultactor>/StockQuoteProj/servlet/rpcrouter</faultactor> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP request Using POST with a Mandatory Header:

POST /StockQuote HTTP/1.1 Host: www.stockquoteserver.com Content-Type: text/xml; charset="utf-8" Content-Length: nnnn SOAPAction: "Some-URI" <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Header> <t:Transaction xmlns:t="some-URI" SOAP-ENV:mustUnderstand="1"> 12345 </t:Transaction> </SOAP-ENV:Header> <SOAP-ENV:Body> <m:GetLastTradePrice xmlns:m="Some-URI"> <symbol>DEF</symbol> </m:GetLastTradePrice> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP request Using POST with multiple request parameters:

http://java.boot.by/wsd-guide/wsd-guide.html 29 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

POST /StockQuote HTTP/1.1 Host: www.stockquoteserver.com Content-Type: text/xml; charset="utf-8" Content-Length: nnnn SOAPAction: "Some-URI" <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <m:GetLastTradePriceDetailed xmlns:m="Some-URI"> <Symbol>DEF</Symbol> <Company>DEF Corp</Company> <Price>34.1</Price> </m:GetLastTradePriceDetailed> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP response with a Mandatory Header:

HTTP/1.1 200 OK Content-Type: text/xml; charset="utf-8" Content-Length: nnnn <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Header> <t:Transaction xmlns:t="some-URI" xsi:type="xsd:int" mustUnderstand="1"> 12345 </t:Transaction> </SOAP-ENV:Header> <SOAP-ENV:Body> <m:GetLastTradePriceResponse xmlns:m="Some-URI"> <Price>34.5</Price> </m:GetLastTradePriceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP response with a Struct:

HTTP/1.1 200 OK Content-Type: text/xml; charset="utf-8" Content-Length: nnnn <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <m:GetLastTradePriceResponse xmlns:m="Some-URI"> <PriceAndVolume> <LastTradePrice> 34.5 </LastTradePrice> <DayVolume> 10000 </DayVolume>
http://java.boot.by/wsd-guide/wsd-guide.html 30 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

</PriceAndVolume> </m:GetLastTradePriceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP response Failing to honor Mandatory Header:

HTTP/1.1 500 Internal Server Error Content-Type: text/xml; charset="utf-8" Content-Length: nnnn <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>SOAP-ENV:MustUnderstand</faultcode> <faultstring>SOAP Must Understand Error</faultstring> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Example of SOAP HTTP response Failing to handle Body:

HTTP/1.1 500 Internal Server Error Content-Type: text/xml; charset="utf-8" Content-Length: nnnn <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Server Error</faultstring> <detail> <e:myfaultdetails xmlns:e="Some-URI"> <message> My application didn't work </message> <errorcode> 1001 </errorcode> </e:myfaultdetails> </detail> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

Create a SOAP message that contains an attachment.


The SOAP with Attachments API for Java (SAAJ) provides a standard way to send XML documents over the Internet from the Java platform. It is based on the SOAP 1.1 and SOAP with Attachments specifications, which define a basic framework for exchanging XML messages.

http://java.boot.by/wsd-guide/wsd-guide.html 31 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

The process of creation and sending SOAP message includes following steps:

Creating a SOAP connection Creating a SOAP message Populating the message Sending the message Retrieving the reply

A SAAJ client is a standalone client. That is, it sends point-to-point messages directly to a Web service that is implemented for requestresponse messaging. Request-response messaging is synchronous, meaning that a request is sent and its response is received in the same operation. A request-response message is sent over a SOAPConnection object via the method SOAPConnection.call, which sends the message and blocks until it receives a response. A standalone client can operate only in a client role, that is, it can only send requests and receive their responses. A SOAPMessage object represents an XML document that is a SOAP message. A SOAPMessage object always has a required SOAP part, and it may also have one or more attachment parts. The SOAP part must always have a SOAPEnvelope> object, which must in turn always contain a SOAPBody object. The SOAPEnvelope object may also contain a SOAPHeader object, to which one or more headers can be added. A SOAPMessage object represents an XML document that is a SOAP message. A SOAPMessage object always has a required SOAP part, and it may also have one or more attachment parts. The SOAP part must always have a SOAPEnvelope object, which must in turn always contain a SOAPBody> object. The SOAPEnvelope object may also contain a SOAPHeader> object, to which one or more headers can be added. The SOAPBody object can hold XML fragments as the content of the message being sent. If you want to send content that is not in XML format or that is an entire XML document, your message will need to contain an attachment part in addition to the SOAP part. There is no limitation on the content in the attachment part, so it can include images or any other kind of content, including XML fragments and documents. Common types of attachment include sound, picture, and movie data: .mp3, .jpg, and .mpg files. The first thing a SAAJ client needs to do is get a connection in the form of a SOAPConnection object. A SOAPConnection object is a pointto-point connection that goes directly from the sender to the recipient. The connection is created by a SOAPConnectionFactory object. A client obtains the default implementation for SOAPConnectionFactory by calling the following line of code:

SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();

The client can use factory to create a SOAPConnection object.

SOAPConnection connection = factory.createConnection();

Messages, like connections, are created by a factory. To obtain a MessageFactory object, you get an instance of the default implementation for the MessageFactory class. This instance can then be used to create a SOAPMessage object:

MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage message = messageFactory.createMessage();

All of the SOAPMessage objects that messageFactory creates, including message in the previous line of code, will be SOAP messages. This means that they will have no pre-defined headers. The new SOAPMessage object message automatically contains the required elements SOAPPart, SOAPEnvelope, and SOAPBody, plus the optional element SOAPHeader (which is included for convenience). The SOAPHeader and SOAPBody objects are initially empty, and the following sections will illustrate some of the typical ways to add content. Content can be added to the SOAPPart object, to one or more AttachmentPart objects, or to both parts of a message. As stated earlier, all messages have a SOAPPart object, which has a SOAPEnvelope object containing a SOAPHeader object and a SOAPBody object. One way to add content to the SOAP part of a message is to create a SOAPHeaderElement object or a SOAPBodyElement object and add an XML fragment that you build with the method SOAPElement.addTextNode. The first three lines of the following code fragment access the SOAPBody object body, which is used to create a new SOAPBodyElement object and add it to body. The argument passed to the createName method is a Name object identifying the SOAPBodyElement being added. The last line adds the XML string passed to the method addTextNode:

SOAPPart soapPart = message.getSOAPPart();


http://java.boot.by/wsd-guide/wsd-guide.html 32 / 133 2004/6/13 12:07:06

SCDJWS Study Guide

SOAPEnvelope envelope = soapPart.getSOAPEnvelope(); SOAPBody body = envelope.getSOAPBody(); SOAPBodyElement bodyElement = body.addBodyElement( envelope.createName("text", "hotitems", "http://hotitems.com/products/gizmo"); bodyElement.addTextNode("some-xml-text");

Another way is to add content to the SOAPPart object by passing it a javax.xml.transform.Source object, which may be a SAXSource, DOMSource, or StreamSource object. The Source object contains content for the SOAP part of the message and also the information needed for it to act as source input. A StreamSource object will contain the content as an XML document; the SAXSource or DOMSource object will contain content and instructions for transforming it into an XML document. The following code fragments illustrates adding content as a DOMSource object. The first step is to get the SOAPPart object from the SOAPMessage object. Next the code uses methods from the JAXP API to build the XML document to be added. It uses a DocumentBuilderFactory object to get a DocumentBuilder object. Then it parses the given file to produce the document that will be used to initialize a new DOMSource object. Finally, the code passes the DOMSource object domSource to the method SOAPPart.setContent:

SOAPPart soapPart = message.getSOAPPart(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbFactory.newDocumentBuilder(); Document document = builder.parse("file:///foo.bar/soap.xml"); DOMSource domSource = new DOMSource(document); soapPart.setContent(domSource);

This code would work equally well with a SAXSource or a StreamSource object. You use the setContent method when you want to send an existing SOAP message. If you have an XML document that you want to send as the content of a SOAP message, you use the addDocument method on the body of the message:

SOAPBodyElement docElement = body.addDocument(document);

This allows you to keep your application data in a document that is separate from the SOAP envelope unless and until it is time to send that data as a message. A Message object may have no attachment parts, but if it is to contain anything that is not in XML format, that content must be contained in an attachment part. There may be any number of attachment parts, and they may contain anything from plain text to image files. In the following code fragment, the content is an image in a JPEG file, whose URL is used to initialize the javax.activation. DataHandler object handler. The Message object message creates the AttachmentPart object attachPart, which is initialized with the data handler containing the URL for the image. Finally, the message adds attachPart to itself:

URL url = new URL("http://foo.bar/img.jpg"); DataHandler handler = new DataHandler(url); AttachmentPart attachPart = message.createAttachmentPart(handler); message.addAttachmentPart(attachPart);

A SOAPMessage object can also give content to an AttachmentPart object by passing an Object and its content type to the method createAttachmentPart:

AttachmentPart attachPart = message.createAttachmentPart( "content-string", "text/plain"); message.addAttachmentPart(attachPart);

Once you have populated a SOAPMessage object, you are ready to send it. A client uses the SOAPConnection method call to send a message. This method sends the message and then blocks until it gets back a response. The arguments to the method call are the message being sent and a URL object that contains the URL specifying the endpoint of the receiver.

http://java.boot.by/wsd-guide/wsd-guide.html 33 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

SOAPMessage response = soapConnection.call(message, endpoint);

Describe the restrictions placed on the use of SOAP by the WS-I Basic Profile 1.0a.
BP 1.0 - Messaging - XML Representation of SOAP Messages. When a MESSAGE contains a soap:Fault element, that element MUST NOT have element children other than faultcode, faultstring, faultactor and detail. CORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <faultcode>soap:Client</faultcode> <faultstring>Invalid message format</faultstring> <faultactor>http://example.org/someactor</faultactor> <detail> <m:msg xmlns:m='http://example.org/faults/exceptions'> There were <b>lots</b> of elements in the message that I did not understand </m:msg> <m:Exception xmlns:m='http://example.org/faults/exceptions'> <m:ExceptionType>Severe</m:ExceptionType> </m:Exception> </detail> </soap:Fault>

INCORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <faultcode>soap:Client</faultcode> <faultstring>Invalid message format</faultstring> <faultactor>http://example.org/someactor</faultactor> <detail>There were <b>lots</b> of elements in the message that I did not understand </detail> <m:Exception xmlns:m='http://example.org/faults/exceptions' > <m:ExceptionType>Severe</m:ExceptionType> </m:Exception> </soap:Fault>

When a MESSAGE contains a soap:Fault element its element children MUST be unqualified. CORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns='' > <faultcode>soap:Client</faultcode> <faultstring>Invalid message format</faultstring> <faultactor>http://example.org/someactor</faultactor> <detail> <m:msg xmlns:m='http://example.org/faults/exceptions'> There were <b>lots</b> of elements in the message that
http://java.boot.by/wsd-guide/wsd-guide.html 34 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

I did not understand </m:msg> </detail> </soap:Fault>

INCORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <soap:faultcode>soap:Client</soap:faultcode> <soap:faultstring>Invalid message format</soap:faultstring> <soap:faultactor>http://example.org/someactor</soap:faultactor> <soap:detail> <m:msg xmlns:m='http://example.org/faults/exceptions'> There were <b>lots</b> of elements in the message that I did not understand </m:msg> </soap:detail> </soap:Fault>

A RECEIVER MUST accept fault messages that have any number of ELEMENTS, including zero, appearing as children of the detail element. Such children can be qualified or unqualified. A RECEIVER MUST accept fault messages that have any number of qualified or unqualified ATTRIBUTES, including zero, appearing on the detail element. The namespace of qualified attributes can be anything other than "http://schemas.xmlsoap.org/soap/envelope/". A RECEIVER MUST accept fault messages that carry an xml:lang attribute on the faultstring element. When a MESSAGE contains a faultcode element the content of that element SHOULD be one of the fault codes defined in SOAP 1.1 or a namespace qualified fault code. The faultcode values defined below MUST be used in the faultcode element when describing faults. Table 2.2. SOAP Fault Codes
Error VersionMismatch MustUnderstand Description The processing party found an invalid namespace for the SOAP Envelope element. An immediate child element of the SOAP Header element that was either not understood or not obeyed by the processing party contained a SOAP mustUnderstand attribute with a value of "1". The Client class of errors indicate that the message was incorrectly formed or did not contain the appropriate information in order to succeed. For example, the message could lack the proper authentication or payment information. It is generally an indication that the message should not be resent without change. The Server class of errors indicate that the message could not be processed for reasons not directly attributable to the contents of the message itself but rather to the processing of the message. For example, processing could include communicating with an upstream processor, which didn't respond. The message may succeed at a later point in time.

Client

Server

When a MESSAGE contains a faultcode element the content of that element SHOULD NOT use of the SOAP 1.1 "dot" notation to refine the meaning of the Fault. CORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:c='http://example.org/faultcodes' >

http://java.boot.by/wsd-guide/wsd-guide.html 35 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<faultcode>c:ProcessingError</faultcode> <faultstring>An error occured while processing the message </faultstring> </soap:Fault>

CORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <faultcode>soap:Server</faultcode> <faultstring>An error occured while processing the message </faultstring> </soap:Fault>

INCORRECT:

<soap:Fault xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:c='http://example.org/faultcodes' > <faultcode>soap:Server.ProcessingError</faultcode> <faultstring>An error occurred while processing the message </faultstring> </soap:Fault>

A MESSAGE MUST NOT contain soap:encodingStyle attributes on any of the elements whose namespace name is "http://schemas.xmlsoap.org/ soap/envelope/". A MESSAGE MUST NOT contain soap:encodingStyle attributes on any element that is a child of soap:Body. A MESSAGE described in an rpc-literal binding MUST NOT contain soap:encodingStyle attribute on any elements are grandchildren of soap: Body. A MESSAGE MUST NOT contain a Document Type Declaration (DTD). A MESSAGE MUST NOT contain Processing Instructions (PI). A RECEIVER MUST accept messages that contain an XML Declaration. A MESSAGE MUST NOT have any element children of soap:Envelope following the soap:Body element. CORRECT:

<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <soap:Body> <p:Process xmlns:p='http://example.org/Operations' > <m:Data xmlns:m='http://example.org/information' > Here is some data with the message </m:Data> </p:Process> </soap:Body> </soap:Envelope>

http://java.boot.by/wsd-guide/wsd-guide.html 36 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

INCORRECT:

<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' > <soap:Body> <p:Process xmlns:p='http://example.org/Operations' /> </soap:Body> <m:Data xmlns:m='http://example.org/information' > Here is some data with the message </m:Data> </soap:Envelope>

A MESSAGE MUST be serialized as either UTF-8 or UTF-16. The media type of a MESSAGE's envelope MUST indicate the correct character encoding, using the charset parameter. A MESSAGE containing a soap:mustUnderstand attribute MUST only use the lexical forms "0" and "1". The children of the soap:Body element in a MESSAGE MUST be namespace qualified. A RECEIVER MUST generate a fault if they encounter a message whose document element has a local name of "Envelope" but a namespace name that is not "http://schemas.xmlsoap.org/soap/envelope/". A RECEIVER MUST NOT mandate the use of the xsi:type attribute in messages except as required in order to indicate a derived type.

Describe the function of SOAP in a Web service interaction and the advantages and disadvantages of using SOAP messages.
HTTP is a transport-level protocols and SOAP is a messaging-layer (communication) protocol. SOAP can be used in combination with a variety of transport protocols - including SMTP, JMS, and other protocols in addition to HTTP - and does not depend on any particular network protocol. Although HTTP is a widely used protocol for SOAP, SOAP toolkit vendors have also started providing support for other protocols, like SMTP. SOAP messages may travel across several different transport-layer protocols before they reach their ultimate destination SOAP advantages.

Platform independent. SOAP decouples the encoding and communications protocol from the runtime environment. Web service can receive a SOAP payload from a remote service, and the platform details of the source are entirely irrelevant. Language independent. Anything can generate XML, from Perl scripts to C++ code to J2EE app servers. So, as of the 1.1 version of the SOAP specification, anyone and anything can participate in a SOAP conversation, with a relatively low barrier to entry. Uses XML to send and receive messages. SOAP is also a simple way to accomplish remote object/component/service communications. It formalizes the vocabulary definition in a form that's now familiar, popular, and accessible (XML). If you know XML, you can figure out the basics of SOAP encoding pretty quickly. Uses standard internet HTTP protocol. SOAP runs over HTTP, which eliminates firewall problems. When using HTTP as the protocol binding, an RPC call maps naturally to an HTTP request and an RPC response maps to an HTTP response. SOAP is very simple compared to RMI, CORBA, and DCOM because it does not deal with certain ancillary but important aspects of remote object systems. A protocol for exchanging information in a decentralized and distributed environment. SOAP is, transport protocol-independent and can therefore potentially be used in combination with a variety of protocols. Vendor neutral.

SOAP disadvantages

http://java.boot.by/wsd-guide/wsd-guide.html 37 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

The SOAP specification contains no mention of security facilities. SOAP 1.1 specification does not specify a default encoding for the message body. There is an encoding defined in the spec, but it is not required that you use this encoding to be compliant: Any custom encoding that you choose can be specified in the encodingStyle attribute of the message or of individual elements in the message. Because SOAP deals with objects serialized to plain text and not with stringified remote object references (interoperable object references, IORs, as defined in CORBA), distributed garbage collection has no meaning. SOAP clients do not hold any stateful references to remote objects.

Chapter 3. Describing and Publishing (WSDL and UDDI)

Explain the use of WSDL in Web services, including a description of WSDL's basic elements, binding mechanisms and the basic WSDL operation types as limited by the WS-I Basic Profile 1.0a.
WSDL is an XML-based language that allows formal XML desriptions of the interfaces of Web services:

Interface information describing all publicly available functions. Data type information for all message requests and message responses. Binding information about the transport protocol to be used. Address information for locating the specified service.

WSDL benefits:

It is an interface description is a contract between the server developers and the client developers (like Java interface represents a contract between client code and the actual Java object). It has formal descriptions which allows tool support, e.g. code template generators, integrate new services with little or no manual code.

WSDL language can be described as having two layers: 1. The service definition layer describes abstract properties:

data types message types operations services

2. The binding layer describes concrete properties:


protocols data formats

The definitions element MUST be the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document. An actual WSDL document consists of a set of definitions of the following kinds:

types - Contains XML Schema element and type definitions. The types element describes all the data types used between the client and server. WSDL is not tied exclusively to a specific typing system, but it uses the W3C XML Schema specification as its default choice. If the service uses only XML Schema built-in simple types, such as strings and integers, the types element is not required. message - Consistes of either a number of named parts typed by XML Schema elements, or a single part typed by a XML Schema type. The message element describes a one-way message, whether it is a single message request or a single message response. It defines the name of the message and contains zero or more message part elements, which can refer to message parameters or message return values. portType - describing a set of operations, each being either:
r

one-way: The endpoint receives an input message. (NOTE: The WS-I BP 1.0 restricts the valid wsdl:operations to one-way and request-response operations).

<wsdl:definitions .... > <wsdl:portType .... > * <wsdl:operation name="nmtoken"> <wsdl:input name="nmtoken"? message="qname"/>
http://java.boot.by/wsd-guide/wsd-guide.html 38 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

</wsdl:operation> </wsdl:portType > </wsdl:definitions>

request-response: The endpoint receives an input message and then responds with an output message (like RPC - Remote Procedure Call). (NOTE: The WS-I BP 1.0 restricts the valid wsdl:operations to one-way and request-response operations).

<wsdl:definitions .... > <wsdl:portType .... > * <wsdl:operation name="nmtoken" parameterOrder="nmtokens"> <wsdl:input name="nmtoken"? message="qname"/> <wsdl:output name="nmtoken"? message="qname"/> <wsdl:fault name="nmtoken" message="qname"/>* </wsdl:operation> </wsdl:portType > </wsdl:definitions>

solicit-response: The endpoint sends an output message and then receives an input message (NOTE: A DESCRIPTION MUST NOT use Solicit-Response and Notification type operations in a wsdl:portType definition - R2303 - BP 1.0).

<wsdl:definitions .... > <wsdl:portType .... > * <wsdl:operation name="nmtoken" parameterOrder="nmtokens"> <wsdl:output name="nmtoken"? message="qname"/> <wsdl:input name="nmtoken"? message="qname"/> <wsdl:fault name="nmtoken" message="qname"/>* </wsdl:operation> </wsdl:portType > </wsdl:definitions>

notification: The endpoint sends an output message (NOTE: A DESCRIPTION MUST NOT use Solicit-Response and Notification type operations in a wsdl:portType definition - R2303 - BP 1.0).

<wsdl:definitions .... > <wsdl:portType .... > * <wsdl:operation name="nmtoken" parameterOrder="nmtokens"> <wsdl:output name="nmtoken"? message="qname"/> </wsdl:operation> </wsdl:portType > </wsdl:definitions>

The portType element combines multiple message elements to form a complete one-way or round-trip operation. For example, a portType can combine one request and one response message into a single request/response operation, most commonly used in SOAP services. Note that a portType can (and frequently does) define multiple operations.

binding - Selects communication protocol and data formats for each operation and message. The binding element describes the concrete specifics of how the service will be implemented on the wire. WSDL includes built-in extensions for defining SOAP services, and SOAP-specific information therefore goes here. (NOTE: For interoperability the WS-I BP 1.0 requires that all messages must be sent using the SOAP 1.1 protocol over an HTTP transport as described in Section 3 of the WSDL 1.1 spec. The SOAP messages must be in either "document-literal" or "rpc-literal" form). The WS-I BP 1.0 requires that a wsdl:binding and its

http://java.boot.by/wsd-guide/wsd-guide.html 39 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

wsdl:portType have the same list of wsdl:operations. A perfect matching between the two lists is established through a 1-1 and onto relation from the wsdl:binding to the wsdl:portType. The wsdl:binding should completely bind all operations within a wsdl:portType. service - Describes a collection of named ports, each associated with a binding and a network address. The service element defines the address for invoking the specified service. Most commonly, this includes a URL for invoking the SOAP service.

The simplified structure of a WSDL document is:

<definitions> <!-- root WSDL element --> <types> <!-- defines data types to be transmitted --> </types> <message> <!-- defines messages to be transmitted --> </message> <portType> <!-- defines operations (functions) to be supported --> </portType> <binding> <!-- defines how will the messages be transmitted on the wire --> </binding> <service> <!-- defines location of web service --> </service> </definitions>

WSDL document grammar:

<wsdl:definitions name="nmtoken"? targetNamespace="uri"?> <import namespace="uri" location="uri"/>* <wsdl:documentation .... /> ? <wsdl:types> ? <wsdl:documentation .... />? <xsd:schema .... />* <-- extensibility element --> * </wsdl:types> <wsdl:message name="nmtoken"> * <wsdl:documentation .... />? <part name="nmtoken" element="qname"? type="qname"?/> * </wsdl:message> <wsdl:portType name="nmtoken">* <wsdl:documentation .... />? <wsdl:operation name="nmtoken">* <wsdl:documentation .... /> ? <wsdl:input name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:input> <wsdl:output name="nmtoken"? message="qname">? <wsdl:documentation .... /> ?
http://java.boot.by/wsd-guide/wsd-guide.html 40 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

</wsdl:output> <wsdl:fault name="nmtoken" message="qname"> * <wsdl:documentation .... /> ? </wsdl:fault> </wsdl:operation> </wsdl:portType> <wsdl:binding name="nmtoken" type="qname">* <wsdl:documentation .... />? <-- extensibility element --> * <wsdl:operation name="nmtoken">* <wsdl:documentation .... /> ? <-- extensibility element --> * <wsdl:input> ? <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:input> <wsdl:output> ? <wsdl:documentation .... /> ? <-- extensibility element --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <wsdl:documentation .... /> ? <-- extensibility element --> * </wsdl:fault> </wsdl:operation> </wsdl:binding> <wsdl:service name="nmtoken"> * <wsdl:documentation .... />? <wsdl:port name="nmtoken" binding="qname"> * <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:port> <-- extensibility element --> </wsdl:service> <-- extensibility element --> * </wsdl:definitions>

Example of simple WSDL (SOAP 1.1 Request-Response via HTTP):

<?xml version="1.0" encoding="UTF-8"?> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd1="http://example.com/stockquote.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <schema targetNamespace="http://example.com/stockquote.xsd" xmlns="http://www.w3.org/2000/10/XMLSchema"> <element name="TradePriceRequest"> <complexType> <all> <element name="tickerSymbol" type="string"/> </all>
http://java.boot.by/wsd-guide/wsd-guide.html 41 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

</complexType> </element> <element name="TradePrice"> <complexType> <all> <element name="price" type="float"/> </all> </complexType> </element> </schema> </types> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> <message name="GetLastTradePriceOutput"> <part name="body" element="xsd1:TradePrice"/> </message> <portType name="StockQuotePortType"> <operation name="GetLastTradePrice"> <input message="tns:GetLastTradePriceInput"/> <output message="tns:GetLastTradePriceOutput"/> </operation> </portType> <binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetLastTradePrice"> <soap:operation soapAction="http://example.com/GetLastTradePrice"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> </binding> <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> </definitions>

Describe how W3C XML Schema is used as a typing mechanism in WSDL 1.1.
The types element encloses data type definitions that are relevant for the exchanged messages. For maximum interoperability and platform neutrality, WSDL prefers the use of XSD as the canonical type system, and treats it as the intrinsic type system.

<definitions .... > <types> <xsd:schema .... />* </types> </definitions>


http://java.boot.by/wsd-guide/wsd-guide.html 42 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

The XSD type system can be used to define the types in a message regardless of whether or not the resulting wire format is actually XML, or whether the resulting XSD schema validates the particular wire format. This is especially interesting if there will be multiple bindings for the same message, or if there is only one binding but that binding type does not already have a type system in widespread use. A DESCRIPTION MUST NOT use QName references to elements in namespaces that have been neither imported, nor defined in the referring WSDL document. A QName reference to a Schema component in a DESCRIPTION MUST use the namespace defined in the targetNamespace attribute on the xsd:schema element, or to a namespace defined in the namespace attribute on an xsd:import element within the xsd:schema element. All xsd:schema elements contained in a wsdl:types element of a DESCRIPTION MUST have a targetNamespace attribute with a valid and nonnull value, UNLESS the xsd:schema element has xsd:import and/or xsd:annotation as its only child element(s). In a DESCRIPTION, array declarations MUST NOT extend or restrict the soapenc:Array type. In a DESCRIPTION, array declarations MUST NOT use wsdl:arrayType attribute in the type declaration. In a DESCRIPTION, array declaration wrapper elements SHOULD NOT be named using the convention ArrayOfXXX. A MESSAGE containing serialized arrays MUST NOT include the soapenc:arrayType attribute. CORRECT:

Given the WSDL Description: <xsd:element name="MyArray1" type="tns:MyArray1Type"/> <xsd:complexType name="MyArray1Type"> <xsd:sequence> <xsd:element name="x" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> The SOAP message would serialize as (omitting namespace declarations for clarity): <MyArray1> <x>abcd</x> <x>efgh</x> </MyArray1>

INCORRECT:

Given the WSDL Description: <xsd:element name="MyArray2" type="tns:MyArray2Type"/> <xsd:complexType name="MyArray2Type" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" > <xsd:complexContent> <xsd:restriction base="soapenc:Array"> <xsd:sequence> <xsd:element name="x" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence>
http://java.boot.by/wsd-guide/wsd-guide.html 43 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<xsd:attribute ref="soapenc:arrayType" wsdl:arrayType="tns:MyArray2Type[]"/> </xsd:restriction> </xsd:complexContent> </xsd:complexType> The SOAP message would serialize as (omitting namespace declarations for clarity): <MyArray2 soapenc:arrayType="tns:MyArray2Type[]" > <x>abcd</x> <x>efgh</x> </MyArray2>

Describe the use of UDDI data structures. Consider the requirements imposed on UDDI by the WS-I Basic Profile 1.0a.
UDDI supports the following five core data structures: 1. 2. 3. 4. 5. Business Entity Business Service Binding Template tModel Publisher Assertion

This division by information type provides simple partitions to assist in the rapid location and understanding of the different information that makes up a registration.

http://java.boot.by/wsd-guide/wsd-guide.html 44 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

The businessEntity structure The businessEntity structure represents all known information about a business or entity that publishes descriptive information about the entity as well as the services that it offers. From an XML standpoint, the businessEntity is the top-level data structure that accommodates holding descriptive information about a business or entity. Service descriptions and technical information are expressed within a businessEntity by a containment relationship. Structure Specification:

<element name="businessEntity" type="uddi:businessEntity" /> <complexType name="businessEntity"> <sequence> <element ref="uddi:discoveryURLs" minOccurs="0" /> <element ref="uddi:name" maxOccurs="unbounded" /> <element ref="uddi:description" minOccurs="0" maxOccurs="unbounded" /> <element ref="uddi:contacts" minOccurs="0" /> <element ref="uddi:businessServices" minOccurs="0" /> <element ref="uddi:identifierBag" minOccurs="0" /> <element ref="uddi:categoryBag" minOccurs="0" /> </sequence> <attribute name="businessKey" type="uddi:businessKey" use="required" /> <attribute name="operator" type="string" use="optional" /> <attribute name="authorizedName" type="string" use="optional" /> </complexType>

The businessService structure The businessService structures each represent a logical service classification. The name of the element includes the term business in an attempt to describe the purpose of this level in the service description hierarchy. Each businessService structure is the logical child of a single businessEntity structure. The identity of the containing (parent) businessEntity is determined by examining the embedded businessKey value. If no businessKey value is present, the businessKey must be obtainable by searching for a businessKey value in any parent structure containing the businessService. Each businessService element contains descriptive information in business terms outlining the type of technical services found within each businessService element. In some cases, businesses would like to share or reuse services, e.g. when a large enterprise publishes separate businessEntity structures. This can be established by using the businessService structure as a projection to an already published businessService. Any businessService projected in this way is not managed as a part of the referencing businessEntity, but centrally as a part of the referenced businessEntity. This means that changes of the businessService by the referenced businessEntity are automatically valid for the service projections done by referencing businessEntity structures. In order to specify both referenced and referencing businessEntity structures correctly, service projections can only be published by a save_business message with the referencing businessKey present in the businessEntity structure and both the referenced businessKey and the referenced businessService present in the businessService structure. Structure Specification:

<element name="businessService" type="uddi:businessService" /> <complexType name="businessService"> <sequence> <element ref="uddi:name" minOccurs="0" maxOccurs="unbounded" /> <element ref="uddi:description" minOccurs="0" maxOccurs="unbounded" /> <element ref="uddi:bindingTemplates" minOccurs="0" /> <element ref="uddi:categoryBag" minOccurs="0" /> </sequence>
http://java.boot.by/wsd-guide/wsd-guide.html 45 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<attribute name="serviceKey" type="uddi:serviceKey" use="required" /> <attribute name="businessKey" type="uddi:businessKey" use="optional" /> </complexType>

The bindingTemplate structure Technical descriptions of Web services are accommodated via individual contained instances of bindingTemplate structures. These structures provide support for determining a technical entry point or optionally support remotely hosted services, as well as a lightweight facility for describing unique technical characteristics of a given implementation. Support for technology and application specific parameters and settings files are also supported. Since UDDIs main purpose is to enable description and discovery of Web Service information, it is the bindingTemplate that provides the most interesting technical data. Each bindingTemplate structure has a single logical businessService parent, which in turn has a single logical businessEntity parent. Structure Specification:

<element name="bindingTemplate" type="uddi:bindingTemplate" /> <complexType name="bindingTemplate"> <sequence> <element ref="uddi:description" minOccurs="0" maxOccurs="unbounded" /> <choice> <element ref="uddi:accessPoint" /> <element ref="uddi:hostingRedirector" /> </choice> <element ref="uddi:tModelInstanceDetails" /> </sequence> <attribute name="serviceKey" type="uddi:serviceKey" use="optional" /> <attribute name="bindingKey" type="uddi:bindingKey" use="required" /> </complexType>

The tModel structure Being able to describe a Web service and then make the description meaningful enough to be useful during searches is an important UDDI goal. Another goal is to provide a facility to make these descriptions useful enough to learn about how to interact with a service that you dont know much about. In order to do this, there needs to be a way to mark a description with information that designates how it behaves, what conventions it follows, or what specifications or standards the service is compliant with. Providing the ability to describe compliance with a specification, concept, or even a shared design is one of the roles that the tModel structure fills. The tModel structure takes the form of keyed metadata (data about data). In a general sense, the purpose of a tModel within the UDDI registry is to provide a reference system based on abstraction. Thus, the kind of data that a tModel represents is pretty nebulous. In other words, a tModel registration can define just about anything, but in the current revision, two conventions have been applied for using tModels: as sources for determining compatibility and as keyed namespace references. The information that makes up a tModel is quite simple. Theres a key, a name, an optional description, and then a URL that points somewhere presumably somewhere where the curious can go to find out more about the actual concept represented by the metadata in the tModel itself. There are two places within a businessEntity registration that you'll find references to tModels. In this regard, tModels are special. Whereas the other data within the businessEntity (e.g. businessService and bindingTemplate data) exists uniquely with one uniquely keyed instance as a member of one unique parent businessEntity, tModels are used as references. This means that you'll find references to specific tModel instances in many businessEntity structures.

http://java.boot.by/wsd-guide/wsd-guide.html 46 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Defining the technical fingerprint. The primary role that a tModel plays is to represent a technical specification. An example might be a specification that outlines wire protocols, interchange formats and interchange sequencing rules. Examples can be seen in the RosettaNet Partner Interface Processes specification, the Open Applications Group Integration Specification and various Electronic Document Interchange (EDI) efforts. Software that communicates with other software across some communication medium invariably adheres to some pre-agreed specifications. In situations where this is true, the designers of the specifications can establish a unique technical identity within a UDDI registry by registering information about the specification in a tModel. Once registered in this way, other parties can express the availability of Web services that are compliant with a specification by simply including a reference to the tModel identifier (called a tModelKey) in their technical service descriptions bindingTemplate data. This approach facilitates searching for registered Web services that are compatible with a particular specification. Once you know the proper tModelKey value, you can find out whether a particular business or entity has registered a Web service that references that tModel key. In this way, the tModelKey becomes a technical fingerprint that is unique to a given specification. Defining an abstract namespace reference. The other place where tModel references are used is within the identifierBag, categoryBag, address and publisherAssertion structures that are used to define organizational identity and various classifications. Used in this context, the tModel reference represents a relationship between the keyed name-value pairs to the super-name, or namespace within which the name-value pairs are meaningful. An example of this can be seen in the way a business or entity can express the fact that their US tax code identifier (which they are sure they are known by to their partners and customers) is a particular value. To do this, let's assume that we find a tModel that is named US Tax Codes, with a description United States business tax code numbers as defined by the United States Internal Revenue Service. In this regard, the tModel still represents a specific concept but instead of being a technical specification, it represents a unique area within which tax code IDs have a particular meaning. Once this meaning is established, a business can use the tModelKey for the tax code tModel as a unique reference that qualifies the remainder of the data that makes up an entry in the identifierBag data. To get things started, the UDDI Operator Sites have registered a number of useful tModels, including NAICS (an industry code taxonomy), UNSPC (a product and service category code taxonomy), and ISO 3166 (a geographical region code taxonomy). Structure Specification:

<element name="tModel" type="uddi:tModel" /> <complexType name="tModel"> <sequence> <element ref="uddi:name" /> <element ref="uddi:description" minOccurs="0" maxOccurs="unbounded" /> <element ref="uddi:overviewDoc" minOccurs="0" /> <element ref="uddi:identifierBag" minOccurs="0" /> <element ref="uddi:categoryBag" minOccurs="0" /> </sequence> <attribute name="tModelKey" type="uddi:tModelKey" use="required" /> <attribute name="operator" type="string" use="optional" /> <attribute name="authorizedName" type="string" use="optional" /> </complexType>

The publisherAssertion structure Many businesses, like large enterprises or marketplaces, are not effectively represented by a single businessEntity, since their description and discovery are likely to be diverse. As a consequence, several businessEntity structures can be published, representing individual subsidiaries of a large enterprise or individual participants of a marketplace. Nevertheless, they still represent a more or less coupled community and would like to make some of their relationships visible in their UDDI registrations. Therefore, two related businesses use the xx_publisherAssertion messages, publishing assertions of business relationships.
http://java.boot.by/wsd-guide/wsd-guide.html 47 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

In order to eliminate the possibility that one publisher claims a relationship between both businesses that is in fact not reciprocally recognized, both publishers have to agree that the relationship is valid by publishing their own publisherAssertion. Therefore, both publishers have to publish exactly the same information. When this happens, the relationship becomes visible. In the case that a publisher is responsible for both businesses, the relationship automatically becomes visible after publishing just one of both assertions that make up the relationship. The publisherAssertion structure consists of the three elements fromKey (the first businessKey), toKey (the second businessKey) and keyedReference. The keyedReference designates the asserted relationship type in terms of a keyName keyValue pair within a tModel, uniquely referenced by a tModelKey. All three parts of the keyedReference the tModelKey, the keyName, and the keyValue are mandatory in this context. Empty (zero length) keyName and keyValue elements are permitted.

<element name="publisherAssertion" type="uddi:publisherAssertion" /> <complexType name="publisherAssertion"> <sequence> <element ref="uddi:fromKey" /> <element ref="uddi:toKey" /> <element ref="uddi:keyedReference" /> </sequence> </complexType>

BP 1.0 Requirements - Service Publication and Discovery REGDATA of type uddi:bindingTemplate representing a conformant INSTANCE MUST contain the uddi:accessPoint element. CORRECT:

<bindingTemplate bindingKey="..."> <description xml:lang="EN">BarSOAPPort</description> <accessPoint>http://example.org/myBarSOAPPort</accessPoint> <tModelInstanceDetails> ... </tModelInstanceDetails> </bindingTemplate>

INCORRECT:

<bindingTemplate bindingKey="..."> <description xml:lang="EN">BarSOAPPort</description> <hostingRedirector bindingKey="..."/> <tModelInstanceDetails> ... </tModelInstanceDetails> </bindingTemplate>

REGDATA of type uddi:tModel representing a conformant Web service type MUST use WSDL as the description language. REGDATA of type uddi:tModel representing a conformant Web service type MUST be categorized using the uddi:types taxonomy and a categorization of "wsdlSpec".

http://java.boot.by/wsd-guide/wsd-guide.html 48 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

The wsdl:binding that is referenced by REGDATA of type uddi:tModel MUST itself conform to the Profile.

Describe the basic functions provided by the UDDI Publish and Inquiry APIs to interact with a UDDI business registry.
Publish API functions The messages in this section represent commands that require authenticated access to an UDDI Operator Site, and are used to publish and update information contained in a UDDI compatible registry. Each business should initially select one Operator Site to host their information. Once chosen, information can only be updated at the site originally selected. UDDI provides no automated means to reconcile multiple or duplicate registrations. The messages defined in this section all behave synchronously and are callable via HTTPPOST only. HTTPS is used exclusively for all of the calls defined in this publisher's API. The publishing API calls defined that UDDI operators support are:

add_publisherAssertions: Used to add relationship assertions to the existing set of assertions. delete_binding: Used to remove an existing bindingTemplate from the bindingTemplates collection that is part of a specified businessService structure. delete_business: Used to delete registered businessEntity information from the registry. delete_publisherAssertions: Used to delete specific publisher assertions from the assertion collection controlled by a particular publisher account. Deleting assertions from the assertion collection will affect the visibility of business relationships. Deleting an assertion will cause any relationships based on that assertion to be invalidated. delete_service: Used to delete an existing businessService from the businessServices collection that is part of a specified businessEntity. delete_tModel: Used to hide registered information about a tModel. Any tModel hidden in this way is still usable for reference purposes and accessible via the get_tModelDetail> message, but is simply hidden from find_tModel> result sets. There is no way to actually cause a tModel to be deleted, except by administrative petition. discard_authToken: Used to inform an Operator Site that a previously provided authentication token is no longer valid and should be considered invalid if used after this message is received and until such time as an authToken value is recycled or reactivated at an operator's discretion. See get_authToken. get_assertionStatusReport: Used to get a status report containing publisher assertions and status information. This report is useful to help an administrator manage active and tentative publisher assertions. Publisher assertions are used in UDDI to manage publicly visible relationships between businessEntity structures. Relationships are a feature introduced in generic 2.0 that help manage complex business structures that require more than one businessEntity or more than one publisher account to manage parts of a businessEntity. Returns an assertionStatusReport that includes the status of all assertions made involving any businessEntity controlled by the requesting publisher account. get_authToken: Used to request an authentication token from an Operator Site. Authentication tokens are required when using all other APIs defined in the publishers API. This function serves as the program's equivalent of a login request. get_publisherAssertions: Used to get a list of active publisher assertions that are controlled by an individual publisher account. Returns a publisherAssertions message containing all publisher assertions associated with a specific publisher account. Publisher assertions are used to control publicly visible business relationships. get_registeredInfo: Used to request an abbreviated synopsis of all information currently managed by a given individual. save_binding: Used to register new bindingTemplate information or update existing bindingTemplate information. Use this to control information about technical capabilities exposed by a registered business. save_business: Used to register new businessEntity information or update existing businessEntity information. Use this to control the overall information about the entire business. Of the save_xx APIs this one has the broadest effect. In UDDI V2, a feature is introduced where save_business can be used to reference a businessService that is parented by another businessEntity. save_service: Used to register or update complete information about a businessService exposed by a specified businessEntity. save_tModel: Used to register or update complete information about a tModel. set_publisherAssertions: used to save the complete set of publisher assertions for an individual publisher account. Replaces any existing assertions, and causes any old assertions that are not reasserted to be removed from the registry. Publisher assertions are used to control publicly visible business relationships.

Inquiry API functions The messages in this section represent inquiries that anyone can make of any UDDI Operator Site at any time. These messages all behave synchronously and are required to be exposed via HTTP-POST only. Other synchronous or asynchronous mechanisms may be provided at the discretion of the individual UDDI Operator Site or UDDI compatible registry. The publicly accessible queries are:

find_binding: Used to locate specific bindings within a registered businessService. Returns a bindingDetail message. find_business: Used to locate information about one or more businesses. Returns a businessList message. find_relatedBusinesses: Used to locate information about businessEntity registrations that are related to a specific business entity whose key is passed in the inquiry. The Related Businesses feature is used to manage registration of business units and subsequently relate them based on organizational hierarchies or business partner relationships. Returns a relatedBusinessesList message. find_service: Used to locate specific services within a registered businessEntity. Returns a serviceList message. find_tModel: Used to locate one or more tModel information structures. Returns a tModelList structure. get_bindingDetail: Used to get full bindingTemplate information suitable for making one or more service requests. Returns a bindingDetail message.

http://java.boot.by/wsd-guide/wsd-guide.html 49 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

get_businessDetail: Used to get the full businessEntity information for one or more businesses or organizations. Returns a businessDetail message. get_businessDetailExt: Used to get extended businessEntity information. Returns a businessDetailExt message. get_serviceDetail: Used to get full details for a given set of registered businessService data. Returns a serviceDetail message. get_tModelDetail>: Used to get full details for a given set of registered tModel data. Returns a tModelDetail message.

Chapter 4. JAX-RPC

Explain the service description model, client connection types, interaction modes, transport mechanisms/protocols, and endpoint types as they relate to JAX-RPC.
JAX-RPC is for Web services interoperability across heterogeneous platforms and languages. This makes JAX-RPC a key technology for Web services integration. You can use the standard JAX-RPC programming model to develop Web service clients and endpoints based on SOAP. A Web service endpoint is described using a Web Services Description Language (WSDL) document. JAX-RPC enables JAX-RPC clients to invoke Web services developed across heterogeneous platforms. In a similar manner, JAX-RPC Web service endpoints can be invoked by heterogeneous clients. JAX-RPC requires SOAP and WSDL standards for this cross-platform interoperability. JAX-RPC provides an easy to develop programming model for development of SOAP based Web services. You can use the RPC programming model to develop Web service clients and endpoints. For typical scenarios, you are not exposed to the complexity of the underlying runtime mechanisms (for example, SOAP protocol level mechanisms, marshalling and unmarshalling). A JAX-RPC runtime system (a library) abstracts these runtime mechanisms for the Web services programming model. This simplifies Web service development. JAX-RPC provides support for WSDL-to-Java and Java-to-WSDL mapping as part of the development of Web service clients and endpoints. In a typical development environment, tools provide these mapping functionality. This further simplifies the application development. JAX-RPC enables a Web service endpoint to be developed using either a Java Servlet or Enterprise JavaBeans (EJB) component model. A Web service endpoint is deployed on either the Web container or EJB container based on the corresponding component model. These endpoints are described using a WSDL document. This WSDL document can be published in public or private registry, though this is not required. A client uses this WSDL document and invokes the Web service endpoint. A JAX-RPC client can use stubs-based, dynamic proxy or dynamic invocation interface (DII) programming models to invoke a heterogeneous Web service endpoint. JAX-RPC requires SOAP over HTTP for interoperability. JAX-RPC provides support for SOAP message processing model through the SOAP message handler functionality. This enables developers to build SOAP specific extensions to support security, logging and any other facility based on the SOAP messaging. JAX-RPC uses SAAJ API for SOAP message handlers. SAAJ provides a standard Java API for constructing and manipulating SOAP messages with attachments. JAX-RPC provides support for document-based messaging. Using JAX-RPC, any MIME-encoded content can be carried as part of a SOAP message with attachments. This enables exchange of XML documents, images and other MIME types across Web services. JAX-RPC supports HTTP level session management and SSL based security mechanisms. This enables you to develop secure Web services. More advanced SOAP message-level security will be addressed in the evolution of JAX-RPC technology. Steps for Implementing a Service: 1. Define Web Service Endpoint Interface 2. Implement Web Service class and methods 3. Package and deploy Endpoint Interface example: package com.example; import java.rmi.Remote; import java.rmi.RemoteException; public interface HelloIF extends Remote { public String sayHello(String s) throws RemoteException; } Service endpoint interface may be: 1. Java java.rmi.Remote Interface 2. Generated from WSDL Web Service can be implemented in form: 1. Java class (for servlet-based endpoint)

http://java.boot.by/wsd-guide/wsd-guide.html 50 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

package com.example; public class HelloImpl implements HelloIF { public String message = "Hello "; public String sayHello (String s) { return message + s; } } NOTE: Your implementation class does not throw RemoteException. This is the responsibility of the container as this implementation will be deployed in a managed J2EE container. 2. Stateless session bean (for EJB-based endpoint) Endpoint interface:

package com.example; public interface Greeting extends Remote { public String sayHello(String name) throws RemoteException; }

Stateless Session Bean Class:

package com.example; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import java.rmi.RemoteException; public class GreetingBean implements SessionBean { public String sayHello(String name) throws RemoteException { return "Hello" + name; } public void ejbCreate() { } // Standard callback methods public void ejbActivate() { } public void ejbPassivate() { } public void ejbRemove() { } public void setSessionContext(SessionContext ctx) { } }

Deployment Descriptor:

<?xml version='1.0' encoding='UTF-8'?> <ejb-jar version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"> <enterprise-beans> <session> <ejb-name>GreetingBeen</ejb-name> <service-endpoint>com.example.Greeting</service-endpoint> <ejb-class>com.example.GreetingBeen</ejb-class> <session-type>Stateless</session-type>

http://java.boot.by/wsd-guide/wsd-guide.html 51 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<transaction-type>Container</transaction-type> <security-identity> <use-caller-identity/> </security-identity> </session> </enterprise-beans> </ejb-jar>

Given a set of requirements for a Web service, such as transactional needs, and security requirements, design and develop Web service applications that use servlet-based endpoints and EJB based endpoints.
EJB based endpoint JSR 109 standardizes webservice in J2EE 1.4 using JAX-RPC. EJB 2.1 exposes Stateless Session bean as a web service endpoint using JAX-RPC interface and any webservice client can access the EJB webservice using SOAP 1.1 over HTTP. The developer can choose a web service endpoint interface for a stateless session bean whenever he wants to expose the functionality of the bean as a web service endpoint through WSDL. The clients for ejb webservice endpoint may be Java clients and/or clients written in a programming language other than Java. A Java client that accesses the ejb web service has to use JAX-RPC client APIs. This is an example shows how can you expose your existing EJB applications as a webservice endpoint and how a pure Java client accesses the ejb webservice. We will use a simple Stateless Session bean TimeBean that displays the current time and locale information. For exposing the webservice endpoint you do not need to have home or remote interfaces for the EJBs, only the end-point interface that extends java.rmi.Remote and bean implementation class is required. Following the code for the service-endpoint for the EJB:

package time; import java.rmi.RemoteException; import java.rmi.Remote; public interface TimeService extends Remote { public String getDateTime (String name) throws RemoteException; }

Then we have to define the end-point interface in ejb-jar.xml as follows:

<session> <display-name>TimeServiceEJB</display-name> <ejb-name>TimeServiceEJB</ejb-name> <service-endpoint>time.TimeService</service-endpoint> <ejb-class>time.TimeServiceBean</ejb-class> <session-type>Stateless</session-type> ... </session>

The WSDL file defines the web services e.g. the following MyTimeService.wsdl describes the Time ejb webservice:

<?xml version="1.0" encoding="UTF-8"?> <definitions name="MyTimeService" targetNamespace="urn:oracle-ws" xmlns:tns="urn:oracle-ws"


http://java.boot.by/wsd-guide/wsd-guide.html 52 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"> <types/> <message name="TimeService_getDateTime"> <part name="String_1" type="xsd:string"/> </message> <message name="TimeService_getDateTimeResponse"> <part name="result" type="xsd:string"/> </message> <portType name="TimeService"> <operation name="getDateTime" parameterOrder="String_1"> <input message="tns:TimeService_getDateTime"/> <output message="tns:TimeService_getDateTimeResponse"/> </operation> </portType> <binding name="TimeServiceBinding" type="tns:TimeService"> <operation name="getDateTime"> <input> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" use="encoded" namespace="urn:oracle-ws"/> </input> <output> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" use="encoded" namespace="urn:oracle-ws"/> </output> <soap:operation soapAction=""/> </operation> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/> </binding> <service name="MyTimeService"> <port name="TimeServicePort" binding="tns:TimeServiceBinding"> <soap:address location="REPLACE_WITH_ACTUAL_URL"/></port> </service> </definitions>

The mapping.xml file specifies the Java to WSDL mapping i.e. it contains the mapping between package names and XML namespaces, WSDL root types and Java artifacts, and the set of mappings for services. For example we will have the following contents for our mapping.xml:

<package-mapping> <package-type>time</package-type> <namespaceURI>urn:oracle-ws</namespaceURI> </package-mapping>

Deployment of webservices requires a deployment descriptor named webservices.xml in META-INF of the ejb-jar file. This descriptor specifies the set of web service descriptions that are to be deployed into the J2EE Application Server and the dependencies they have on container resources and services:

<webservice-description>

http://java.boot.by/wsd-guide/wsd-guide.html 53 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<webservice-description-name>TimeServiceEJB</webservice-description-name> <wsdl-file>META-INF/MyTimeService.wsdl</wsdl-file> <jaxrpc-mapping-file>META-INF/mapping.xml</jaxrpc-mapping-file> <port-component> <description>port component description</description> <port-component-name>TimeServicePort</port-component-name> <wsdl-port> <namespaceURI>urn:oracle-ws</namespaceURI> <localpart>TimeServicePort</localpart> </wsdl-port> <service-endpoint-interface>time.TimeService</service-endpoint-interface> <service-impl-bean> <ejb-link>TimeServiceEJB</ejb-link> </service-impl-bean> </port-component> </webservice-description>

Servlet based endpoint During the deployment of a service endpoint component on a servlet container based JAX-RPC runtime system, a service endpoint class is associated with a servlet. The associated servlet class is provided by the JAX-RPC runtime system (not by service endpoint developer) during the deployment. This association is configured in a manner specific to a JAX-RPC runtime system and its deployment tool. For example, a JAX-RPC deployment tool may configure a 1-1 association between a servlet class and service endpoint class. The associated servlet class corresponds to the configured transport binding for the service endpoint. For example, the servlet class javax.servlet.http. HttpServlet is used for the HTTP transport. The associated servlet typically takes the responsibility of handling transport specific processing of an RPC request and for initiating dispatch to the target service endpoint instance. Each Servlet.service(...) method maps to a single remote method invocation on the target service endpoint instance. The thread model (whether single threaded or concurrent) for the remote method invocation on the service endpoint instance depends on the runtime system specific servlet associated with the corresponding endpoint class. The Servlet specification provides facility for both concurrent and single threaded model (the latter through the SingleThreadModel interface) for the service(...) method on a servlet. When processing an incoming SOAP request for a one-way operation, the associated servlet is required to send back an HTTP response code of 200 or 202 as soon as it has identified the incoming request as being one-way and before it dispatches it to the target service endpoint instance.

Given an set of requirements, design and develop a Web sevice client, such as a J2EE client and a stand-alone Java client, using the appropriate JAX-RPC client connection style.
JAX-RPC Client Environment:

Service endpoint can be implemented using any platform or language. May generate client code from WSDL:
r r

Static stub (compile time) Dynamic proxy (runtime)

May call Web Service directly:


r

Dynamic invocation interface (DII)

Can use either J2SE or J2EE programming model.

There are three Web Service Client programming models: 1. Stub-based (least dynamic) Both interface (WSDL) and implementation (stub) created at compile time. 2. Dynamic proxy

http://java.boot.by/wsd-guide/wsd-guide.html 54 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Interface (WSDL) created at compile time. Implementation (dynamic proxy) created at runtime. 3. Dynamic invocation interface (DII) Both interface (WSDL) and implementation created at runtime. Stub-based Invocation Model

Stub class gets generated at compile time Instantiated using vendor-generated Service implementation class Best performance Stub class implements javax.xml.rpc.Stub interface and Web Service definition interface (com.example.HelloIF)

package javax.xml.rpc; import java.util.Iterator; public interface Stub { /** * Standard property: User name for authentication. */ public static final String USERNAME_PROPERTY = Call.USERNAME_PROPERTY; /** * Standard property: Password for authentication. */ public static final String PASSWORD_PROPERTY = Call.PASSWORD_PROPERTY; /** * Standard property: Target service endpoint address. The * URI scheme for the endpoint address specification must * correspond to the protocol/transport binding for this * stub class. */ public static final String ENDPOINT_ADDRESS_PROPERTY = "javax.xml.rpc.service.endpoint.address"; /** * Standard property: This boolean property is used by a service * client to indicate whether or not it wants to participate in * a session with a service endpoint. If this property is set to * true, the service client indicates that it wants the session * to be maintained. If set to false, the session is not maintained. * The default value for this property is false. */ public static final String SESSION_MAINTAIN_PROPERTY = Call.SESSION_MAINTAIN_PROPERTY; public void _setProperty(String name, Object value); public Object _getProperty(String name); public Iterator _getPropertyNames(); }

http://java.boot.by/wsd-guide/wsd-guide.html 55 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Steps for Stub-Based Invocation Client: 1. 2. 3. 4. Generate Stubs Create Client code Compile the Client code with remote interface and stubs in CLASSPATH Run the Client with JAX-RPC generated code and runtime

Stand-alone Stub-based Client example:

package com.example; import javax.xml.rpc.Stub; public class HelloClient { public static void main(String[] args) { try { Stub stub = (Stub) (new MyHelloService_Impl().getHelloIFPort()); stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]); HelloIF hello = (HelloIF) stub; println(hello.sayHello("Duke!")); } catch (Exception ex) { ex.printStackTrace(); } } }

J2EE Stub-based Client example:

package com.example; import javax.xml.rpc.Stub; public class HelloClient { public void callSayHello { try { Context ic = new InitialContext(); Service service = (Service) ic.lookup("java:comp/env/service/HelloService"); HelloIF hello = (HelloIF) service.getHelloServiceProviderPort(); println(hello.sayHello("Duke!")); } catch (Exception ex) { ex.printStackTrace(); } } }

http://java.boot.by/wsd-guide/wsd-guide.html 56 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Dynamic Proxy-based Invocation Model


At Runtime Application provides the WSDL Dynamic proxy is generated on the fly by JAX-RPC runtime system Slower than stub-based: proxy created and casted More portable than stub-based: does not depend on vendor generated service class before runtime

Dynamic Proxy Client example:

package com.example; import java.net.URL; import javax.xml.rpc.Service; import javax.xml.rpc.JAXRPCException; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceFactory; public class HelloClient { public static void main(String[] args) { try { String UrlString = "http://localhost:8080/ProxyHelloWorld.wsdl"; String nameSpaceUri = "http://sample.proxy.org/wsdl"; String serviceName = "HelloWorld"; // maps to service name in WSDL String portName = "HelloIFPort"; // maps to port name in WSDL URL helloWsdlUrl = new URL(UrlString); ServiceFactory serviceFactory = ServiceFactory.newInstance(); // Create a Service object named helloService

// Destination for service endpoint retrieval QName qn = new QName(nameSpaceUri, portName); // Create a proxy with type of interface 'com.example.HelloIF' HelloIF myProxy = (HelloIF) helloService.getPort(qn, com.example.HelloIF.class); System.out.println(myProxy.sayHello("Duke")); } catch (Exception ex) { ex.printStackTrace(); } } }

WSDL:

... <service name="HelloWorld"> <port name="HelloIFPort" binding="tns:HelloWorldBinding"> <soap:address location="http://example.com/HelloWorld"/> </port> </service> ...

The javax.xml.rpc.Service interface :

http://java.boot.by/wsd-guide/wsd-guide.html 57 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

package javax.xml.rpc; import javax.xml.namespace.QName; import javax.xml.rpc.encoding.TypeMappingRegistry; import javax.xml.rpc.handler.HandlerRegistry; public interface Service { /** * The getPort method returns either an instance of a generated * stub implementation class or a dynamic proxy. A service client * uses this dynamic proxy to invoke operations on the target * service endpoint. The <code>serviceEndpointInterface</code> * specifies the service endpoint interface that is supported by * the created dynamic proxy or stub instance. */ public java.rmi.Remote getPort(QName portName, Class serviceEndpointInterface) throws ServiceException; /** * The getPort method returns either an instance of a generated * stub implementation class or a dynamic proxy. The parameter * <code>serviceEndpointInterface</code> specifies the service * endpoint interface that is supported by the returned stub or * proxy. In the implementation of this method, the JAX-RPC * runtime system takes the responsibility of selecting a protocol * binding (and a port) and configuring the stub accordingly. * The returned <code>Stub</code> instance should not be * reconfigured by the client. */ public java.rmi.Remote getPort(Class serviceEndpointInterface) throws ServiceException; public Call[] getCalls(QName portName) throws ServiceException; public Call createCall(QName portName) throws ServiceException; public Call createCall(QName portName, QName operationName) throws ServiceException; public Call createCall(QName portName, String operationName) throws ServiceException; public Call createCall() throws ServiceException; public QName getServiceName(); public java.util.Iterator getPorts() throws ServiceException; public java.net.URL getWSDLDocumentLocation(); public TypeMappingRegistry getTypeMappingRegistry(); public HandlerRegistry getHandlerRegistry(); }

Dynamic Invocation Interface (DII) Model


Gives complete control to client programmer Most dynamic but complex programming Create JAX-RPC javax.xml.rpc.Call object first, set operation and parameters during runtime Could combine with UDDI lookup and WSDL parsing for dynamic lookup and discovery Used when service definition interface is NOT known until runtime

Dynamic Invocation Interface (DII) Client example:

package com.example; import javax.xml.rpc.Call; import javax.xml.rpc.Service; import javax.xml.rpc.JAXRPCException;


http://java.boot.by/wsd-guide/wsd-guide.html 58 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

import javax.xml.namespace.QName; import javax.xml.rpc.ServiceFactory; import javax.xml.rpc.ParameterMode; public class HelloClient { private static String endpoint = "http://localhost:8080/dynamic-jaxrpc/dynamic"; private static String qnameService = "Hello"; private static String qnamePort = "HelloIF"; private static String BODY_NAMESPACE_VALUE = "http://dynamic.org/wsdl"; private static String ENCODING_STYLE_PROPERTY = "javax.xml.rpc.encodingstyle.namespace.uri"; private static String NS_XSD = "http://www.w3.org/2001/XMLSchema"; private static String URI_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"; public static void main(String[] args) { try { ServiceFactory factory = ServiceFactory.newInstance(); Service service = factory.createService(new QName(qnameService)); QName port = new QName(qnamePort); //create JAX-RPC Call using JAX-RPC Service's createCall() method. Call call = service.createCall(port); // Configure your Call instance with its setter methods call.setTargetEndpointAddress(endpoint); call.setProperty(Call.SOAPACTION_USE_PROPERTY, new Boolean(true)); call.setProperty(Call.SOAPACTION_URI_PROPERTY, ""); call.setProperty(ENCODING_STYLE_PROPERTY, URI_ENCODING); QName QNAME_TYPE_STRING = new QName(NS_XSD, "string"); call.setReturnType(QNAME_TYPE_STRING); call.setOperationName(new QName(BODY_NAMESPACE_VALUE "sayHello")); call.addParameter("String_1", QNAME_TYPE_STRING, ParameterMode.IN); String[] params = { "Duke!" }; // Invoke the WS operation using the JAX-RPC Call's invoke method String result = (String) call.invoke(params); System.out.println(result); } catch (Exception ex) { ex.printStackTrace(); } } }

The javax.xml.rpc.Call interface:

package javax.xml.rpc; import javax.xml.namespace.QName; import java.util.Iterator; import java.util.List; import java.util.Map; /** * The <code>javax.xml.rpc.Call</code> interface provides support * for the dynamic invocation of a service endpoint. The * <code>javax.xml.rpc.Service</code> interface acts as a factory * for the creation of <code>Call</code> instances. */ public interface Call {

http://java.boot.by/wsd-guide/wsd-guide.html 59 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

/** * Standard property: User name for authentication */ public static final String USERNAME_PROPERTY = "javax.xml.rpc.security.auth.username"; /** * Standard property: Password for authentication */ public static final String PASSWORD_PROPERTY = "javax.xml.rpc.security.auth.password"; /** * Standard property for operation style. This property is * set to "rpc" if the operation style is rpc; "document" * if the operation style is document. */ public static final String OPERATION_STYLE_PROPERTY = "javax.xml.rpc.soap.operation.style"; /** * Standard property for SOAPAction. This boolean property * indicates whether or not SOAPAction is to be used. The * default value of this property is false indicating that * the SOAPAction is not used. */ public static final String SOAPACTION_USE_PROPERTY = "javax.xml.rpc.soap.http.soapaction.use"; /** * Standard property for SOAPAction. Indicates the SOAPAction * URI if the <code>javax.xml.rpc.soap.http.soapaction.use</code> * property is set to <code>true</code>. */ public static final String SOAPACTION_URI_PROPERTY = "javax.xml.rpc.soap.http.soapaction.uri"; /** * Standard property for encoding Style: Encoding style specified * as a namespace URI. The default value is the SOAP 1.1 encoding * <code>http://schemas.xmlsoap.org/soap/encoding/</code> */ public static final String ENCODINGSTYLE_URI_PROPERTY = "javax.xml.rpc.encodingstyle.namespace.uri"; /** * Standard property: This boolean property is used by a service * client to indicate whether or not it wants to participate in * a session with a service endpoint. If this property is set to * true, the service client indicates that it wants the session * to be maintained. If set to false, the session is not maintained. * The default value for this property is <code>false</code>. */ public static final String SESSION_MAINTAIN_PROPERTY = "javax.xml.rpc.session.maintain"; /** * Indicates whether <code>addParameter</code> and * <code>setReturnType</code> methods * are to be invoked to specify the parameter and return type * specification for a specific operation. */ public boolean isParameterAndReturnSpecRequired(QName operationName); /** * Adds a parameter type and mode for a specific operation. * Note that the client code may not call any * <code>addParameter</code> and <code>setReturnType</code> * methods before calling the <code>invoke</code> method. In * this case, the Call implementation class determines the * parameter types by using reflection on parameters, using * the WSDL description and configured type mapping registry.
http://java.boot.by/wsd-guide/wsd-guide.html 60 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

*/ public void addParameter(String paramName, QName xmlType, ParameterMode parameterMode); /** * Adds a parameter type and mode for a specific operation. * This method is used to specify the Java type for either * OUT or INOUT parameters. * * @param paramName Name of the parameter * @param xmlType XML datatype of the parameter * @param javaType The Java class of the parameter * @param parameterMode Mode of the parameter-whether * ParameterMode.IN, OUT or INOUT */ public void addParameter(String paramName, QName xmlType, Class javaType, ParameterMode parameterMode); /** * Gets the XML type of a parameter by name. */ public QName getParameterTypeByName(String paramName); /** * Sets the return type for a specific operation. Invoking * <code>setReturnType(null)</code> removes the return * type for this Call object. */ public void setReturnType(QName xmlType); /** * Sets the return type for a specific operation. */ public void setReturnType(QName xmlType, Class javaType); /** * Gets the return type for a specific operation. */ public QName getReturnType(); /** * Removes all specified parameters from this <code>Call</code> instance. * Note that this method removes only the parameters and not * the return type. The <code>setReturnType(null)</code> is * used to remove the return type. */ public void removeAllParameters(); /** * Gets the name of the operation to be invoked using this Call instance. */ public QName getOperationName(); /** * Sets the name of the operation to be invoked using this * <code>Call</code> instance. */ public void setOperationName(QName operationName); /** * Gets the qualified name of the port type. */ public QName getPortTypeName(); /** * Sets the qualified name of the port type.

http://java.boot.by/wsd-guide/wsd-guide.html 61 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

*/ public void setPortTypeName(QName portType); /** * Sets the address of the target service endpoint. * This address must correspond to the transport specified * in the binding for this <code>Call</code> instance. */ public void setTargetEndpointAddress(String address); /** * Gets the address of a target service endpoint. */ public String getTargetEndpointAddress(); /** * Sets the value for a named property. JAX-RPC specification * specifies a standard set of properties that may be passed * to the <code>Call.setProperty</code> method. */ public void setProperty(String name, Object value); /** * Gets the value of a named property. */ public Object getProperty(String name); /** * Removes a named property. */ public void removeProperty(String name); /** * Gets the names of configurable properties supported by * this <code>Call</code> object. */ public Iterator getPropertyNames(); // Remote Method Invocation methods /** * Invokes a specific operation using a synchronous request-response * interaction mode. */ public Object invoke(Object[] inputParams) throws java.rmi.RemoteException; /** * Invokes a specific operation using a synchronous request-response * interaction mode. */ public Object invoke(QName operationName, Object[] inputParams) throws java.rmi.RemoteException; /** * Invokes a remote method using the one-way interaction mode. The * client thread does not block waiting for the completion of the * server processing for this remote method invocation. This method * must not throw any remote exceptions. This method may throw a * <code>JAXRPCException</code> during the processing of the one-way * remote call. */ public void invokeOneWay(Object[] params); /** * Returns a <code>Map</code> of {name, value} for the output parameters of
http://java.boot.by/wsd-guide/wsd-guide.html 62 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

* the last invoked operation. The parameter names in the * returned Map are of type <code>java.lang.String</code>. */ public Map getOutputParams(); /** * Returns a <code>List</code> values for the output parameters * of the last invoked operation. */ public List getOutputValues(); }

Table 4.1. Usage scenarios of the three Web Service service client styles.
Static stub Dynamic proxy Dynamic Invocation Interface (DII) Considerable changes to the Web service expected, such as: Web service not expected to change Some changes to the Web Service expected, such as the location of the service

Location of the service Request/response format Data types

Most common scenario You can generate a stub class either from WSDL (using WSDL2Java) or from a service endpoint interface. A generated stub class is required to implement both javax.xml.rpc.Stub and the service endpoint interface. This stub interface provides APIs to configure stubs by setting properties like endpoint address, session, user name, password, etc.

Less common

Less common

The client at runtime creates dynamic proxy stubs using the javax.xml.rpc. Service interface. The client has a priori knowledge of the WSDL and the service it is going to invoke. It uses the javax.xml.rpc.ServiceFactory classes to create the service and get the proxy.

This software pattern eliminates the need for clients to know in advance a service's exact name and parameters. A DII client can discover this information at runtime using a service broker that can look up the service's information. This flexibility in service discovery enables the run-time system to use service brokers, which can adopt varying service discovery mechanisms - ebXML registries, UDDI, etc.

Given a set of requirements, develop and configure a Web service client that accesses a stateful Web service.
1212

Explain the advantages and disadvantages of a WSDL to Java vs. a Java to WSDL development approach.
WSDL to Java: 1. 2. 3. 4. Convenient when WSDL document already exists More powerful Requires WSDL and XML Schema knowledge Easy to stray outside of WS-I BP 1.0, harming interoperability

Java to WSDL: 1. Easier to use 2. No need to learn WSDL or XML Schema 3. Less control over published service contract

Describe the advantages and disadvantages of web service applications that use either synchronous/request response, oneway RPC, or non-blocking RPC invocation modes.
http://java.boot.by/wsd-guide/wsd-guide.html 63 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Synchrous request-response mode:

Client's thread blocks until a return value or exception is returned

One-way RPC mode:


Client's thread continues processing No return value or exception is expected

Example:

... <portType name="HelloOneWayIF"> <operation name="oneWayValueType"> <input message="tns:HelloOneWayIF_oneWayValueType"/> </operation> </portType> <binding name="HelloOneWayIFBinding" type="tns:HelloOneWayIF"> <operation name="oneWayValueType"> <input> <soap:body use="literal"/> </input> <soap:operation soapAction=""/> </operation> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/> </binding> ...

Non-blocking RPC invocation mode:


A client invokes a remote procedure and continues in its thread without blocking Later, the client processes the remote method return by performing a blocked receive call or by polling for the return value

Use the JAX-RPC Handler API to create a SOAP message handler, describe the function of a handler chain, and describe the role of SAAJ when creating a message handler.
JAX-RPC handlers allow you to intercept a SOAP message at various times during a service invocation. Handlers can exist on both the client and the server side. If you use JAX-RPC on the client side, you can have a handler process a SOAP request message right before it goes on the network, and you can process the response message before it is returned to the client. Similarly, you can intercept an incoming SOAP request message on the server before invoking the service implementation, as well as the outgoing response. Several handlers can be combined into what is called a "handler chain". Each handler processes the SOAP message, which is then passed on to the next handler in the chain. The exact sequence in which this happens is configurable. To develop a JAX-RPC handler, you simply create a class that implements the javax.xml.rpc.handler.Handler interface. It has three methods to handle SOAP requests, responses and faults, respectively. Handlers are defined in the JAX-RPC specification. However, the "Enterprise Web Services" (JSR109) specification describes how they are used in a J2EE environment and adds some clarification to the way handlers are managed by the application server. We will assume that your Web service runs on a J2EE application server and hence we will follow the definitions of JSR109 as well as JAX-RPC. Handlers are shared across multiple service invocations. In other words, they can store information that is only valid for a particular client or server instance. You can compare this to the way servlets are handled. When a new instance of a handler is created, its init(...) method is called. That allows you to set up things that you can use for multiple invocations. Before the handler is removed, the destroy() method is called, so that you can do cleanup in there. As a rule of thumb, however, you should avoid storing any state in a handler altogether.
http://java.boot.by/wsd-guide/wsd-guide.html 64 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Handlers can be configured either programmatically or, in case you are running a J2EE application server, they are configured in the Web service deployment descriptor. Handlers and handler chains are defined on a per service basis. They can be defined in both the server and client side deployment descriptors. Listing below shows the deployment descriptor for our sample service, showing how a handler class called handler.PerformanceHandler is registered for the HelloWorld service:

<webservices> <webservice-description> <webservice-description-name>HelloWorldService</webservice-description-name> <wsdl-file>WEB-INF/wsdl/HelloWorld.wsdl</wsdl-file> <jaxrpc-mapping-file>WEB-INF/HelloWorld_mapping.xml</jaxrpc-mapping-file> <port-component> <port-component-name>HelloWorld</port-component-name> <wsdl-port> <namespaceURI>http://pack</namespaceURI> <localpart>HelloWorld</localpart> </wsdl-port> <service-endpoint-interface>pack.HelloWorld</service-endpoint-interface> <service-impl-bean> <servlet-link>pack_HelloWorld</servlet-link> </service-impl-bean> <handler> <handler-name>handler.PerformanceHandler</handler-name> <handler-class>handler.PerformanceHandler</handler-class> </handler> </port-component> </webservice-description> </webservices>

Multiple handlers would be defined here to form a chain as mentioned above. If multiple handlers that are involved in one service invocation need to share information, they can do so by adding properties to the message context as it is passed from handler to handler. This message context will be available from the request to the response. In other words, we can use it to store information on an incoming request that we can reuse when the response comes back. Now let's look at how you can create a handler that measures the response time of your service implementation. We will assume that you have created a HelloWorld web service, which simply returns a String message. Listing below shows the code for the service implementation bean:

public class HelloWorld { public String helloWorld(String message) { return "Hello " + message; } }

The handler will be configured for the server that hosts the Web service. It will be invoked on both the request and the response message, so that we can measure the elapsed time. Each handler must implement the javax.xml.rpc.handler.Handler interface. Or, you can make your life a bit easier by simply inheriting the javax.xml.rpc.handler.GenericHandler class, which provides default implementations for all the methods. For storing performance results, we use a class called Logger, which we set up in the init() method. Moreover, the application server passes a javax.xml.rpc.handler.HandlerInfo object into this method, which we need to cache as well:

public class PerformanceHandler extends GenericHandler { protected HandlerInfo info = null; protected Logger logger = null;

http://java.boot.by/wsd-guide/wsd-guide.html 65 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

public void init(HandlerInfo arg) { info = arg; logger = Logger.getLogger("c://temp//HelloWorldServiceLog"); } public void destroy() { try { logger.close(); } catch (Exception x) {} } ... }

Note that we close the Logger object when the handler instance is destroyed. Each handler implements the handleRequest method, which is invoked when a request message arrives:

public boolean handleRequest(MessageContext context) { try { Date startTime = new Date(); context.setProperty("startTime", startTime); } catch (Exception x) { x.printStackTrace(); } return true; }

Here you can see that we store the current time in the message context as a property called "startTime". The application server will guarantee that the same message context object is passed into the handleResponse method, so that we can measure the elapsed time there:

public boolean handleResponse(MessageContext context) { try { Date startTime = (Date)context.getProperty("startTime"); Date endTime = new Date(); long elapsedTime = endTime.getTime() - startTime.getTime(); logger.write("Elapsed time is " + elapsedTime+"\n"); } catch (Exception x) { x.printStackTrace(); } return true; }

JAX-RPC defines a mechanism with which you can manage service invocations by intercepting request and response messages without having to change the actual service consumer or provider. In J2EE, you can configure handlers in a deployment descriptor, without writing any code, providing you with a powerful way of controlling SOAP messages as they pass through your system. Handlers let you access/modify SOAP request and response messages, but typically used to process service contexts in SOAP header blocks. Possible example handlers: encryption, decryption, authentication, authorization, logging, auditing, caching. Handlers are pluggable and chainable through standardized programming API, portable across implementations. Handler has its own lifecycle: JAX-RPC runtime system calls init(...), destroy() of a handler. Handler instances can be pooled (stateless). MessageContext is used to share properties among handlers in a handler chain. On the service client side: a request handler is invoked before an RPC request is communicated to the target service endpoint, a response or fault handler is invoked before an RPC response is returned to the client.

http://java.boot.by/wsd-guide/wsd-guide.html 66 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

On a service endpoint: a request handler is invoked before an RPC request is dispatched to the target service endpoint, a response or fault handler is invoked before communication back to the service client from the target service endpoint. javax.xml.rpc.handler.Handler interface is required to be implemented by a SOAP message handler:

package javax.xml.rpc.handler; import javax.xml.namespace.QName; public interface Handler { public boolean handleRequest(MessageContext context); // 'false' will block the HandlerChain public boolean handleResponse(MessageContext context); // 'false' will block the HandlerChain public boolean handleFault(MessageContext context); // 'false' will block the HandlerChain public abstract void init(HandlerInfo config); public abstract void destroy(); public QName[] getHeaders(); }

or extend GenericHandler abstract class:

package javax.xml.rpc.handler; import javax.xml.namespace.QName; public abstract class GenericHandler implements Handler { protected GenericHandler() {} public boolean handleRequest(MessageContext context) { return true; } public boolean handleResponse(MessageContext context) { return true; } public boolean handleFault(MessageContext context) { return true; } public void init(HandlerInfo config) {} public void destroy() {} public abstract QName[] getHeaders(); }

Sample handler which extends GenericHandler:

public class SampleSOAPHeaderHandler extends GenericHandler{ public boolean handleRequest(MessageContext ctx){ try{ SOAPMessageContext mc = (SOAPMessageContext)ctx; SOAPMessage msg = mc.getMessage(); SOAPPart sp = msg.getSOAPPart(); SOAPEnvelop se = sp.getEnvelop(); SOAPHeader header= se.getHeader(); // now we can process the header

http://java.boot.by/wsd-guide/wsd-guide.html 67 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

if (everything is fine) { return true; // with 'true' handler chain continues processing } else { return false; // return 'false' results in chaining to stop } } catch(Exception ex){} } }

Configurable on both client and endpoint side:


Server side in jaxrpc-ri.xml file Client side in config.xml file

jaxrpc-ri.xml (server side config): <?xml version="1.0" encoding="UTF-8" ?> <webServices xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/dd" version="1.0" targetNamespaceBase="http://com.test/wsdl" typeNamespaceBase="http://com.test/types" urlPatternBase="/test"> <endpoint name="MyHandlerApp" interface="service.HandlerTest" implementation="service.HandlerTestImpl"> <handlerChains> <chain runAt="server"> <!-- this handler declares that it understands the "loginfo" header --> headerprops"> <property name="name" value="server1" /> </handler> <handler className="service.ServerHandler2"> <property name="name" value="server2" /> </handler> </chain> </handlerChains> </endpoint> <endpointMapping endpointName="MyHandlerApp" urlPattern="/test" /> </webServices>

Example of generic SOAP message handler:

package com.example; public class MySOAPMessageHandler implements javax.xml.rpc.handler.Handler { public MySOAPMessageHandler() { ... } public boolean handleRequest(MessageContext context){ try { SOAPMessageContext smc = (SOAPMessageContext)context; SOAPMessage msg = smc.getMessage(); SOAPPart sp = msg.getSOAPPart(); SOAPEnvelope se = sp.getEnvelope(); SOAPHeader sh = se.getHeader();

http://java.boot.by/wsd-guide/wsd-guide.html 68 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

// Process one or more header blocks // ... // Next step based on the processing model for this handler } catch(Exception ex) { // throw exception } } ... }

Server side handler:

package service; import javax.xml.namespace.QName; import javax.xml.rpc.handler.soap.SOAPMessageContext; import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.handler.*; import javax.xml.soap.*; /** * This class implements a handler by extending the abstract * class javax.xml.rpc.handler.GenericHandler. */ public class ServerHandler1 extends GenericHandler { private HandlerInfo handlerInfo; private String name; public void init(HandlerInfo info) { handlerInfo = info; // this parameter was configured in jaxrpc-ri.xml name = (String) info.getHandlerConfig().get("name"); System.out.println("ServerHandler1: name = " + name); } /* * This method is declared abstract in GenericHandler and must * be defined here. See ServerHandler2 for another way to implement. */ public QName[] getHeaders() { return handlerInfo.getHeaders(); } /* * This handler will check incoming messages for the header * specified in jaxrpc-ri.xml. It doesn't do anything with the * information besides output it, but it could be used to determine * what type of processing should be performed on this message * before passing on to the ultimate recipient. */ public boolean handleRequest(MessageContext context) { // ... } }

config.xml (client side config):

http://java.boot.by/wsd-guide/wsd-guide.html 69 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<?xml version="1.0" encoding="UTF-8"?> <configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> <wsdl location="http://localhost:8080/handler/test?WSDL" packageName="handlersample"> <handlerChains> <chain runAt="client"> <handler className="client.ClientHandler1"> <!-- Send a property to this handler --> <property name="name" value="My Client Handler" /> </handler> </chain> </handlerChains> </wsdl> </configuration>

Client side handler:

package client; import javax.xml.namespace.QName; import javax.xml.rpc.handler.soap.SOAPMessageContext; import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.handler.*; import javax.xml.soap.*; /** * This class implements a handler by extending the abstract * class javax.xml.rpc.handler.GenericHandler. */ public class ClientHandler1 extends GenericHandler { HandlerInfo handlerInfo; String name; public void init(HandlerInfo info) { handlerInfo = info; // this parameter was configured in config.xml name = (String) info.getHandlerConfig().get("name"); System.out.println("ClientHandler1: name = " + name); } /* * This method is declared abstract in GenericHandler and must * be defined here. Another way to implement is to keep an array * of QNames and set them in the init() method to info.getHeaders(). */ public QName[] getHeaders() { return handlerInfo.getHeaders(); } public boolean handleRequest(MessageContext context) { try { // get the soap header SOAPMessageContext smc = (SOAPMessageContext) context; SOAPMessage message = smc.getMessage(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPHeader header = message.getSOAPHeader(); if (header == null) { header = envelope.addHeader(); }

http://java.boot.by/wsd-guide/wsd-guide.html 70 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

// Add logger element with musUnderstand=1. // Will use the default actor "next" for this example, otherwise // use loggerElement.setActor(String actorURI). // The element will contain a ficticuous log level for // this example. System.out.println("ClientHandler1: adding loggerElement"); SOAPHeaderElement loggerElement = header.addHeaderElement( envelope.createName("loginfo", "ns1", "http://example.com/headerprops")); loggerElement.setMustUnderstand(true); loggerElement.setValue("10"); // Add simple element describing the client making the request. System.out.println("ClientHandler1: adding nameElement"); SOAPHeaderElement nameElement = header.addHeaderElement( envelope.createName("clientname", "ns1", "http://example.com/headerprops")); nameElement.addTextNode("Duke"); } catch (Exception e) { throw new JAXRPCException(e); } // return true to continue message processing return true; } }

A handler chain represents an ordered list of handlers. This grouping helps you define policies that you want associated with the handler invocation model. Examples of such policies include order of invocation, style of invocation (for example, a one-way call invokes only handleRequest(); no handleResponse()), etc. Another possible policy you can set on the handler chain: A handler chain can invoke a handler based on the qname of the outermost element of a SOAP header. This association can be configured to the handler through the Handler. init(...) method passing a HandlerInfo object. The handler chain continues processing the handlers only if the current processing handler returns true. You can associate a handler chain with SOAP actors (or roles) by specifying the URIs of the actors. By default, a handler chain is always associated with the special SOAP actor http://schemas.xmlsoap.org/soap/actor/next. A handler chain is registered on a per service endpoint basis, as indicated by the qualified name of the WSDL port.

package javax.xml.rpc.handler; import java.util.List; import java.util.Map; public interface HandlerChain extends List { public boolean handleRequest(MessageContext context); public boolean handleResponse(MessageContext context); public boolean handleFault(MessageContext context); public void init(Map config); public void destroy(); public void setRoles(String[] soapActorNames); public java.lang.String[] getRoles(); }

Chapter 5. SOAP and XML Processing APIs (JAXP, JAXB, and SAAJ)

Describe the functions and capabilities of the APIs included within JAXP.
SAX
http://java.boot.by/wsd-guide/wsd-guide.html 71 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

1212 DOM 1212 TrAX (Transformation API for XML) TrAX is an API for transforming XML documents using XSLT style sheets. TrAX is a Java API and has been defined to provide common access to different XSLT Processors. TrAX is part of the JAXP API, which combines a number of Java APIs. The TrAX API extends the original JAXP mission to include XML transformations: provide a vendor and implementation agnostic standard Java API for specifying and executing XML transformations. This is important to note, because TrAX is more than just a standard interface for XSLT engines - it is designed to be used as a general-purpose transformation interface for XML documents. TrAX isn't a competitor to the existing DOM and SAX APIs used to represent and process XML, but a common Java API to bridge the various XML transformation methods (a la JDBC, JNDI, etc.) including SAX Events and XSLT Templates. In fact, TrAX relies upon a SAX2- and DOM-level-2-compliant XML parser/XSLT engine. JAXP 1.0 allows the developer to change XML parsers by setting a property, and TrAX provides the same functionality for XSLT engines. Here is a sample of how to apply an XSLT stylesheet to an XML document and write the results out to a file. In this example, both the stylesheet and the XML document exist as files, but they could just as easily have come from any Java InputStream or Reader class. The same follows for the results of the transformation; I could've just as easily written the results out to any Java OutputStream or Writer class.

// 1. create the XML content input source: // can be a DOM node, SAX stream, or any Java input stream/reader String xmlInputFile = "myXMLinput.xml"; Source xmlSource = new StreamSource(new FileInputStream(xmlInputFile)); // 2. create the XSLT Stylesheet input source // can be a DOM node, SAX stream, or a java input stream/reader String xsltInputFile = "myXsltStylesheet.xsl"; Source xsltSource = new StreamSource(new FileInputStream(xsltInputFile)); // 3. create the result target of the transformation // can be a DOM node, SAX stream, or a java out stream/reader String xmlOutputFile = "result.html"; Result transResult = new StreamResult(new FileOutputStream(xmlOutputFile)); // 4. create the transformerfactory and transformer instance TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(xsltSource); // 5. execute transformation and fill result target object t.transform(xmlSource, transResult);

The first three stanzas simply establish our inputs and result targets, and aren't that interesting, with one exception. Notice that the XSLT stylesheet isn't handled via a different class in TrAX. It's treated just like any other XML source document, because that's exactly what it is. We use the stream implementations of the Source and Result interfaces from the javax.xml.transform.stream package to handle reading the data from our file streams. In the fourth stanza, we use the TransformerFactory to get an instance of a Transformer, and then use the Source instance for the XSLT stylesheet we created in the second stanza to define the transformation that this transformer will perform. A Transformer actually executes the transformation and assembles the result. A single Transformer instance can be reused, but it is not thread-safe. In this example, the XSLT stylesheet is reprocessed for each successive transformation. A very common case is that the same transformation is applied multiple times to different Sources, perhaps in different threads. A more efficient approach in this case is to process the transformation stylesheet once, and save this object for successive transformations. This is achieved through the use of the TrAX Templates interface:

http://java.boot.by/wsd-guide/wsd-guide.html 72 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

// we've already set up our content Source instance, // XSLT Source instance, TransformerFactory, and // Result target from the previous example // process the XSLT stylesheet into a Templates instance // with our TransformerFactory instance Templates t = tf.newTemplates(xsltSource); // whenever you need to execute this transformation, create // a new Transformer instance from the Templates instace Transformer trans = t.newTransformer(); // execute transformation and fill result target object trans.transform(xmlSource, transResult);

While the Transformer performs the transformation, a Templates instance is the actual run-time representation of the processed transformation instructions. Templates instances may be reused to increase performance, and they are thread-safe. It might seem odd that an interface has a plural name, but it stems from the fact that an XSLT stylesheet consists of a collection of one or more xsl:template elements. Each template element defines a transformation in that stylesheet, so it follows that the simplest name for a representation of a collection of template elements is Templates. One of the main reasons the TrAX API is so clean and simple is the Interface-driven approach to design. The highest-level interfaces define the essential entities that are being modeled, and the interactions are left to the implementations. The interfaces themselves aren't very interesting. They are essentially marker interfaces. Source The Source interface is a generic container for existing XML documents that will be used in a transformation as either the input document or the stylesheet. Serve as a single vendor-neutral object for multiple types of input. Implementations of the Source interface provide access to the XML document to be processed. TrAX defines Source implementations for DOM trees (DOMSource); SAX 2.0 InputSources (SAXSource); and Java InputStreams, Readers and any of their derived classes (StreamSource).

package javax.xml.transform; public interface Source { public void setSystemId(String systemId); public String getSystemId(); }

Result The Result interface is a generic container for an XML document that will be produced by a transformation. Serve as a single object for multiple types of output, so there can be simple process method signatures. Implementations of the Result interface provide access to the transformed XML document. TrAX defines Result implementations for DOM trees (DOMResult); SAX 2.0 ContentHandlers (SAXResult); and Java OutputStreams, Writers and any of their derived classes (StreamResult).

package javax.xml.transform; public interface Result { public static final String PI_DISABLE_OUTPUT_ESCAPING; public static final String PI_ENABLE_OUTPUT_ESCAPING; public void setSystemId(String url); public String getSystemId(); }

Templates

http://java.boot.by/wsd-guide/wsd-guide.html 73 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Templates is a thread-safe interface that represents a compiled stylesheet. It can quickly create new Transformer objects without having to reread and reparse the original stylesheet. Its particularly useful when you want to use the same stylesheet in multiple threads. The runtime representation of the transformation instructions. A template implementation is the optimized, in-memory representation of an XML transformation that is processed and ready to be executed. Templates objects are safe to use in concurrent threads. To reuse a single Template instance in multiple concurrent threads, multiple Transformer instances would have to be created via the Templates. newTransformer() factory method. Each Transformer instance may be used completely independently in concurrent threads, and both the Templates and the Transformer instances can be reused for subsequent transformations.

package javax.xml.transform; public interface Templates { public Transformer newTransformer() throws TransformerConfigurationException; public Properties getOutputProperties(); }

Transformer Transformer is the abstract class that represents a compiled stylesheet. It transforms Source objects into Result objects. A single Transformer can transform multiple input documents in sequence but not in parallel. Act as a per-thread execution context for transformations, act as an interface for performing the transformation. A Transformer is the object that actually applies the transformation to the source document and creates the result document. However, it is not responsible for outputting, or serializing, the result of the transformation. This is the responsibility of the transformation engine's serializer and this behavior can be modified via the setOutputProperty(java.lang.String name, java.lang.String value) method. The configurable OutputProperties are defined in the OutputKeys class, and are described in the XSLT 1.0 Specification. Transformers are immutable, they cannot change which Templates instance gets applied to the Source.

package javax.xml.transform; public abstract class Transformer { protected Transformer(); public void transform(Source input, Result output) throws TransformerException; public void setParameter(String name, Object value); public Object getParameter(String name); public void clearParameters(); public void setURIResolver(URIResolver resolver); public URIResolver getURIResolver(); public void setOutputProperties(Properties serialization) throws IllegalArgumentException; public Properties getOutputProperties(); public void setOutputProperty(String name, String value) throws IllegalArgumentException; public String getOutputProperty(String name) throws IllegalArgumentException; public void setErrorListener(ErrorListener listener) throws IllegalArgumentException; public ErrorListener getErrorListener(); }

TransformerFactory TransformerFactory is an abstract factory that creates new Transformer and Templates objects. The concrete subclass that newInstance() instantiates is specified by the javax.xml.transform.TransformerFactory Java system property. If this class is not set, a platform dependent default class is chosen. Serve as a vendor-neutral Processor interface for XSLT and similar processors. The TransformerFactory is primarily responsible for creating new Transformer>s and Templates objects. New instances of Transformer are created via the static newTransformer() method. Processing Source instances into Templates objects is handled by the newTemplates(Source source) method.

package javax.xml.transform; public abstract class TransformerFactory {


http://java.boot.by/wsd-guide/wsd-guide.html 74 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

protected TransformerFactory(); public static TransformerFactory newInstance() throws TransformerFactoryConfigurationError; public Transformer newTransformer(Source source) throws TransformerConfigurationException; public Transformer newTransformer() throws TransformerConfigurationException; public Templates newTemplates(Source source) throws TransformerConfigurationException; public Source getAssociatedStylesheet(Source source, String media, String title, String charset) throws TransformerConfigurationException; public void setURIResolver(URIResolver resolver); public URIResolver getURIResolver(); public boolean getFeature(String name); public void setAttribute(String name, Object value) throws IllegalArgumentException; public Object getAttribute(String name) throws IllegalArgumentException; public void setErrorListener(ErrorListener listener) throws IllegalArgumentException; public ErrorListener getErrorListener(); }

Given a scenario, select the proper mechanism for parsing and processing the information in an XML document.
SAX:

SAX is an event-driven XML parser that is appropriate for high-speed processing of XML because it does not produce a representation of the data in memory. SAX automatically perform structure validation. Event-based parsers (SAX) provide a data-centric view of XML. When an element is encountered, the idea is to process it and then forget about it. The event-based parser returns the element, its list of attributes, and the content. This is more efficient for many types of applications, especially searches. It requires less code and less memory since there is no need to build a large tree in memory as you are scanning for a particular element, attribute, and/or content sequence in an XML document.

DOM:

DOM produces an in-memory data representation, which allows an application to manipulate the contents in memory DOM automatically perform structure validation. Tree-based parsers (DOM) provide a document-centric view of XML. In tree-based parsing, an in-memory tree is created for the entire document, which is extremely memory-intensive for large documents. All elements and attributes are available at once, but not until the entire document has been parsed. This technique is useful if you need to navigate around the document and perhaps change various document chunks, which is precisely why it is useful for the Document Object Model (DOM), the aim of which is to manipulate documents via scripting languages or Java.

JAXB:

JAXB application can perform structure and content validation with Java classes that it generates from a schema. A JAXB application builds an in-memory data structure, like a DOM, by marshalling an XML document to build a content tree, which contains objects that are instances of the derived classes. However, unlike a DOM tree, a content tree is specific to one source schema, does not contain extra tree-manipulation functionality, allows access to its data with the derived classes' accessor methods, and is not built dynamically. For these reasons, a JAXB application uses memory more efficiently than a DOM application does. If the content of a document is more dynamic and not well-constrained, DOM and SAX are more appropriate than JAXB for processing XML content that does not have a well-known schema prior to processing the content. Build object trees representing XML data that is valid against the XML Schema by either unmarshalling the data from a document or instantiating the classes you created. Access and modify the data. Optionally validate the modifications to the data relative to the constraints expressed in the XML Schema. Marshal the data to new XML documents.

Describe the functions and capabilities of JAXB, including the JAXB process flow, such as XML-to-Java and Java-to-XML, and the binding and validation mechanisms provided by JAXB.
JAXB defines an architecture for binding XML schemata to Java objects. These bindings allow you to unmarshal XML documents into a

http://java.boot.by/wsd-guide/wsd-guide.html 75 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

hierarchy of Java objects and marshal the Java objects into XML with minimal effort. If you work a lot with XML, you know how tedious it can be to write Simple API for XML (SAX) or Document Object Model (DOM) code to convert XML into Java objects that mean something to your program. JAXB generates code automatically so you can go about the business of processing data instead of parsing it.

Latest version of JAXB supports XML schema definitions and allows additional binding declarations to be defined inside of the schema using XML schema annotations. The JAXB API, defined in the javax.xml.bind package, is a set of interfaces through which client applications communicate with code generated from a schema. The center of the JAXB API is JAXBContext, the client' s entry point. It provides an abstraction for managing the XML-Java binding information necessary to implement the JAXB binding framework operations: unmarshal, marshal and validate. These three aspects of JAXB are covered by three separate interfaces. Instances of those interfaces can be created from a JAXBContext object:

http://java.boot.by/wsd-guide/wsd-guide.html 76 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

javax.xml.bind.Unmarshaller - governs the process of deserializing XML data into Java content trees, optionally validating the XML data as it is unmarshalled.

package javax.xml.bind; import java.io.File; import java.io.InputStream; import java.net.URL; import javax.xml.bind.JAXBException; import javax.xml.bind.PropertyException; import javax.xml.bind.UnmarshallerHandler; import javax.xml.bind.ValidationEventHandler; import javax.xml.transform.Source; import org.w3c.dom.Node; import org.xml.sax.InputSource; public interface Unmarshaller { public Object unmarshal(File f) throws JAXBException; public Object unmarshal(InputStream is) throws JAXBException; public Object unmarshal(URL url) throws JAXBException; public Object unmarshal(InputSource source) throws JAXBException; public Object unmarshal(Node node) throws JAXBException; public Object unmarshal(Source source) throws JAXBException; public UnmarshallerHandler getUnmarshallerHandler(); public void setValidating(boolean validating) throws JAXBException; public boolean isValidating() throws JAXBException; public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; public void setProperty(String name, Object value) throws PropertyException; public Object getProperty(String name) throws PropertyException; }

javax.xml.bind.Marshaller - governs the process of serializing Java content trees back into XML data.

package javax.xml.bind; import java.io.OutputStream; import java.io.Writer; import javax.xml.bind.JAXBException; import javax.xml.bind.PropertyException; import javax.xml.bind.ValidationEventHandler; import javax.xml.transform.Result; import org.w3c.dom.Node; import org.xml.sax.ContentHandler; public interface Marshaller { public static final String JAXB_ENCODING = "jaxb.encoding"; public static final String JAXB_FORMATTED_OUTPUT = "jaxb.formatted.output"; public static final String JAXB_SCHEMA_LOCATION = "jaxb.schemaLocation"; public static final String JAXB_NO_NAMESPACE_SCHEMA_LOCATION = "jaxb.noNamespaceSchemaLocation"; public void marshal(Object obj, Result result) throws JAXBException; public void marshal(Object obj, OutputStream os) throws JAXBException; public void marshal(Object obj, Writer writer) throws JAXBException;
http://java.boot.by/wsd-guide/wsd-guide.html 77 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

public void marshal(Object obj, ContentHandler handler) throws JAXBException; public void marshal(Object obj, Node node) throws JAXBException; public org.w3c.dom.Node getNode(Object contentTree) throws JAXBException; public void setProperty(String name, Object value) throws PropertyException; public Object getProperty(String name) throws PropertyException; public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; }

javax.xml.bind.Validator - performs the validation on an in-memory object graph.

package javax.xml.bind; import javax.xml.bind.JAXBException; import javax.xml.bind.PropertyException; import javax.xml.bind.ValidationEventHandler; public interface Validator { public void setEventHandler(ValidationEventHandler handler) throws JAXBException; public ValidationEventHandler getEventHandler() throws JAXBException; public boolean validate(Object subrootObj) throws JAXBException; public boolean validateRoot(Object rootObj) throws JAXBException; public void setProperty(String name, Object value) throws PropertyException; public Object getProperty(String name) throws PropertyException; }

JAXBContext is an abstract class defined in the API, so its actual implementation is vendor-dependent. To create a new instance of JAXBContext, you use the static newInstance(contextPath) method.

JAXBContext context = JAXBContext.newInstance("org.acme.foo:org.acme.bar");

The contextPath contains a list of Java package names that contain schema derived interfaces. The value of this parameter initializes the JAXBContext object so that it is capable of managing the schema derived interfaces. The client application must supply a context path which is a list of colon (':') separated java package names that contain schema derived classes. In this way, the unmarshaller will look at a document and figure out which package to use. This makes it easy to read in different types of documents without knowing their type in advance. Unmarshalling (XML-to-Java) An unmarshaller is used to read XML and build an object tree from classes generated by the compiler. To read an XML file, you would simply do:

... JAXBContext jaxbContext = JAXBContext.newInstance(packageName); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setValidating(true); Item item = (Item) unmarshaller.unmarshal(new File("item.xml")); ...

There are other overloaded versions that take different types of input, such as InputStream or InputSource. You can even unmarshal a javax.xml.transform.Source object. All in all, it's similar to the way DOM trees are parsed. Here are some more examples of unmarshalling:

http://java.boot.by/wsd-guide/wsd-guide.html 78 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Unmarshalling from a File:

JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); Object o = u.unmarshal( new File( "xmlFile.xml" ) );

Unmarshalling from an java.io.InputStream:

InputStream is = new FileInputStream( "xmlFile.xml" ); JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); Object o = u.unmarshal( is );

Unmarshalling from a java.net.URL:

JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); URL url = new URL( "http://server.com/xmlFile.xml" ); Object o = u.unmarshal( url );

Unmarshalling from a StringBuffer using a javax.xml.transform.stream.StreamSource:

JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); StringBuffer xmlStr = new StringBuffer( "<?xml version='1.0'?> ..." ); Object o = u.unmarshal( new StreamSource( new StringReader( xmlStr.toString() ) ) );

Unmarshalling from a org.w3c.dom.Node:

JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); Unmarshaller u = jc.createUnmarshaller(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File( "xmlFile.xml")); Object o = u.unmarshal( doc );

By default, Unmarshaller is very forgiving. Even if a document is invalid, it tries to recover from errors. If the document is so broken that it cannot be read, an javax.xml.bind.UnmarshalException (child of javax.xml.bind.JAXBException) will be thrown. It's often desirable to get more information about errors or reject documents with errors. The first step to do this is to set ValidationEventHandler to the Unmarshaller. A ValidationEventHandler can explicitly tell a JAXB implementation whether it should reject a document or try to recover from errors. It also gives you more information, such as line numbers, about errors. An Unmarshaller can validate a document with the schema while unmarshalling. With this option turned on, it rejects anything short of a valid document. However, W3C XML Schema validation can be very costly. Another possibility is to set up a SAX pipeline in such a way that your XML parser does the validation; alternately, you could install a stand-alone validator in the pipeline. In this way, for example, you can change your schema to change what you get from the compiler, while maintaining the scrutiny of the original schema. Marshalling (Java-to-XML) A Marshaller is used to write an object graph into XML. To write an object o to a file, you would do:
http://java.boot.by/wsd-guide/wsd-guide.html 79 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

... JAXBContext jaxbContext = JAXBContext.newInstance(packageName); Marshaller marshaller = jaxbContext.createMarshaller(); ObjectFactory itemMaker = new ObjectFactory(); Item item = itemMaker.createItem(); marshaller.marshal(item, new FileOutputStream("newIem.xml")); ...

There are other overloaded versions which allow you to produce XML as a a DOM tree or as SAX events. For example, by using StringWriter, you can marshal an object into a string. You can also marshal an object graph to a javax.xml.transform.Result object. Here are some more examples of marshalling: Marshalling to a File:

OutputStream os = new FileOutputStream( "xmlFile.xml" ); m.marshal( obj, os );

Marshalling to a SAX ContentHandler:

// assume MyContentHandler instanceof ContentHandler m.marshal( obj, new MyContentHandler() );

Marshalling to a DOM Node:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); m.marshal( obj, doc );

Marshalling to a java.io.OutputStream:

m.marshal( obj, System.out );

Marshalling to a java.io.Writer:

m.marshal( obj, new PrintWriter( System.out ) );

Marshalling to a javax.xml.transform.SAXResult:

// assume MyContentHandler instanceof ContentHandler SAXResult result = new SAXResult( new MyContentHandler() ); m.marshal( obj, result );

Marshalling to a javax.xml.transform.DOMResult:

http://java.boot.by/wsd-guide/wsd-guide.html 80 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

DOMResult result = new DOMResult(); m.marshal( obj, result );

Although each of the marshal methods accepts a java.lang.Object as its first parameter, JAXB Providers are not required to be able to marshal any arbitrary java.lang.Object. If the JAXBContext object that was used to create this Marshaller does not have enough information to know how to marshal the object parameter (or any objects reachable from it), then the marshal operation will throw a MarshalException>. By default, the Marshaller will use UTF-8 encoding when generating XML data to a java.io.OutputStream, or a java.io.Writer. Use the setProperty API to change the ouput encoding used during these marshal operations. You can control the behavior of marshalling by setting Marshaller properties. For example, you can toggle indentation of the XML:

... Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true)); ...

JAXB can produce XML as SAX events. That is, you can pass ContentHandler and have it receive SAX events from a JAXB object. This gives client apps plenty of chances to modify XML. For example, you can add and remove elements or attributes, use one of the freely available serializers for better output, or write your own XML serializer that prints XML in your preferred way. Finally, you can ask a Marshaller to marshal an invalid object graph by setting a ValidationEventHandler. If a provider supports error recovery, you can tell it to write XML even if it's incomplete. If the boolean ValidationEventHandler.handleEvent(ValidationEvent event) method throws an unchecked runtime exception, the JAXB Provider must treat that as if the method returned false, effectively terminating whatever operation was in progress at the time (unmarshal, validate, or marshal). The method returns: true if the JAXB Provider should attempt to continue the current unmarshal, validate, or marshal operation after handling this warning/error, false if the provider should terminate the current operation with the appropriate UnmarshalException, ValidationException, or MarshalException. Validation There are three forms of Validation in JAXB: 1. Unmarshal-Time Validation This form of validation enables a client application to receive information about validation errors and warnings detected while unmarshalling XML data into a Java content tree and is completely orthogonal to the other types of validation. To enable or disable it use method Unmarhaller.setValidating(...). All JAXB Providers are REQUIRED to support this operation. 2. On-Demand Validation This form of validation enables a client application to receive information about validation errors and warnings detected in the Java content tree. At any point, client applications can call the Validator.validate(...) method on the Java content tree (or any subtree of it). All JAXB Providers are REQUIRED to support this operation. 3. Fail-Fast Validation This form of validation enables a client application to receive immediate feedback about modifications to the Java content tree that violate type constraints on Java Properties as defined in the specification. JAXB Providers are NOT REQUIRED support this type of validation. Of the JAXB Providers that do support this type of validation, some may require you to decide at schema compile time whether or not a client application will be allowed to request fail-fast validation at runtime. The Validator class is responsible for managing On-Demand Validation. The Unmarshaller class is responsible for managing UnmarshalTime Validation during the unmarshal operations. Although there is no formal method of enabling validation during the marshal operations, the Marshaller may detect errors, which will be reported to the ValidationEventHandler registered on it. JAXB has the capability to validate an object graph in memory without actually writing it to XML. This allows client apps to check if a graph is okay and ready to process; if not, validation will identify objects that contain errors so that, for example, client apps can ask users to fix those.

http://java.boot.by/wsd-guide/wsd-guide.html 81 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

The following code validates the object "item":

... JAXBContext jaxbContext = JAXBContext.newInstance(packageName); ObjectFactory itemMaker = new ObjectFactory(); Item item = itemMaker.createItem(); Validator validator = jaxbContext.createValidator(); if(! validator.validate(item)) { System.err.println("Not valid !!!"); } ...

To receive detailed information about errors, you need to register ValidationEventHandler with the Validator, just like you did in Unmarshaller and Marshaller. This is analogous to registering an ErrorHandler for a SAX parser. You can also first marshal an object graph and then validate XML (for example by Java API for validators). But doing so makes it much harder to associate errors with their sources, which makes debugging harder for humans. Validation after marshalling will give you errors like "missing <foo> element," but you can hardly know what is actually wrong in the object graph. Validity is not enforced while you are modifying an object graph; you ALWAYS have to explicitly validate it. To edit a valid object graph into another valid object graph, you may need to go through invalid intermediate states. If validity is enforced on every step of mutation, this becomes impossible. Customization Through the Schema The binding language is an XML based language which defines constructs referred to as binding declarations. A binding declaration can be used to customize the default binding between an XML schema component and its Java representation. The schema for binding declarations is defined in the namespace http://java.sun.com/xml/ns/jaxb. This specification uses the namespace prefix "jaxb" to refer to the namespace of binding declarations. For example:

<jaxb: binding declaration >

A binding compiler interprets the binding declaration relative to the source schema and a set of default bindings for that schema. Therefore a source schema need not contain a binding declarations for every schema component. This makes the job of a JAXB application developer easier. There are two ways to associate a binding declaration with a schema element:

as part of the source schema (inline annotated schema). external to the source schema in an external binding declaration.

The syntax and semantics of the binding declaration is the same regardless of which of the above two methods is used for customization. Inline Annotated Schema This method of customization utilizes on the appinfo element specified by the XML Schema. A binding declaration is embedded within the appinfo element as illustrated below:

<xs:annotation> <xs:appinfo> <binding declaration> </xs:appinfo> </xs:annotation>

http://java.boot.by/wsd-guide/wsd-guide.html 82 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

The inline annotation where the binding declaration is used identifies the schema component. Here are the changes you must make to the schema to make JAXB generate java.util.Vector rather than java.util.ArrayList, its default collection (the collecionType value must be either "indexed" or any fully qualified class name that implements java.util.List). Note that the top-level schema tag needs to be changed too:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="1.0"> ... <xs:annotation> <xs:appinfo> <jxb:globalBindings collectionType="java.util.Vector" /> </xs:appinfo> </xs:annotation> ...

The annotation tag introduces a part of the schema that is usually intended for schema processing software. The appinfo tag introduces instructions for a particular processing application (in this case, JAXB's xjc code-generation tool). Usually, each application uses its own namespace, as JAXB has done here. Before customization:

<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="todolist"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" minOccurs="0" name="item" type="entry"/> </xs:sequence> </xs:complexType> </xs:element> ... </xs:schema>

public class TodolistTypeImpl implements ... { protected com.sun.xml.bind.util.ListImpl _Item = new com.sun.xml.bind.util.ListImpl(new java.util.ArrayList()); ... }

After customization:

<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="1.0"> <xs:annotation> <xs:appinfo>


http://java.boot.by/wsd-guide/wsd-guide.html 83 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<jxb:globalBindings collectionType="java.util.Vector" /> </xs:appinfo> </xs:annotation> <xs:element name="todolist"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" minOccurs="0" name="item" type="entry"/> </xs:sequence> </xs:complexType> </xs:element> ... </xs:schema>

public class TodolistTypeImpl implements ... { protected com.sun.xml.bind.util.ListImpl _Item = new com.sun.xml.bind.util.ListImpl(new java.util.Vector()); ... }

External Binding Declaration> The external binding declaration format enables customized binding without requiring modification of the source schema. Unlike inline annotation, the remote schema component to which the binding declaration applies must be identified explicitly. The jaxb:bindings element enables the specification of a remote schema context to associate its binding declaration(s) with. Minimally, an external binding declaration follows the following format:

<jaxb:bindings schemaLocation = "xs:anyURI"> <jaxb:bindings node = "xs:string">* <binding declaration> <jaxb:bindings> </jaxb:bindings>

The attributes schemaLocation and node are used to construct a reference to a node in a remote schema. The binding declaration is applied to this node by the binding compiler as if the binding declaration was embedded in the nodes xs:appinfo element. The attribute values are interpreted as follows:

schemaLocation - It is a URI reference to a remote schema. node - It is an XPath 1.0 expression that identifies the schema node within schemaLocation to associate binding declarations with.

Use the SAAJ APIs to create and manipulate a SOAP message.


SAAJ - SOAP with Attachments API for Java - contains APIs for creating and populating SOAP messages which might or might not contain attachments. It also contains APIs for sending point to point, non-provider-based, request and response SOAP messages. SOAP message is made of SOAP Envelope and zero or more attachments. The SOAP Envelope is then made of SOAP Header and SOAP Body. SOAP attachment allows the SOAP message to contain not only the XML data but also non-XML data such as JPG file. And it uses the MIME multipart as container for these non-XML data. The SAAJ API provides the SOAPMessage class to represent a SOAP message, the SOAPPart class to represent the SOAP part, the SOAPEnvelope interface to represent the SOAP envelope, and so on. When you create a new SOAPMessage object, it will automatically have the parts that are required to be in a SOAP message. In other words, a new SOAPMessage object has a SOAPPart object that contains a SOAPEnvelope object. The SOAPEnvelope object in turn
http://java.boot.by/wsd-guide/wsd-guide.html 84 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

automatically contains an empty SOAPHeader object followed by an empty SOAPBody object. If you do not need the SOAPHeader object, which is optional, you can delete it. The rationale for having it automatically included is that more often than not you will need it, so it is more convenient to have it provided. The SOAPHeader object may contain one or more headers with information about the sending and receiving parties. The SOAPBody object, which always follows the SOAPHeader object if there is one, provides a simple way to send information intended for the ultimate recipient. For example, if there is a SOAPFault object, it must be in the SOAPBody object. A SOAP message may include one or more attachment parts in addition to the SOAP part. The SOAP part may contain only XML content; as a result, if any of the content of a message is not in XML format, it must occur in an attachment part. So, if for example, you want your message to contain a binary file, your message must have an attachment part for it. Note that an attachment part can contain any kind of content, so it can contain data in XML format as well. The SAAJ API provides the AttachmentPart class to represent the attachment part of a SOAP message. A SOAPMessage object automatically has a SOAPPart object and its required subelements, but because AttachmentPart objects are optional, you have to create and add them yourself. SAAJ API belongs to javax.xml.soap.* package. SOAPConnection provides request/response SOAP message exchange. SOAPMessage creates and populates SOAP message (consists of SOAPPart and AttachmentPart).

javax.xml.soap.MessageFactory is a factory for creating SOAP 1.1-based messages.

public abstract class MessageFactory { public static MessageFactory newInstance() throws SOAPException { ... } public abstract SOAPMessage createMessage() throws SOAPException;

http://java.boot.by/wsd-guide/wsd-guide.html 85 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

... }

javax.xml.soap.SOAPMessage is a Java technology abstraction for a SOAP 1.1 message. Contains EXACTLY ONE SOAPPart and ZERO OR MORE AttachmentParts.

public abstract class SOAPMessage { public abstract SOAPPart getSOAPPart(); public abstract Iterator getAttachments(); public abstract Iterator getAttachments(MimeHeaders headers); ... }

javax.xml.soap.SOAPPart is the first part of a multi-part message when there are attachments.

public abstract class SOAPPart implements org.w3c.dom.Document { public abstract SOAPEnvelope getEnvelope() throws SOAPException; ... }

javax.xml.soap.AttachmentPart can contain any data (for example: JPEG images, XML business documents, etc.) If a SOAPMessage object has one or more attachments, each AttachmentPart object must have a MIME header to indicate the type of data it contains. It may also have additional MIME headers to identify it or to give its location, which are optional but can be useful when there are multiple attachments. When a SOAPMessage object has one or more AttachmentPart objects, its SOAPPart object may or may not contain message content. Steps of SAAJ Programming 1. Creating a message (SOAPMessage) Use MessageFactory to as a factory of messages. SOAPMessage object has the following:

SOAPPart object
r

SOAPEnvelope object

empty SOAPHeader object empty SOAPBody object

Example:

MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage();

Result:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body/> </SOAP-ENV:Envelope>

2. Accessing elements of a message

http://java.boot.by/wsd-guide/wsd-guide.html 86 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Approach 1: from SOAPEnvelope object:

SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody();

Approach 2: from SOAPMessage object:

SOAPHeader header = message.getSOAPHeader(); SOAPBody body = message.getSOAPBody();

3. Adding contents to the body Example:

SOAPBody body = message.getSOAPBody(); SOAPFactory soapFactory = SOAPFactory.newInstance(); Name bodyName = soapFactory.createName("GetLastTradePrice", "m", "http://wombat.ztrade.com"); SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

Will produce following XML:

<m:GetLastTradePrice xmlns:m="http://wombat.ztrade.com"> ... </m:GetLastTradePrice>

Example:

Name name = soapFactory.createName("symbol"); SOAPElement symbol = bodyElement.addChildElement(name); symbol.addTextNode("SUNW");

Generates XML fragment like following:

<symbol>SUNW</symbol>

4. Getting a SOAPConnection object

SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();

All SOAP messages are sent and received over a connection. With the SAAJ API, the connection is represented by a SOAPConnection object, which goes from the sender directly to its destination. This kind of connection is called a point-to-point connection because it goes from one endpoint to another endpoint. Messages sent using the SAAJ API are called requestresponse messages. They are sent over a SOAPConnection object with the method call, which sends a message (a request) and

http://java.boot.by/wsd-guide/wsd-guide.html 87 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

then blocks until it receives the reply (a response). 5. Sending a message

// Create an endpint point which is either URL or String type java.net.URL endpoint = new URL("http://wombat.ztrade.com/quotes"); // Send a SOAPMessage (request) and then wait for SOAPMessage (response) SOAPMessage response = connection.call(message, endpoint);

A SAAJ client calls the SOAPConnection method call on a SOAPConnection object to send a message. The call method takes two arguments, the message being sent and the destination to which the message should go. This message is going to the stock quote service indicated by the URL object endpoint. 6. Getting the content of a message

SOAPBody soapBody = response.getSOAPBody(); java.util.Iterator iterator = soapBody.getChildElements(bodyName); SOAPBodyElement bodyElement = (SOAPBodyElement)iterator.next(); String lastPrice = bodyElement.getValue(); System.out.print("The last price for SUNW is "); System.out.println(lastPrice);

In order to access bodyElement, you need to call the method getChildElements on soapBody. Passing bodyName to getChildElements returns a java.util.Iterator object that contains all of the child elements identified by the Name object bodyName. You already know that there is only one, so just calling the method next on it will return the SOAPBodyElement you want. Note that the method Iterator.next() returns a Java Object, so it is necessary to cast the Object it returns to a SOAPBodyElement object before assigning it to the variable bodyElement. Adding content to SOAPHeader To add content to the header, you need to create a SOAPHeaderElement object. As with all new elements, it must have an associated Name object, which you can create using the message's SOAPEnvelope object or a SOAPFactory object. For example, suppose you want to add a conformance claim header to the message to state that your message conforms to the WS-I Basic Profile. The following code fragment retrieves the SOAPHeader object from message and adds a new SOAPHeaderElement object to it. This SOAPHeaderElement object contains the correct qualified name and attribute for a WS-I conformance claim header:

SOAPHeader header = message.getSOAPHeader(); Name headerName = soapFactory.createName("Claim", "wsi", "http://ws-i.org/schemas/conformanceClaim/"); SOAPHeaderElement headerElement = header.addHeaderElement(headerName);

At this point, header contains the SOAPHeaderElement object headerElement identified by the Name object headerName. Note that the addHeaderElement method both creates headerElement and adds it to header. XML fragment generated:

<SOAP-ENV:Header> <wsi:Claim conformsTo="http://ws-i.org/profiles/basic1.0/" xmlns:wsi="http://ws-i.org/schemas/conformanceClaim/"/> </SOAP-ENV:Header>

A conformance claim header has no content. For a different kind of header, you might want to add content to headerElement. The following line of code uses the method addTextNode to do this:

http://java.boot.by/wsd-guide/wsd-guide.html 88 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

headerElement.addTextNode("order");

Now you have the SOAPHeader object header that contains a SOAPHeaderElement object whose content is "order". Adding content to SOAPBody The process for adding content to the SOAPBody object is the same as the process for adding content to the SOAPHeader object. You access the SOAPBody object, add a SOAPBodyElement object to it, and add text to the SOAPBodyElement object. It is possible to add additional SOAPBodyElement objects, and it is possible to add subelements to the SOAPBodyElement objects with the method addChildElement. For each element or child element, you add content with the method addTextNode. The following example shows adding multiple SOAPElement objects and adding text to each of them:

SOAPBody body = soapFactory.getSOAPBody(); Name bodyName = soapFactory.createName("PurchaseLineItems", "PO", "http://sonata.fruitsgalore.com"); SOAPBodyElement purchaseLineItems = body.addBodyElement(bodyName); Name childName = soapFactory.createName("Order"); SOAPElement order = purchaseLineItems.addChildElement(childName); childName = soapFactory.createName("Product"); SOAPElement product = order.addChildElement(childName); product.addTextNode("Apple"); childName = soapFactory.createName("Price"); SOAPElement price = order.addChildElement(childName); price.addTextNode("1.56");

The code first creates the SOAPBodyElement object purchaseLineItems, which has a fully qualified name associated with it. That is, the Name object for it has a local name, a namespace prefix, and a namespace URI. As you saw earlier, a SOAPBodyElement object is required to have a fully qualified name, but child elements added to it, such as SOAPElement objects, may have Name objects with only the local name. The SAAJ code in the preceding example produces the following XML in the SOAP body:

<PO:PurchaseLineItems xmlns:PO="http://www.sonata.fruitsgalore/order"> <Order> <Product>Apple</Product> <Price>1.56</Price> </Order> </PO:PurchaseLineItems>

Adding and accessing attachments Create from AttachmentPart object:

AttachmentPart attachment = message.createAttachmentPart();

AttachmentPart is made of two parts: application-specific content and associated MIME headers (Content-Type):

attachment.setMimeHeader("Content-Type", "application/xml");

http://java.boot.by/wsd-guide/wsd-guide.html 89 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

> Adding contents to attachment (Option 1: Setting 'Content' and 'ContentId'):

String stringContent = "Update address for Sunny Skies " stringContent += "Inc., to 10 Upbeat Street, Pleasant Grove, CA 95439"; attachment.setContent(stringContent, "text/plain"); attachment.setContentId("update_address"); message.addAttachmentPart(attachment);

The code fragment above shows one of the ways to use the method setContent. This method takes two parameters, the first being a Java Object containing the content and the second being a String giving the content type. The Java Object may be a String, a stream, a javax. xml.transform.Source object, or a javax.activation.DataHandler object. The Java Object being added in the following code fragment is a String, which is plain text, so the second argument must be "text/plain". The code also sets a content identifier, which can be used to identify this AttachmentPart object. After you have added content to attachment, you need to add it to the SOAPMessage object, which is done in the last line. As with AttachmentPart.setContent(...), the Object may be a String, a stream, a javax.xml.transform.Source object, or a javax.activation. DataHandler object. Adding Contents to Attachment (Option 2: Using DataHandler):

// Create DataHandler object URL url = new URL ("http://greatproducts.com/gizmos/img.jpg"); DataHandler dataHandler = new DataHandler(url); AttachmentPart attachment = message.createAttachmentPart(dataHandler); // Note that there is no need to set Content Type attachment.setContentId("attached_image"); message.addAttachmentPart(attachment);

The other method for creating an AttachmentPart object with content takes a DataHandler object, which is part of the JavaBeans Activation Framework (JAF). Using a DataHandler object is fairly straightforward. First you create a java.net.URL object for the file you want to add as content. Then you create a DataHandler object initialized with the URL object: You might note two things about the previous code fragment. First, it sets a header for Content-ID with the method setContentId(...). This method takes a String that can be whatever you like to identify the attachment. Second, unlike the other methods for setting content, this one does not take a String for Content-Type. This method takes care of setting the Content-Type header for you, which is possible because one of the things a DataHandler object does is determine the data type of the file it contains. Accessing attachments:

java.util.Iterator iterator = message.getAttachments(); while (iterator.hasNext()) { AttachmentPart attachment = (AttachmentPart)iterator.next(); String id = attachment.getContentId(); String type = attachment.getContentType(); System.out.print("Attachment " + id + " has content type " + type); if (type == "text/plain") { Object content = attachment.getContent(); System.out.println("Attachment " + "contains:\n" + content); } }

Adding attributes to SOAPHeaderElement SOAP Header attributes: actor and mustUnderstand The attribute actor is optional, but if it is used, it must appear in a SOAPHeaderElement object. Its purpose is to indicate the recipient of a
http://java.boot.by/wsd-guide/wsd-guide.html 90 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

header element. The default actor is the message's ultimate recipient; that is, if no actor attribute is supplied, the message goes directly to the ultimate recipient. An actor is an application that can both receive SOAP messages and forward them to the next actor. The ability to specify one or more actors as intermediate recipients makes it possible to route a message to multiple recipients and to supply header information that applies specifically to each of the recipients. For example, suppose that a message is an incoming purchase order. Its SOAPHeader object might have SOAPHeaderElement objects with actor attributes that route the message to applications that function as the order desk, the shipping desk, the confirmation desk, and the billing department. Each of these applications will take the appropriate action, remove the SOAPHeaderElement objects relevant to it, and send the message on to the next actor. An actor is identified by its URI. For example, the following line of code, in which orderHeader is a SOAPHeaderElement object, sets the actor to the given URI:

orderHeader.setActor("http://gizmos.com/orders");

Additional actors may be set in their own SOAPHeaderElement objects. The following code fragment first uses the SOAPMessage object message to get its SOAPHeader object header. Then header creates two SOAPHeaderElement objects, each of which sets its actor attribute:

SOAPHeader header = message.getSOAPHeader(); SOAPFactory soapFactory = SOAPFactory.newInstance(); String nameSpace = "ns"; String nameSpaceURI = "http://gizmos.com/NSURI"; Name order = soapFactory.createName("orderDesk", nameSpace, nameSpaceURI); SOAPHeaderElement orderHeader = header.addHeaderElement(order); orderHeader.setActor("http://gizmos.com/orders"); Name shipping = soapFactory.createName("shippingDesk", nameSpace, nameSpaceURI); SOAPHeaderElement shippingHeader = header.addHeaderElement(shipping); shippingHeader.setActor("http://gizmos.com/shipping");

Retrieving all SOAPHeaderElements with a particular Actor The SOAPHeader interface provides two methods that return a java.util.Iterator object over all of the SOAPHeaderElement objects with an actor that matches the specified actor. The first method, examineHeaderElements, returns an iterator over all of the elements with the specified actor:

// Note that an Actor is identified by an URL Iterator headerElements = header.examineHeaderElements("http://gizmos.com/orders");

The second method, extractHeaderElements, not only returns an iterator over all of the SOAPHeaderElement objects with the specified actor attribute but also detaches them from the SOAPHeader object. So, for example, after the order desk application has done its work, it would call extractHeaderElements to remove all of the SOAPHeaderElement> objects that applied to it:

// Actors are detached from the SOAPHeader object Iterator headerElements = header.extractHeaderElements("http://gizmos.com/orders");

Creating SOAPHeaderElement with mustUnderstand attribute The Java code:

SOAPHeader header = message.getSOAPHeader();


http://java.boot.by/wsd-guide/wsd-guide.html 91 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Name name = soapFactory.createName("Transaction", "t", "http://gizmos.com/orders"); SOAPHeaderElement transaction = header.addHeaderElement(name); transaction.setMustUnderstand(true); transaction.addTextNode("5");

The XML fragment:

<SOAP-ENV:Header> <t:Transaction xmlns:t="http://gizmos.com/orders" SOAP-ENV:mustUnderstand="1"> 5 </t:Transaction> </SOAP-ENV:Header>

SOAPFault object Represents SOAP Fault element in SOAP body. Parties that can generate SOAPFault (for example):

Recipient of a message in point-to-point messaging (Indicates missing address information in purchase order SOAP message) Messaging provider in messaging provider-based messaging (Messaging provider cannot deliver the message due to server failure)

SOAPFault Object Contains: 1. fault code (mandatory) Required in SOAPFault Object (VersionMismatch, MustUnderstand, Client, Server). 2. fault string (mandatory) Human readable explanation of the fault 3. fault actor (conditional) Required if SOAPHeader object has one or more actor attributes 4. Detail object (conditional) Required if the fault is error related to the SOAPBody object. If not present in Client fault, SOAPBody is assumed to be OK. SOAPFault with no Detail object:

// Create SOAPBody object SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope(); SOAPBody body = envelope.getBody(); // Create and fill up SOAPFault object. // Note that Detail object is not being set here since the fault has // nothing to do with SOAPBody SOAPFault fault = body.addFault(); fault.setFaultCode("Server"); fault.setFaultActor("http://gizmos.com/orders"); fault.setFaultString("Server not responding");

SOAPFault with Detail object:

// Create SOAPFault object SOAPFault fault = body.addFault();

http://java.boot.by/wsd-guide/wsd-guide.html 92 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

// Set fault code and fault string fault.setFaultCode("Client"); fault.setFaultString("Message does not have necessary info"); // Detail object contains two DetailEntry's Detail detail = fault.addDetail(); Name entryName = envelope.createName("order", "PO", "http://gizmos.com/orders/"); DetailEntry entry = detail.addDetailEntry(entryName); entry.addTextNode("quantity element does not have a value"); Name entryName2 = envelope.createName("confirmation", "PO", "http://gizmos.com/confirm"); DetailEntry entry2 = detail.addDetailEntry(entryName2); entry2.addTextNode("Incomplete address: no zip code");

Retrieving SOAPFault:

// Get SOAPBody object SOAPBody body = newmsg.getSOAPPart().getEnvelope().getBody(); // Check if SOAPFault is present in the message if ( body.hasFault() ) { SOAPFault newFault = body.getFault(); String code = newFault.getFaultCode(); String string = newFault.getFaultString(); String actor = newFault.getFaultActor(); if ( actor != null ) { System.out.println(" fault actor = " + actor); } }

Retrieving Detail Object:

// Get Detail object Detail newDetail = newFault.getDetail(); // Get the list of DetailEntry's if ( newDetail != null) { Iterator it = newDetail.getDetailEntries(); while ( it.hasNext() ) { DetailEntry entry = (DetailEntry)it.next(); String value = entry.getValue(); System.out.println(" Detail entry = " + value); } }

Chapter 6. JAXR

Describe the function of JAXR in Web service architectural model, the two basic levels of business registry functionality supported by JAXR, and the function of the basic JAXR business objects and how they map to the UDDI data structures.
1212

Use JAXR to connect to a UDDI business registry, execute queries to locate services that meet specific requirements, and publish or update information about a business service.
1212

Chapter 7. J2EE Web Services


http://java.boot.by/wsd-guide/wsd-guide.html 93 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Identify the characteristics of and the services and APIs included in the J2EE platform.
1212

Explain the benefits of using the J2EE platform for creating and deploying Web service applications.
1212

Describe the functions and capabilities of the JAXP, DOM, SAX, JAXR, JAX-RPC, and SAAJ in the J2EE platform.
1212

Describe the role of the WS-I Basic Profile when designing J2EE Web services.
1212

Chapter 8. Security

Explain basic security mechanisms including: transport level security, such as basic and mutual authentication and SSL, message level security, XML encryption, XML Digital Signature, and federated identity and trust.
There are two ways with which we can ensure security with Web Services. They are: 1. Security at Transport level 2. Security at XML level Security at Transport level Transport level security is based on Secure Sockets Layer (SSL) or Transport Layer Security (TLS) that runs beneath HTTP. SSL and TLS provide security features including authentication, data protection, and cryptographic token support for secure HTTP connections. To run with HTTPS, the service endpoint address must be in the form https://. The integrity and confidentiality of transport data, including SOAP messages and HTTP basic authentication, is confirmed when you use SSL and TLS. Web services applications can also use Federal Information Processing Standard (FIPS) approved ciphers for more secure TLS connections. Implementing security at the transport level means, securing the network protocol, a Web Service uses for communication. SSL is the Industry accepted standard protocol for secured encrypted communications over TCP/IP. In this model, a Web Service client will use SSL to open a secure socket to a Web Service. The client then sends and receives SOAP messages over this secured socket using HTTPS. The SSL implementation takes care of ensuring privacy by encrypting all the network traffic on the socket. SSL can also authenticate the Web Service to the client using the PKI infrastructure. HTTPS provides encryption, which ensures privacy and message integrity. HTTPS also authenticates through the use of certificates, which can be used on the server side, the client side, or both. HTTPS with server-side certificates is the most common configuration on the Web today. In this configuration, clients can authenticate servers, but servers cannot authenticate clients. However, HTTPS can also be used in conjunction with basic or digest authentication, which provides a weaker form of authentication for clients. HTTP basic authentication uses a user name and password to authenticate a service client to a secure endpoint. A simple way to provide authentication data for the service client is to authenticate to the protected service endpoint to the HTTP basic authentication. The basic authentication is located in the HTTP header that carries the SOAP request. When the application server receives the HTTP request, the user name and password are retrieved and verified using the authentication mechanism specific to the server. Although the basic authentication data is base64-encoded, sending data over HTTPS is recommended. The integrity and confidentiality of the data can be protected by the Secure Sockets Layer (SSL) protocol. Security at XML level There are some standards available for securing Web Services at XML level. They are:

http://java.boot.by/wsd-guide/wsd-guide.html 94 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

XML Encryption The W3C is coordinating XML Encryption. Its goal is to develop XML syntax for representing encrypted data and to establish procedures for encrypting and decrypting such data. Unlike SSL, with XML Encryption, you can encrypt only the data that needs to be encrypted, for example, only the credit card information in a purchase order XML document:

<purchaseOrder> <name>Alice Smith</name> <address> ... </address> <EncryptedData xmlns='http://www.w3.org/2000/11/temp-xmlenc'> <EncryptionMethod Algorithm="urn:nist-gov:tripledes-ede-cbc"> <s0:IV xmlns:s0='http://somens'>ABCD</s0:IV> </EncryptionMethod> <KeyInfo xmlns='http://www.w3.org/2000/09/xmldsig#'> <KeyName>SharedKey</KeyName> </KeyInfo> <CipherData>A23B45C56</CipherData> </EncryptedData> <prodNumber>8a32gh19908</prodNumber> <quantity>1</quantity> </purchaseOrder>

In XML Encryption, your plaintext is either an element or that element's content (that's the finest granularity you getyou can't encrypt, say, half an element's content). After encryption, you get an XML element called EncryptedData, containing the ciphertext in Base64-encoded format. That EncryptedData element replaces your plaintext. That is, if you encrypt element bar in this snippet below:

<foo> <bar>secret text</bar> </foo>


http://java.boot.by/wsd-guide/wsd-guide.html 95 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

you'll get back something like this:

<foo> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns=...> <!-- some info, including the ciphertext --> </EncryptedData> </foo>

Whereas if you encrypt element bar's content, the result will look similar to this:

<foo> <bar> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns=...> <!-- some info, including the ciphertext --> </EncryptedData> </bar> </foo>

Note the difference between the Type attributes in the two examples. From looking at this attribute, we can tell immediately whether the plaintext is an element of just its content. EncryptedData is shown below. In this structure "?" denotes zero or one occurrence; "+" denotes one or more occurrences; "*" denotes zero or more occurrences; and the empty element tag means the element must be empty:

<EncryptedData Id? Type? MimeType? Encoding?> <EncryptionMethod/>? <ds:KeyInfo> <EncryptedKey>? <AgreementMethod>? <ds:KeyName>? <ds:RetrievalMethod>? <ds:*>? </ds:KeyInfo>? <CipherData> <CipherValue>? <CipherReference URI?>? </CipherData> <EncryptionProperties>? </EncryptedData>

EncryptedData's most important element, CipherData, either directly contains the ciphertext in CipherValue, or, if CipherReference> is used, a reference to it. The other elements are optional because usually the receiving party already has the information they contain. For instance, EncryptionMethod lets you specify the algorithm and key size, but usually you and the other party will agree on those beforehand. The same goes for KeyInfo: it gives you the flexibility to give the other party the material to decrypt your message, but you'd probably want to sent it through some out-of-band mechanism. EncryptionProperties> serves as another optional element used for, optional information, such as a date/time stamp. Consider the following fictitious payment information, which includes identification information and information appropriate to a

http://java.boot.by/wsd-guide/wsd-guide.html 96 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

payment method (e.g., credit card, money transfer, or electronic check):

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <CreditCard Limit='5,000' Currency='USD'> <Number>4019 2445 0277 5567</Number> <Issuer>Example Bank</Issuer> <Expiration>04/02</Expiration> </CreditCard> </PaymentInfo>

Credit card number is sensitive information. If the application wishes to keep that information confidential, it can encrypt the CreditCard element:

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <EncryptedData Type='http://www.w3.org/2001/04/xmlenc#Element' xmlns='http://www.w3.org/2001/04/xmlenc#'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </PaymentInfo>

By encrypting the entire CreditCard element from its start to end tags, the identity of the element itself is hidden. The CipherData element contains the encrypted serialization of the CreditCard element. Encrypting XML Element Content (Elements) As an alternative scenario, it may be useful for intermediate agents to know that John used a credit card with a particular limit, but not the card's number, issuer, and expiration date. In this case, the content (character data or children elements) of the CreditCard element is encrypted:

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <CreditCard Limit='5,000' Currency='USD'> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Content'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </CreditCard> </PaymentInfo>

Encrypting XML Element Content (Character Data) We can consider the scenario in which all the information except the actual credit card number can be in the clear, including the fact that the Number element exists:

http://java.boot.by/wsd-guide/wsd-guide.html 97 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<?xml version='1.0'?> <PaymentInfo xmlns='http://example.org/paymentv2'> <Name>John Smith</Name> <CreditCard Limit='5,000' Currency='USD'> <Number> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Content'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData> </Number> <Issuer>Example Bank</Issuer> <Expiration>04/02</Expiration> </CreditCard> </PaymentInfo>

Both CreditCard and Number are in the clear, but the character data content of Number is encrypted. Encrypting Arbitrary Data and XML Documents> If the application scenario requires all of the information to be encrypted, the whole document is encrypted as an octet sequence. This applies to arbitrary data including XML documents:

<?xml version='1.0'?> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' MimeType='text/xml'> <CipherData> <CipherValue>A23B45C56</CipherValue> </CipherData> </EncryptedData>

Super-Encryption: Encrypting EncryptedData An XML document may contain zero or more EncryptedData elements. EncryptedData cannot be the parent or child of another EncryptedData element. However, the actual data encrypted can be anything, including EncryptedData and EncryptedKey elements (i. e., super-encryption). During super-encryption of an EncryptedData or EncryptedKey element, one must encrypt the entire element. Encrypting only the content of these elements, or encrypting selected child elements is an invalid instance under the provided schema. For example, consider the following:

<pay:PaymentInfo xmlns:pay='http://example.org/paymentv2'> <EncryptedData Id='ED1' xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Element'> <CipherData> <CipherValue>originalEncryptedData</CipherValue> </CipherData> </EncryptedData> </pay:PaymentInfo>

A valid super-encryption of "//xenc:EncryptedData[@Id='ED1']" would be:

<pay:PaymentInfo xmlns:pay='http://example.org/paymentv2'>
http://java.boot.by/wsd-guide/wsd-guide.html 98 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<EncryptedData Id='ED2' xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.w3.org/2001/04/xmlenc#Element'> <CipherData> <CipherValue>newEncryptedData</CipherValue> </CipherData> </EncryptedData> </pay:PaymentInfo>

where the CipherValue content of 'newEncryptedData' is the base64 encoding of the encrypted octet sequence resulting from encrypting the EncryptedData element with Id='ED1'.

XML Digital Signature XML Digital Signature, like any other digital signing technology, provides authentication, data integrity (tamper-proofing), and nonrepudiation. Of all the XML-based security initiatives, the XML digital signature effort is the furthest along. The W3C (World Wide Web Consortium) and the IETF (Internet Engineering Task Force) jointly coordinate this effort. The project aims to develop XML syntax for representing digital signatures over any data type. The XML digital signature specification also defines procedures for computing and verifying such signatures. Another important area that XML digital signature addresses is the canonicalization of XML documents. Canonicalization enables the generation of the identical message digest and thus identical digital signatures for XML documents that are syntactically equivalent but different in appearance due to, for example, a different number of white spaces present in the documents. So why XML Digital Signature? XML Digital Signature provides a flexible means of signing and supports diverse sets of Internet transaction models. For example, you can sign individual items or multiple items of an XML document. The document you sign can be local or even a remote object, as long as those objects can be referenced through a URI (Uniform Resource Identifier). You can sign not only XML data, but also non-XML data. A signature can be either enveloped or enveloping, which means the signature can be either embedded in a document being signed or reside outside the document. XML digital signature also allows multiple signing levels for the same content, thus allowing flexible signing semantics. For example, the same content can be semantically signed, cosigned, witnessed, and notarized by different people. The XML signature specification is an extremely flexible tool for generating digitally signed XML documents. It supports signing complete XML documents, parts of XML documents and even non-XML documents. The resulting signature is a well-formed XML fragment that can either be used on its own (a standalone XML document) or embedded within a more complex XML document.

http://java.boot.by/wsd-guide/wsd-guide.html 99 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

XML Signature Forms: 1. Enveloped An enveloped signature is useful when you have a simple XML document which you to guarantee the integrity of. For example, XKMS messages can use enveloped signatures to convey "trustable" answers from a server back to a client. The signature is over the XML content that contains the signature as an element. The content provides the root XML document element. Obviously, enveloped signatures must take care not to include their own value in the calculation of the SignatureValue. Signature is enveloped within the content been signed:

<doc Id="myID"> <myElement> ... </myElement> <Signature> ... <Reference URI="#myID"/> ... </Signature> </doc>

2. Enveloping An enveloping signature is useful when the signing facility wants to add its own metadata (such as a timestamp) to a signature - it doesn't have to modify the source document, but can include additional data covered by the signature within the signature document it generates. (An XML Digital Signature can sign multiple objects at once, so enveloping is usually combined with another format). The signature is over content found within an Object element of the signature itself. The Object (or its content) is identified via a Reference (via a URI fragment identifier or transform). Signature envelopes the contents to be signed:

<Signature> ... <Reference URI="#myRefObjectID"> ... </Reference> <Object Id="myRefObjectID"> <doc> <myElement> ... </myElement> ... </doc> </Object> </Signature>

3. Detached A detached signature is useful when you can't modify the source; the downside is that it requires two XML documents - the source and its signature - to be carried together. In other words, it requires a packaging format - enter SOAP headers.

http://java.boot.by/wsd-guide/wsd-guide.html 100 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

The signature is over content external to the Signature element, and can be identified via a URI or transform. Consequently, the signature is "detached" from the content it signs. This definition typically applies to separate data objects, but it also includes the instance where the Signature and data object reside within the same XML document but are sibling elements. Signature is external to the content that is signed:

<Signature> ... <Reference URI="http://www.buy.com/books/purchaseWS"/> ... </Signature>

XML Signatures are applied to arbitrary digital content (data objects) via an indirection. Data objects are digested, the resulting value is placed in an element (with other information) and that element is then digested and cryptographically signed. XML digital signatures are represented by the Signature element which has the following structure (where "?" denotes zero or one occurrence; "+" denotes one or more occurrences; and "*" denotes zero or more occurrences):

<Signature ID?> <SignedInfo> <CanonicalizationMethod/> <SignatureMethod/> (<Reference URI? > (<Transforms>)? <DigestMethod> <DigestValue> </Reference>)+ </SignedInfo> <SignatureValue> (<KeyInfo>)? (<Object ID?>)* </Signature>

Signatures are related to data objects via URIs. Within an XML document, signatures are related to local data objects via fragment identifiers. Such local data can be included within an enveloping signature or can enclose an enveloped signature. Detached signatures are over external network resources or local data objects that reside within the same XML document as sibling elements; in this case, the signature is neither enveloping (signature is parent) nor enveloped (signature is child). Since a Signature element (and its Id attribute value/name) may co-exist or be combined with other elements (and their IDs) within a single XML document, care should be taken in choosing names such that there are no subsequent collisions that violate the ID uniqueness validity constraint. Simple example:

<Signature Id="MyFirstSignature" xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/> <Reference URI="http://www.w3.org/TR/2000/REC-xhtml1-20000126/"> <Transforms> <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> </SignedInfo>

http://java.boot.by/wsd-guide/wsd-guide.html 101 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<SignatureValue>MC0CFFrVLtRlk=...</SignatureValue> <KeyInfo> <KeyValue> <DSAKeyValue> <P>...</P><Q>...</Q><G>...</G><Y>...</Y> </DSAKeyValue> </KeyValue> </KeyInfo> </Signature>

The required SignedInfo element is the information that is actually signed. Core validation of SignedInfo consists of two mandatory processes: validation of the signature over SignedInfo and validation of each Reference digest within SignedInfo. Note that the algorithms used in calculating the SignatureValue are also included in the signed information while the SignatureValue element is outside SignedInfo. The CanonicalizationMethod is the algorithm that is used to canonicalize the SignedInfo element before it is digested as part of the signature operation. Note that this example is not in canonical form. The SignatureMethod is the algorithm that is used to convert the canonicalized SignedInfo into the SignatureValue. It is a combination of a digest algorithm and a key dependent algorithm and possibly other algorithms such as padding, for example RSA-SHA1. The algorithm names are signed to resist attacks based on substituting a weaker algorithm. To promote application interoperability we specify a set of signature algorithms that MUST be implemented, though their use is at the discretion of the signature creator. We specify additional algorithms as RECOMMENDED or OPTIONAL for implementation; the design also permits arbitrary user specified algorithms. Each Reference element includes the digest method and resulting digest value calculated over the identified data object. It also may include transformations that produced the input to the digest operation. A data object is signed by computing its digest value and a signature over that value. The signature is later checked via reference and signature validation. KeyInfo indicates the key to be used to validate the signature. Possible forms for identification include certificates, key names, and key agreement algorithms and information - we define only a few. KeyInfo is optional for two reasons. First, the signer may not wish to reveal key information to all document processing parties. Second, the information may be known within the application's context and need not be represented explicitly. Since KeyInfo is outside of SignedInfo, if the signer wishes to bind the keying information to the signature, a Reference can easily identify and include the KeyInfo as part of the signature. How to Create an XML Signature: 1. Determine which resources are to be signed. This will take the form of identifying the resources through a Uniform Resource Identifier (URI).

"http://www.abccompany.com/index.html" would reference an HTML page on the Web "http://www.abccompany.com/logo.gif" would reference a GIF image on the Web "http://www.abccompany.com/xml/po.xml" would reference an XML file on the Web "http://www.abccompany.com/xml/po.xml#sender1" would reference a specific element in an XML file on the Web

2. Calculate the digest of each resource. In XML signatures, each referenced resource is specified through a Reference element and its digest (calculated on the identified resource and not the Filename>Reference element itself) is placed in a DigestValue child element like:

<Reference URI="http://www.abccompany.com/news/2000/03_27_00.htm"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> <Reference URI="http://www.w3.org/TR/2000/WD-xmldsig-core-20000228/signature-example.xml">


http://java.boot.by/wsd-guide/wsd-guide.html 102 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>UrXLDLBIta6skoV5/A8Q38GEw44=</DigestValue> </Reference>

The DigestMethod element identifies the algorithm used to calculate the digest. 3. Collect the Reference elements Collect the Reference elements (with their associated digests) within a SignedInfo element like:

<SignedInfo Id="foobar"> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1" /> <Reference URI="http://www.abccompany.com/news/2000/03_27_00.htm"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> <Reference URI="http://www.w3.org/TR/2000/WD-xmldsig-core-20000228/signature-example.xml"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>UrXLDLBIta6skoV5/A8Q38GEw44=</DigestValue> </Reference> </SignedInfo>

The CanonicalizationMethod element indicates the algorithm was used to canonize the SignedInfo element. Different data streams with the same XML information set may have different textual representations, e.g. differing as to whitespace. To help prevent inaccurate verification results, XML information sets must first be canonized before extracting their bit representation for signature processing. The SignatureMethod element identifies the algorithm used to produce the signature value. 4. Signing Calculate the digest of the SignedInfo element, sign that digest and put the signature value in a SignatureValue element:

<SignatureValue>MC0E LE=</SignatureValue>

5. Add key information If keying information is to be included, place it in a KeyInfo element. Here the keying information contains the X.509 certificate for the sender, which would include the public key needed for signature verification:

<KeyInfo> <X509Data> <X509SubjectName>CN=Ed Simon,O=XMLSec Inc.,ST=OTTAWA,C=CA</X509SubjectName> <X509Certificate>MIID5jCCA0+gA...lVN</X509Certificate> </X509Data> </KeyInfo>

6. Enclose in a Signature element

http://java.boot.by/wsd-guide/wsd-guide.html 103 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

Place the SignedInfo, SignatureValue, and KeyInfo elements into a Signature element. The Signature element comprises the XML signature:

<?xml version="1.0" encoding="UTF-8"?> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo Id="foobar"> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1" /> <Reference URI="http://www.abccompany.com/news/2000/03_27_00.htm"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> <Reference URI="http://www.w3.org/TR/2000/WD-xmldsig-core-20000228/signature-example.xml"> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>UrXLDLBIta6skoV5/A8Q38GEw44=</DigestValue> </Reference> </SignedInfo> <SignatureValue>MC0E~LE=</SignatureValue> <KeyInfo> <X509Data> <X509SubjectName>CN=Ed Simon,O=XMLSec Inc.,ST=OTTAWA,C=CA</X509SubjectName> <X509Certificate> MIID5jCCA0+gA...lVN </X509Certificate> </X509Data> </KeyInfo> </Signature>

Verifying an XML Signature. A brief description of how to verify an XML signature: 1. Verify the signature of the SignedInfo element. To do so, recalculate the digest of the SignedInfo element (using the digest algorithm specified in the SignatureMethod element) and use the public verification key to verify that the value of the SignatureValue element is correct for the digest of the SignedInfo element. 2. If this step passes, recalculate the digests of the references contained within the SignedInfo element and compare them to the digest values expressed in each Reference element's corresponding DigestValue element.

XKMS (XML Key Management Specification) [see next section] SAML (Security Assertion Markup Language) [see next section]

Federated identity and trust There are two possible identity management architectures, one based on a centralized model and the other, on a federated model. In the centralized model, a single operator performs authentication and authorization by owning and controlling all the identity information. In the federated model, both authentication and authorization tasks are distributed among federated communities. One advantage of the centralized model is that, because a single operator owns and controls everything, constructing and managing the identity network could be easier than with the federated model. However, the centralized model has serious downsides. The most serious one is the dangerous potential for the single operator becoming a tollgate for all transactions over the Internet. For example,
http://java.boot.by/wsd-guide/wsd-guide.html 104 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

the operator might charge a fee for every transaction you make. You might have to pay a few cents or dollars whenever you perform a transaction on eBay. The centralized model has another serious problem: the single operator could represent a single point of security failure or hacker attack. One more reason why the centralized model has not garnered any support, especially from the business community, is because a single operator can take away the most important business assetthat is, customer identity and profile informationfrom an organization. That results in a serious threat to businesses such as banks and brokerage houses whose success depends on their customer information. This information represents one of the most critical assets to a business, one it is not willing to give up to a third party. The federated model, driven by the Liberty Alliance Project, is designed to correct the centralized model's problems. The goal of the Liberty Alliance Project is to create an open standard for identity, authentication, and authorization, which will lower e-commerce costs and accelerate organizations' commercial opportunities, while at the same time increasing customer satisfaction. In a Liberty architecture, organizations can maintain their own customer/employee data while sharing identity data with partners based on their business objectives and customer preferences. In the federated identity management architecture scheme, three roles could exist. The first is the role of a consumer. As a consumer, you can have multiple identity profiles, and you can ask different identity providers to maintain these profiles. For example, you might want your HMO to manage your healthcare profile and your brokerage house to maintain your brokerage profile. In fact, as a consumer, you can pick and choose which identity provider to maintain your profile based on price, credibility, service, and so on. In this model, consumers have a final say in terms of who can access what information. Consumers can be a person, a business, or a software entity. In this case, the HMO and brokerage house play the role of identity provider. Identity providers maintain user profile information and can interoperate among themselves as long as they have permission to do so from the profile's owner, the consumer. Identity providers are expected to compete for your business in the future in the same way HMOs, banks, and brokerage houses compete for your business today. The third role is that of the service provider, the merchant who has services to offer consumers. Service providers can customize their services to each consumer by retrieving relevant identity profiles from the identity providers. For example, your travel agent might discover your travel and dining preferences from the identity provider you designated to maintain your travel preference. In the phase with no federation (separate login for each site), a consumer must log in separately to each site. This phase will then evolve into an environment where multiple identity networks exist. Within a single identity network, single sign-on can be achieved. However, no network-to-network identity propagation is available at this stage. Eventually, these individually constructed and operating identity networks will work together by exchanging their consumers' identity information, thus providing a truly seamless, global-scale identity network, the Liberty Alliance Project's ultimate goal. The ATM network serves as an analogy for the federated network. Initially, individual banks issued their own ATM cards, and different banks did not interoperate. At this stage, you could not use your ATM card in an ATM machine owned and operated by another bank. These days, you can use your credit card or ATM card in any ATM machine, as long as the bank that owns the machine and your bank are members of the same affiliation network. In the not too distant future, it is not a stretch to think about a single global network to which all banks directly or indirectly belong. The identity network should evolve similarly. One possible challenge of the federated identity network model is that because there are many parties involved, the standard has to be defined in an unambiguous manner. The Liberty Alliance Project addresses that challenge. Federated Identity allows users to link identity information between accounts without centrally storing personal information. Also, the user can control when and how their accounts and attributes are linked and shared between domains and Service Providers, allowing for greater control over their personal data. In practice, this means that users can be authenticated by one company or website and be recognized and delivered personalized content and services in other locations without having to re-authenticate or sign on with a separate username and password. "Circle of Trust" is enabled through federated identity and is defined as a group of service providers that share linked identities and have pertinent business agreements in place regarding how to do business and interact with identities. Once a user has been authenticated by a Circle of Trust identity provider, that individual can be easily recognized and take part in targeted services from other service providers within that Circle of Trust. It should be noted that this concept of trust-based relationships between organizations and their individual or joint customers has existed in the offline business world for years; two common examples would include travel alliances and affiliate business partnerships.

Identify the purpose and benefits of Web services security oriented initiatives and standards such as Username Token Profile, SAML, XACML, XKMS, WS-Security, and the Liberty Project.
SAML Security Assertions Markup Language effort, or SAML, which is being defined by the OASIS (Organization for the Advancement of Structured Information) security services technical committee. The committee aims to outline a standard XML framework for exchanging authentication and authorization information. In a nutshell, SAML is an XML-based framework for exchanging security information. As a framework, it deals with three things. First, it defines syntax and semantics of XML-encoded assertion messages. Second, it defines request and response protocols between requesting and asserting parties for exchanging security information. Third, it defines rules for using assertions with standard transport and message frameworks. For example, it defines how SAML assertion messages can transport using SOAP over HTTP. The security information for exchanging is expressed in the form of assertions about subjects, where a subject is an entity (either human or computer) that has an identity in some security domain. A typical example of a subject is a person, identified by his or her

http://java.boot.by/wsd-guide/wsd-guide.html 105 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

email address in a particular Internet DNS domain. Assertions can convey information about authentication acts performed by subjects, attributes of subjects, and authorization decisions about whether subjects are allowed to access certain resources. Assertions are represented as XML constructs and have a nested structure, whereby a single assertion might contain several different internal statements about authentication, authorization, and attributes. Note that assertions containing authentication statements merely describe acts of authentication that happened previously. Assertions are issued by SAML authorities, namely, authentication authorities, attribute authorities, and policy decision points. SAML defines a protocol by which clients can request assertions from SAML authorities and get a response from them. This protocol, consisting of XML-based request and response message formats, can be bound to many different underlying communications and transport protocols; SAML currently defines one binding, to SOAP over HTTP. SAML authorities can use various sources of information, such as external policy stores and assertions that were received as input in requests, in creating their responses. Thus, while clients always consume assertions, SAML authorities can be both producers and consumers of assertions. One major design goal for SAML is Single Sign-On (SSO), the ability of a user to authenticate in one domain and use resources in other domains without re-authenticating. However, SAML can be used in various configurations to support additional scenarios as well. Several profiles of SAML are currently being defined that support different styles of SSO and the securing of SOAP payloads. XACML XACML stands for Extensible Access Control Markup Language, and its primary goal is to standardize access control language in XML syntax. A standard access control language results in lower costs because there is no need to develop an application-specific access control language or write the access control policy in multiple languages. Plus, system administrators need to understand only one language. With XACML, it is also possible to compose access control policies from the ones created by different parties. In a nutshell, XACML is a general-purpose access control policy language. This means that it provides a syntax (defined in XML) for managing access to resources. XACML is an OASIS standard that describes both a policy language and an access control decision request/response language (both written in XML). The policy language is used to describe general access control requirements, and has standard extension points for defining new functions, data types, combining logic, etc. The request/response language lets you form a query to ask whether or not a given action should be allowed, and interpret the result. The response always includes an answer about whether the request should be allowed using one of four values: Permit, Deny, Indeterminate (an error occurred or some required value was missing, so a decision cannot be made) or Not Applicable (the request can't be answered by this service). The typical setup is that someone wants to take some action on a resource. They will make a request to whatever actually protects that resource (like a filesystem or a web server), which is called a Policy Enforcement Point (PEP). The PEP will form a request based on the requester's attributes, the resource in question, the action, and other information pertaining to the request. The PEP will then send this request to a Policy Decision Point (PDP), which will look at the request and some policy that applies to the request, and come up with an answer about whether access should be granted. That answer is returned to the PEP, which can then allow or deny access to the requester. Note that the PEP and PDP might both be contained within a single application, or might be distributed across several servers. In addition to providing request/response and policy languages, XACML also provides the other pieces of this relationship, namely finding a policy that applies to a given request and evaluating the request against that policy to come up with a yes or no answer. There are many existing proprietary and application-specific languages for doing this kind of thing but XACML has several points in its favor:

It's standard. By using a standard language, you're using something that has been reviewed by a large community of experts and users, you don't need to roll your own system each time, and you don't need to think about all the tricky issues involved in designing a new language. Plus, as XACML becomes more widely deployed, it will be easier to interoperate with other applications using the same standard language. It's generic. This means that rather than trying to provide access control for a particular environment or a specific kind of resource, it can be used in any environment. One policy can be written which can then be used by many different kinds of applications, and when one common language is used, policy management becomes much easier. It's distributed. This means that a policy can be written which in turn refers to other policies kept in arbitrary locations. The result is that rather than having to manage a single monolithic policy, different people or groups can manage sub-pieces of policies as appropriate, and XACML knows how to correctly combine the results from these different policies into one decision. It's powerful. While there are many ways the base language can be extended, many environments will not need to do so. The standard language already supports a wide variety of data types, functions, and rules about combining the results of different policies. In addition to this, there are already standards groups working on extensions and profiles that will hook XACML into other standards like SAML and LDAP, which will increase the number of ways that XACML can be used.

Every enterprise has a need to secure resources accessed by employees, partners, and customers. For example, browser based access to portals which aggregate resources (web pages, applications, services, etc.) are typical in today's enterprises. Clients send requests to

http://java.boot.by/wsd-guide/wsd-guide.html 106 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

servers for resources, but before a server can return that resource it must determine if the requester is authorized to use the resource. This is where XACML fits in. XACML provides a policy language which allows administrators to define the access control requirements for their application resources. The language and schema support include data types, functions, and combining logic which allow complex (or simple) rules to be defined. XACML also includes an access decision language used to represent the runtime request for a resource. When a policy is located which protects a resource, functions compare attributes in the request against attributes contained in the policy rules ultimately yielding a permit or deny decision. When a client makes a resource request upon a server, the entity charged with access control by enforcing authorization is called the Policy Enforcement Point. In order to enforce policy, this entity will formalize attributes describing the requester at the Policy Information Point and delegate the authorization decision to the Policy Decision Point. Applicable policies are located in a policy store and evaluated at the Policy Decision Point, which then returns the authorization decision. Using this information, the Policy Enforcement Point can deliver the appropriate response to the client. An administrator creates policies in the XACML language. The key top-level element is the PolicySet which aggregates other PolicySet elements or Policy elements. The Policy element is composed principally of Target, Rule and Obligation elements and is evaluated at the Policy Decision Point to yield and access decision. Since multiple policies may be found applicable to an access decision, (and since a single policy can contain multiple Rules) Combining Algorithms are used to reconcile multiple outcomes into a single decision. Standard Combining Algorithms are defined for Deny-Overrides, Permit-Overrides, First Applicable, and Only-One Applicable outcomes. The Target element is used to associate a requested resource to an applicable Policy. It contains conditions that the requesting Subject, Resource, or Action must meet for a Policy Set, Policy, or Rule to be applicable to the resource. The Target includes a build-in scheme for efficient indexing/lookup of Policies. Rules provide the conditions which test the relevant attributes within a Policy. Any number of Rule elements may be used each of which generates a true or false outcome. Combining these outcomes yields a single decision for the Policy, which may be "Permit", "Deny", "Indeterminate", or a "NotApplicable" decision. Attributes provide the typed values that represent both a resource requester and the Policy's condition predicates. When describing the requester, attributes may include an issue date and time, issuer identification, and optionally are contained in the Subject, Environment, Resource and Action elements of the access request. The Attribute Designator element is used to retrieve attribute values from a request by specifying the name, type, and issuer of attributes. The SubjectAttributeDesignator, ResourceAttributeDesignator, ActionAttributeDesignator, and EnvironmentAttributeDesignator each retrieves attributes from the respective elements in the request. An AttributeSelector element is used to locate request attributes using XPATH queries. Since queries can return collections of attributes (all of the same primitive type) they are placed in a Bag. Functions are then used to compare attributes contained within a Bag. XKMS (XML Key Management Specification) XKMS stands for the XML Key Management Specification and consists of two parts: XKISS (XML Key Information Service Specification) and XKRSS (XML Key Registration Service Specification). XKISS defines a protocol for resolving or validating public keys contained in signed and encrypted XML documents, while XKRSS defines a protocol for public key registration, revocation, and recovery. The key aspect of XKMS is that it serves as a protocol specification between an XKMS client and an XKMS server in which the XKMS server provides trust services to its clients (in the form of Web services) by performing various PKI (public key infrastructure) operations, such as public key validation, registration, recovery, and revocation on behalf of the clients. Now let's talk about why we need XKMS. To explain it, I must discuss PKI first. PKI proves important for e-commerce and Web services. However, one of the obstacles to PKI's wide adoption is that PKI operations such as public key validation, registration, recovery, and revocation are complex and require large amounts of computing resources, which prevents some applications and small devices such as cell phones from participating in PKIbased e-commerce or Web services transactions. XKMS enables an XKMS server to perform these PKI operations. In other words, applications and small devices, by sending XKMS messages over SOAP (Simple Object Access Protocol), can ask the XKMS server to perform the PKI operations. In this regard, the XKMS server provides trust services to its clients in the form of Web services. [PKI refers to a set of security services for authentication, encryption and digital certificate management under which documents are encrypted with a private key and decrypted using a publicly available key accessible to the recipient via a network. PKI differs from private key technology, like Kerberos, in which a single key that is shared by the sender and receiver is used to encrypt and decrypt a message or document.] XKMS defines a Web services interface to a public key infrastructure. This makes it easy for applications to interface with key-related services, like registration and revocation, and location and validation. Most developers will only ever need to worry about implementing XKMS clients. XKMS server components are mostly implemented by providers of public key infrasructure (PKI) providers, such as Entrust, Baltimore and VeriSign. VeriSign, for example, provides an XKMS responder that can be used to register and query VeriSign's certificate store. Even SSL server ID's can be validated in real-time using the XKMS interface. XKMS is a foundational specification for secure Web services, enabling Web services to register and manage cryptographic keys used for digital signatures and encryption. When combined with WS-Security, XKMS makes it easier than ever for developers to deploy enterprise applications in the form of secure Web services available to business partners beyond the firewall. With XKMS, developers can integrate authentication, digital signature, and encryption services, such as certificate processing and revocation status checking, into applications in a matter of hours - without the constraints and complications associated with proprietary PKI software toolkits.

http://java.boot.by/wsd-guide/wsd-guide.html 107 / 133 2004/6/13 12:07:07

SCDJWS Study Guide

XKMS Functions An XKMS-compliant service supports the following operations:

Register: XKMS services can be used to register key pairs for escrow services. Generation of the public key pair may be performed by either the client or the registration service. Once keys are registered, the XKMS-compliant service manages the revocation and recovery of registered keys, whether client- or server-generated. Additional functions are reissue, revoke, and recover. Locate: The Locate service is used to retrieve a public key registered with an XKMS-compliant service. The public key can in turn be used to encrypt a document or verify a signature. Validate: The Validate service is used to ensure that a public key registered with an XKMS-compliant service is valid, and has not expired or been revoked. The validation service can also be used to check attributes against a public key.

These services can be complimented by having cryptographic capabilities on the client, but client crypto is not required. For example, if a client must generate keys, then some crypto code, resident on the client, performs the key generation. However, the client can just as easily have the XKMS service generate the keys that are subsequently managed through the service. For security, however, most client applications generate a keypair, and then register the public key with the CA. The Benefits of XKMS XKMS provides many benefits. The most important benefits are that XKMS is:

Easy to use: The developer-friendly syntax used in XKMS eliminates the necessity for PKI toolkits and proprietary plug-ins. The XKMS specification allows developers to rapidly implement trust features, incorporating cryptographic support for XML digital signatures and XML encryption using standard XML toolkits. Quick to deploy: By simplifying application development, XKMS removes the need to delay PKI deployment because of , and instead, moves the complexity of PKI to server side components. Developers can now focus on their core competency of developing applications rather than the complexities surrounding a PKI deployment. Open: The common XML vocabulary used to describe authentication, authorization, and profile information in XML documents makes XKMS services completely platform, vendor, and transport-protocol-neutral. The XKMS specification has been submitted to the World Wide Web Consortium (W3C) as an open standard for distribution and registration of keys. Ideal for mobile devices: XKMS allow mobile devices to access full-featured PKI through ultra-minimal-footprint client device interfaces. Future-proof: Supports new and emerging PKI developments since the impact of future PKI developments is restricted to serverside components. By restricting the impact of future PKI developments and advancements to the server-side components, XKMS protects developers and applications from becoming incompatible with the latest developments in PKI.

WS-Security The goal of WS-Security is to enable applications to construct secure SOAP message exchanges. The WS-Security (Web Services Security) specification defines a set of SOAP header extensions for end-to-end SOAP messaging security. It supports message integrity and confidentiality by allowing communicating partners to exchange signed and encrypted messages in a Web services environment. Because it is based on XML digital signature and XML Encryption standards, you can digitally sign and encrypt any combination of message parts. WS-Security supports multiple security models, such as username/password-based and certificate-based models. It also supports multiple security technologies, including Kerberos, PKI, SAML, and so on. In addition, it supports multiple security tokens; for example, tokens that contain Kerberos tickets, X.509 certificates, or SAML assertions. The following example illustrates a message with a username security token:

(001) <?xml version="1.0" encoding="utf-8"?> (002) <S:Envelope xmlns:S="http://www.w3.org/2001/12/soap-envelope" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> (003) <S:Header> (004) <m:path xmlns:m="http://schemas.xmlsoap.org/rp/"> (005) <m:action>http://fabrikam123.com/getQuote</m:action> (006) <m:to>http://fabrikam123.com/stocks</m:to> (007) <m:id>uuid:84b9f5d0-33fb-4a81-b02b-5b760641c1d6</m:id> (008) </m:path> (009) <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext"> (010) wsse:UsernameToken Id="MyID"> (011) <wsse:Username>Zoe</wsse:Username> (012) </wsse:UsernameToken> (013) <ds:Signature>

http://java.boot.by/wsd-guide/wsd-guide.html 108 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

(014) <ds:SignedInfo> (015) <ds:CanonicalizationMethod Algorithm="..."/> (016) <ds:SignatureMethod Algorithm="..."/> (017) <ds:Reference URI="#MsgBody"> (018) <ds:DigestMethod Algorithm="..."/> (019) <ds:DigestValue>LyLsF0Pi4wPU...</ds:DigestValue> (020) </ds:Reference> (021) </ds:SignedInfo> (022) <ds:SignatureValue>DJbchm5gK...</ds:SignatureValue> (023) <ds:KeyInfo> (024) <wsse:SecurityTokenReference> (025) <wsse:Reference URI="#MyID"/> (026) </wsse:SecurityTokenReference> (027) </ds:KeyInfo> (028) </ds:Signature> (029) </wsse:Security> (030) </S:Header> (031) <S:Body Id="MsgBody"> (032) <tru:StockSymbol xmlns:tru="http://fabrikam123.com/payloads"> QQQ </tru:StockSymbol> (033) </S:Body> (034) </S:Envelope>

The first two lines start the SOAP envelope. Line (003) begins the headers that are associated with this SOAP message. Lines (004) to (008) specify how to route this message (as defined in WS-Routing). Line (009) starts the Security header that we define in WS-Security specification. This header contains security information for an intended receiver. This element continues until line (029). Lines (010) to (012) specify a security token that is associated with the message. In this case, it defines username of the client using the UsernameToken. Note that here we assume the service knows the password - in other words, it is a shared secret. Lines (013) to (028) specify a digital signature. This signature ensures the integrity of the signed elements (that they aren't modified). The signature uses the XML Signature specification. In this example, the signature is based on a key generated from the users' password; typically stronger signing mechanisms would be used. Lines (014) to (021) describe the digital signature. Line (015) specifies how to canonicalize (normalize) the data that is being signed. Lines (017) to (020) select the elements that are signed. Specifically, line (017) indicates that the S:Body element is signed. In this example only the message body is signed; typically additional elements of the message, such as parts of the routing header, should be included in the signature. Line (022) specifies the signature value of the canonicalized form of the data that is being signed as defined in the XML Signature specification. Lines (023) to (027) provide a hint as to where to find the security token associated with this signature. Specifically, lines (024) to (025) indicate that the security token can be found at (pulled from) the specified URL. Lines (031) to (033) contain the body (payload) of the SOAP message. Protecting the message content from being intercepted (confidentiality) or illegally modified (integrity) are primary security concerns. WS-Security specification provides a means to protect a message by encrypting and/or digitally signing a body, a header, an attachment, or any combination of them (or parts of them). Message integrity is provided by leveraging XML Signature in conjunction with security tokens to ensure that messages are transmitted without modifications. The integrity mechanisms are designed to support multiple signatures, potentially by multiple actors, and to be extensible to support additional signature formats. Message confidentiality leverages XML Encryption in conjunction with security tokens to keep portions of a SOAP message confidential. The encryption mechanisms are designed to support additional encryption processes and operations by multiple actors. The Security header block provides a mechanism for attaching security-related information targeted at a specific receiver (SOAP actor). This MAY be either the ultimate receiver of the message or an intermediary. Consequently, this header block MAY be present multiple

http://java.boot.by/wsd-guide/wsd-guide.html 109 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

times in a SOAP message. An intermediary on the message path MAY add one or more new sub-elements to an existing Security header block if they are targeted for the same SOAP node or it MAY add one or more new headers for additional targets. As stated, a message MAY have multiple Security header blocks if they are targeted for separate receivers. However, only one Security header block can omit the S:actor attribute and no two Security header blocks can have the same value for S:actor. Message security information targeted for different receivers MUST appear in different Security header blocks. The Security header block without a specified S:actor can be consumed by anyone, but MUST NOT be removed prior to the final destination as determined by WS-Routing. As elements are added to the Security header block, they should be prepended to the existing elements. As such, the Security header block represents the signing and encryption steps the message sender took to create the message. This prepending rule ensures that the receiving application MAY process sub-elements in the order they appear in the Security header block, because there will be no forward dependency among the sub-elements. Note that WS-Security specification does not impose any specific order of processing the sub-elements. The receiving application can use whatever policy is needed. When a sub-element refers to a key carried in another sub-element (for example, a signature sub-element that refers to a binary security token sub-element that contains the X.509 certificate used for the signature), the key-bearing security token SHOULD be prepended subsequent to the key-using sub-element being added, so that the key material appears before the key-using sub-element. The following illustrates the syntax of this header:

<S:Envelope> <S:Header> ... <Security S:actor="..." S:mustUnderstand="..."> <!-actor attribute is optional, however no two instances of the header block may omit an actor or specify the same actor --> ... </Security> ... </S:Header> ... </S:Envelope>

The following sample message illustrates the use of security tokens, signatures, and encryption. For this example, we use a fictitious "RoutingTransform" that selects the immutable routing headers along with the message body:

(001) <?xml version="1.0" encoding="utf-8"?> (002) <S:Envelope xmlns:S="http://www.w3.org/2001/12/soap-envelope" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"> (003) <S:Header> (004) <m:path xmlns:m="http://schemas.xmlsoap.org/rp/"> (005) <m:action>http://fabrikam123.com/getQuote</m:action> (006) <m:to>http://fabrikam123.com/stocks</m:to> (007) <m:from>mailto:johnsmith@fabrikam123.com</m:from> (008) <m:id>uuid:84b9f5d0-33fb-4a81-b02b-5b760641c1d6</m:id> (009) </m:path> (010) <wsse:Security> (011) <wsse:BinarySecurityToken ValueType="wsse:X509v3" Id="X509Token" EncodingType="wsse:Base64Binary"> (012) MIIEZzCCA9CgAwIBAgIQEmtJZc0rqrKh5i... (013) </wsse:BinarySecurityToken> (014) <xenc:EncryptedKey> (015) <xenc:EncryptionMethod Algorithm= "http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> (016) <ds:KeyInfo> (017) <ds:KeyName>CN=Hiroshi Maruyama, C=JP</ds:KeyName> (018) </ds:KeyInfo> (019) <xenc:CipherData> (020) <xenc:CipherValue>d2FpbmdvbGRfE0lm4byV0...
http://java.boot.by/wsd-guide/wsd-guide.html 110 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

(021) (022) (023) (024) (025) (026) (027) (028) (029)

</xenc:CipherValue> </xenc:CipherData> <xenc:ReferenceList> <xenc:DataReference URI="#enc1"/> </xenc:ReferenceList> </xenc:EncryptedKey> <ds:Signature> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> (030) <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> (031) <ds:Reference> (032) <ds:Transforms> (033) <ds:Transform Algorithm="http://...#RoutingTransform"/> (034) <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> (035) </ds:Transforms> (036) <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> (037) <ds:DigestValue>LyLsF094hPi4wPU... (038) </ds:DigestValue> (039) </ds:Reference> (040) </ds:SignedInfo> (041) <ds:SignatureValue> (042) Hp1ZkmFZ/2kQLXDJbchm5gK... (043) </ds:SignatureValue> (044) <ds:KeyInfo> (045) <wsse:SecurityTokenReference> (046) <wsse:Reference URI="#X509Token"/> (047) </wsse:SecurityTokenReference> (048) </ds:KeyInfo> (049) </ds:Signature> (050) </wsse:Security> (051) </S:Header> (052) <S:Body> (053) <xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" Id="enc1"> (054) <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#3des-cbc"/> (055) <xenc:CipherData> (056) <xenc:CipherValue>d2FpbmdvbGRfE0lm4byV0... (057) </xenc:CipherValue> (058) </xenc:CipherData> (059) </xenc:EncryptedData> (060) </S:Body> (061) </S:Envelope>

Lines (003)-(051) contain the SOAP message headers. Lines (004)-(009) specify the message routing information (as define in WS-Routing). In this case we are sending the message to the http://fabrikam123.com/stocks service requesting the "getQuote" action. Lines (010)-(050) represent the Security header block. This contains the security-related information for the message. Lines (011)-(013) specify a security token that is associated with the message. In this case, it specifies an X.509 certificate that is encoded as Base64. Line (012) specifies the actual Base64 encoding of the certificate. Lines (014)-(026) specify the key that is used to encrypt the body of the message. Since this is a symmetric key, it is passed in an encrypted form. Line (015) defines the algorithm used to encrypt the key. Lines (016)-(018) specify the name of the key that was used
http://java.boot.by/wsd-guide/wsd-guide.html 111 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

to encrypt the symmetric key. Lines (019)-(022) specify the actual encrypted form of the symmetric key. Lines (023)-(025) identify the encryption block in the message that uses this symmetric key. In this case it is only used to encrypt the body (Id="enc1"). Lines (027)-(049) specify the digital signature. In this example, the signature is based on the X.509 certificate. Lines (028)-(040) indicate what is being signed. Specifically, Line (029) indicates the canonicalization algorithm (exclusive in this example). Line (030) indicate the signature algorithm (rsa over sha1 in this case). Lines (031)-(039) identify the parts of the message that are being signed. Specifically, Line (033) identifies a "transform". This fictitious transforms selects the immutable portions of the routing header and the message body. Line (034) specifies the canonicalization algorithm to use on the selected message parts from line (033). Line (036) indicates the digest algorithm use on the canonicalized data. Line (037) specifies the digest value resulting from the specified algorithm on the canonicalized data. Lines (041)-(043) indicate the actual signature value - specified in Line (042). Lines (044)-(048) indicate the key that was used for the signature. In this case, it is the X.509 certificate included in the message. Line (046) provides a URI link to the Lines (011)-(013). The body of the message is represented by Lines (052)-(060). Lines (053)-(059) represent the encrypted metadata and form of the body using XML Encryption. Line (053) indicates that the "element value" is being replaced and identifies this encryption. Line (054) specifies the encryption algorithm - Triple-DES in this case. Lines (055)-(058) contain the actual cipher text (i.e., the result of the encryption). Note that we don't include a reference to the key as the key references this encryption - Line (024). Liberty Project

Create an open standard for identity, authentication and authorization. Objective: lower costs, accelerate commercial opportunities, and increase customer satisfaction Federated standard will enable every business to:
r r r

Maintain their own customer/employee/device data. Tie data to an individuals or businesss identity. Share data with partners according to its business objectives, and customers preferences.

Given a scenario, implement J2EE based web service web-tier and/or EJB-tier basic security mechanisms, such as mutual authentication, SSL, and access control.
JAX-RPC implementation has to support HTTP Basic authentication. JAX-RPC specifciation does not require JAX-RPC implementation to support certificate based mutual authentication using HTTP/S (HTTP over SSL). HTTP Basic Authentication 1. Add the appropriate security elements to the web.xml deployment descriptor:

<?xml version="1.0"?> <web-app version="2.4" ...> <display-name>Basic Authentication Security Example</display-name> <security-constraint> <web-resource-collection> <web-resource-name>SecureHello</web-resource-name> <url-pattern>/hello</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint>

http://java.boot.by/wsd-guide/wsd-guide.html 112 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

<user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> </login-config> <security-role> <role-name>admin</role-name> </security-role> </web-app>

2. Set security properties in the client code:

try { Stub stub = createProxy(); stub._setProperty(javax.xml.rpc.Stub.USERNAME_PROPERTY, username); stub._setProperty(javax.xml.rpc.Stub.PASSWORD_PROPERTY, password); stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, endpointAddress); HelloIF hello = (HelloIF)stub; System.out.println(hello.sayHello(" Duke (secure)" )); } catch (Exception ex) { ex.printStackTrace(); }

Mutual Authentication 1. Configure SSL connector 2. Add the appropriate security elements to the web.xml deployment descriptor:

<?xml version="1.0"?> <web-app version="2.4" ...> <display-name>Secure Mutual Authentication Example</display-name> <security-constraint> <web-resource-collection> <web-resource-name>SecureHello</web-resource-name> <url-pattern>/hello</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>CLIENT-CERT</auth-method> </login-config> </web-app>

3. Set Security Properties in client code:


http://java.boot.by/wsd-guide/wsd-guide.html 113 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

try { Stub stub = createProxy(); System.setProperty("javax.net.ssl.keyStore", keyStore); System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword); System.setProperty("javax.net.ssl.trustStore", trustStore); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY,endpointAddress); HelloIF hello = (HelloIF)stub; System.out.println(hello.sayHello(" Duke! secure!")); } catch (Exception ex) { ex.printStackTrace(); }

Describe factors that impact the security requirements of a Web service, such as the relationship between the client and service provider, the type of data being exchanged, the message format, and the transport mechanism.
1212

Chapter 9. Developing Web Services

Describe the steps required to configure, package, and deploy J2EE Web services and service clients, including a description of the packaging formats, such as .ear, .war, .jar, deployment descriptor settings, the associated Web Services description file, RPC mapping files, and service reference elements used for EJB and servlet endpoints.
1212

Given a set of requirements, develop code to process XML files using the SAX, DOM, XSLT, and JAXB APIs.
1212

Given an XML schema for a document style Web service create a WSDL file that describes the service and generate a service implementation.
1212

Given a set of requirements, develop code to create an XML-based, document style, Web service using the JAX-RPC APIs.
1212

Implement a SOAP logging mechanism for testing and debugging a Web Service application using J2EE Web Service APIs.
1212

Given a set of requirements, develop code to handle system and service exceptions and faults received by a Web services client.
1212

http://java.boot.by/wsd-guide/wsd-guide.html 114 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

Chapter 10. General Design and Architecture

Describe the characteristics of a service oriented architecture and how Web Services fits to this model.
1212

Given a scenario, design a J2EE service using the Business Delegate, Service Locator, and/or Proxy client-side design patterns and the Adapter, Command, Web Service Broker, and/or Faade server-side patterns.
Business Delegate Problem:

You want to hide clients from the complexity of remote communication with business service components. Business components are exposed to clients leading to coupling and fine-grained access.

Forces:

Clients need access to business services. Complexity of remote objects. You want to avoid unnecessary invocation of remote services. Clients and business components become tightly coupled. You want to minimize coupling between clients and the business services, thus hiding the underlying implementation details of the service, such as lookup and access. Business services APIs may change. You want to hide the details of service creation, reconfiguration, and invocation retries from the clients.

Solution:

Use a Business Delegate to encapsulate access to a business service. The Business Delegate hides the implementation details of the business service, such as lookup and access mechanisms. Use a Business Delegate to reduce coupling between presentationtier clients and business services:

Consequences:

Reduces coupling, increases maintainability. Implements failure recovery: Retry or Synchronize.

http://java.boot.by/wsd-guide/wsd-guide.html 115 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

Translates network (System) Exceptions to Business service Exceptions. Exposes simpler, uniform Interface to the business tier. Performance enhancing cache. Hides complexities of remote services.

Service Locator Problem:

Clients want to transparently locate business components and services in a uniform manner.

Forces:

Vendor dependencies are exposed to the clients, we want to encapsulate vendor dependencies for registry implementations, and hide the dependency and complexity from the clients. Complexity and duplication of lookup and creation. Clients want to centralize and reuse the implementation of lookup mechanisms. Clients may need to reestablish connection to a previously accessed business object. Clients want to avoid performance overhead related to initial context creation and service lookups.

Solution:

Use a Service Locator to implement and encapsulate service and component lookup. A Service Locator hides the complexities of Initial Context creation, lookup, and object re-creation:

Consequences:

Abstracts complexity of lookups. Uniform lookup for all clients. Improves network performance. Improves client performance by caching.

Proxy Problem:

Provide a stand-in or placeholder to another object, in order to control access to it.

http://java.boot.by/wsd-guide/wsd-guide.html 116 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

Forces:

The The The You

desired object may be inaccessible (if it exists in a different address space). desired object may be expensive to instantiate and you want to delay its creation until absolutely necessary. desired object may need to be protected from unauthorized access. may need to perform special actions upon accessing the desired object.

Solution:

Use a Proxy to provide a separate implementation of interface and working code for location transparency:

Consequences:

Decouples interface and implementation by providing two objects. Proxy handles all incoming requests to the object, it knows how to contact the object if it is remotely located. Proxy passes along all authorized communication to the object (and prevents unauthorized communication). If the Implementation class changes, the Proxy remains the same. An example is the EJB's Remote Interface.

Session Faade Problem:

Tight coupling between clients and business tier; fine-grained access.

Forces:

You want to avoid giving clients direct access to business-tier components, to prevent tight coupling with the clients. Numerous business objects are exposed over the network. No uniform access to business tier. You want to centralize and aggregate all business logic that needs to be exposed to remote clients. Clients are exposed to complex interactions and interdependencies of business objects. You want to hide the complex interactions and interdependencies between business components and services to improve manageability, centralize logic, increase flexibility, and improve ability to cope with changes.

Solution:

Use a Session Faade to encapsulate business-tier components and expose a coarse-grained service to remote clients. Clients access a Session Faade instead of accessing business components directly. Use a Session Faade to encapsulate the complexity of interactions:

http://java.boot.by/wsd-guide/wsd-guide.html 117 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

Consequences:

Controller layer for business tier. Uniform exposure of business components. Reduces coupling between the tiers. Provides a uniform coarse-grained access. Centralizes business logic. Centralizes security management. Centralizes transaction control. Exposes fewer remote interfaces to clients. Improves performance, reduces fine-grained remote methods.

Adapter (Wrapper) Problem:

Convert the interface of a class into another interface clients expect.

Forces:

A potentially reusable class may not have the appropriate interface required by the particular application domain.

Solution:

Adapter lets classes work together that could not otherwise because of incompatible interfaces. Use an Adapter pattern to adapt one interface to another:

http://java.boot.by/wsd-guide/wsd-guide.html 118 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

Consequences:

Adapter pattern maps the interface of one class onto another so that they can work together. These incompatible classes may come from different libraries or frameworks. Adapter pattern can be used to expose existing component as Web Service. Adapter pattern helps resolve integration issues.

Command Problem:

There are a lot of similar methods, and the interface to implement that kind of object is becoming heavy.

Forces:

Too many public methods for other objects to call. An interface that is unworkable and always changing. You feel that a method name must include prose describing the exact action, and this is preventing layering your code.

Solution:

Encapsulate a request as a Command object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

http://java.boot.by/wsd-guide/wsd-guide.html 119 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

Consequences:

Command pattern is an example of pluggable behavior that enforce client access to Web Services. The Command pattern is commonly used for gathering requests from client objects and packaging them into a single object for processing. The Command pattern allows for having well defined command interfaces that are implemented by the object that provides the processing for the client requests packaged as commands. Command design pattern provides a convenient way to store and execute an "Undo" function. Command decouples the object that invokes the operation from the one that knows how to perform it. Commands can be manipulated and extended like any other object. Commands can be made into a composite command. Commands can be stored. Since a command encapsulates all the data for a given request, it can be created and initialized at one point and applied at another.

Web Service Broker Problem:

You want to provide access to one or more services using XML and web protocols.

Forces:

You want to reuse and expose existing services to clients. You want to monitor and potentially limit the usage of exposed services, based on your business requirements and system resource usage. Your services must be exposed using open standards to enable integration of heterogeneous applications. You want to bridge the gap between business requirements and existing service capabilities.

Solution:

Use a Web Service Broker to expose and broker one or more services in your application to external clients as a Web Service using XML and standard web protocols:

http://java.boot.by/wsd-guide/wsd-guide.html 120 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

Consequences:

Introduces a layer between client and service. Existing remote Session Faades need be refactored to support local access. Network performance may be impacted due to web protocols. Coordinates interactions among one or more services, aggregates responses and may demarcate and compensate transactions.

Describe alternatives for dealing with issues that impact the quality of service provided by a Web service and methods to improve the system reliability, maintainability, security, and performance of a service.
1212

Describe how to handle the various types of return values, faults, errors, and exceptions that can occur during a Web service interaction.
1212

Describe the role that Web services play when integrating data, application functions, or business processes in a J2EE application.
1212

Describe how to design a stateless Web service that exposes the functionality of a stateful business process.
1212

Chapter 11. Endpoint Design and Architecture

Given a scenario, design Web service applications using information models that are either procedure-style or documentstyle.
Choosing Between an RPC-Style (remote procedure call) and a Message-Style (document-style) Web Service. RPC-style Web services are interface driven, which means that the business methods of the underlying stateless session EJB determine

http://java.boot.by/wsd-guide/wsd-guide.html 121 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

how the Web service works. When clients invoke the Web service, they send parameter values to the Web service, which executes the corresponding methods and sends back the return values. The relationship is synchronous, which means that the client waits for a response from the Web service before it continues with the remainder of its application. Create an RPC-style Web service if your application has the following characteristics:

The The The The

client invoking the Web service needs an immediate response. client and Web service work in a back-and-forth, conversational way. behavior of the Web service can be expressed as an interface. Web service is process-oriented rather than data-oriented.

Examples of RPC-style Web services include providing the current weather conditions in a particular location; returning the current price for a given stock; or checking the credit rating of a potential trading partner prior to the completion of a business transaction. In each case the information is returned immediately, implying a synchronous relationship between the client and the Web service. RPC is essentially a Remote Procedure call in which the client sends a SOAP request to execute an operation on the Web Service. The SOAP request contains the name of method to be executed and the parameter it takes. The server running the Web Service converts this request to appropriate objects (java method call, EJB method call etc with parameters of defined type), executes the operation and sends the response as SOAP message to client. At the client side, this response is used to form appropriate objects and return the required information (output) to the client. RPC-style Web Services are tightly coupled because the sending parameters and return values are as described in WSDL (Web Service Description Language ) file and are wrapped in the SOAP body. Following is an example SOAP Body of RPC-style Web Service, which invokes GetStockQuote method with input parameter "ORCL":

<SOAP-ENV:Envelope...> <SOAP-ENV:Body> <m:GetStockQuote xmlns:m="urn:xmethods:example"> <m:Symbol>ORCL</m:Symbol> </m:GetStockQuote> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

RPC-style Web Services follow call/response semantics, and hence they are synchronous, which means that the client sends the request and waits for the response till the request is processed completely. You should create a message-style (document-style) Web service if your application has the following characteristics:

The client has an asynchronous relationship with the Web service, or in other words, the client does not expect an immediate response. The Web service is data-oriented rather than process-oriented.

Examples of message-style Web services include processing a purchase order; accepting a request for new DSL home service; or responding to a request for quote order from a customer. In each case, the client sends an entire document, such as purchase order, to the Web service and assumes that the Web service is processing it in some way, but the client does not require an answer right away or even at all. If your Web service will work in this asynchronous, document-driven manner, then you should consider designing it as a message-style Web service. NOTE: Document-Style web servives can use both one-way (non-blocking) calls and two-way (requestresponse) calls, but preferrable choice will be one-way calls. Document-Style Web Service are loosely coupled and the request/response are in the form of XML documents. The client sends the parameter to the Web Service as XML document, instead of discrete set of parameter values. The Web Service processes the document, executes the operation and constructs & sends the response to the client as an XML document. There is no direct mapping between the server objects (parameters, method calls etc) and the values in XML documents. The application has to take care of mapping the XML data values. The SOAP Body of a Document-Style carries one or more XML documents, within its body. The protocol places no constraint on how that document needs to be structured, which is totally handled at the application level. Document-Style Web Service follows asynchronous processing. Following is an example SOAP body for Document-Style Web Service:

<SOAP-ENV:Envelope ...> <SOAP-ENV:Body> <StockQuoteRequest symbol="ORCL"/> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

http://java.boot.by/wsd-guide/wsd-guide.html 122 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

The parameters of the methods which are to be exposed by the document style Web Service should be of type XML element only. The return type of the method can be either an XML element or void. The Simple Object Access Protocol (SOAP) offers two messaging styles: RPC (Remote Procedure Call) and document style. One is for creating tightly coupled, inter-object style interfaces for Web services components; the other is for developing loosely coupled, application-to-application and system-to-system interfaces. RPC-Style An RPC is a way for an application running in one execution thread on a system to call a procedure belonging to another application running in a different execution thread on the same or a different system. RPC interfaces are based on a request-response model where one program calls, or requests a service of, another across a tightly coupled interface. In Web services applications, one service acts as a client, requesting a service; the other as a server, responding to that request. RPC interfaces have two parts: the call-level interface seen by the two applications, and the underlying protocol for moving data from one application to the other. NOTE, it may be not only request-response (two-way) RPC call, but also one-way RPC call (but more often it is used with two-way calls). The call-level interface to an RPC procedure looks just like any other method call in the programming language being used. It consists of a method name and a parameter list. The parameter list is made up of the variables passed to the called procedure and those returned as part of its response. For Web services, SOAP defines the wiring between the calling and called procedures. At the SOAP level, the RPC interface appears as a series of highly structured XML messages moving between the client and the server where the Body of each SOAP message contains an XML representation of the call or return stack:

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <sm:someMethod xmlns:sm="http://www.xyz.com/sm"> <someParams> <item>100</item> <item>200</item> </someParams> </sm:someMethod> </env:Body> </env:Envelope>

The transformation from call-level interface to XML and back occurs through the magic of two processes: marshaling and serialization. 1. The process begins with the client calling a method implemented as a remote procedure. The client actually calls a proxy stub that acts as a surrogate for the real procedure. The proxy stub presents the same external interface to the caller as would the real procedure, but instead of implementing the procedure's functionality, implements the processes necessary for preparing and transporting data across the interface. 2. The proxy stub gathers the parameters it receives through its parameter list into a standard form, in this case, into a SOAP message, through a process called marshaling. 3. The proxy stub encodes the parameters as appropriate during the marshaling process to ensure the recipient can correctly interpret their values. Encoding may be as simple as identifying the correct structure and data type as attributes on the XML tag enclosing the parameter's value or as complex as converting the content to a standard format such as Base64. The final product of the marshaling process is a SOAP message representation of the call stack. 4. The proxy stub serializes the SOAP message across the transport layer to the server. Serialization involves converting the SOAP message into a TCP/IP buffer stream and transporting that buffer stream between the client and the server. The server goes through the reverse process to extract the information it needs. A listener service on the server deserializes the transport stream and calls a proxy stub on the server that unmarshals the parameters, decodes and binds them to internal variables and data structures, and invokes the called procedure. The listener process may be, for example, a J2EE servlet, JSP (JavaServer Page), or Microsoft ASP (Active Server Page). The client and server reverse roles and the inverse process occurs to return the server's response to the client. Document-Style The difference between RPC-Style and Document-Style is primarily in the control you have over the marshaling process. With RPC-style messaging, standards govern that process. With document-style messaging, you make the decisions: you convert data from internal variables into XML; you place the XML into the Body element of the encapsulating SOAP document; you determine the schema(s), if
http://java.boot.by/wsd-guide/wsd-guide.html 123 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

any, for validating the document's structure; and you determine the encoding scheme, if any, for interpreting data item values. The SOAP document simply becomes a wrapper containing whatever content you decide. For example, the SOAP document shown in following example contains an XML namespace reference, http://www.xyz.com/genealogy, that presumably includes all the information a receiving program needs for validating the message's structure and content, and for correctly interpreting data values:

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <xyz:family xmlns:xyz="http://www.xyz.com/genealogy"> <parents> <father age="29">Mikalai</father> <mother age="29">Volha</mother> </parents> <children> ... </children> </xyz:family> </env:Body> </env:Envelope>

If you compare the steps involved in typical document-style message exchange process with those involved in processing an RPC-style message, you will notice they are essentially parallel processes: 1. The SOAP client uses an Extensible Stylesheet Language Transformation (XSLT) and the DOM parser, or some other means, to create an XML document. 2. The SOAP client places this XML document into the Body of a SOAP message. 3. The SOAP client optionally includes a namespace reference in the message that other applications can use for validating the encapsulated document's format and content. The namespace reference may be included as an attribute either on one of the SOAP elements or on the XML document's root element. If the document does not include a namespace reference, the client and server must agree on some other scheme for validating and interpreting the document's contents. 4. The SOAP client serializes the message to the SOAP server across either an HTTP or SMTP bound interface. The SOAP server reverses the process, potentially using a different XSLT, to validate, extract, and bind the information it needs from the XML document to its own internal variables. The roles reverse and the two follow inverse processes for returning and accessing any response values. The rules guiding the marshaling process are the primary difference between this process and that for RPC-style messages. With document-style, you as the SOAP client's author create those rules. RPC-style messaging maps to the object-oriented, component-technology space. It is an alternative to other component technologies such as DCOM and CORBA where component models are built around programmable interfaces and languages such as Java and C#. RPC-style messaging's strength in this space lies in its platform independence. It offers a standards-based, platform-independent component technology, implemented over standard Internet protocols. One of the benefits of this style's XML layer is that clients and servers can use different programming languages, or technologies, to implement their respective side of the interface, which means one side can choose one set of technologies, such as J2EE's JAX-RPC, while the other chooses a completely different set, such as .NET's C#. RPC-style messaging's standards heritage can be an important consideration in hybrid environments (one using multiple technologies such as J2EE and .NET) and can provide a transition path between different technologies. RPC-Style messaging's weaknesses

Strong coupling If you change the number, order, or data types of the parameters to the call-level interface, you must make the change on both sides of the interface. Synchronicity Most programming languages assume synchronous method calls: the calling program normally waits for the called program to execute and return any results before continuing. Web services are asynchronous by nature and, in comparison to technologies such as DCOM and CORBA, long running. You may want to take advantage of Web services' asynchronous nature to avoid the user having to wait for calls to complete by developing asynchronous RPC calls, but that adds another level of complexity to your application. Some tools hide this complexity using callbacks, or other techniques, to enable processing overlap between the request and the response. Check to see if the tools you' re using let you choose between synchronous and asynchronous RPC calls. Marshaling and serialization overhead

http://java.boot.by/wsd-guide/wsd-guide.html 124 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

Marshaling and serializing XML is more expensive than marshaling and serializing a binary data stream. With XML, at least one side of the interface, and possibly both, involves some parsing in order to move data between internal variables and the XML document. There is also the cost of moving encoded text, which can be larger in size than its binary equivalent, across the interface. The coupling and synchronicity issues are common to RPC-based component technologies. So they are really not discriminators when making comparisons between these technologies. The marshaling and serialization overhead is greater for RPC-style messaging and places this messaging style at a relative disadvantage. However, with today's high-speed processors and networks, performance is generally not an issue. Document-style messaging is clearly an option in any situation where an XML document is one of the interface parameters. It is ideal for passing complex business documents, such as invoices, receipts, customer orders, or shipping manifests. Documentstyle messaging uses an XML document and a stylesheet to specify the content and structure of the information exchanged across the interface, making it an obvious choice in situations where a document's workflow involves a series of services where each service processes a subset of the information within the document. Each service can use an XSLT to validate, extract, and transform only the elements it needs from the larger XML document; with the exception of those elements, the service is insensitive to changes in other parts of the document. The XSLT insulates the service from changes in the number, order, or type of data elements being exchanged. As long as the service creating the document maintains backwards compatibility, it can add or rearrange the elements it places into a document without affecting other services. Those services can simply ignore any additional data. Document-style messaging is also agnostic on the synchronicity of the interface; it works equally well for both synchronous and asynchronous interfaces. Document-style messaging's weaknesses

No standard service identification mechanism With document-style messaging, the client and server must agree on a service identification mechanism: a way for a document's recipient to determine which service(s) need to process that document. SOAP header entries offer one option; you can include information in the document's header that helps identify the service(s) needed. WS-Routing makes just such a proposal. Another option is to name elements in the Body of the message for the services that need to process the payload the elements contain. You might ask how that differs from schema-based RPC-style messaging. You would be right in assuming there is little or no difference except possibly in terms of the number of "calls" that can be made per message. A third option is to perform either structure or content analysis as part of a service selection process in order to identify the services needed to process the document. Marshaling and serialization overhead Document-style messaging suffers from the same drawbacks as RPC-style messaging in this area. However, the problem may be more severe with document-style messaging. Document-style messaging incurs overhead in three areas: in using DOM, or another technique, to build XML documents; in using DOM, or SAX, to parse those documents in order to extract data values; and in mapping between extracted data values and internal program variables. Tools generating equivalent RPC-style interfaces optimize these transformations. You may have trouble achieving the same level of efficiency in your applications using standard tools.

There are two compelling reasons to use document-style messaging. One is to gain the independence it provides. Its strength lies in decoupling interfaces between services to the point that they can change completely independently of one another. The other is that document-style messaging puts the full power of XML for structuring and encoding information at your disposal. The latter is one reason many consider document-style superior to RPC-style messaging. RPC-style messaging's strength is as a bridging component technology. It is a good option for creating new components and for creating interfaces between Web services and existing components - you simply wrap existing components with RPC-style Web services interfaces. RPC-style messaging is also an excellent component standard in situations where you are using multiple technologies, such as J2EE and .NET, and want to develop sharable components. Document-style messaging's strengths are in situations where an XML document is part of the data being passed across the interface, where you want to leverage the full power of XML and XSL, and in instances where you want to minimize coupling between services forming an interface, such as in application-to-application and system-to-system interfaces. WSDL Example for RPC-Style:

... <message name="myMethodRequest"> <part name="x" type="xsd:int"/> </message> <portType name="PT"> <operation name="myMethod">

http://java.boot.by/wsd-guide/wsd-guide.html 125 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

<input message="myMethodRequest"/> </operation> </portType> ...

RPC-Literal SOAP message for this request:

<soap:Envelope> <soap:Body> <myMethod> <x>5</x> </myMethod> </soap:Body> </soap:Envelope>

WSDL Example for Document-Style:

<types> <schema> <element name="xElement" type="xsd:int"/> </schema> </types> <message name="myMethodRequest"> <part name="x" element="xElement"/> </message> <portType name="PT"> <operation name="myMethod"> <input message="myMethodRequest"/> </operation> </portType>

Document-Literal SOAP message:

<soap:Envelope> <soap:Body> <xElement>5</xElement> </soap:Body> </soap:Envelope>

Describe the function of the service interaction and processing layers in a Web service.
1212

Describe the tasks performed by each phase of an XML-based, document oriented, Web service application, including the consumption, business processing, and production phases.
http://java.boot.by/wsd-guide/wsd-guide.html 126 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

1212

Design a Web service for an asynchronous, document-style process and describe how to refactor a Web service from a synchronous to an asynchronous model.
1212

Describe how the characteristics, such as resource utilization, conversational capabilities, and operational modes, of the various types of Web service clients impact the design of a Web service or determine the type of client that might interact with a particular service.
1212

Appendixes
Appendix A. First Appendix

SAAJ API
SAAJ Interfaces

package javax.xml.soap; public interface Node extends org.w3c.dom.Node { public abstract String getValue(); public abstract void setParentElement(SOAPElement parent) throws SOAPException; public abstract SOAPElement getParentElement(); public abstract void detachNode(); public abstract void recycleNode(); public abstract void setValue(String value); }

package javax.xml.soap; public interface Text extends Node, org.w3c.dom.Text { public abstract boolean isComment(); }

package javax.xml.soap; import java.util.Iterator; public interface SOAPElement extends Node, org.w3c.dom.Element {

http://java.boot.by/wsd-guide/wsd-guide.html 127 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

public abstract SOAPElement addChildElement(Name name) throws SOAPException; public abstract SOAPElement addChildElement(String localName) throws SOAPException; public abstract SOAPElement addChildElement(String localName, String prefix) throws SOAPException; public abstract SOAPElement addChildElement( String localName, String prefix, String uri) throws SOAPException; public abstract SOAPElement addChildElement(SOAPElement element) throws SOAPException; public abstract SOAPElement addTextNode(String text) throws SOAPException; public abstract SOAPElement addAttribute(Name name, String value) throws SOAPException; public abstract SOAPElement addNamespaceDeclaration( String prefix, String uri) throws SOAPException; public abstract String getAttributeValue(Name name); public abstract Iterator getAllAttributes(); public abstract String getNamespaceURI(String prefix); public abstract Iterator getNamespacePrefixes(); public abstract Name getElementName(); public abstract boolean removeAttribute(Name name); public abstract boolean removeNamespaceDeclaration(String prefix); public abstract Iterator getChildElements(); public abstract Iterator getChildElements(Name name); public abstract void setEncodingStyle(String encodingStyle) throws SOAPException; public abstract String getEncodingStyle(); public abstract void removeContents(); public abstract Iterator getVisibleNamespacePrefixes(); }

package javax.xml.soap; import org.w3c.dom.Document; import java.util.Locale; public interface SOAPBody extends SOAPElement { public abstract SOAPFault addFault() throws SOAPException; public abstract boolean hasFault();

http://java.boot.by/wsd-guide/wsd-guide.html 128 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

public abstract SOAPFault getFault(); public abstract SOAPBodyElement addBodyElement(Name name) throws SOAPException; public abstract SOAPFault addFault(Name faultCode, String faultString, Locale locale) throws SOAPException; public abstract SOAPFault addFault(Name faultCode, String faultString) throws SOAPException; public abstract SOAPBodyElement addDocument(Document document) throws SOAPException; }

package javax.xml.soap; public interface SOAPBodyElement extends SOAPElement {}

package javax.xml.soap; import java.util.Locale; public interface SOAPFault extends SOAPBodyElement { public abstract void setFaultCode(String faultCode) throws SOAPException; public abstract String getFaultCode(); public abstract void setFaultActor(String faultActor) throws SOAPException; public abstract String getFaultActor(); public abstract void setFaultString(String faultString) throws SOAPException; public abstract String getFaultString(); public abstract Detail getDetail(); public abstract Detail addDetail() throws SOAPException; public abstract void setFaultCode(Name name) throws SOAPException; public abstract Name getFaultCodeAsName(); public abstract void setFaultString(String faultString, Locale locale) throws SOAPException; public abstract Locale getFaultStringLocale(); }

package javax.xml.soap; public interface SOAPEnvelope extends SOAPElement { public abstract Name createName(String localName, String prefix, String uri) throws SOAPException; public abstract Name createName(String localName) throws SOAPException;

http://java.boot.by/wsd-guide/wsd-guide.html 129 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

public abstract SOAPHeader getHeader() throws SOAPException; public abstract SOAPBody getBody() throws SOAPException; public abstract SOAPHeader addHeader() throws SOAPException; public abstract SOAPBody addBody() throws SOAPException; }

package javax.xml.soap; import java.util.Iterator; public interface SOAPHeader extends SOAPElement { public abstract SOAPHeaderElement addHeaderElement(Name name) throws SOAPException; // does not detach headers public abstract Iterator examineHeaderElements(String actor); // detaches headers public abstract Iterator extractHeaderElements(String actor); public abstract Iterator examineMustUnderstandHeaderElements(String actor); public abstract Iterator examineAllHeaderElements(); public abstract Iterator extractAllHeaderElements(); }

package javax.xml.soap; public interface SOAPHeaderElement extends SOAPElement { public abstract void setActor(String actorURI); public abstract String getActor(); public abstract void setMustUnderstand(boolean mustUnderstand); public abstract boolean getMustUnderstand(); }

SAAJ API Classes.

package javax.xml.soap; import java.io.IOException; import java.io.InputStream; public abstract class MessageFactory { protected MessageFactory() {} public static MessageFactory newInstance() throws SOAPException { ... }
http://java.boot.by/wsd-guide/wsd-guide.html 130 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

public abstract SOAPMessage createMessage() throws SOAPException; public abstract SOAPMessage createMessage( MimeHeaders mimeheaders, InputStream inputstream) throws IOException, SOAPException; ... }

package javax.xml.soap; import javax.activation.DataHandler; import java.io.IOException; import java.io.OutputStream; import java.util.Iterator; public abstract class SOAPMessage { public SOAPMessage() {} public abstract String getContentDescription(); public abstract void setContentDescription(String description); public abstract SOAPPart getSOAPPart(); public abstract void removeAllAttachments(); public abstract int countAttachments(); public abstract Iterator getAttachments(); public abstract Iterator getAttachments(MimeHeaders headers); public abstract void addAttachmentPart(AttachmentPart attachmentpart); public abstract AttachmentPart createAttachmentPart(); public AttachmentPart createAttachmentPart(DataHandler datahandler) { ... } public abstract MimeHeaders getMimeHeaders(); public AttachmentPart createAttachmentPart(Object content, String contentType) { ... } public abstract void saveChanges() throws SOAPException; public abstract boolean saveRequired(); public abstract void writeTo(OutputStream out) throws SOAPException, IOException; public SOAPBody getSOAPBody() throws SOAPException { ... } public SOAPHeader getSOAPHeader() throws SOAPException { ... } public void setProperty(String property, Object value) throws SOAPException { ... } public Object getProperty(String property) throws SOAPException { ... } }

package javax.xml.soap; import javax.xml.transform.Source; import java.util.Iterator; public abstract class SOAPPart implements org.w3c.dom.Document { public SOAPPart() {} public abstract SOAPEnvelope getEnvelope() throws SOAPException; public String getContentId() { ...
http://java.boot.by/wsd-guide/wsd-guide.html 131 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

} public String getContentLocation() { ... } public void setContentId(String contentId) { ... } public void setContentLocation(String contentLocation) { ... } public abstract void removeMimeHeader(String header); public abstract void removeAllMimeHeaders(); public abstract String[] getMimeHeader(String name); public abstract void setMimeHeader(String name, String value); public abstract void addMimeHeader(String name, String value); public abstract Iterator getAllMimeHeaders(); public abstract Iterator getMatchingMimeHeaders(String names[]); public abstract Iterator getNonMatchingMimeHeaders(String names[]); public abstract void setContent(Source source) throws SOAPException; public abstract Source getContent() throws SOAPException; }

package javax.xml.soap; import java.util.Locale; public interface SOAPFault extends SOAPBodyElement { public abstract void setFaultCode(String faultCode) throws SOAPException; public abstract String getFaultCode(); public abstract void setFaultActor(String faultActor) throws SOAPException; public abstract String getFaultActor(); public abstract void setFaultString(String faultString) public abstract String getFaultString(); public abstract Detail getDetail(); public abstract Detail addDetail() throws SOAPException; public abstract void setFaultCode(Name name) throws SOAPException; public abstract Name getFaultCodeAsName(); public abstract void setFaultString(String faultString, Locale locale) throws SOAPException; public abstract Locale getFaultStringLocale(); }

Second Section
sdsds

Third Section
sdsds

Bibliography
[BP-1.0] Basic Profile Version 1.0a - Final Specification (http://www.ws-i.org/Profiles/Basic/2003-08/BasicProfile-1.0a.html). [SOAP-1.1] Simple Object Access Protocol (SOAP) 1.1 (http://www.w3.org/TR/2000/NOTE-SOAP-20000508). [WSDL-1.1] Web Services Description Language (WSDL) 1.1 (http://www.w3.org/TR/wsdl).

http://java.boot.by/wsd-guide/wsd-guide.html 132 / 133 2004/6/13 12:07:08

SCDJWS Study Guide

[UDDI-2.0-DS] UDDI Version 2.03 Data Structure Reference (http://uddi.org/pubs/DataStructure-V2.03-Published-20020719.htm). [UDDI-2.0-API] UDDI Version 2.04 API Specification (http://uddi.org/pubs/ProgrammersAPI-V2.04-Published-20020719.htm). [XML-DSIG] XML Digital Signature (http://www.w3.org/Signature). [XML-SIG] XML-Signature Syntax and Processing (http://www.w3.org/TR/2002/REC-xmldsig-core-20020212). [XML-ENCR] XML Encryption Syntax and Processing (http://www.w3.org/TR/2002/REC-xmlenc-core-20021210). [SAML] SAML (http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=security). [XACML] XACML (http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=xacml). [WS-SEC] Web Services Security (WS-Security) (http://www-106.ibm.com/developerworks/webservices/library/ws-secure/).

http://java.boot.by/wsd-guide/wsd-guide.html 133 / 133 2004/6/13 12:07:08

SCWCD 1.4 Study Guide

SCWCD 1.4 Study Guide


IBA JV Mikalai Zaikin
<NZaikin[at]iba.by>

Copyright 2004 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. May 2004
Revision History Revision 0.6 Proposed Final Draft 3. Revision 0.5 Proposed Final Draft 2. Revision 0.4 Proposed Final Draft 1. Revision 0.3 Chapters 9-10 updates. Revision 0.2 Chapters 1-8 updates. Revision 0.1 Initial release. 22 Dec 2003 MZ 12 Jan 2004 MZ 15 Jan 2004 MZ 19 Jan 2004 MZ 5 Apr 2004 MZ 7 May 2004 MZ

Abstract The purpose of this document is to help in preparation for exam CX-310-081 (Sun Certified Web Component Developer using the J2EE Platform 1.4). This document should not be used as the only study material for SCWCD 1.4 test. It covers all objective topics, but it is not enough. I tried to make this document as much accurate as possible, but if you find any error, please let me know.
http://java.boot.by/wcd-guide/wcd-guide.html 1 / 166 2004/6/13 12:08:14

SCWCD 1.4 Study Guide

Table of Contents Foreword Preface I. Exam Objectives 1. The Servlet Technology Model For each of the HTTP Methods (such as GET, POST, HEAD, and so on) describe the purpose of the method and the technical characteristics of the HTTP Method protocol, list triggers that might cause a Client (usually a Web browser) to use the method; and identify the HttpServlet method that corresponds to the HTTP Method. Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request. Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response. Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method. 2. The Structure and Deployment of Web Applications Construct the file and directory structure of a Web Application that may contain (a) static content, (b) JSP pages, (c) servlet classes, (d) the deployment descriptor, (e) tag libraries, (f) JAR files, and (g) Java class files; and describe how to protect resource files from HTTP access. Describe the purpose and semantics for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servletclass, servlet-mapping, servlet-name, and welcome-file. Construct the correct structure for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servlet-class, servletmapping, servlet-name, and welcome-file. Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed. 3. The Web Container Model For the ServletContext initialization parameters: write servlet code to access initialization parameters; and create the deployment descriptor elements for declaring initialization parameters. For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multi-threading issues

http://java.boot.by/wcd-guide/wcd-guide.html 2 / 166 2004/6/13 12:08:14

SCWCD 1.4 Study Guide

associated with each scope. Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper. Describe the Web container life cycle event model for requests, sessions, and web applications; create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use. Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource. 4. Session Management Write servlet code to store objects into a session object and retrieve objects from a session object. Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed. Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another. Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting. 5. Web Application Security Based on the servlet specification, compare and contrast the following security mechanisms: (a) authentication, (b) authorization, (c) data integrity, and (d) confidentiality. In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role. Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type. 6. The JavaServer Pages (JSP) Technology Model Identify, describe, or write the JSP code for the following elements: (a) template text, (b) scripting elements (comments, directives, declarations, scriptlets, and expressions), (c) standard and custom actions, and (d) expression language elements. Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'. Write a JSP Document (XML-based document) that uses the correct syntax. Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call

http://java.boot.by/wcd-guide/wcd-guide.html 3 / 166 2004/6/13 12:08:14

SCWCD 1.4 Study Guide

the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method. Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception. Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language. Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp:include standard action). 7. Building JSP Pages Using the Expression Language (EL) Given a scenario, write EL code that accesses the following implicit variables including: pageScope, requestScope, sessionScope, and applicationScope, param and paramValues, header and headerValues, cookie, initParam and pageContext. Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator). Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators. Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor. 8. Building JSP Pages Using Standard Actions Given a design goal, create a code snippet using the following standard actions: jsp:useBean (with attributes: 'id', 'scope', 'type', and 'class'), jsp:getProperty, and jsp:setProperty (with all attribute combinations). Given a design goal, create a code snippet using the following standard actions: jsp:include, jsp:forward, and jsp:param. 9. Building JSP Pages Using Tag Libraries For a custom tag library or a library of Tag Files, create the 'taglib' directive for a JSP page. Given a design goal, create the custom tag structure in a JSP page to support that goal. Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library. 10. Building a Custom Tag Library Describe the semantics of the "Classic" custom tag event model when each event method (doStartTag, doAfterBody, and doEndTag) is executed, and explain what the return value for each event method means; and write a tag handler class. Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes. Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor. Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag.

http://java.boot.by/wcd-guide/wcd-guide.html 4 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag. 11. J2EE Patterns Given a scenario description with a list of issues, select a pattern that would solve the issues. The list of patterns you must know are: Intercepting Filter, Model-ViewController, Front Controller, Service Locator, Business Delegate, and Transfer Object. Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-View-Controller, Front Controller, Service Locator, Business Delegate, and Transfer Object. II. Appendixes A. First Appendix First Section Second Section Third Section Bibliography

Foreword
A preface.

Preface
This document is available in 2 formats: single page and chunked pages If you would like to have PDF (printable eBook for Adobe Acrobat Reader) version or CHM (single file copy of web-site to browse offline) version of SCWCD Study Guide, please, contact me.

Exam Objectives
Chapter 1. The Servlet Technology Model

For each of the HTTP Methods (such as GET, POST, HEAD, and so on) describe the purpose of the method and the technical characteristics of the HTTP Method protocol, list triggers that might cause a Client (usually a Web browser) to use the method; and identify the HttpServlet method that corresponds to the HTTP Method.
http://java.boot.by/wcd-guide/wcd-guide.html 5 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

The HttpServlet abstract subclass adds additional methods beyond the basic Servlet interface that are automatically called by the service method in the HttpServlet class to aid in processing HTTPbased requests. These methods are (HTTP 1.1):

doGet for handling HTTP GET requests.

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a GET request. Overriding this method to support a GET request also automatically supports an HTTP HEAD request. A HEAD request is a GET request that returns NO BODY in the response, only the request header fields. When overriding this method, read the request data, write the response headers, get the response's writer or output stream object, and finally, write the response data. It's best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DisplayServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<html><head><title>Display Information"); out.println("</title></head><body>"); out.println("Hello, World"); out.println("</body></html>"); } }

The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body. The GET method should be safe, that is, without any side effects for which users are held responsible. For example, most form queries have no side effects. If a client request is
http://java.boot.by/wcd-guide/wcd-guide.html 6 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

intended to change stored data, the request should use some other HTTP method (for example, POST method). The GET method should also be idempotent, meaning that it can be safely repeated. Sometimes making a method safe also makes it idempotent. For example, repeating queries is both safe and idempotent, but buying a product online or modifying data is neither safe nor idempotent. GET method purpose. The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. In short, this method should be used for getting (retrieving) data only. It should not be used for storing data in DB. GET method technical characteristics. Query string or form data during this method is simply appended to the URL as namevalue pairs separated with '&'.

name1=value1&name2=value2&name3=value3

Query length is limited (it depends on servlet container's plaform, but usually should not exceed 1024 bytes). Users can see data in the browser's address bar.

http://some-server.com/some-script?name1=value1&name2=value2&name3=value3

Only ASCII (text) data can be sent to server with GET method. Easy to bookmark. GET method triggers. The web browser sends an HTTP GET request when:

http://java.boot.by/wcd-guide/wcd-guide.html 7 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide


r r r

The user types a URL in the browser's address bar. The user clicks a link. Retrieve a resource which was defined in src (image) or href (cascade style sheet) attributes.

<img src="image.gif">

<link href="style.css" rel="stylesheet" type="text/css">

The user (or JavaScript) submits a form that specifies attribute method="GET":

<form action="/servlet/display" method="GET"> First Name: <input type="text" name="firstName"><p> Last Name: <input type="text" name="lastName"><p> <input type="submit" value="Display"> </form>

The user (or JavaScript) submits a form that specifies NO method attribute (forms use method GET BY DEFAULT):

<form action="/servlet/display"> First Name: <input type="text" name="firstName"><p> Last Name: <input type="text" name="lastName"><p> <input type="submit" value="Display"> </form>

doPost for handling HTTP POST requests.

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a POST request.
http://java.boot.by/wcd-guide/wcd-guide.html 8 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

The HTTP POST method allows the client to send data of UNLIMITED length to the Web server a single time and is useful when posting information such as credit card numbers. When overriding this method, read the request data, write the response headers, get the response's writer or output stream object, and finally, write the response data. It's best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DisplayServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<html><head><title>Display Information"); out.println("</title></head><body>"); out.println("Hello, World"); out.println("</body></html>"); } }

The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body. This method does not need to be either safe or idempotent. Operations requested through POST can have side effects for which the user can be held accountable, for example, updating stored data or buying items online. POST method purpose. The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:
r r

Annotation of existing resources; Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; Providing a block of data, such as the result of submitting a form, to a datahandling process;

http://java.boot.by/wcd-guide/wcd-guide.html 9 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide


r

Extending a database through an append operation.

In short, this method should be used for posting newgroups messages, submitting long data fields to a database (such as a SQL insert of lengthy string), or sending binary files to server. POST method technical characteristics. Sends information to the server such as form fields, large text bodies, and key-value pairs. Hides form data from users because it is not passed as a query string, but in the message body. Sends UNLIMITED length data as part of its HTTP request body. For sending ASCII (text) or binary data. Disallows bookmarks. POST method triggers. The web browser sends an HTTP POST request when:
r

The user (or JavaScript) submits a form that specifies attribute method="POST":

<form action="/servlet/display" method="POST"> First Name: <input type="text" name="firstName"><p> Last Name: <input type="text" name="lastName"><p> <input type="submit" value="Display"> </form>

doPut for handling HTTP PUT requests.

protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a PUT request. The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.
http://java.boot.by/wcd-guide/wcd-guide.html 10 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

When overriding this method, leave intact any content headers sent with the request (including Content-Length, Content-Type, Content-Transfer-Encoding, Content-Encoding, ContentBase, Content-Language, Content-Location, Content-MD5, and Content-Range). If your method cannot handle a content header, it must issue an error message and discard the request. This method does not need to be either safe or idempotent. Operations that doPut performs can have side effects for which the user can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage. The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource.

<form enctype="multipart/form-data" action="some_url" method="PUT"> <input type="file" name="fileToUpload" value="Select File"> <input type="submit" value="Upload"> <input type="reset" value="Reset"> </form>

doDelete for handling HTTP DELETE requests.

protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a DELETE request. The DELETE operation allows a client to remove a document or Web page from the server. This method does not need to be either safe or idempotent. Operations requested through DELETE can have side effects for which users can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage. doHead for handling HTTP HEAD requests.

protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

http://java.boot.by/wcd-guide/wcd-guide.html 11 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Receives an HTTP HEAD request from the protected service method and handles the request. The client sends a HEAD request when it wants to see ONLY the HEADERS of a response, such as Content-Type or Content-Length. The HTTP HEAD method counts the output bytes in the response to set the Content-Length header accurately. The doHead method in HttpServlet is a specialized form of the doGet method that returns only the headers produced by the doGet method. doOptions for handling HTTP OPTIONS requests.

protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a OPTIONS request. The OPTIONS request determines which HTTP methods the server supports and returns an appropriate header. For example, if a servlet overrides doGet, this method returns the following header:

Allow: GET, HEAD, TRACE, OPTIONS

doTrace for handling HTTP TRACE requests.

protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a TRACE request. The doTrace method generates a response containing all instances of the headers sent in the TRACE request to the client, so that they can be used in debugging. There's no need to override this method. Typically when developing HTTP-based servlets, a Servlet Developer will only concern himself with the doGet and doPost methods. The other methods are considered to be methods for use by programmers very familiar with HTTP programming.

Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the
http://java.boot.by/wcd-guide/wcd-guide.html 12 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

request.
HTTP Protocol Parameters. Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request. When the request is an HttpServletRequest object, the container populates the parameters from the URI query string and POST-ed data. The parameters are stored 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 Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data. You should only use this method when you are sure the parameter has only ONE value. If the parameter might have MORE than one value, use getParameterValues(String). If you use this method with a multivalued parameter, the value returned is equal to the FIRST value in the array returned by getParameterValues. If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method. getParameterNames Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an EMPTY Enumeration. getParameterValues Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. If the parameter has a single value, the array has a length of 1. getParameterMap Returns an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.

public interface ServletRequest {

http://java.boot.by/wcd-guide/wcd-guide.html 13 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

public java.lang.String getParameter(java.lang.String name); public java.util.Enumeration getParameterNames(); public java.lang.String[] getParameterValues(java.lang.String name); public java.util.Map getParameterMap(); }

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 be the FIRST value in the array of String objects returned by getParameterValues. The getParameterMap method returns a java.util.Map of the parameter of the request, which contains names as keys and parameter values as map values.

public void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException { Enumeration e = request.getParameterNames(); PrintWriter out = res.getWriter (); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getParameter(name); out.println(name + " = " + value); } }
Data from the query string and the post body are aggregated into the request parameter set. Query string data is presented BEFORE post body 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). The following are the conditions that must be met before post FORM data will be populated to the parameter set: 1. 2. 3. 4. The request is an HTTP or HTTPS request. The HTTP method is POST. The content type is application/x-www-form-urlencoded. The servlet has made an initial call of any of the 'getParameter' family of methods on the request object.

If the conditions are not met and the post form data is not included in the parameter set, the post data must still be available to the servlet via the request object's input stream. If the conditions are met, post form data will no longer be available for reading directly from the request object's input stream. Headers.
http://java.boot.by/wcd-guide/wcd-guide.html 14 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

A servlet can access the headers of an HTTP request through the following methods of the HttpServletRequest interface:

getHeader Returns the value of the specified request header as a String. If the request did not include a header of the specified name, this method returns null. If there are multiple headers with the same name, this method returns the first head in the request. The header name is case insensitive. You can use this method with any request header. getHeaders Returns all the values of the specified request header as an Enumeration of String objects. Some headers, such as Accept-Language can be sent by clients as several headers each with a different value rather than sending the header as a comma separated list. If the request did not include any headers of the specified name, this method returns an EMPTY Enumeration. The header name is case INSENSITIVE. You can use this method with any request header. getHeaderNames Returns an enumeration of all the header names this request contains. If the request has no headers, this method returns an empty enumeration.

The getHeader method returns a header given the name of the header. There can be multiple headers with the same name, e.g. Cache-Control headers, in an HTTP request. If there are multiple headers with the same name, the getHeader method returns the first header 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.

public interface HttpServletRequest { public java.lang.String getHeader(java.lang.String name); public java.util.Enumeration getHeaders(java.lang.String name); public java.util.Enumeration getHeaderNames(); }

Headers may contain String representations of int or Date data. The following convenience methods of the HttpServletRequest interface provide access to header data in a one of these formats:

getIntHeader

http://java.boot.by/wcd-guide/wcd-guide.html 15 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Returns the value of the specified request header as an int. If the request does not have a header of the specified name, this method returns -1. If the header cannot be converted to an integer, this method throws a NumberFormatException. The header name is case INSENSITIVE. getDateHeader Returns the value of the specified request header as a long value that represents a Date object. Use this method with headers that contain dates, such as If-Modified-Since. The date is returned as the number of milliseconds since January 1, 1970 GMT. The header name is case insensitive. If the request did not have a header of the specified name, this method returns -1. If the header can't be converted to a date, the method throws an IllegalArgumentException. 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.

public interface HttpServletRequest { public int getIntHeader(java.lang.String name); public long getDateHeader(java.lang.String name); }

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getHeader(name); out.println(name + " = " + value); } }

Cookies. The HttpServletRequest interface provides the getCookies method to obtain an array of cookies that
http://java.boot.by/wcd-guide/wcd-guide.html 16 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

are present in the request. This method returns null if no cookies were sent. The 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. Several cookies might have the same name but different path attributes.

public interface HttpServletRequest { public Cookie[] getCookies(); }

package javax.servlet.http; public class Cookie implements java.lang.Cloneable { ... public Cookie(java.lang.String name, java.lang.String value); public java.lang.String getName(); public java.lang.String getPath(); public java.lang.String getValue(); ... }

Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response.
Headers. A servlet can set headers of an HTTP response via the following methods of the HttpServletResponse interface:

setHeader Sets a response header with the given name and value. If the header had already been set, the new value OVERWRITES the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.

http://java.boot.by/wcd-guide/wcd-guide.html 17 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

addHeader Adds a response header with the given name and value. This method allows response headers to have multiple values.

public interface HttpServletResponse extends javax.servlet.ServletResponse { public void setHeader(java.lang.String name, java.lang.String value); public void addHeader(java.lang.String name, java.lang.String value); }

The setHeader method sets a header with a given name and value. A previous header is replaced by the new header. Where a set of header values exist for the name, the values are cleared and replaced with the new value. The addHeader method adds a header value to the set with a given name. If there are no headers already associated with the name, a new set is created. Headers may contain data that represents 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 Sets a response header with the given name and integer value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value. setDateHeader Sets a response header with the given name and date-value. The date is specified in terms of milliseconds since the epoch. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value. addIntHeader Adds a response header with the given name and integer value. This method allows response headers to have multiple values. addDateHeader Adds a response header with the given name and date-value. The date is specified in terms of milliseconds since the epoch. This method allows response headers to have multiple values.

http://java.boot.by/wcd-guide/wcd-guide.html 18 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

public interface HttpServletResponse extends javax.servlet.ServletResponse { public void setIntHeader(java.lang.String name, int value); public void setDateHeader(java.lang.String name, long date); public void addIntHeader(java.lang.String name, int value); public void addDateHeader(java.lang.String name, long date); }

To be successfully transmitted back to the client, headers must be set before the response is committed. Headers set after the response is committed will be IGNORED by the servlet container. Content type. The charset for the MIME body response can be specified explicitly using the setContentType (String) method. Explicit specifications take precedence over implicit specifications. If no charset is specified, ISO-8859-1 will be used. The setContentType method MUST be called BEFORE getWriter and BEFORE committing the response for the character encoding to be used. There are 2 ways to define content type:

ServletResponse.setContentType(String); HttpServletResponse.setHeader("Content-Type", "text/html");

Acquire a text stream. To send CHARACTER data, use the PrintWriter object returned by ServletResponse.getWriter()

public interface ServletResponse { public java.io.PrintWriter getWriter() throws IOException; }

Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). Calling flush() on the PrintWriter commits the response. Either this method or getOutputStream() may be called to write the body, NOT BOTH. Acquire a binary stream.
http://java.boot.by/wcd-guide/wcd-guide.html 19 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

ServletResponse.getOutputStream() provides an output stream for sending BINARY data to the client. A ServletOutputStream object is normally retrieved via this method.

public interface ServletResponse { public ServletOutputStream getOutputStream() throws IOException; }

The servlet container does NOT encode the binary data. Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, NOT BOTH. Redirect an HTTP request to another URL. The HttpServletResponse.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.

public interface HttpServletResponse extends javax.servlet.ServletResponse { public void sendRedirect(java.lang.String location) throws IOException; }

Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading / the container interprets it as relative to the current request URI. If the location is relative with a leading / the container interprets it as relative to the servlet container root. If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to. This method will have the side effect of committing the response, if it has 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 this method are called, the data is ignored.
http://java.boot.by/wcd-guide/wcd-guide.html 20 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

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, this method must throw an IllegalStateException. Add cookies to the response. The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

public interface HttpServletResponse extends javax.servlet.ServletResponse { public void addCookie(Cookie cookie); }

Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.

Describe the purpose and event sequence of the servlet life cycle: (1) servlet class loading, (2) servlet instantiation, (3) call the init method, (4) call the service method, and (5) call destroy method.
A servlet is managed through a well defined life cycle that defines how it is loaded and instantiated, is initialized, handles requests from clients, and 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 implement directly or indirectly through the GenericServlet or HttpServlet abstract classes. Servlet class loading and instantiation. The servlet container is responsible for loading and instantiating servlets. The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is needed to service a request. When the servlet engine is started, needed servlet classes must be located by the servlet container. The servlet container loads the servlet class using normal Java class loading facilities. The loading may be from a local file system, a remote file system, or other network services.

http://java.boot.by/wcd-guide/wcd-guide.html 21 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

After loading the Servlet class, the container instantiates it for use. Servlet class initialization. After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read persistent configuration data, initialize costly resources (such as JDBC connections), and perform other onetime activities. The container initializes the servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface.

public interface Servlet { public void init(ServletConfig config) throws ServletException; }

This configuration object allows the servlet to access name-value initialization parameters from theWeb application's configuration information. The configuration object also gives the servlet access to an object (implementing the ServletContext interface) that describes the servlet's runtime environment. During initialization, the servlet instance can throw an UnavailableException or a ServletException. In this case, the servlet must not be placed into active service and must be released by the servlet container. The destroy method is not called as it is considered unsuccessful initialization. A new instance may be instantiated and initialized by the container after a failed initialization. The exception to this rule is when an UnavailableException indicates a minimum time of unavailability, and the container must wait for the period to pass before creating and initializing a new servlet instance. Request handling. After a servlet is properly initialized, the servlet container may use it to handle client requests. Requests are represented by request objects of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface.

public interface Servlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; }
http://java.boot.by/wcd-guide/wcd-guide.html 22 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.

public abstract class HttpServlet extends javax.servlet.GenericServlet implements java.io.Serializable { protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException; }

Note that a servlet instance placed into service by a servlet container may handle NO requests during its lifetime. End of service. The servlet container is not required to keep a servlet loaded for any particular period of time. A servlet instance may be kept active in a servlet container for a period of milliseconds, for the lifetime of the servlet container (which could be a number of days, months, or years), or any amount of time in between. When the servlet container determines that a servlet should be removed from service, it calls the destroy method of the Servlet interface to allow the servlet to release any resources it is using and save any persistent state. For example, the container may do this when it wants to conserve memory resources, or when it is being shut down.

public interface Servlet { public void destroy(); }

Before the servlet container calls the destroy method, it must allow any threads that are currently running in the service method of the servlet to complete execution, or exceed a serverdefined time limit. Once the destroy method is called on a servlet instance, the container may not route other requests to that 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.

http://java.boot.by/wcd-guide/wcd-guide.html 23 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

After the destroy method completes, the servlet container must release the servlet instance so that it is eligible for garbage collection.

Chapter 2. The Structure and Deployment of Web Applications

Construct the file and directory structure of a Web Application that may contain (a) static content, (b) JSP pages, (c) servlet classes, (d) the deployment descriptor, (e) tag libraries, (f) JAR files, and (g) Java class files; and describe how to protect resource files from HTTP access.
A Web application exists as a structured hierarchy of directories. The root of this hierarchy serves as the document root for files that are part of the application. For example, for a Web application with the context path /catalog in a Web container, the index.html file at the base of the Web application hierarchy can be served to satisfy a request from /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. 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 by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls. Hence, if the Application Developer needs access, from servlet code, to application specific configuration information that he does not wish to be exposed directly to the Web client, he may place it under this directory. Since requests are matched to resource mappings in a case-sensitive manner, client requests for /WEB-INF/foo, /WEb-iNf/foo, for example, should not result in contents of the Web application located under /WEB-INF being returned, nor any form of directory listing thereof. The contents of the WEB-INF directory are:

The /WEB-INF/web.xml deployment descriptor. The /WEB-INF/classes/ directory for servlet and utility classes. The classes in this directory must be available to the application class loader. The /WEB-INF/lib/*.jar area for Java ARchive files. These files contain servlets, beans, and other utility classes useful to the Web application. The Web application class loader must be able to load classes from any of these archive files.

The Web application class loader must load classes from the WEB-INF/classes directory first, and then from library JARs in the WEB-INF/lib directory. Also, any requests from the client to access the resources in WEB-INF/ directory MUST be returned with a SC_NOT_FOUND (404) response. Web applications can be packaged and signed into a Web ARchive format (WAR) file using the standard Java archive tools. For example, an application for issue tracking might be distributed in an archive file called issuetrack.war.

http://java.boot.by/wcd-guide/wcd-guide.html 24 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

When packaged into such a form, a META-INF directory will be present which contains information useful to Java archive tools. This directory MUST NOT be directly served as content by the container in response to a Web client's request, though its contents are visible to servlet code via the getResource and getResourceAsStream calls on the ServletContext. Also, any requests to access the resources in META-INF directory must be returned with a SC_NOT_FOUND (404) response. Tag extensions written in JSP using tag files can be placed in one of two locations. The first possibility is in the /META-INF/tags/ directory (or a subdirectory of /META-INF/tags/) in a JAR file installed in the /WEB-INF/lib/ directory of the web application. Tags placed here are typically part of a reusable library of tags that can be easily dropped into any web application. The second possibility is in the /WEB-INF/tags/ directory (or a subdirectory of /WEB-INF/tags/) of the web application. Tags placed here are within easy reach and require little packaging. Only files with a .tag or .tagx extension are recognized by the container to be tag files. Tag files that appear in any other location are not considered tag extensions and must be ignored by the JSP container. For example, a tag file that appears in the root of a web application would be treated as content to be served. The following 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/lib/jstl.jar /WEB-INF/jsp/example-taglib.tld /WEB-INF/jsp/debug-taglib.tld /WEB-INF/jsp2/jsp2-example-taglib.tld /WEB-INF/tags/displayProducts.tag /WEB-INF/tags/helloWorld.tag /WEB-INF/tags/panel.tag /WEB-INF/tags/xhtmlbasic.tag /WEB-INF/classes/com/mycorp/servlets/MyServlet.class /WEB-INF/classes/com/mycorp/util/MyUtils.class

Describe the purpose and semantics for each of the following deployment descriptor
http://java.boot.by/wcd-guide/wcd-guide.html 25 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

elements: error-page, init-param, mime-mapping, servlet, servlet-class, servlet-mapping, servlet-name, and welcome-file.
Error pages. To allow developers to customize the appearance of content returned to a Web client when a servlet generates an error, the deployment descriptor defines a list of error page descriptions. The syntax allows the configuration of resources to be returned by the container either when a servlet or filter calls sendError on the response for specific status codes, or if the servlet generates an exception or error that propagates to the container. If the sendError method is called on the response, the container consults the list of error page declarations for the Web application that use the status-code syntax and attempts a match. If there is a match, the container returns the resource as indicated by the location entry. A servlet or filter may throw the following exceptions during processing of a request:

runtime exceptions or errors ServletExceptions or subclasses thereof IOExceptions or subclasses thereof

The Web application may have declared error pages using the exception-type element. In this case the container matches the exception type by comparing the exception thrown with the list of error-page definitions that use the exception-type element. A match results in the container returning the resource indicated in the location entry. The closest match in the class heirarchy wins. If no error-page declaration containing an exception-type fits using the class-heirarchy match, and the exception thrown is a ServletException or subclass thereof, the container extracts the wrapped exception, as defined by the ServletException.getRootCause method. A second pass is made over the error page declarations, again attempting the match against the error page declarations, but using the wrapped exception instead. error-page declarations using the exception-type element in the deployment descriptor MUST be unique up to the class name of the exception-type. Similarly, error-page declarations using the status-code element MUST be unique in the deployment descriptor up to the status code. If a servlet generates an error that is not handled by the error page mechanism as described above, the container must ensure to send a response with status 500. The default servlet and container will use the sendError method to send 4xx and 5xx status responses, so that the error mechanism may be invoked. The default servlet and container will use the setStatus method for 2xx and 3xx responses and will not invoke the error page mechanism. You can specify a mapping between the status code returned in an HTTP response or a Java
http://java.boot.by/wcd-guide/wcd-guide.html 26 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

programming language exception returned by any Web component and a Web resource. To set up the mapping, you add an error-page element to the Web application deployment descriptor.

<!-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-page contains a mapping between an error code or an exception type to the path of a resource in the Web application. The sub-element exception-type contains a fully qualified class name of a Java exception type. The sub-element location element contains the location of the resource in the web application relative to the root of the web application. The value of the location MUST have a leading '/'.

<web-app> ... <error-page> <exception-type>exception.BookNotFoundException</exception-type> <location>/errorpage.html</location> </error-page> </web-app>

<web-app>
http://java.boot.by/wcd-guide/wcd-guide.html 27 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

... <error-page> <exception-type>exception.OrderException</exception-type> <location>/errorpage.jsp</location> </error-page> </web-app>

<web-app> ... <error-page> <error-code>404</error-code> <location>/404.html</location> </error-page> </web-app>

Init parameters. After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read persistent configuration data, initialize costly resources (such as JDBC connections), and perform other onetime activities. The container initializes the servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface. This configuration object allows the servlet to access name-value initialization parameters from the Web application's configuration information.

<!-The init-param element contains a name/value pair as an initialization param of the servlet --> <!ELEMENT init-param (param-name, param-value, description?)>

A servlet configuration object used by a servlet container to pass information to a servlet during initialization.

getInitParameter

http://java.boot.by/wcd-guide/wcd-guide.html 28 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. getInitParameterNames Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an EMPTY Enumeration if the servlet has no initialization parameters.

public interface ServletConfig { public java.lang.String getInitParameter(java.lang.String name); public java.util.Enumeration getInitParameterNames(); }

<web-app> ... <servlet> <servlet-name>catalog</servlet-name> <servlet-class>com.mycorp.CatalogServlet</servlet-class> <init-param> <param-name>bgcolor</param-name> <param-value>yellow</param-value> </init-param> </servlet> ... </web-app>

... private String bgcolor; public void init(ServletConfig config) throws ServletException { super.init(config); try { bgcolor = config.getInitParameter("bgcolor"); System.out.println("bgcolor: " + bgcolor); } catch (Exception e) { System.out.println("error: " + e.toString()); } }
http://java.boot.by/wcd-guide/wcd-guide.html 29 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

MIME mapping. The mime-mapping defines a mapping between an extension and a mime type (example: "text/ plain"). The extension element contains a string describing an extension, such as "txt".

<!-The mime-mapping element defines a mapping between an extension and a mime type. --> <!ELEMENT mime-mapping (extension, mime-type)>

<web-app> ... <mime-mapping> <extension>pdf</extension> <mime-type>application/pdf</mime-type> </mime-mapping> ... </web-app>

Servlet. The servlet is used to declare a servlet. It contains the declarative data of a servlet. The jsp-file element contains the full path to a JSP file within the web application beginning with a "/". If a jsp-file is specified and the load-on-startup element is present, then the JSP should be precompiled and loaded. The servlet-name element contains the canonical name of the servlet. Each servlet
http://java.boot.by/wcd-guide/wcd-guide.html 30 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

name is UNIQUE within the web application. The element content of servlet-name MUST NOT be empty. The servlet-class contains the fully qualified class name of the servlet. The run-as element specifies the identity to be used for the execution of a component. It contains an optional description, and the name of a security role specified by the role-name element. The element loadon-startup indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the Web application. The element content of this element must be an INTEGER indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-startup value. The security-role-ref element declares the security role reference in a component's or in a deployment component's code. It consists of an optional description, the security role name used in the code (role-name), and an optional link to a security role (role-link). If the security role is not specified, the deployer must choose an appropriate security role.

http://java.boot.by/wcd-guide/wcd-guide.html 31 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

The servlet-class element contains the fully qualified class name of the servlet.

<!-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*)>

Servlet mapping. The servlet-mapping defines a mapping between a servlet and a URL pattern. The path used for mapping to a servlet is the request URL from the request object minus the context path and the path parameters. The URL path mapping rules below are used in order. The first successful match is used with no further matches attempted: 1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet. 2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the '/' character as a path separator. The longest match determines the servlet selected. 3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container
http://java.boot.by/wcd-guide/wcd-guide.html 32 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last '.' character. 4. If neither of the previous three rules result 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. The container MUST use case-sensitive string comparisons for matching. In the Web application deployment descriptor, the following syntax is used to define mappings:

A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping. A string beginning with a '*.' prefix is used as an extension mapping. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null. All other strings are used for exact matches only.

Request_URI = Context_Path [1] + Servlet_Path [2] + Path_Info [3] + Query_String [4] http://server.com/my_app_context[1]/catalog[2]/product[3]?mode=view[4] Context path. Specifies the path prefix associated with a web application mapping. For a default application (rooted at the base of the web server's URL namespace), the context path is an empty string. For a non-default application, the context path starts with a forward slash ('/') but does not end with one. For example, /my_app_context maps requests that include /my_app_context to the my_app_context application. The HttpServletRequest.getContextPath() method returns a string representing the context path. Servlet path. Specifies the portion of the URL that matches the servlet mapping. This starts with a slash ('/'). The HttpServletRequest.getServletPath() method returns a string representing the servlet path. Path information. Comprises the remaining portion of the request path prior to query string parameters. The HttpServletRequest.getPathInfo() method returns a string representing the remainder of the path. Query string. Is contained in the request URL after the path. The HttpServletRequest.getQueryString() method returns null if the URL does not have a query string. Same as the value of the CGI variable QUERY_STRING.
http://java.boot.by/wcd-guide/wcd-guide.html 33 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<web-app> ... <servlet-mapping> <servlet-name>catalog</servlet-name> <url-pattern>/catalog/*</url-pattern> </servlet-mapping> ... </web-app>

<!-The servlet-mapping element defines a mapping between a servlet and a url pattern --> <!ELEMENT servlet-mapping (servlet-name, url-pattern)>

Welcome files. Web Application developers can define an ordered list of partial URIs called welcome files in the Web application deployment descriptor. The purpose of this mechanism is to allow the deployer to specify an ordered list of partial URIs for the container to use for appending to URIs when there is a request for a URI that corresponds to a directory entry in the WAR not mapped to a Web component. This kind of request is known as a valid partial request. The use for this facility is made clear by the following common example: A welcome file of 'index. html' can be defined so that a request to a URL like host:port/webapp/directory/, where 'directory' is
http://java.boot.by/wcd-guide/wcd-guide.html 34 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

an entry in the WAR that is not mapped to a servlet or JSP page, is returned to the client as 'host: port/webapp/directory/index.html'. If a Web container receives a valid partial request, the Web container must examine the welcome file list defined in the deployment descriptor. The welcome file list is an ordered list of partial URLs with no trailing or leading '/'. The Web server must append each welcome file in the order specified in the deployment descriptor to the partial request and check whether a static resource or servlet in the WAR is mapped to that request URI. The Web container must send the request to the first resource in the WAR that matches. If no matching welcome file is found in the manner described, the container may handle the request in a manner it finds suitable. For some configurations this may mean returning a directory listing or for others returning a 404 response. Consider a Web application where:

<welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list>

/foo/index.html /foo/default.jsp /foo/orderform.html /foo/home.gif /catalog/default.jsp /catalog/products/shop.jsp /catalog/products/register.jsp

A request URI of /foo will be redirected to a URI of /foo/. A request URI of /foo/ will be returned as /foo/index.html. A request URI of /catalog will be redirected to a URI of /catalog/. A request URI of /catalog/ will be returned as /catalog/default.jsp. A request URI of /catalog/index.html will cause a 404 (not found). A request URI of /catalog/products will be redirected to a URI of /catalog/products/.
http://java.boot.by/wcd-guide/wcd-guide.html 35 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

A request URI of /catalog/products/ will be passed to the "default" servlet, if any. If no "default" servlet is mapped, the request may cause a 404 (not found), may cause a directory listing including shop.jsp and register.jsp, or may cause other behavior defined by the container.

<web-app> ... <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> </welcome-file-list> ... </web-app>

Construct the correct structure for each of the following deployment descriptor elements: error-page, init-param, mime-mapping, servlet, servlet-class, servlet-mapping, servletname, and welcome-file.
Error pages.

<!-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)>

Init parameters.

http://java.boot.by/wcd-guide/wcd-guide.html 36 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<!-The init-param element contains a name/value pair as an initialization param of the servlet --> <!ELEMENT init-param (param-name, param-value, description?)>

MIME mapping.

<!-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)>

Servlet.

http://java.boot.by/wcd-guide/wcd-guide.html 37 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<!-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)>

http://java.boot.by/wcd-guide/wcd-guide.html 38 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Servlet mapping.

<!-The servlet-mapping element defines a mapping between a servlet and a url pattern --> <!ELEMENT servlet-mapping (servlet-name, url-pattern)>

Welcome files.

<!-The welcome-file-list contains an ordered list of welcome files elements. --> <!ELEMENT welcome-file-list (welcome-file+)>

Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed.
Web applications can be packaged and signed into a Web ARchive format (WAR) file using the standard Java archive tools. For example, an application for issue tracking might be distributed in an archive file called issuetrack.war. When packaged into such a form, a META-INF directory will be present which contains information useful to Java archive tools. This directory must not be directly served as content by the container in response to a Web clients request, though its contents are visible to servlet code via the getResource and getResourceAsStream calls on the ServletContext. Also, any requests to access the resources in META-INF directory must be returned with a SC_NOT_FOUND(404) response. A WAR usually contains following resources:

Servlets, JavaServer Pages (JSP), Custom Tag Libraries. Server-side utility classes (database beans, shopping carts, and so on). Static web resources (HTML, image, and sound files, and so on). Client-side classes (applets and utility classes).

http://java.boot.by/wcd-guide/wcd-guide.html 39 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

The directory structure of a Web application consists of two parts. The first part is the public directory structure containing HTML/XML documents, JSP pages, images, applets, and so on. The container appropriately serves the directory's contents against incoming requests. The second part is a special WEB-INF directory that contains the following files and directories:

web.xml - the web application deployment descriptor. Tag Library Descriptor files. classes/ - a directory that contains server-side classes: servlet, utility classes, and JavaBeans components. lib/ - a directory that contains JAR archives of libraries (tag libraries and any utility libraries called by server-side classes). tags/ - a directory that contains Tag files (made easily accessible to JSPs without the need to explicitly write a Tag Library Descriptor files).

The structure of the WAR files looks like this:

WEB-INF/ WEB-INF/web.xml WEB-INF/classes/ WEB-INF/lib/ WEB-INF/tags/

To prepare the web application for deployment, package it in a WAR file using the following jar utility command from the top-level directory of the application:

jar cvf web_app.war .

where web_app is the web application name.

Chapter 3. The Web Container Model

For the ServletContext initialization parameters: write servlet code to access initialization parameters; and create the deployment descriptor elements for declaring initialization parameters.
The following methods of the ServletContext interface allow the servlet access to context
http://java.boot.by/wcd-guide/wcd-guide.html 40 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

initialization parameters associated with a Web application as specified by the Application Developer in the deployment descriptor:

getInitParameter Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. This method can make available configuration information useful to an entire "web application". For example, it can provide a webmasters email address or the name of a system that holds critical data. getInitParameterNames Returns the names of the context's initialization parameters as an Enumeration of String objects, or an EMPTY Enumeration if the context has NO initialization parameters.

Initialization parameters are used by an Application Developer to convey setup information. Typical examples are a Webmasters e-mail address, or the name of a system that holds critical data.

public interface ServletContext { public java.lang.String getInitParameter(java.lang.String name); public java.util.Enumeration getInitParameterNames(); }

Context initialization parameters that define shared String constants used within your application, which can be customized by the system administrator who is installing your application. The values actually assigned to these parameters can be retrieved in a servlet or JSP page by calling:

javax.servlet.ServletContext context = getServletContext(); String value = context.getInitParameter("webmaster");

where "webmaster" matches the param-name element of one of these initialization parameters. You can define any number of context initialization parameters, including zero:

<web-app> ... <context-param>

http://java.boot.by/wcd-guide/wcd-guide.html 41 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<param-name>webmaster</param-name> <param-value>myaddress@mycompany.com</param-value> <description> The EMAIL address of the administrator to whom questions and comments about this application should be addressed. </description> </context-param> ... </web-app>

<!-The context-param element contains the declaration of a web applications servlet context initialization parameters. --> <!ELEMENT context-param (param-name, param-value, description?)>

For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multi-threading issues associated with each scope.
Request 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 the RequestDispatcher). Attributes are accessed with the following methods of the ServletRequest interface:

getAttribute Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. Attributes can be set two ways. The servlet container may set attributes to make available custom information about a request. Attributes can also be set programatically using setAttribute(String, Object). This allows information to be embedded into a request before a RequestDispatcher call. Attribute names should follow the same conventions as package names. This specification reserves names matching java.*, javax.*, and sun.*. getAttributeNames

http://java.boot.by/wcd-guide/wcd-guide.html 42 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Returns an Enumeration containing the names of the attributes available to this request. This method returns an EMPTY Enumeration if the request has no attributes available to it. setAttribute Stores an attribute in this request. Attributes are reset between requests. This method is most often used in conjunction with RequestDispatcher. Attribute names should follow the same conventions as package names. Names beginning with java.*, javax.*, and com.sun.*, are reserved for use by Sun Microsystems. If the object passed in is null, the effect is the same as calling removeAttribute(String). removeAttribute Removes an attribute from this request. This method is not generally needed as attributes only persist as long as the request is being handled.

Only ONE attribute value may be associated with an attribute name.

package javax.servlet; public interface ServletRequest { public java.lang.Object getAttribute(java.lang.String name); public java.util.Enumeration getAttributeNames(); public void setAttribute(java.lang.String name, java.lang.Object o); public void removeAttribute(java.lang.String name); }

Attribute names beginning with the prefixes of "java." and "javax." are RESERVED for definition by this specification. Similarly, attribute names beginning with the prefixes of "sun.", and "com. sun." are reserved for definition by Sun Microsystems. It is suggested that all attributes placed in the attribute set be named in accordance with the reverse domain name convention suggested by the Java Programming Language Specification for package naming. Session Attributes. 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 handles a request identified as being a part of the same session.

getAttribute Returns the object bound with the specified name in this session, or null if no object is bound under the name.

http://java.boot.by/wcd-guide/wcd-guide.html 43 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

getAttributeNames Returns an Enumeration of String objects containing the names of all the objects bound to this session. setAttribute Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced. After this method executes, and if the new object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueBound. The container then notifies any HttpSessionAttributeListeners in the web application. If an object was already bound to this session of this name that implements HttpSessionBindingListener, its HttpSessionBindingListener.valueUnbound method is called. If the value passed in is null, this has the same effect as calling removeAttribute(). removeAttribute Removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing. After this method executes, and if the object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueUnbound. The container then notifies any HttpSessionAttributeListeners in the web application.

package javax.servlet.http; public interface HttpSession { public java.lang.Object getAttribute(java.lang.String name); public java.util.Enumeration getAttributeNames(); public void setAttribute(java.lang.String name, java.lang.Object value); public void removeAttribute(java.lang.String name); }

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.

http://java.boot.by/wcd-guide/wcd-guide.html 44 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Multiple servlets executing request threads may have active access to a single session object at the same time. The Developer has the responsibility for synchronizing access to session resources as appropriate. Within an application marked as distributable, all requests that are part of a session must be handled by one Java Virtual Machine (JVM) at a time. The container must be able to handle all objects placed into instances of the HttpSession class using the setAttribute or putValue methods appropriately. The following restrictions are imposed to meet these conditions:

The container must accept objects that implement the Serializable interface. The container may choose to support storage of other designated objects in the HttpSession, such as references to Enterprise JavaBeans components and transactions. Migration of sessions will be handled by container-specific facilities.

The distributed servlet container must throw an IllegalArgumentException for objects where the container cannot support the mechanism necessary for migration of the session storing them. Containers must notify any session attributes implementing the HttpSessionActivationListener during migration of a session. They must notify listeners of passivation prior to serialization of a session, and of activation after deserialization of a session. Application Developers writing distributed applications should be aware that since the container may run in more than one Java virtual machine, the developer cannot depend on static variables for storing an application state. They should store such states using an enterprise bean or a database. Context Attributes. A servlet can bind an object attribute into the context by name. Any attribute 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 Binds an object to a given attribute name in this servlet context. If the name specified is already used for an attribute, this method will REPLACE the attribute with the new to the new attribute. If listeners are configured on the ServletContext the container notifies them accordingly. If a null value is passed, the effect is the same as calling removeAttribute(). Attribute names should follow the same convention as package names. The Java Servlet API specification reserves names matching java.*, javax.*, and sun.*. getAttribute Returns the servlet container attribute with the given name, or null if there is no attribute by that name. An attribute allows a servlet container to give the servlet additional information not already provided by this interface. See your server documentation for information about its attributes. A list of supported attributes can be retrieved using

http://java.boot.by/wcd-guide/wcd-guide.html 45 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

getAttributeNames. The attribute is returned as a java.lang.Object or some subclass. Attribute names should follow the same convention as package names. The Java Servlet API specification reserves names matching java.*, javax.*, and sun.*. getAttributeNames Returns an Enumeration containing the attribute names available within this servlet context. Use the getAttribute(String) method with an attribute name to get the value of an attribute. removeAttribute Removes the attribute with the given name from the servlet context. After removal, subsequent calls to getAttribute(String) to retrieve the attributes value will return null. If listeners are configured on the ServletContext the container notifies them accordingly.

package javax.servlet; public interface ServletContext { public void setAttribute(java.lang.String name, java.lang.Object object); public java.lang.Object getAttribute(java.lang.String name); public java.util.Enumeration getAttributeNames(); public void removeAttribute(java.lang.String name); }

Context attributes are LOCAL to the JVM in which they were created. This prevents ServletContext attributes from being a shared memory store in a distributed container. When information needs to be shared between servlets running in a distributed environment, the information should be placed into a session, stored in a database, or set in an Enterprise JavaBeans component.

Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper.
Request processing model. The container, when receiving an incoming request, processes the request as follows:

Identifies the target Web resource according to the rules of mappings. If there are filters matched by servlet name and the Web resource has a <servlet-name>, the container builds the chain of filters matching in the order declared in the deployment descriptor. The last filter in this chain corresponds to the last <servlet-name> matching

http://java.boot.by/wcd-guide/wcd-guide.html 46 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

filter and is the filter that invokes the target Web resource. If there are filters using <url-pattern> matching and the <url-pattern> matches the request URI according to the rules of mappings, the container builds the chain of <url-pattern> matched filters in the same order as declared in the deployment descriptor. The last filter in this chain is the last <url-pattern> matching filter in the deployment descriptor for this request URI. The last filter in this chain is the filter that invokes the first filter in the <servlet-name> matching chain, or invokes the target Web resource if there are none.

The order the container uses in building the chain of filters to be applied for a particular request URI is as follows: 1. First, the <url-pattern> matching filter mappings in the same order that these elements appear in the deployment descriptor. 2. Next, the <servlet-name> matching filter mappings in the same order that these elements appear in the deployment descriptor. Writing and configuring a filter. Filters are Java components that allow on the fly transformations of payload and header information in both the request into a resource and the response from a resource. Filters differ from Web components in that they usually do not themselves create a response. Instead, a filter provides functionality that can be "attached" to any kind of Web resource. As a consequence, a filter should not have any dependencies on a Web resource for which it is acting as a filter, so that it can be composable with more than one type of Web resource. A filter is a reusable piece of code that can transform the content of HTTP requests, responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource. Filters can act on dynamic or static content. The main tasks that a filter can perform are as follows:

Query the request and act accordingly. Block the request-and-response pair from passing any further. Modify the request headers and data. You do this by providing a customized version of the request. Modify the response headers and data. You do this by providing a customized version of the response. Interact with external resources.

You can configure a Web resource to be filtered by a chain of zero, one, or more filters in a specific order. This chain is specified when the Web application containing the component is deployed and is instantiated when a Web container loads the component. The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package.

http://java.boot.by/wcd-guide/wcd-guide.html 47 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

The application developer creates a filter by implementing the javax.servlet.Filter interface and providing a public constructor taking NO arguments. The class is packaged in the Web Archive along with the static content and servlets that make up the Web application. A filter is declared using the <filter> element in the deployment descriptor. A filter or collection of filters can be configured for invocation by defining <filter-mapping> elements in the deployment descriptor. This is done by mapping filters to a particular servlet by the servlet's logical name, or mapping to a group of servlets and static content resources by mapping a filter to a URL pattern.

package javax.servlet; public interface Filter { public void init(FilterConfig filterConfig) throws ServletException; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException; public void destroy(); }

The most important method in this interface is the doFilter method, which is passed request, response, and filter chain objects. This method can perform the following actions:

Examine the request headers. Customize the request object if it wishes to modify request headers or data. Customize the response object if it wishes to modify response headers or data. Invoke the next entity in the filter chain. If the current filter is the last filter in the chain that ends with the target Web component or static resource, the next entity is the resource at the end of the chain; otherwise, it is the next filter that was configured in the WAR. It invokes the next entity by calling the doFilter method on the chain object (passing in the request and response it was called with, or the wrapped versions it may have created). Alternatively, it can choose to block the request by not making the call to invoke the next entity. In the latter case, the filter is responsible for filling out the response. Examine response headers after it has invoked the next filter in the chain. Throw an exception to indicate an error in processing.

In addition to doFilter, you must implement the init and destroy methods. The init method is called by the container when the filter is instantiated. If you wish to pass initialization parameters to the filter, you retrieve them from the FilterConfig object passed to init. After deployment of the Web application, and before a request causes the container to access a Web resource, the container must locate the list of filters that must be applied to the Web resource as described below. The container must ensure that it has instantiated a filter of the appropriate class for each filter in the list, and called its init(FilterConfig config) method. The filter may throw an exception to indicate that it cannot function properly. If the exception is of type UnavailableException, the container may examine the isPermanent attribute of the exception and may choose to retry the filter at some later time.
http://java.boot.by/wcd-guide/wcd-guide.html 48 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Only ONE instance per <filter> declaration in the deployment descriptor is instantiated per Java Virtual Machine (JVM) of the container. The container provides the filter config as declared in the filter's deployment descriptor, the reference to the ServletContext for the Web application, and the set of initialization parameters. When the container receives an incoming request, it takes the first filter instance in the list and calls its doFilter method, passing in the ServletRequest and ServletResponse, and a reference to the FilterChain object it will use. The doFilter method of a filter will typically be implemented following this or some subset of the following pattern: 1. The method examines the request's headers. 2. The method may wrap the request object with a customized implementation of ServletRequest or HttpServletRequest in order to modify request headers or data. 3. The method may wrap the response object passed in to its doFilter method with a customized implementation of ServletResponse or HttpServletResponse to modify response headers or data. 4. The filter may invoke the next entity in the filter chain. The next entity may be another filter, or if the filter making the invocation is the last filter configured in the deployment descriptor for this chain, the next entity is the target Web resource. The invocation of the next entity is effected by calling the doFilter method on the FilterChain object, and passing in the request and response with which it was called or passing in wrapped versions it may have created. The filter chain's implementation of the doFilter method, provided by the container, must locate the next entity in the filter chain and invoke its doFilter method, passing in the appropriate request and response objects. Alternatively, the filter chain can block the request by not making the call to invoke the next entity, leaving the filter responsible for filling out the response object. After invocation of the next filter in the chain, the filter may examine response headers. Alternatively, the filter may have thrown an exception to indicate an error in processing. If the filter throws an UnavailableException during its doFilter processing, the container must not attempt continued processing down the filter chain. It may choose to retry the whole chain at a later time if the exception is not marked permanent. When the last filter in the chain has been invoked, the next entity accessed is the target servlet or resource at the end of the chain. Before a filter instance can be removed from service by the container, the container must first call the destroy method on the filter to enable the filter to release any resources and perform other cleanup operations.

5. 6.

7. 8.

public final class ExampleFilter implements Filter { private String attribute = null; private FilterConfig filterConfig = null;

http://java.boot.by/wcd-guide/wcd-guide.html 49 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.attribute = filterConfig.getInitParameter("attribute"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Store ourselves as a request attribute (if requested) if (attribute != null) { request.setAttribute(attribute, this); } // Time and log the subsequent processing long startTime = System.currentTimeMillis(); chain.doFilter(request, response); long stopTime = System.currentTimeMillis(); filterConfig.getServletContext().log (this.toString() + ": " + (stopTime - startTime) + " milliseconds"); } public void destroy() { this.attribute = null; this.filterConfig = null; } }

<web-app> ... <!-- Define servlet-mapped and path-mapped example filters --> <filter> <filter-name>Servlet Mapped Filter</filter-name> <filter-class>filters.ExampleFilter</filter-class> <init-param> <param-name>attribute</param-name> <param-value>filters.ExampleFilter.SERVLET_MAPPED</param-value> </init-param> </filter> <filter> <filter-name>Path Mapped Filter</filter-name>
http://java.boot.by/wcd-guide/wcd-guide.html 50 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<filter-class>filters.ExampleFilter</filter-class> <init-param> <param-name>attribute</param-name> <param-value>filters.ExampleFilter.PATH_MAPPED</param-value> </init-param> </filter> <!-- Define filter mappings for the defined filters --> <filter-mapping> <filter-name>Servlet Mapped Filter</filter-name> <servlet-name>invoker</servlet-name> </filter-mapping> <filter-mapping> <filter-name>Path Mapped Filter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping> ... </web-app>

Here is another example of a filter declaration:

<filter> <filter-name>Image Filter</filter-name> <filter-class>com.acme.ImageServlet</filter-class> </filter>

Once a filter has been declared in the deployment descriptor, the assembler uses the filtermapping element to define servlets and static resources in the Web application to which the filter is to be applied. Filters can be associated with a servlet using the servlet-name element. For example, the following code example maps the Image Filter filter to the ImageServlet servlet:

<filter-mapping> <filter-name>Image Filter</filter-name> <servlet-name>ImageServlet</servlet-name> </filter-mapping>

http://java.boot.by/wcd-guide/wcd-guide.html 51 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Filters can be associated with groups of servlets and static content using the url-pattern style of filter mapping:

<filter-mapping> <filter-name>Logging Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

Here the Logging Filter is applied to all the servlets and static content pages in the Web application, because every request URI matches the '/*' URL pattern. The url-pattern matching takes precedence (is applied first) over the servlet-name matching (is applied next).

<!-Declares a filter in the web application. The filter is mapped to either a servlet or a URL pattern in the filter-mapping element, using the filter-name value to reference. Filters can access the initialization parameters declared in the deployment descriptor at runtime via the FilterConfig interface. Used in: web-app --> <!ELEMENT filter (icon?, filter-name, display-name?, description?, filter-class, init-param*)>

<!-Declaration of the filter mappings in this web application. The container uses the filter-mapping declarations to decide which filters to apply to a request, and in what order. The container matches the request URI to a Servlet in the normal way. To determine which filters to apply it matches filter-mapping declarations either on servlet-name, or on url-pattern for each filter-mapping element, depending on which style is used. The order in which filters are invoked is the order in which filter-mapping declarations that match
http://java.boot.by/wcd-guide/wcd-guide.html 52 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

a request URI for a servlet appear in the list of filter-mapping elements.The filter-name value must be the value of the <filter-name> sub-elements of one of the <filter> declarations in the deployment descriptor. Used in: web-app --> <!ELEMENT filter-mapping (filter-name, (url-pattern | servlet-name), dispatcher*)>

The dispatcher has four legal values: FORWARD, REQUEST, INCLUDE, and ERROR. A value of FORWARD means the Filter will be applied under RequestDispatcher.forward() calls. A value of REQUEST means the Filter will be applied under ordinary client calls to the PATH or SERVLET. A value of INCLUDE means the Filter will be applied under RequestDispatcher.include() calls. A value of ERROR means the Filter will be applied under the error page mechanism. The absence of any dispatcher elements in a filter-mapping indicates a default of applying filters only under ordinary client calls to the PATH or SERVLET (REQUEST).

<filter-mapping> <filter-name>Logging Filter</filter-name> <url-pattern>/products/*</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping>

This example would result in the Logging Filter being invoked by client requests starting / products/... and underneath a request dispatcher forward() call where the request dispatcher has path commencing /products/.... Wrapping request and response objects. As well as performing basic pre and post processing operations a filter can also wrap up the request or response objects in a custom wrapper. Such custom wrappers can then modify the information provided to the servlet via a request object or process information generated by the servlet via the response object. There are four classes that make up the Wrapping API. These are the javax.servlet.ServletRequestWrapper, javax.servlet.ServletResponseWrapper, javax.servlet.http. HttpServletRequestWrapper and javax.servlet.http.HttpServletResponseWrapper. These classes implement the respective interfaces (e.g. ServletRequest, ServletResponse, HttpServletRequest and HttpServletResponse) and can thus be used anywhere that these interfaces are specified. Most notably they can therefore be used inside a Filter to wrap the actual request or response object
http://java.boot.by/wcd-guide/wcd-guide.html 53 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

up so that the filter can control either the data accessed by the Servlet (or JSP) or generated by the Servlet or JSP. A particular use of these wrappers is to perform some pre or post processing of the data being used or generated by the Servlet so that the Servlet does not need to know about this processing. A filter that modifies a response must usually capture the response before it is returned to the client. The way to do this is to pass a stand-in stream to the servlet that generates the response. The stand-in stream prevents the servlet from closing the original response stream when it completes and allows the filter to modify the servlet's response. To pass this stand-in stream to the servlet, the filter creates a response wrapper that overrides the getWriter or getOutputStream method to return this stand-in stream. The wrapper is passed to the doFilter method of the filter chain. Wrapper methods default to calling through to the wrapped request or response object. This approach follows the well-known Wrapper or Decorator pattern described in 'Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995)'. To override request methods, you wrap the request in an object that extends ServletRequestWrapper or HttpServletRequestWrapper. To override response methods, you wrap the response in an object that extends ServletResponseWrapper or HttpServletResponseWrapper. Example of filter with wrapper (post processing of servlet's output):

public final class HitCounterFilter implements Filter { private FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Counter counter = (Counter)filterConfig.getServletContext(). getAttribute("hitCounter"); writer.println(); writer.println("==============="); writer.println("The number of hits is: " + counter.incCounter()); writer.println("==============="); // Log the resulting string writer.flush(); filterConfig.getServletContext().log(sw.getBuffer().toString());

http://java.boot.by/wcd-guide/wcd-guide.html 54 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

PrintWriter out = response.getWriter(); CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse)response); chain.doFilter(request, wrapper); CharArrayWriter caw = new CharArrayWriter(); caw.write(wrapper.toString(). substring(0, wrapper.toString().indexOf("</body>")-1)); caw.write("<p>\n<center><center>" + messages.getString("Visitor") + "<font color='red'>" + counter.getCounter() + "</font><center>"); caw.write("\n</body></html>"); response.setContentLength(caw.toString().length()); out.write(caw.toString()); out.close(); } public void destroy() { this.filterConfig = null; } }

public class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; public String toString() { return output.toString(); } public CharResponseWrapper(HttpServletResponse response) { super(response); output = new CharArrayWriter(); } public PrintWriter getWriter() { return new PrintWriter(output); } }

HitCounterFilter wraps the response in a CharResponseWrapper. The wrapped response is passed to the next object in the filter chain. Next servlet writes (buffers) its response into the stream created by CharResponseWrapper. When chain.doFilter returns, HitCounterFilter retrieves the
http://java.boot.by/wcd-guide/wcd-guide.html 55 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

servlet's response from PrintWriter and writes it to a buffer (CharArrayWriter). The filter inserts the value of the counter into the buffer, resets the content length header of the response, and finally writes the contents of the buffer to the response stream.

Describe the Web container life cycle event model for requests, sessions, and web applications; create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use.
The application events facility gives the Web Application Developer greater control over the lifecycle of the ServletContext and HttpSession and ServletRequest, allows for better code factorization, and increases efficiency in managing the resources that the Web application uses. Application event listeners are classes that implement one or more of the servlet event listener interfaces. They are instantiated and registered in the Web container at the time of the deployment of the Web application. They are provided by the Developer in the WAR. Servlet event listeners support event notifications for state changes in the ServletContext, HttpSession and ServletRequest objects. Servlet context listeners are used to manage resources or state held at a JVM level for the application. HTTP session listeners are used to manage state or resources associated with a series of requests made into a Web application from the same client or user. Servlet request listeners are used to manage state across the lifecycle of servlet requests. There may be multiple listener classes listening to each event type, and the Developer may specify the order in which the container invokes the listener beans for each event type. Servlet Context Events and Listeners. Implementations of the following interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application. All ServletContextListeners are notified of context initialization before any filter or servlet in the web application is initialized. All servlets and filters have been destroyed before any ServletContextListeners are notified of context destruction.

package javax.servlet; public interface ServletContextListener extends java.util.EventListener { public void contextDestroyed(ServletContextEvent sce); public void contextInitialized(ServletContextEvent sce); }
http://java.boot.by/wcd-guide/wcd-guide.html 56 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

This is the event class for notifications about changes to the servlet context of a web application:

package javax.servlet; public class ServletContextEvent extends java.util.EventObject { public ServletContext getServletContext(); }

Implementations of the following interface receive notifications of changes to the attribute list on the servlet context of a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

attributeAdded notifies that a new attribute was added to the servlet context. Called after the attribute is added. attributeRemoved notifies that an existing attribute has been removed from the servlet context. Called after the attribute is removed. attributeReplaced( notifies that an attribute on the servlet context has been replaced. Called after the attribute is replaced.

package javax.servlet; public interface ServletContextAttributeListener extends java.util.EventListener { public void attributeAdded(ServletContextAttributeEvent scae); public void attributeRemoved(ServletContextAttributeEvent scae); public void attributeReplaced(ServletContextAttributeEvent scae); }

This is the event class for notifications about changes to the attributes of the servlet context of a web application:

package javax.servlet; public class ServletContextAttributeEvent extends javax.servlet.ServletContextEvent { public java.lang.String getName();
http://java.boot.by/wcd-guide/wcd-guide.html 57 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

public java.lang.Object getValue(); }

HTTP Session Events and Listeners. Implementations of the following interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

package javax.servlet.http; public interface HttpSessionListener extends java.util.EventListener { public void sessionCreated(HttpSessionEvent hse); public void sessionDestroyed(HttpSessionEvent hse); }

This is the class representing event notifications for changes to sessions within a web application:

package javax.servlet.http; public class HttpSessionEvent extends java.util.EventObject { public HttpSession getSession(); }

Following listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application:

attributeAdded notifies that a new attribute was added to the session. Called after the attribute is added. attributeRemoved notifies that an existing attribute has been removed from the session. Called after the attribute is removed. attributeReplaced notifies that an attribute has been replaced in the session. Called after the attribute is replaced.

http://java.boot.by/wcd-guide/wcd-guide.html 58 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

package javax.servlet.http; public interface HttpSessionAttributeListener extends java.util.EventListener { public void attributeAdded(HttpSessionBindingEvent hsbe); public void attributeRemoved(HttpSessionBindingEvent hsbe); public void attributeReplaced(HttpSessionBindingEvent hsbe); }

Events of the following type are either sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the deployment descriptor when any attribute is bound, unbound or replaced in a session. The session binds the object by a call to HttpSession.setAttribute and unbinds the object by a call to HttpSession.removeAttribute. The getValue function returns the value of the attribute that has been added, removed or replaced. If the attribute was added (or bound), this is the value of the attribute. If the attribute was removed (or unbound), this is the value of the removed attribute. If the attribute was replaced, this is the OLD value of the attribute.

package javax.servlet.http; public class HttpSessionBindingEvent extends javax.servlet.http.HttpSessionEvent { public java.lang.String getName(); public HttpSession getSession(); public java.lang.Object getValue(); // returns : // new value for added (bounded) attributes, // old value for replaced and removed (unbounded) attributes }

When container migrates a session between VMs in a distributed container setting, all session attributes implementing the HttpSessionActivationListener interface are notified. Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.

package javax.servlet.http; public interface HttpSessionActivationListener extends java.util.EventListener {


http://java.boot.by/wcd-guide/wcd-guide.html 59 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

public void sessionDidActivate(HttpSessionEvent hse); public void sessionWillPassivate(HttpSessionEvent hse); }

The following interface causes an OBJECT to be notified when it is bound to or unbound from a session. The object is notified by an HttpSessionBindingEvent object. This may be as a result of a servlet programmer explicitly unbinding an attribute from a session, due to a session being invalidated, or due to a session timing out.

package javax.servlet.http; public interface HttpSessionBindingListener extends java.util.EventListener { public void valueBound(HttpSessionBindingEvent hsbe); public void valueUnbound(HttpSessionBindingEvent hsbe); }

Servlet Request Events and Listeners. A ServletRequestListener can be implemented by the developer interested in being notified of requests coming in and out of scope in a web component. A request is defined as coming into scope when it is about to enter the first servlet or filter in each web application, as going out of scope when it exits the last servlet or the first filter in the chain.

package javax.servlet; public interface ServletRequestListener { requestInitialized(ServletRequestEvent sre); requestDestroyed(ServletRequestEvent sre); }

Events of this kind indicate lifecycle events for a ServletRequest. The source of the event is the ServletContext of this web application.

package javax.servlet;

http://java.boot.by/wcd-guide/wcd-guide.html 60 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

public class ServletRequestEvent extends java.util.EventObject { public ServletRequest getServletRequest(); public ServletContext getServletContext(); }

A ServletRequestAttributeListener can be implemented by the developer interested in being notified of request attribute changes. Notifications will be generated while the request is within the scope of the web application in which the listener is registered. A request is defined as coming into scope when it is about to enter the first servlet or filter in each web application, as going out of scope when it exits the last servlet or the first filter in the chain.

package javax.servlet; public interface ServletRequestAttributeListener { public void attributeAdded(ServletRequestAttributeEvent srae); public void attributeRemoved(ServletRequestAttributeEvent srae); public void attributeReplaced(ServletRequestAttributeEvent srae); }

The following is the event class for notifications of changes to the attributes of ServletRequest in an application. The getValue() function returns the value of the attribute that has been added, removed or replaced. If the attribute was added, this is the value of the attribute. If the attribute was removed, this is the value of the REMOVED attribute. If the attribute was replaced, this is the OLD value of the attribute.

package javax.servlet; public class ServletRequestAttributeEvent extends ServletRequestEvent { public java.lang.String getName(); public java.lang.Object getValue(); }

Table 3.1. Events and Listener Interfaces

http://java.boot.by/wcd-guide/wcd-guide.html 61 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Scope

Event Initialization and destruction Attribute added, removed, or replaced Created and destroyed Activated and passivated (migrated)

Listener Interface and Event Class ServletContextListener, ServletContextEvent ServletContextAttributeListener, ServletContextAttributeEvent HttpSessionListener, HttpSessionEvent HttpSessionActivationListener, HttpSessionEvent HttpSessionAttributeListener, HttpSessionBindingEvent (note the class name !) HttpSessionBindingListener (note, interface must be implemented by attribute class !), HttpSessionBindingEvent ServletRequestListener, ServletRequestEvent ServletRequestAttributeListener, ServletRequestAttributeEvent

Servlet Context

HTTP Session

Attribute added, removed, or replaced Object bound or unbound Initialized and destroyed Attribute added, removed, or replaced

Servlet Request

The Developer of the Web application provides listener classes implementing one or more of the listener classes in the servlet API. Each listener class must have a public constructor taking NO arguments. The listener classes are packaged into the WAR, either under the WEB-INF/classes archive entry, or inside a JAR in the WEB-INF/lib directory. Listener classes are declared in the Web application deployment descriptor using the listener element. They are listed by class name in the order in which they are to be invoked. During Web application execution, listeners are invoked in the order of their registration. On application shutdown, listeners are notified in REVERSE order to their declarations with notifications to session listeners preceeding notifications to context listeners. Session listeners must be notified of session invalidations prior to context listeners being notified of application shutdown.

<web-app> ... <listener> <listener-class>listeners.ContextListener</listener-class> </listener> ... </web-app>

http://java.boot.by/wcd-guide/wcd-guide.html 62 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

In distributed Web containers, HttpSession instances are scoped to the particular JVM servicing session requests, and the ServletContext object is scoped to the Web container's JVM. Distributed containers are not required to propagate either servlet context events or HttpSession events to other JVMs. Listener class instances are scoped to one per deployment descriptor declaration per Java Virtual Machine.

Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource.
RequestDispatcher description. RequestDispatcher defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. An object implementing the RequestDispatcher interface may be obtained via the following methods:

ServletContext.getRequestDispatcher(String path) ServletContext.getNamedDispatcher(String name) ServletRequest.getRequestDispatcher(String path)

The ServletContext.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 and begin with a '/'. The method uses the path to look up a servlet, using the servlet path matching rules, wraps it with a RequestDispatcher object, and returns the resulting object. If no servlet can be resolved based on the given path, a RequestDispatcher is provided that returns the content for that path. The ServletContext.getNamedDispatcher method takes a String argument indicating the NAME of a servlet known to the ServletContext. If a servlet is found, it is wrapped with a RequestDispatcher object and the object is 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 that are relative to the path of the current request (not relative to the root of the ServletContext), the ServletRequest. getRequestDispatcher method is provided in the ServletRequest interface. The behavior of this method is similar to the method of the same name in the ServletContext. The servlet container uses information in the request object to transform the given relative path against the current
http://java.boot.by/wcd-guide/wcd-guide.html 63 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

servlet to a complete path. For example, in a context rooted at '/' and 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"). RequestDispatcher creation and using.

public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { RequestDispatcher dispatcher = request.getRequestDispatcher("/template.jsp"); if (dispatcher != null) dispatcher.forward(request, response); } }

forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner"); if (dispatcher != null) dispatcher.include(request, response); } }

Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes. The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

package javax.servlet; public interface RequestDispatcher { public void forward(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException; public void include(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException; }
http://java.boot.by/wcd-guide/wcd-guide.html 64 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

The include method of the RequestDispatcher interface may be called at ANY time. The target servlet of the include method has access to all aspects of the request object, but its use of the response object is more limited. It can only write information to the ServletOutputStream or Writer of the response object and commit a response by writing content past the end of the response buffer, or by explicitly calling the flushBuffer method of the ServletResponse interface. It CANNOT set headers or call any method that affects the headers of the response. Any attempt to do so must be ignored. The forward method of the RequestDispatcher interface may be called by the calling servlet ONLY when NO output has been committed to the client. If output data exists in the response buffer that has not been committed, the content must be cleared 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 must reflect those of the original request. Before the forward method of the RequestDispatcher interface returns, the response content MUST be sent and committed, and closed by the servlet container. The ServletContext and ServletRequest methods that create RequestDispatcher objects using path information allow the optional attachment of query string information to the path. For example, a Developer may obtain a RequestDispatcher by using the following code:

String path = "/raisins.jsp?orderno=5"; RequestDispatcher rd = context.getRequestDispatcher(path); rd.include(request, response);

Parameters specified in the query string used to create the RequestDispatcher take precedence over other parameters of the same name passed to the included servlet. The parameters associated with a RequestDispatcher are scoped to apply only for the duration of the include or forward call. Additional request-scoped attributes. Except for servlets obtained by using the getNamedDispatcher method, a servlet that has been invoked by another servlet using the include method of RequestDispatcher has access to the path by which it was invoked. The following request attributes must be set:

http://java.boot.by/wcd-guide/wcd-guide.html 65 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide


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 request object and their values must be equal to the request URI, context path, servlet path, path info, and query string of the INCLUDED servlet, respectively. If the request is subsequently included, these attributes are replaced for that include. If the included servlet was obtained by using the getNamedDispatcher method, these attributes MUST NOT be set. Except for servlets obtained by using the getNamedDispatcher method, a servlet that has been invoked by another servlet using the forward method of RequestDispatcher has access to the path of the ORIGINAL request. The following request attributes must be set:

javax.servlet.forward.request_uri javax.servlet.forward.context_path javax.servlet.forward.servlet_path javax.servlet.forward.path_info javax.servlet.forward.query_string

The values of these attributes must be equal to the return values of the HttpServletRequest methods getRequestURI, getContextPath, getServletPath, getPathInfo, getQueryString respectively, invoked on the request object passed to the first servlet object in the call chain that received the request from the client. These attributes are accessible from the forwarded servlet via the getAttribute method on the request object. Note that these attributes must always reflect the information in the original request even under the situation that multiple forwards and subsequent includes are called. If the forwarded servlet was obtained by using the getNamedDispatcher method, these attributes must not be set.

Chapter 4. Session Management

Write servlet code to store objects into a session object and retrieve objects from a session object.
Sessions are represented by an HttpSession object. You access a session by calling the
http://java.boot.by/wcd-guide/wcd-guide.html 66 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

HttpServletRequest.getSession() or HttpServletRequest.getSession(boolean) method of a request object. This method returns the current session associated with this request, or, if the request does not have a session, it creates one (unless boolean argument is false). You can associate object-valued attributes with a session by name. Such attributes are accessible by any Web component that belongs to the same Web context and is handling a request that is part of the same session. For example, you can save shopping cart as a session attribute. This allows the shopping cart to be saved between requests and also allows cooperating servlets to access the cart. Some servlet adds items to the cart; another servlet displays, deletes items from, and clears the cart; and next servlet retrieves the total cost of the items in the cart.

public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal(); ... } }

package javax.servlet.http; public interface HttpSession { public java.lang.Object getAttribute(java.lang.String name); public java.util.Enumeration getAttributeNames(); public void removeAttribute(java.lang.String name); public void setAttribute(java.lang.String name, java.lang.Object value); }

Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed.
http://java.boot.by/wcd-guide/wcd-guide.html 67 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

A session is considered 'new' when it is only a prospective session and has not been established. Because HTTP is a request-response based protocol, an HTTP session is considered to be new until a client 'joins' it. A client joins a session when session tracking information has been 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 a 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.

These conditions define the situation where the servlet container has no mechanism by which to associate a request with a previous request. To obtain a session, use the getSession() or getSession(boolean) method of the javax.servlet.http. HttpServletRequest object. When you first obtain the HttpSession object, the one of three ways used to establish tracking of the session: cookies, URL rewriting, or Secure Sockets Layer (SSL) information. Assume the servlet container uses cookies. In such a case the servlet container creates a unique session ID and typically sends it back to the browser as a cookie. Each subsequent request from this user (at the same browser) passes the cookie containing the session ID, and the servlet container uses this ID to find the user's existing HttpSession object. If argument in getSession(boolean) method is set to true, the HttpSession object is created if it does not already exist (the same as call of getSession() method). If argument in getSession(boolean) method is set to false, the HttpSession object is NOT created if it does not already exist and method returns null. You can end a session:

Automatically by servlet container if a session is inactive for a specified time. The administrators provide a way to specify the amount of time after which to invalidate a session. By coding the servlet to call the HttpSession.invalidate() method on the session object.

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 int HttpSession.getMaxInactiveInterval() (sec.) method of the HttpSession interface. This timeout can be changed by the Developer using the HttpSession.setMaxInactiveInterval(int) (sec.) method of the HttpSession interface. The timeout periods used by these methods are defined in SECONDS. By definition, if the timeout period for a session is set to -1 (or ANY NEGATIVE), the

http://java.boot.by/wcd-guide/wcd-guide.html 68 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

session will never expire. The session invalidation will not take effect until all servlets using that session have exited the service method. Once the session invalidation is initiated, a new request must not be able to see that session.

package javax.servlet.http; public interface HttpSession { public int getMaxInactiveInterval(); public void setMaxInactiveInterval(int interval); public void invalidate(); public boolean isNew(); }

Another way to configure session timeout (for all sessions within one web-application) is to use deployment descriptor (web.xml). 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. If the timeout is 0 or less, the container ensures the default behaviour of sessions is NEVER to time out. If this element is not specified, the container must set its default timeout period.

<web-app> ... <session-config> <session-timeout>30</session-timeout> <!-- 30 minutes --> </session-config> </web-app>

Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another.
Object is added to session. Listener notification.

package listeners; import javax.servlet.http.HttpSessionAttributeListener;


http://java.boot.by/wcd-guide/wcd-guide.html 69 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

import javax.servlet.http.HttpSessionBindingEvent; public final class SessionListener implements HttpSessionAttributeListener { public void attributeAdded(HttpSessionBindingEvent event) { System.out.println("attributeAdded"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } public void attributeRemoved(HttpSessionBindingEvent event) { System.out.println("attributeRemoved"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } public void attributeReplaced(HttpSessionBindingEvent event) { System.out.println("attributeReplaced"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } }

<web-app> ... <listener> <listener-class>listeners.SessionListener</listener-class> </listener> </web-app>

Object is added to session. Object notification.

package beans; import javax.servlet.http.HttpSessionBindingListener; import javax.servlet.http.HttpSessionBindingEvent; public class CounterBean implements HttpSessionBindingListener { private int count = 1;
http://java.boot.by/wcd-guide/wcd-guide.html 70 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

public int getValue() { return count; } public void increment() { count++; } public void valueBound(HttpSessionBindingEvent event) { System.out.println("attributeBounded"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } public void valueUnbound(HttpSessionBindingEvent event) { System.out.println("attributeUnbounded"); System.out.println(event.getSession().getId()); System.out.println(event.getName() + "', '" + event.getValue()); } }

Note, you don't need to (and must not) configure HttpSessionBindingListener in the deployment descriptor, just make a class implementing this interface. Object migrates from one VM to another. Object notification.

package beans; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionEvent; public class CounterBean implements HttpSessionActivationListener { private int count = 1; public int getValue() { return count; } public void increment() { count++; }

http://java.boot.by/wcd-guide/wcd-guide.html 71 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

public void sessionWillPassivate(HttpSessionEvent se) { System.out.println("session is about to be passivated"); // save counter's value to persistent storage .... } public void sessionDidActivate(HttpSessionEvent se) { System.out.println("session has just been activated"); // retrieve counter's value from persistent storage .... } }

Note, you don't need to (and must not) configure HttpSessionActivationListener in the deployment descriptor, just make a class implementing this interface.

Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting.
The following approaches are using for tracking a user's sessions:

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' (uppercase !).

Set-Cookie: JSESSIONID=49EBBB19A1B2F8D10EE075F6F14CB8C9; Path=/

SSL Sessions Secure Sockets Layer, the encryption technology used in the HTTPS protocol, has a builtin mechanism allowing multiple requests from a client to be unambiguously identified as being part of a session. A servlet container can easily use this data to define a session. URL Rewriting URL rewriting is the lowest common denominator of session tracking. When a client will

http://java.boot.by/wcd-guide/wcd-guide.html 72 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

not accept a cookie, URL rewriting may be used by the server as the basis for session tracking. URL rewriting involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session. The session ID must be encoded as a path parameter in the URL string. The name of the parameter must be 'jsessionid' (lowercase !). Here is an example of a URL containing encoded path information:

http://www.myserver.com/catalog/index.html; jsessionid=1234

package javax.servlet.http; public interface HttpSession { public boolean isRequestedSessionIdFromCookie(); public boolean isRequestedSessionIdFromURL(); public boolean isRequestedSessionIdValid(); }

There are 2 methods in the HttpServletResponse for URL rewriting:

encodeURL(String) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary. For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies. encodeRedirectURL(String) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. Because the rules for making this determination can differ from those used to decide whether to encode a normal link, this method is separated from the encodeURL method. All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

http://java.boot.by/wcd-guide/wcd-guide.html 73 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

package javax.servlet.http; public interface HttpServletResponse extends javax.servlet.ServletResponse { public java.lang.String encodeURL(java.lang.String url); public java.lang.String encodeRedirectURL(java.lang.String url) }

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ... out.print("<form action='"); out.print(response.encodeURL("SessionExample")); out.print("' "); out.println("method='post'>"); }

Chapter 5. Web Application Security

Based on the servlet specification, compare and contrast the following security mechanisms: (a) authentication, (b) authorization, (c) data integrity, and (d) confidentiality.
Authentication. Authentication means by which communicating entities prove to one another that they are acting on behalf of specific identities that are authorized for access. Authentication is any process by which you verify that someone is who they claim they are. This usually involves a username and a password, but can include any other method of demonstrating identity, such as a smart card, retina scan, voice recognition, or fingerprints. Authentication is equivalent to showing your drivers license at the ticket counter at the airport. Authorization (access control for resources).

http://java.boot.by/wcd-guide/wcd-guide.html 74 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Authorization means by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints. Authorization is finding out if the person, once identified, is permitted to have the resource. This is usually determined by finding out if that person is a part of a particular group, if that person has paid admission, or has a particular level of security clearance. Authorization is equivalent to checking the guest list at an exclusive party, or checking for your ticket when you go to the opera. Data Integrity. Data integrity means used to prove that information has not been modified by a third party while in transit. Confidentiality (Data Privacy). Confidentiality means used to ensure that information is made available only to users who are authorized to access it.

In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role.
Specifying Security Constraints. Security constraints are a declarative way of defining the protection of web content. A security constraint associates authorization and or user data constraints with HTTP operations on web resources. A security constraint, which is represented by security-constraint in deployment descriptor, consists of the following elements:

web resource collection (web-resource-collection in deployment descriptor) authorization constraint (auth-constraint in deployment descriptor) user data constraint (user-data-constraint in deployment descriptor)

A security constraint that does not contain an authorization constraint shall combine with authorization constraints that name or imply roles to allow unauthenticated access. The special case of an authorization constraint that names NO roles shall combine with any other constraints to OVERRIDE their affects and cause access to be PRECLUDED. The HTTP operations and web resources to which a security constraint applies (i.e. the constrained requests) are identified by one or more web resource collections. A web resource collection consists of the following elements:

URL patterns (url-pattern in deployment descriptor) HTTP methods (http-method in deployment descriptor)

http://java.boot.by/wcd-guide/wcd-guide.html 75 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

An authorization constraint establishes a requirement for authentication and names the authorization roles permitted to perform the constrained requests. A user must be a member of at least one of the named roles to be permitted to perform the constrained requests. The special role name '*' is a shorthand for all role names defined in the deployment descriptor. An authorization constraint that names NO roles indicates that access to the constrained requests MUST NOT be permitted under any circumstances. An authorization constraint consists of the following element:

role name (role-name in deployment descriptor)

A user data constraint establishes a requirement that the constrained requests be received over a protected transport layer connection. The strength of the required protection is defined by the value of the transport guarantee. A transport guarantee of INTEGRAL is used to establish a requirement for content integrity and a transport guarantee of CONFIDENTIAL is used to establish a requirement for confidentiality. The transport guarantee of NONE indicates that the container must accept the constrained requests when received on any connection including an unprotected one. A user data constraint consists of the following element:

transport guarantee (transport-guarantee in deployment descriptor)

If no authorization constraint applies to a request, the container must accept the request without requiring user authentication. If no user data constraint applies to a request, the container must accept the request when received over any connection including an unprotected one.

<security-constraint> <web-resource-collection> <web-resource-name>restricted methods</web-resource-name> <url-pattern>/*</url-pattern> <url-pattern>/acme/wholesale/*</url-pattern> <url-pattern>/acme/retail/*</url-pattern> <http-method>DELETE</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint/> </security-constraint>

'/*' DELETE access precluded '/*' PUT access precluded

http://java.boot.by/wcd-guide/wcd-guide.html 76 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

'/acme/wholesale/*' DELETE access precluded

<security-constraint> <web-resource-collection> <web-resource-name>wholesale</web-resource-name> <url-pattern>/acme/wholesale/*</url-pattern> <http-method>GET</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint> <role-name>SALESCLERK</role-name> </auth-constraint> </security-constraint>

'/acme/wholesale/*' GET SALESCLERK

<security-constraint> <web-resource-collection> <web-resource-name>wholesale</web-resource-name> <url-pattern>/acme/wholesale/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>CONTRACTOR</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint>

'/acme/wholesale/*' POST CONTRACTOR CONFIDENTIAL

<!-The security-constraint element is used to associate security constraints with one or more web resource collections

http://java.boot.by/wcd-guide/wcd-guide.html 77 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

Used in: web-app --> <!ELEMENT security-constraint (display-name?, web-resource-collection+, auth-constraint?, user-data-constraint?)>

Web resource.

<!-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. Used in: security-constraint --> <!ELEMENT web-resource-collection (web-resource-name, description?, url-pattern*, http-method*)>

Transport guarantee.

<!-The user-data-constraint element is used to indicate how data communicated between the client and container should be protected. Used in: security-constraint --> <!ELEMENT user-data-constraint (description?, transport-guarantee)>

Login configuration.

http://java.boot.by/wcd-guide/wcd-guide.html 78 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<!-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. Used in: web-app --> <!ELEMENT login-config (auth-method?, realm-name?, form-login-config?)>

<!-- login configuration uses form-based authentication --> <login-config> <auth-method>FORM</auth-method> <realm-name>Form-Based Authentication Area</realm-name> <form-login-config> <form-login-page>/protected/login.jsp</form-login-page> <form-error-page>/protected/error.jsp</form-error-page> </form-login-config> </login-config>

Security role.

<!-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: web-app Example: <security-role> <description> This role includes all employees who are authorized to access the employee service application. </description>
http://java.boot.by/wcd-guide/wcd-guide.html 79 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<role-name>employee</role-name> </security-role> --> <!ELEMENT security-role (description?, role-name)>

<!-- Security roles referenced by web application --> <security-role> <role-name>user</role-name> </security-role> <security-role> <role-name>admin</role-name> </security-role>

Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENTCERT); describe how the type works; and given a scenario, select an appropriate type.
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

HTTP Basic Authentication. HTTP Basic Authentication, which is based on a username and password, is the authentication mechanism defined in the HTTP/1.0 specification. A web server requests a web client to authenticate the user. As part of the request, the web server passes the realm (a string) in which the user is to be authenticated. The realm string of Basic Authentication does not have to reflect any particular security policy domain (confusingly also 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. User passwords are sent in simple base64 ENCODING (not ENCRYPTED !), and the target server is not authenticated. Additional protection can alleviate some of these concerns: a secure transport mechanism (HTTPS), or security at the network level (such as the IPSEC protocol or VPN strategies) is applied in some deployment scenarios.
http://java.boot.by/wcd-guide/wcd-guide.html 80 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<web-app> <security-constraint> <web-resource-collection> <web-resource-name>User Auth</web-resource-name> <url-pattern>/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>manager</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>User Auth</realm-name> </login-config> <security-role> <role-name>admin</role-name> </security-role> <security-role> <role-name>manager</role-name> </security-role> </web-app>

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, e.g. HTTPS Client Authentication. As Digest Authentication is not currently in widespread use, servlet containers are encouraged but NOT REQUIRED to support it. The advantage of this method is that the cleartext password is protected in transmission, it cannot be determined from the digest that is submitted by the client to the server. Digested password authentication supports the concept of digesting user passwords. This causes the stored version of the passwords to be encoded in a form that is not easily reversible, but that the Web server can still utilize for authentication. From a user perspective, digest authentication acts almost identically to basic authentication in that it triggers a login dialog. The difference between basic and digest authentication is that on the network connection
http://java.boot.by/wcd-guide/wcd-guide.html 81 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

between the browser and the server, the password is encrypted, even on a non-SSL connection. In the server, the password can be stored in clear text or encrypted text, which is true for all login methods and is independent of the choice that the application deployer makes.

<web-app> <security-constraint> <web-resource-collection> <web-resource-name>User Auth</web-resource-name> <url-pattern>/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>manager</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>DIGEST</auth-method> <realm-name>User Auth</realm-name> </login-config> <security-role> <role-name>admin</role-name> </security-role> <security-role> <role-name>manager</role-name> </security-role> </web-app>

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 a single-sign-on from within the browser. Servlet containers that are not J2EE technology compliant are not required to support the HTTPS protocol. Client-certificate authentication is a more secure method of authentication than either BASIC or FORM authentication. It uses HTTP over SSL, in which the server and, optionally, the client authenticate one another with Public Key Certificates. Secure Sockets Layer (SSL) provides data encryption, server authentication, message integrity, and optional client authentication for a TCP/IP connection. You can think of a public key certificate as the digital equivalent of a

http://java.boot.by/wcd-guide/wcd-guide.html 82 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

passport. It is issued by a trusted organization, which is called a certificate authority (CA), and provides identification for the bearer. If you specify client-certificate authentication, the Web server will authenticate the client using the client's X.509 certificate, a public key certificate that conforms to a standard that is defined by X.509 Public Key Infrastructure (PKI). Prior to running an application that uses SSL, you must configure SSL support on the server and set up the public key certificate.

<web-app> <security-constraint> <web-resource-collection> <web-resource-name>User Auth</web-resource-name> <url-pattern>/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>manager</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>CLIENT-CERT</auth-method> <realm-name>User Auth</realm-name> </login-config> <security-role> <role-name>admin</role-name> </security-role> <security-role> <role-name>manager</role-name> </security-role> </web-app>

Form Based Authentication. The look and feel of the 'login screen' cannot be varied using the web browser's built-in authentication mechanisms. This specification introduces a required 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. The login form must contain fields for entering a username and a password. These fields must be named j_username and j_password, respectively.

http://java.boot.by/wcd-guide/wcd-guide.html 83 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

When a user attempts to access a protected web resource, the container checks the user's authentication. If the user is authenticated and possesses authority to access the resource, the requested web resource is activated and a reference to it is returned. If the user is not authenticated, all of the following steps occur: 1. The login form associated with the security constraint is sent to the client and the URL path triggering the authentication is stored by the container. 2. The user is asked to fill out the form, including the username and password fields. 3. The client posts the form back to the server. 4. The container attempts to authenticate the user using the information from the form. 5. If authentication fails, the error page is returned using either a forward or a redirect, and the status code of the response is set to 200. 6. If authentication succeeds, the authenticated user's principal is checked to see if it is in an authorized role for accessing the resource. 7. If the user is authorized, the client is redirected to the resource using the stored URL path. The error page sent to a user that is not authenticated contains information about the failure. Form Based Authentication has the same lack of security as Basic Authentication since the user password is transmitted as plain text and the target server is not authenticated. Again additional protection can alleviate some of these concerns: a secure transport mechanism (HTTPS), or security at the network level (such as the IPSEC protocol or VPN strategies) is applied in some deployment scenarios. Form based login and URL based session tracking can be problematic to implement. Form based login should be used only when sessions are 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 work no matter which resource it is for, and to avoid requiring the server to specify the action field of the outbound form. Here is an example 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>

http://java.boot.by/wcd-guide/wcd-guide.html 84 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

<web-app> <security-constraint> <web-resource-collection> <web-resource-name>User Auth</web-resource-name> <url-pattern>/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>manager</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>FORM</auth-method> <realm-name>User Auth</realm-name> <form-login-config> <form-login-page>login.jsp</form-login-page> <form-error-page>error.jsp</form-error-page> </form-login-config> </login-config> <security-role> <role-name>admin</role-name> </security-role> <security-role> <role-name>manager</role-name> </security-role> </web-app>

Chapter 6. The JavaServer Pages (JSP) Technology Model

Identify, describe, or write the JSP code for the following elements: (a) template text, (b) scripting elements (comments, directives, declarations, scriptlets, and expressions), (c) standard and custom actions, and (d) expression language elements.
Template text. 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 Quoting and Escape Conventions.

http://java.boot.by/wcd-guide/wcd-guide.html 85 / 166 2004/6/13 12:08:15

SCWCD 1.4 Study Guide

XML syntax:

<jsp:text> hi you all </jsp:text>

Quoting in Template Text:


A literal <% is quoted by <\% Only when the EL is enabled for a page, a literal $ can be quoted by \$. This is not required but is useful for quoting EL expressions.

Scripting elements. Scripting elements are commonly used to manipulate objects and to perform computation that affects the content generated. Disabling scripting elements can be done by setting the scripting-invalid element to true in the JSP configuration. For example, the following web.xml fragment defines a group that disables scripting elements for all JSP pages delivered using the .jsp extension:

<jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group>

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. Scriptlets 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 inserted into the output stream. Each scripting element has a <%-based syntax as follows:

http://java.boot.by/wcd-guide/wcd-guide.html 86 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

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

White space is optional after <%!, <%, and <%=, and before %>. XML syntax:

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

Declarations. Declarations are used to declare VARIABLES and METHODS in the scripting language used in a JSP page. A declaration must 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. For example, the following declaration below declares an integer, global to the page:

<%! int i; %>

The following declaration does the same and initializes it to zero. This type of initialization should be done with care in the presence of multiple requests on the page:

<%! int i = 0; %>

The next declaration declares a method GLOBAL to the page:

http://java.boot.by/wcd-guide/wcd-guide.html 87 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<%! public String someMethod(int i) { if (i<3) return("..."); ... } %>

Scriptlets. Scriptlets can contain any code fragments that are valid for the scripting language specified in the language attribute of the page directive. Scriptlets are executed at request-processing time. Whether or not they produce any output into the out stream depends on the code in the scriptlet. Scriptlets CAN have side-effects, modifying the objects visible to them. When all scriptlet fragments in a given translation unit are combined in the order they appear in the JSP page, they must yield a valid statement, or sequence of statements, in the specified scripting language. Here is a simple example where the page changed dynamically depending on the time of day.

<% if (Calendar.getInstance().get(Calendar.AM_PM) == Calendar.AM) {%> Good Morning <% } else { %> Good Afternoon <% } %>

A scriptlet can also have a LOCAL variable declaration, for example the following scriptlet just declares and initializes an integer, and later increments it.

<% int i; i= 0; %> About to increment i... <% i++; %>

http://java.boot.by/wcd-guide/wcd-guide.html 88 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

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

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

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

<!-- HTML comments ... -->

These comments are treated as uninterpreted template text by the JSP container. Dynamic content that appears within HTML/XML comments, such as actions, scriptlets and expressions, is
http://java.boot.by/wcd-guide/wcd-guide.html 89 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

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

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

A JSP comment is of the form:

<%-- page code comments --%>

The body of the content is ignored completely. Comments are useful for documentation but also are used to 'comment out' some portions of a JSP page. Note that JSP comments do not nest. An alternative way to place a comment in JSP is to use the comment mechanism of the scripting language. For example:

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

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

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

There may be optional white space after the <%@ and before %>. Directives DO NOT produce any output into the current out stream. There are three directives: the page, the taglib and the include. The page Directive.
http://java.boot.by/wcd-guide/wcd-guide.html 90 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

The page directive defines a number of page dependent properties and communicates these to the JSP container. This <jsp:directive.page> element describes the same information following the XML syntax. 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). An exception to this position independence is the use of the pageEncoding and contentType attributes in the determination of the page character encoding; for this purpose, they should appear at the beginning of the page. There shall be ONLY ONE occurrence of any attribute/value pair defined by this directive in a given translation unit, unless the values for the duplicate attributes are IDENTICAL for all occurrences. The import and pageEncoding attributes are exempt from this rule and can appear multiple times. Multiple uses of the import attribute are cumulative (with ordered set union semantics). The pageEncoding attribute can occur at most once per file (or a translation error will result), and applies only to the file in which it appears. Other such multiple attribute/value (re) definitions result in a fatal translation error if the values do not match. The following directive provides some user-visible information on this JSP page:

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

The following directive requests no buffering, and provides an error page.

<%@ page buffer="none" errorPage="/oops.jsp" %>

The following directive indicates that the scripting language is based on Java, that the types declared in the package com.myco are directly available to the scripting code, and that a buffering of 16KB should be used.

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

http://java.boot.by/wcd-guide/wcd-guide.html 91 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<%@ 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" } { pageEncoding="peinfo" } { isELIgnored="true|false" }

The taglib Directive. The set of significant tags a JSP container interprets can be extended through a tag library. The taglib directive in a JSP page declares that the page uses a tag library, uniquely identifies the tag library using a URI and associates a tag prefix that will distinguish usage of the actions in the library. If a JSP container implementation cannot locate a tag library description, a fatal translation error shall result. It is a fatal translation error for the taglib directive to appear after actions or functions using the prefix. 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>

http://java.boot.by/wcd-guide/wcd-guide.html 92 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

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

tagdir indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory. An implicit tag library descriptor is used. A translation error must occur if the value does not start with /WEB-INF/tags/. A translation error must occur if the value does not point to a directory that exists. A translation error must occur if used in conjunction with the uri attribute. 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 page or tag file. The included file is subject to the access control available to the JSP container. The <jsp:directive.include> element describes the same information following the XML syntax. 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" %>

Syntax:

<%@ include file="relativeURLspec" %>

Summary of Include Mechanisms in JSP 2.0: <%@ include file="..." %>


file relative static

http://java.boot.by/wcd-guide/wcd-guide.html 93 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Content IS parsed by JSP container

<jsp:include page="..." />


page relative static OR dynamic Content is NOT parsed - it is included in place

Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.
page Directive with import attribute. Lets you specify the packages that should be imported by the servlet into which the JSP page gets translated. Generates import statements at top of servlet definition. Default imports: java.lang.*; javax.servlet.*; javax.servlet.jsp.*; javax.servlet.http.*.

<%@ page import="package.class" %>

or multiple classes/packages (separated by comma, NOT semicolon).

<%@ page import="package.classA, package.classB, other.package.*" %>

page Directive with session attribute. Controls whether or not page participates in HTTP sessions. Indicates that session (of type HttpSession) should be bound to existing session. false value means NO sessions will be used automatically. Attempts to access session variable by servlet will cause RUN-TIME failure. By default, it IS part of a session. All related pages have to do this for it to be useful.

http://java.boot.by/wcd-guide/wcd-guide.html 94 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<%@ page session="true" %> <%-- default !!! --%>

or

<%@ page session="false" %>

page Directive with contentType attribute. Specify the MIME type of the page generated by the servlet that results from the JSP page. Attribute value cannot be computed at request time.

<%@ page contentType="MIME-Type" %>

or

<%@ page contentType="MIME-Type; charset=Character-Set" %>

it is the same as (scriptlet):

<% response.setContentType("MIME-Type; charset=Character-Set"); %>

Note, you CANNOT use the contentType attribute for conditional run-time task. The following ALWAYS results in the Excel MIME type (page directive is evaluated only once during translation phase, and not during execution phase):

<% boolean usingExcel = checkUserRequest(request); %>


http://java.boot.by/wcd-guide/wcd-guide.html 95 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<% if (usingExcel) { %> <%@ page contentType="application/vnd.ms-excel" %> <% } %>

the following approach should be used instead :

<% boolean usingExcel = checkUserRequest(request); %> <% if (usingExcel) { %> <% response.setContentType("application/vnd.ms-excel"); %> <% } %>

page Directive with isELIgnored attribute. The attribute is used to control whether the JSP 2.0 Expression Language (EL) is ignored (true) or evaluated normally (false). EL expressions will be ignored by default in JSP 1.2 applications. When upgrading a web application to JSP 2.0, EL expressions WILL BE INTERPRETED by default. The escape sequence '\ $' can be used to escape EL expressions that should not be interpreted by the container. Alternatively, the isELIgnored page directive attribute, or the <el-ignored> configuration element can be used to deactivate EL for entire translation units.

<%@ page isELIgnored="false" %> <!-- default for JSP 2.0 -->

or

<%@ page isELIgnored="true" %> <!-- default for JSP 1.2 -->

include Directive. Lets you insert a file into servlet class at time the JSP file is translated into servlet. Should be placed in document at point where you want file inserted.
http://java.boot.by/wcd-guide/wcd-guide.html 96 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

The include directive lets you reuse navigation bars, tables, and other elements in multiple pages. The include directive includes a file in a JSP document at DOCUMENT TRANSLATION TIME. Included file can contain JSP code. Inclusion is recursive: included files may include files.

<html> <head> <title>Including Files at Translation Time (JSP)</title> </head> <body> <%@ include file="somePage.jsp" %> </body> </html>

taglib Directive. Can be used to define custom tags.

<%@ taglib prefix="example" uri="http://www.server.com/example-taglib" %>

and web.xml:

<taglib> <taglib-uri>http://www.server.com/example-taglib</taglib-uri> <taglib-location>/WEB-INF/example-taglib.tld</taglib-location> </taglib>

Notice the taglib-location specifies the location of the TLD. The taglib-uri is, for the most part, an arbitrary name given to the tag library. The name you give it can't conflict with other tag libraries in your deployment descriptor. In fact, adding the taglib element to the deployment descriptor is actually optional. You could instead reference the TLD directly in the taglib directive:

http://java.boot.by/wcd-guide/wcd-guide.html 97 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<%@ taglib prefix="example" uri="/WEB-INF/example-taglib.tld" %>

This isn't recommended because it reduces flexibility if you ever choose to rename or move the TLD. The uri would have to be changed in every JSP that used it.

Write a JSP Document (XML-based document) that uses the correct syntax.
JSP syntax comment:

<%-- comment --%>

has no XML syntax analog. JSP syntax page directive:

<%@ page ... %>

XML syntax page directive:

<jsp:directive.page ... />

JSP syntax taglib directive:

<%@ taglib ... %>

http://java.boot.by/wcd-guide/wcd-guide.html 98 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

has no XML syntax analog. jsp:root element is annotated with namespace information:

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

A taglib directive of the form

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

is translated into an xmlns:prefix attribute on the root of the JSP document, with a value that depends on uriValue.

If uriValue is a RELATIVE path, then the value used is urn:jsptld:uriValue. If uriValue is a ABSOLUTE path, then uriValue is used directly.

A taglib directive of the form:

<%@ taglib tagdir="tagDirValue" prefix="prefix" %>

is translated into an xmlns:prefix attribute on the root of the JSP document, with a value of the form urn:jsptagdir:tagDirValue. JSP syntax include directive:

http://java.boot.by/wcd-guide/wcd-guide.html 99 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<%@ include file="relativeURL" %>

XML syntax include directive:

<jsp:directive.include file="relativeURL" />

A file on the local system to be included when the JSP page is translated into a servlet. The URL must be a relative one. JSP syntax declaration:

<%! ... %>

XML syntax declaration:

<jsp:declaration> ... </jsp:declaration>

Declarations are translated into a jsp:declaration element. For example:

<%! public String someFunc(int i) { if (i<3) return("..."); } %>

is translated into the following:

http://java.boot.by/wcd-guide/wcd-guide.html 100 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

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

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

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

JSP syntax scriptlet:

<% ... %>

XML syntax scriptlet:

<jsp:scriptlet> ... </jsp:scriptlet>

JSP syntax expression:

<%= ... %>

http://java.boot.by/wcd-guide/wcd-guide.html 101 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

XML syntax expression:

<jsp:expression> ... </jsp:expression>

JSP syntax template text:

some template text

XML syntax template text:

<jsp:text> some template text </jsp:text>

A JSP document syntax:

<html> <title>positiveTagLib</title> <body> <%@ taglib uri="http://java.apache.org/tomcat/examples-taglib" prefix="eg" %> <%@ taglib uri="/tomcat/taglib" prefix="test" %> <%@ taglib uri="WEB-INF/tlds/my.tld" prefix="temp" %> <eg:test toBrowser="true" att1="Working"> Positive Test taglib directive </eg:test> </body> </html>

A XML document syntax:


http://java.boot.by/wcd-guide/wcd-guide.html 102 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:eg="http://java.apache.org/tomcat/examples-taglib" xmlns:test="urn:jsptld:/tomcat/taglib" xmlns:temp="urn:jsptld:/WEB-INF/tlds/my.tld" version="2.0"> <jsp:text><![CDATA[ <html> <title>positiveTagLib</title> <body> ]]></jsp:text> <eg:test toBrowser="true" att1="Working"> <jsp:text>Positive test taglib directive</jsp:text> </eg:test> <jsp:text><![CDATA[ </body> </html> ]]></jsp:text> </jsp:root>

Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method.
JSP page translation. During the translation phase the container locates or creates the JSP page implementation class that corresponds to a given JSP page. This process is determined by the semantics of the JSP page. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page. A tag library may optionally provide a validation method acting on the XML View of a JSP page, to validate that a JSP page is correctly using the library. The translation of a JSP source page into its implementation class can occur at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

http://java.boot.by/wcd-guide/wcd-guide.html 103 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

The JSP container creates a JSP page implementation class for each JSP page. The name of the JSP page implementation class is implementation dependent. The JSP Page implementation object belongs to an implementation-dependent named package. The package used may vary between one JSP and another, so minimal assumptions should be made. As of JSP 2.0, it is illegal to refer to any classes from the unnamed (a.k.a. default) package. This may result in a translation error on some containers, The contract on the JSP page implementation class:

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 via 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 page compilation. A JSP page may be compiled into its implementation class plus deployment information during development (a JSP page can also be compiled at deployment time). In this way JSP page authoring tools and JSP tag libraries may be used for authoring servlets. The benefits of this approach include:

Removal of the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request. Reduction of the footprint needed to run a JSP container, as the Java compiler is not needed.

Compilation of a JSP page in the context of a web application provides resolution of relative URL specifications in include directives and elsewhere, tag library references, and translation-time actions used in custom actions. A JSP page can also be compiled at deployment time. JSP class loading. JSP servlet is loaded. Creating instance of JSP class.

http://java.boot.by/wcd-guide/wcd-guide.html 104 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

JSP servlet instance is created. The enforcement of the contract between the JSP container and the JSP page author is aided by the requirement that the Servlet class corresponding to the JSP page must implement the javax. servlet.jsp.HttpJspPage interface (or the javax.servlet.jsp.JspPage interface if the protocol is not HTTP).

package javax.servlet.jsp; public interface JspPage extends javax.servlet.Servlet { public void jspInit(); public void jspDestroy(); public void _jspService(ServletRequestSubtype request, ServletResponseSubtype response) throws ServletException, IOException; // _jspService - depends on the specific protocol used and // cannot be expressed in a generic way in Java. }

package javax.servlet.jsp; public interface HttpJspPage extends JspPage { public void _jspService(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException; }

The jspInit method. The jspInit method, if present, will be called to prepare the page BEFORE the first request is delivered.

<%! public void jspInit() { ... } %>


http://java.boot.by/wcd-guide/wcd-guide.html 105 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

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. The _jspService method. 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. The formal types of the request/response parameters:

void _jspService(javax.servlet.ServletRequest req, javax.servlet.ServletResponse res) throws IOException, ServletException { ... }

The request and response interfaces together describe a protocol-dependent contract between the JSP container and the class that implements the JSP page. The HTTP contract is defined by the javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse interfaces:

void _jspService(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) throws IOException, ServletException { ... }

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. The jspDestroy method. The JSP container can reclaim resources used by a JSP page when a request is not being serviced by the JSP page by invoking its jspDestroy method, if present.

<%! public void jspDestroy() { ...


http://java.boot.by/wcd-guide/wcd-guide.html 106 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

} %>

Method is optionally defined in JSP page. Method is invoked BEFORE destroying the page.

Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception.
The request object. Protocol dependent subtype of javax.servlet.ServletRequest, e.g: javax.servlet.http.HttpServletRequest. This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, referer, etc.). The request triggering the service invocation. Has a request scope.

<% String path = request.getContextPath(); String name = request.getParameter("name"); %>

The response object. Protocol dependent subtype of javax.servlet.ServletResponse, e.g: javax.servlet.http. HttpServletResponse. This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client. The response to the request. Has a page scope. The out object.
http://java.boot.by/wcd-guide/wcd-guide.html 107 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

An object of type javax.servlet.jsp.JspWriter. This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly. An object that writes into the output stream. Has a page scope.

<html> <body> <% out.println("Hello !"); %> </body> </html>

NOTE, JSP page authors are prohibited from writing directly to either the PrintWriter or OutputStream associated with the ServletResponse. The following example is INVALID:

<html> <body> <% response.getWriter().println("Hello !"); %> </body> </html>

The session object. An object of type javax.servlet.http.HttpSession. This is the HttpSession object associated with the request. Sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive to turn sessions off, in which case attempts to
http://java.boot.by/wcd-guide/wcd-guide.html 108 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

reference the session variable cause errors at the time the JSP page is translated into a servlet. The session object created for the requesting client (if any). This variable is only valid for HTTP protocols. Has a session scope. The config object. An object of type javax.servlet.ServletConfig. The ServletConfig for this JSP page. Has a page scope. The application object. An object of type javax.servlet.ServletContext. The servlet context obtained from the servlet configuration object (as in the call this. getServletConfig().getContext()). Has an application scope.

<% javax.servlet.RequestDispatcher rd; rd = application.getRequestDispatcher("/NextPage.jsp"); rd.forward(request, response); %>

The page object. An object of type java.lang.Object. This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java. The instance of this page's implementation class processing the current request. Has a page scope. The pageContext object. A PageContext is an object that provides a context to store references to objects used by the page, encapsulates implementation-dependent features, and provides convenience methods. A JSP page implementation class can use a PageContext to run unmodified in any compliant JSP
http://java.boot.by/wcd-guide/wcd-guide.html 109 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

container while taking advantage of implementation-specific improvements like high performance JspWriters.

public abstract class PageContext extends JspContext { public abstract java.lang.Exception getException(); public abstract java.lang.Object getPage(); // instance of Servlet public abstract javax.servlet.ServletRequest getRequest(); public abstract javax.servlet.ServletResponse getResponse(); public abstract javax.servlet.ServletConfig getServletConfig(); public abstract javax.servlet.ServletContext getServletContext(); public abstract javax.servlet.http.HttpSession getSession(); public abstract void handlePageException(java.lang.Exception e); public abstract void include(java.lang.String relativeUrlPath); public abstract void forward(java.lang.String relativeUrlPath); }

PageContext extends JspContext to provide useful context information for when JSP technology is used in a Servlet environment. A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically. The PageContext class is an abstract class, designed to be extended to provide implementation dependent implementations thereof, by conformant JSP engine runtime environments. The following methods provide convenient access to implicit objects: getException(), getPage(), getRequest(), getResponse(), getSession(), getServletConfig() and getServletContext(). The following methods provide support for forwarding, inclusion and error handling: forward(), include(), and handlePageException(). The exception object. An object of type java.lang.Throwable. The uncaught Throwable that resulted in the error page being invoked. Has a page scope. A JSP is considered an Error Page if it sets the page directive's isErrorPage attribute to true. If a page has isErrorPage set to true, then the exception implicit scripting language variable of that page is initialized. error.jsp:

<%@ page isErrorPage="true" %>


http://java.boot.by/wcd-guide/wcd-guide.html 110 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

... <%= exception.getMessage() %> <br> With the following stack trace: <br> <% ByteArrayOutputStream baos = new ByteArrayOutputStream(); exception.printStackTrace(new PrintStream(baos)); out.print(baos); %>

Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language.
A tag library is a collection of actions that encapsulate some functionality to be used from within a JSP page. A tag library is made available to a JSP page through a taglib directive that identifies the tag library via a URI (Universal Resource 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. The URI identifying the tag library is associated with a Tag Library Description (TLD) file and with tag handler classes. Both Classic and Simple Tag Handlers (implemented either in Java or as tag files) can be packaged together. The explicit web.xml map provides a explicit description of the tag libraries that are being used in a web application. The implicit map from TLDs means that a JAR file implementing a tag library can be dropped in and used immediatedly through its stable URIs. The use of relative URI specifications in the taglib map enables very short names in the taglib directive. For example, if the map is:

<taglib> <taglib-uri>/myPRlibrary</taglib-uri> <taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib-location> </taglib>

http://java.boot.by/wcd-guide/wcd-guide.html 111 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

then it can be used as:

<%@ taglib uri="/myPRlibrary" prefix="x" %>

Finally, the fallback rule allows a taglib directive to refer directly to the TLD. This arrangement is very convenient for quick development at the expense of less flexibility and accountability. For example, in the case above, it enables:

<%@ taglib uri="/WEB-INF/tlds/PRlibrary_1_4.tld" prefix="x" %>

EL expressions will be ignored by default in JSP 1.2 applications. When upgrading a web application to JSP 2.0, EL expressions will be interpreted by default. The escape sequence '\$' can be used to escape EL expressions that should not be interpreted by the container. Alternatively, the isELIgnored page directive attribute, or the <el-ignored> configuration element can be used to deactivate EL for entire translation units. The default mode for JSP pages in a Web Application delivered using a web.xml using the Servlet 2.4 format is to evaluate EL expressions; this automatically provides the default that most applications want. The default mode can be explicitly changed by setting the value of the el-ignored element. The elignored element is a subelement of jsp-property-group. It has no subelements. Its valid values are true and false. For example, the following web.xml fragment defines a group that deactivates EL evaluation for all JSP pages delivered using the .jsp extension:

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

Page authors can override the default mode through the isELIgnored attribute of the page directive.
http://java.boot.by/wcd-guide/wcd-guide.html 112 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

With the addition of the EL, some JSP page authors, or page authoring groups, may want to follow a methodology where scripting elements are not allowed. The scripting-invalid element is a subelement of jsp-property-group. It has no subelements. Its valid values are true and false. Scripting is ENABLED by default. Disabling scripting elements can be done by setting the scripting-invalid element to true in the JSP configuration. For example, the following web.xml fragment defines a group that disables scripting elements for all JSP pages delivered using the .jsp extension:

<jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group>

Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp: include standard action).
The include directive. Includes a STATIC file in a JSP page, parsing the file's JSP elements. The include directive is processed when the JSP page is TRANSLATED into a servlet class. JSP Syntax:

<%@ include file="relativeFileName" %>

XML Syntax:

<jsp:directive.include file="relativeFileName" />

http://java.boot.by/wcd-guide/wcd-guide.html 113 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Example: include.jsp:

<html> <head><title>An Include Test</title></head> <body bgcolor="white"> The current date and time are : <%@ include file="date.jsp" %> </body> </html>

date.jsp:

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

The jsp:include action. Includes a static file OR the result from another web component. The difference with the include directive is that not the source of the JSP, but it's output is included. The include JSP page is being executed within the servlet engine and it's output is returned to the calling page. The main benefit of using the jsp:include action is that the URL to include can be constructed during execution of the page. However, every included page results in a new request to the servlet engine, which means there is a bit of a performance impact when compared to the include directive. JSP Syntax:

<jsp:include page="{relativeURL | <%= expression %>}" flush="true | false" />

http://java.boot.by/wcd-guide/wcd-guide.html 114 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

or

<jsp:include page="{relativeURL | <%= expression %>}" flush="true | false" > <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+ </jsp:include>

XML Syntax:

<jsp:include page="{relativeURL | %= expression %}" [ flush="true | false" ] />

or

<jsp:include page="{relativeURL | %= expression %}" [ flush="true | false" ] > [ <jsp:param name="parameterName" value="{parameterValue | %= expression %}" /> ]+ </jsp:include>

Examples:

<jsp:include page="scripts/login.jsp" flush="true" />

The following example shows that there are two ways of passing named variables: either pass them on directly in the URL, or add them using jsp:param tags:

http://java.boot.by/wcd-guide/wcd-guide.html 115 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<jsp:include page="includes/page.jsp?param1=value" flush="true"> <jsp:param name="param2" value="value2" /> </jsp:include>

It is also possible to dynamically choose the file to include. This example determines the file to include from a request parameter:

<jsp:include page='<%= request.getParameter("incFile") %>' />

Defining Implicit Includes. The include-prelude element is an optional subelement of jsp-property-group. It has no subelements. Its value is a context-relative path that must correspond to an element in the Web Application. When the element is present, the given path will be automatically included (as in an include directive) at the beginning of the JSP page in the jsp-property-group. When there are more than one include-prelude element in a group, they are to be included in the order they appear. When more than one jsp-property-group applies to a JSP page, the corresponding includeprelude elements will be processed in the same order as they appear in the JSP configuration section of web.xml. The include-coda element is an optional subelement of jsp-property-group. It has no subelements. Its value is a context-relative path that must correspond to an element in the Web Application. When the element is present, the given path will be automatically included (as in an include directive) at the end of the JSP page in the jsp-property-group. When there are more than one include-coda element in a group, they are to be included in the order they appear. When more than one jsp-property-group applies to a JSP page, the corresponding include-coda elements will be processed in the same order as they appear in the JSP configuration section of web.xml. Note that these semantics are in contrast to the way url-patterns are matched for other configuration elements. Preludes and codas follow the same rules as statically included JSP segments. In particular, start tags and end tags must appear in the same file. For example, the following web.xml fragment defines two groups. Together they indicate that everything in directory /two/ have /WEB-INF/jspf/prelude1.jspf and /WEB-INF/jspf/prelude2.jspf at the beginning and /WEB-INF/jspf/coda1.jspf and /WEB-INF/jspf/coda2.jspf at the end, in that order, while other .jsp files only have /WEB-INF/jspf/prelude1.jspf at the beginning and /WEB-INF/jspf/coda1.jspf at the end:

http://java.boot.by/wcd-guide/wcd-guide.html 116 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<jsp-property-group> <url-pattern>*.jsp</url-pattern> <include-prelude>/WEB-INF/jspf/prelude1.jspf</include-prelude> <include-coda>/WEB-INF/jspf/coda1.jspf</include-coda> </jsp-property-group> <jsp-property-group> <url-pattern>/two/*</url-pattern> <include-prelude>/WEB-INF/jspf/prelude2.jspf</include-prelude> <include-coda>/WEB-INF/jspf/coda2.jspf</include-coda> </jsp-property-group>

Chapter 7. Building JSP Pages Using the Expression Language (EL)

Given a scenario, write EL code that accesses the following implicit variables including: pageScope, requestScope, sessionScope, and applicationScope, param and paramValues, header and headerValues, cookie, initParam and pageContext.
There are several implicit objects that are available to EL expressions used in JSP pages. These objects are always available under these names:

pageContext - the PageContext object. Provides an API to access various objects including:
r

r r

context - the context for the JSP page's servlet and any Web components contained in the same application. session - the session object for the client. request - the request triggering the execution of the JSP page.

pageScope - a java.util.Map that maps page-scoped attribute names to their values. requestScope - a java.util.Map that maps request-scoped attribute names to their values. sessionScope - a java.util.Map that maps session-scoped attribute names to their values. applicationScope - a java.util.Map that maps application-scoped attribute names to their values. param - a java.util.Map that maps parameter names to a single String parameter value (obtained by calling ServletRequest.getParameter(String name)). paramValues - a java.util.Map that maps parameter names to a String[] of all values for that parameter (obtained by calling ServletRequest.getParameterValues(String name)). header - a java.util.Map that maps header names to a single String header value (obtained by calling HttpServletRequest.getHeader(String name)). headerValues - a java.util.Map that maps header names to a String[] of all values for that header. cookie - a java.util.Map that maps cookie names to a single Cookie object. Cookies are

http://java.boot.by/wcd-guide/wcd-guide.html 117 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

retrieved according to the semantics of HttpServletRequest.getCookies(). If the same name is shared by multiple cookies, an implementation must use the FIRST one encountered in the array of Cookie objects returned by the getCookies() method. However, users of the cookie implicit object must be aware that the ordering of cookies is currently unspecified in the servlet specification. initParam - a java.util.Map that maps context initialization parameter names to their String parameter value (obtained by calling ServletContext.getInitParameter(String name)).

Examples: The request's URI (obtained from HttpServletRequest):

${pageContext.request.requestURI}

The value of the numberOfItems property of the session-scoped attribute named cart:

${sessionScope.cart.numberOfItems}

The context path:

${pageContext.request.contextPath}

The session-scoped attribute named 'profile' (null if not found):

${sessionScope.profile}

The String value of the productId parameter, or null if not found:

${param.productId}

The value of the productId request parameter:

${param["productId"]}

http://java.boot.by/wcd-guide/wcd-guide.html 118 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

The String[] containing all values of the productId parameter, or null if not found:

${paramValues.productId}

A collection's members can be accessed using square brackets as shown by retrieval of the userName parameter from the param object. Members of an array or List can be accessed if the value in square brackets can be coerced to an int.

<html> <head><title>Customer Profile for ${param["userName"]}</title></head> <body> ... </body> </html>

Maps can be accessed using the dot operator OR square brackets. For example, ${param. userName} is EQUIVALENT to ${param["userName"]}. The host HTTP attribute:

${header["host"]}

Here is an example of accessing a page-scoped object that is called pageColor:

<body bgcolor="${pageScope.pageColor}">

it is equivalent to:

<body bgcolor="${pageScope['pageColor']}">

http://java.boot.by/wcd-guide/wcd-guide.html 119 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Given a scenario, write EL code that uses the following operators: property access (the '.' operator), collection access (the '[]' operator).
The EL borrows the JavaScript syntax for accessing structured data as either a property of an object (with the '.' operator) or as a named array element (with the ["name"] operator). JavaBeans component properties and java.util.Map entries, using the key as the property name, can be accessed this way. Here are some examples:

${myObj.myProperty} ${myObj["myProperty"]} ${myObj['myProperty']} ${myObj[varWithThePropertyName]}

As shown here, an EL expression must always be enclosed within '${' and '}' characters. The first three expressions access a property named myProperty in an object represented by a variable named myObj. The fourth expression access a property with a name that's held by a variable. Instead of a single variable, this syntax can be used with any expression that evaluates to the property name. The ARRAY ACCESS operator is also used for data represented as a collection of indexed elements, such as a Java array or a java.util.List:

${myList[2]} ${myList[aVar + 1]}

Expressions with syntax '${identifier[subexpression]}' are evaluated as follows: 1. Evaluate the identifier and the subexpression; if either resolves to null, the expression is null. 2. If the identifier is a BEAN: The subexpression is coerced to a String value and that string is regarded as a name of one of the bean's properties. The expression resolves to the value of that property; for example, the expression ${name.["lastName"]} translates into the value returned by name. getLastName(). 3. If the identifier is an ARRAY: The subexpression is coerced to an int value and the expression resolves to identifier [subexpression]. For example, for an array named colors, colors[3] represents the fourth object in the array. Because the subexpression is coerced to an int, you can also access that color like this: colors["3"]; in that case, JSTL coerces "3" into 3.

http://java.boot.by/wcd-guide/wcd-guide.html 120 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

4. If the identifier is a LIST: The subexpression is also coerced to an int and the expression resolves to the value returned from identifier.get(subexpression), for example: colorList[3] and colorList["3"] both resolve to the fourth element in the list. 5. If the identifier is a MAP: The subexpression is regarded as one of the map's keys. That expression is not coerced to a value because map keys can be any type of object. The expression evaluates to identifier.get(subexpression), for example, colorMap[Red] and colorMap["Red"]. The former expression is valid only if a scoped variable named Red exists in one of the four JSP scopes and was specified as a key for the map named colorMap. Table 7.1. Summary of [] collection access operator
Identifier type Example use ${colorBean.red} JavaBean ${colorBean["red"]} ${colorBean['red']} ${colorArray[2]} Array ${colorArray["2"]} ${colorList[2]} List ${colorList["2"]} ${colorMap[red]} Map ${colorMap["red"]} colorMap.get(pageContext.findAttribute("red")) colorMap.get("red") colorList.get(2) Array.get(colorArray, 2) colorBean.getRed() Method invoked

You access a map's values through its keys, which you can specify with the [] operator, for example, in table above, ${colorMap[red]} and ${colorMap["red"]}. The former specifies an IDENTIFIER for the key, whereas the latter specifies a STRING. For the identifier, the PageContext. findAttribute method searches all FOUR JSP scopes (searching the page, request, session, and application scopes) for a scoped variable with the name that you specify, in this case, red. On the other hand, if you specify a string, it's passed directly to the map's get method.

Given a scenario, write EL code that uses the following operators: aritmetic operators, relational operators, and logical operators.

http://java.boot.by/wcd-guide/wcd-guide.html 121 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

There are the arithmetic operators here: '+', '-', '*', '/', '%'. You can also use the following for the '/' (division) and '%' (remainder or modulo) operators: div and mod. You can see examples of these being used below:

6 + 7 = ${6+7}<br> 8 x 9 = ${8*9}<br>

The relational operators are shown below: Table 7.2. The relational operators
Symbol version == != < > >= <= eq ne lt gt ge le Text Version

Here are some basic comparisons:

Is 1 less than 2? ${1<2} <br> Does 5 equal 5? ${5==5} <br> Is 6 greater than 7? ${6 gt 7}<br>

The logical operators are the same as the Java Programming Language, but they also have their textual equivalents within the EL. Table 7.3. The logical operators
Symbol version && and Text Version

http://java.boot.by/wcd-guide/wcd-guide.html 122 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

|| !

or not

The empty operator allows you to test the following:


Object references to see if they are null. Strings to see if they are empty. Arrays to see if they are empty. Lists to see if they are empty. Maps to see if they are empty.

You use the operator in the following way:

empty variableName

If any of the above conditions are met, then the operator returns true.

Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.
The EL has qualified functions, reusing the notion of qualification from XML namespaces (and attributes), XSL functions, and JSP custom actions. Functions are mapped to public static methods in Java classes. In JSP 2.0 the map is specified in the TLD. The full syntax:

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

As with the rest of EL, this element can appear in attributes and directly in template text. The prefix ns must match the prefix of a tag library that contains a function whose name and signature matches the function being invoked (func), or a translation error must occur. If the prefix is omitted, the tag library associated with the default namespace is used (this is only possible in JSP documents). In the following standard syntax example, func1 is associated with some-taglib:

http://java.boot.by/wcd-guide/wcd-guide.html 123 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<%@ taglib prefix="some" uri="http://acme.com/some-taglib" %> ${some:func1(true)}

In the following JSP document example, both func2 and func3 are associated with default-taglib:

<some:tag xmlns="http://acme.com/default-taglib" xmlns:some="http://acme.com/some-taglib" xmlns:jsp="http://java.sun.com/JSP/Page"> <some:other value="${func2(true)}"> ${func3(true)} </some:other> </some:tag>

The Tag Library Descriptor (TLD) associated with a tag library lists the functions. Each such function is given a name (as seen in the EL), and a static method in a specific class that will implement the function. The class specified in the TLD must be a public class, and must be specified using a fully-qualified class name (INCLUDING PACKAGES). The specified method must be a public static method in the specified class, and must be specified using a fully-qualified return type followed by the method name, followed by the fully-qualified argument types in parenthesis, separated by COMMAS. Failure to satisfy these requirements shall result in a translation-time error. A tag library can have only one function element in the same tag library with the same value for their name element. If two functions have the same name, a translation-time error shall be generated. The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD). Write class with STATIC function:

package com.example; public class MyELFunctions {


http://java.boot.by/wcd-guide/wcd-guide.html 124 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

public static String concat(String str1, String str2) { return str1 + str2; } }

In order to use concat method we have to add a function element to our tag library descriptor (TLD). You'll have to create a TLD file if it doesn't already exist. A tag library descriptor defines and configures tags in a tag library. Here is /WEB-INF/example-taglib.tld:

<?xml version="1.0" encoding="UTF-8"?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>1.0</tlib-version> <function> <description>Concatenates two strings</description> <name>concat</name> <function-class>com.example.MyELFunctions</function-class> <function-signature> java.lang.String concat(java.lang.String, java.lang.String) </function-signature> </function> </taglib>

Add a taglib element to the deployment descriptor ( /WEB-INF/web.xml):

<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd" version="2.4"> <taglib> <taglib-uri>http://www.server.com/example-taglib</taglib-uri> <taglib-location>/WEB-INF/example-taglib.tld</taglib-location> </taglib> </web-app>
http://java.boot.by/wcd-guide/wcd-guide.html 125 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Notice the taglib-location specifies the location of the TLD. The taglib-uri is, for the most part, an arbitrary name given to the tag library. The name you give it can't conflict with other tag libraries in your deployment descriptor. Adding the taglib element to the deployment descriptor is actually OPTIONAL. You could instead reference the TLD directly in the taglib directive on JSP:

<%@ taglib prefix="my" uri="/WEB-INF/example-taglib.tld" %>

This is NOT recommended because it reduces flexibility if you ever choose to rename or move the TLD. The uri would have to be changed in every JSP that used it. The new JSP looks like the following:

<%@ taglib prefix="my" uri="http://www.server.com/example-taglib" %> <html> <head><title>EL Function example</title></head> <body> str1 is : ${param["str1"]} <br> str2 is : ${param["str2"]} <br> concatenated : ${my:concat(param["str1"], param["str2"])} </body> </html>

The prefix 'my' given in the taglib directive is whatever you choose to distinguish it from tags and functions in other tag libraries used in the JSP.

Chapter 8. Building JSP Pages Using Standard Actions

Given a design goal, create a code snippet using the following standard actions: jsp: useBean (with attributes: 'id', 'scope', 'type', and 'class'), jsp:getProperty, and jsp: setProperty (with all attribute combinations).
Action jsp:useBean.

http://java.boot.by/wcd-guide/wcd-guide.html 126 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

A jsp:useBean action associates an instance of a Java programming language object defined within a given scope and available with a given id with a newly declared scripting variable of the same id. When a jsp:useBean action is used in an scriptless page, or in an scriptless context (as in the body of an action so indicated), there are no Java scripting variables created but instead an EL variable is created. The jsp:useBean action is quite flexible; its exact semantics depends on the attributes given. The basic semantic tries to find an existing object using id and scope. If the object is not found it will attempt to create the object using the other attributes. It is also possible to use this action to give a local name to an object defined elsewhere, as in another JSP page or in a servlet. This can be done by using the type attribute and not providing class or beanName attributes. At least ONE of type and class MUST be present, and it is NOT VALID to provide both class and beanName. If type and class are present, class must be assignable to type (in the Java platform sense). For it not to be assignable is a translation time error. The attribute beanName specifies the name of a Bean, as specified in the JavaBeans specification. It is used as an argument to the instantiate method in the java.beans.Beans class. It must be of the form a.b.c, which may be either a class, or the name of a resource of the form a/b/c.ser that will be resolved in the current ClassLoader. If this is not true, a request-time exception, as indicated in the semantics of the instantiate method will be raised. The value of this attribute can be a request-time attribute expression. In the following example, a Bean with name connection of type com.myco.myapp.Connection is available after actions on this element, either because it was already created and found, or because it is newly created.

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

In the 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>

http://java.boot.by/wcd-guide/wcd-guide.html 127 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

In the following example, the object should have been present in the session. If so, it is given the local name wombat with WombatType. A ClassCastException may be raised if the object is of the wrong class, and an InstantiationException may be raised if the object is not defined:

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

Syntax:

<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"

or

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

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

http://java.boot.by/wcd-guide/wcd-guide.html 128 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

id

The name used to identify the object instance in the specified scopes 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. The scope within which the reference is available. The DEFAULT value is page. See the description of the scope attribute defined earlier herein. A translation error must occur if scope is not one of page, request, session or application. 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. 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. If specified, it defines the type of the scripting variable defined. This allows the type of the scripting variable to be distinct from, but related to, the type of the implementation class specified. The type is required to be either the class itself, a superclass of the class, or an interface implemented by the class specified. The object referenced is required to be of this type, otherwise a java.lang. ClassCastException shall occur at request time when the assignment of the object referenced to the scripting variable is attempted. If unspecified, the value is the same as the value of the class attribute.

scope

class

beanName

type

Action jsp:getProperty. The jsp:getProperty action places the value of a bean instance property, converted to a String, into the implicit out object, from which the value can be displayed as output. The bean instance must be defined as indicated in the name attribute before this point in the page (usually via a jsp: useBean action). The conversion to String is done as in the println methods, i.e. the toString() method of the object is used for Object instances, and the primitive types are converted directly. If the object is not found, a request-time exception is raised. The value of the name attribute in jsp:setProperty and jsp:getProperty will refer to an object that is obtained from the pageContext object through its findAttribute method. The object named by the name must have been "introduced" to the JSP processor using either the jsp:useBean action or a custom action with an associated VariableInfo entry for this name. If the object was not introduced in this manner, the container implementation is recommended (but not required) to raise a translation error, since the page implementation is in violation of the specification. NOTE, a consequence of the previous paragraph is that objects that are stored in, say, the session by a front component are not automatically visible to jsp:setProperty and jsp:getProperty
http://java.boot.by/wcd-guide/wcd-guide.html 129 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

actions in that page unless a jsp:useBean action, or some other action, makes them visible. If the JSP processor can ascertain that there is an alternate way guaranteed to access the same object, it can use that information. For example it may use a scripting variable, but it must guarantee that no intervening code has invalidated the copy held by the scripting variable. The truth is always the value held by the pageContext object. Examples:

<jsp:getProperty name="user" property="name" />

Syntax:

<jsp:getProperty name="name" property="propertyName" />

Table 8.2. jsp:getProperty attributes


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

Action jsp:setProperty. The jsp:setProperty action sets the values of properties in a bean. The name attribute that denotes the bean must be defined before this action appears. There are two variants of the jsp:setProperty action. Both variants set the values of one or more properties in the bean based on the type of the properties. The usual bean introspection is done to discover what properties are present, and, for each, its name, whether it is simple or indexed, its type, and the setter and getter methods. Properties in a Bean can be set from one or more parameters in the request object, from a String constant, or from a computed request-time expression. Simple and indexed properties can be set using jsp:setProperty. When assigning values to indexed properties the value must be an array.
http://java.boot.by/wcd-guide/wcd-guide.html 130 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

The following two actions set a value from the request parameter values:

<jsp:setProperty name="request" property="*" /> <jsp:setProperty name="user" property="user" param="username" />

The following two elemenst set a property from a value:

<jsp:setProperty name="results" property="col" value="${i mod 4}" /> <jsp:setProperty name="results" property="row" value="<%= i/4 %>" />

Syntax:

<jsp:setProperty name="beanName" prop_expr /> prop_expr ::= property="*" | property="propertyName" | property="propertyName" param="parameterName" | property="propertyName" value="propertyValue" propertyValue ::= string

Table 8.3. jsp:setProperty attributes


Attribute name Description The name of a bean instance defined by a jsp:useBean action or some other action. The bean instance must contain the property to be set. The defining action must appear before the jsp:setProperty action in the same file.

http://java.boot.by/wcd-guide/wcd-guide.html 131 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

property

The name of the property whose value will be set. If propertyName is set 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. The name of the request parameter whose value is given to a bean property. The name of the request parameter usually comes from a web form. If param is omitted, 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 action has no effect. An action MAY NOT have both param and value attributes. The value to assign to the given property. This attribute can accept a requesttime attribute expression as a value. An action MAY NOT have both param and value attributes.

param

value

Given a design goal, create a code snippet using the following standard actions: jsp: include, jsp:forward, and jsp:param.
Action jsp:include. A jsp:include action provides for the inclusion of static and dynamic resources in the same context as the current page. Inclusion is into the current value of out. The resource is specified using a relativeURLspec that is interpreted in the context of the web application (i.e. it is mapped). The page attribute of both the jsp:include and the jsp:forward actions are interpreted relative to the current JSP PAGE, while the file attribute in an include directive is interpreted relative to the current JSP FILE. An included page cannot change the response status code or set headers. This precludes invoking methods like setCookie. Attempts to invoke these methods will be IGNORED. The constraint is equivalent to the one imposed on the include method of the RequestDispatcher class. A jsp:include action may have jsp:param subelements that can provide values for some parameters in the request to be used for the inclusion. Request processing resumes in the calling JSP page, once the inclusion is completed. The flush attribute controls flushing. If true, then, if the page output is buffered and the flush attribute is given a true value, then the buffer is flushed prior to the inclusion, otherwise the buffer is not flushed. The default value for the flush attribute is false.

http://java.boot.by/wcd-guide/wcd-guide.html 132 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Examples:

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

The above example is a simple inclusion of an object. The path is interpreted in the context of the Web Application. It is likely a static object, but it could be mapped into, for instance, a servlet via web.xml. Syntax:

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

and

<jsp:include page="urlSpec" flush="true|false"> { <jsp:param .... /> }* </jsp:include>

The first syntax just does a request-time inclusion. In the second case, the values in the param subelements are used to augment the request for the purposes of the inclusion. Table 8.4. jsp:include attributes
Attribute page Description The URL is a relative urlSpec. Relative paths are interpreted relative to the current JSP page. Accepts a request-time attribute value (which must evaluate to a String that is a relative URL specification). Optional boolean attribute. If the value is true, the buffer is flushed now. The default value is false.

flush

Action jsp:forward.

http://java.boot.by/wcd-guide/wcd-guide.html 133 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

A jsp:forward action 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 request object will be adjusted according to the value of the page attribute. A jsp:forward action may have jsp:param subelements that can provide values for some parameters in the request to be used for the forwarding. If the page output is buffered, the buffer is CLEARED prior to forwarding. If the page output is buffered and the buffer was flushed, an attempt to forward the request will result in an IllegalStateException. If the page output was unbuffered and anything has been written to it, an attempt to forward the request will result in an IllegalStateException. The following action might be used to forward to a static page based on some dynamic condition:

<% String whereTo = "/templates/" + someValue; %> <jsp:forward page="<%= whereTo %>" />

Syntax:

<jsp:forward page="relativeURLspec" />

and

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

Table 8.5. jsp:forward attributes


http://java.boot.by/wcd-guide/wcd-guide.html 134 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Attribute page

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

Action jsp:param. The jsp:param element is used to provide key/value information. This element is used in the jsp: include, jsp:forward, and jsp:params elements. A translation error shall occur if the element is used elsewhere. When doing jsp:include or jsp:forward, the included page or forwarded page will see the original request object, with the original parameters augmented with the new parameters, with NEW VALUES TAKING PRECEDENCE over existing values when applicable. The scope of the new parameters is the jsp:include or jsp:forward call; i.e. in the case of an jsp:include the new parameters (and values) will not apply after the include. This is the same behavior as in the ServletRequest include and forward methods. 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. Syntax:

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

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

Chapter 9. Building JSP Pages Using Tag Libraries

For a custom tag library or a library of Tag Files, create the 'taglib' directive for a JSP page.
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

http://java.boot.by/wcd-guide/wcd-guide.html 135 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

the tag library using a URI and associates a tag prefix that will distinguish usage of the actions in the library. If a JSP container implementation cannot locate a tag library description, a fatal translation error shall result. It is a fatal translation error for the taglib directive to appear after actions or functions using the prefix. In the following example, a tag library is introduced and made available to this page using the super prefix; no other tag libraries should be introduced in this page using this prefix. In this particular case, we assume the tag library includes a doMagic element type, which is used within the page.

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

Syntax:

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

Table 9.1. taglib Directive attributes


Attribute uri Description Either an absolute URI or a relative URI specification that uniquely identifies the tag library descriptor associated with this prefix. The URI is used to locate a description of the tag library. Indicates this prefix is to be used to identify tag extensions installed in the /WEBINF/tags/ directory or a subdirectory. An implicit tag library descriptor is used. A translation error must occur if the value does not start with /WEB-INF/tags/. A translation error must occur if the value does not point to a directory that exists. A translation error must occur if used in conjunction with the uri attribute.

tagdir

http://java.boot.by/wcd-guide/wcd-guide.html 136 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

prefix

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

A fatal translation-time error will result if the JSP page translator encounters a tag with name prefix:Name using a prefix that is introduced using the taglib directive, and Name is not recognized by the corresponding tag library.

Given a design goal, create the custom tag structure in a JSP page to support that goal.

<%@ taglib uri="mytags" prefix="codecamp" %> <ol> <!-- repeats N times. A null reps value means repeat once. --> <codecamp:repeat reps='<%=request.getParameter("repeats") %>'> <li><codecamp:prime length="40" /> </codecamp:repeat> </ol>

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.
The center of JSTL is the core taglib. This can be split into five areas: 1. 2. 3. 4. 5. General purpose Variables support Conditional Iterator URL Related

To use the core library, use the following directive:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

http://java.boot.by/wcd-guide/wcd-guide.html 137 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

The prefix attribute specifies the prefix used in the tag name for a particular library. For example, the core library includes a tag named out. When combined with a prefix of c, the full tag would be <c:out>. You are free to use any prefix you like, but you must use different prefixes for each of the four standard tag libraries. You must also put the corresponding .tld file for each tag library in your /WEB-INF directory and use the taglib element in your web.xml file to include the tag library:

<taglib> <taglib-uri>http://java.sun.com/jstl/core</taglib-uri> <taglib-location>/WEB-INF/tld/core.tld</taglib-location> </taglib>

General purpose tags. The general-purpose tags let you display variable values, and enclose a group of tags within a try-catch block. The <c:out> action provides a capability similar to JSP expressions such as <%= scripting-languageexpression %> or ${el-expression}. For example:

You have <c:out value="${sessionScope.user.itemCount}"/> items.

By default, <c:out> converts the characters <, >, ', ", & to their corresponding character entity codes (e.g. < is converted to &lt;). If these characters are not converted, the page may not be rendered properly by the browser, and it could also open the door for cross-site scripting attacks. The conversion may be bypassed by specifying false to the escapeXml attribute. The <c: out> action also supports the notion of DEFAULT values for cases where the value of an EL expression is null. In the example below, the value "unknown" will be displayed if the property city is not accessible.

<c:out value="${customer.address.city}" default="unknown"/>

http://java.boot.by/wcd-guide/wcd-guide.html 138 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

The second option is to specify the default value as the content of the <c:out> tag:

<c:out value="${customer.address.street}"> No address available </c:out>

Syntax: Without a body:

<c:out value="value" [escapeXml="{true|false}"] [default="defaultValue"] />

With a body (contains default value):

<c:out value="value" [escapeXml="{true|false}"]> default value </c:out>

The <c:catch> action allows page authors to handle errors from any action in a uniform fashion, and allows for error handling for multiple actions at once. <c:catch> provides page authors with granular error handling: Actions that are of central importance to a page should not be encapsulated in a <c:catch>, so their exceptions will propagate to an error page, whereas actions with secondary importance to the page should be wrapped in a <c:catch>, so they never cause the error page mechanism to be invoked. The exception thrown is stored in the scoped variable identified by var, which always has page scope. If no exception occurred, the scoped variable identified by var is removed if it existed. If var is missing, the exception is simply caught and not saved. Syntax:

<c:catch [var="varName"]> nested actions


http://java.boot.by/wcd-guide/wcd-guide.html 139 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

</c:catch>

Variables support tags. The action <c:set> is used to set the value of a JSP scoped attribute as follows:

<c:set var="foo" value="value"/>

In the following example, the <c:set> action sets the value of the att1 scoped variable to the output of the acme:foo action. <c:set> like all JSTL actions that create scoped attributes creates scoped attributes in 'page' scope by DEFAULT:

<c:set var="att1"> <acme:foo>mumbojumbo</acme:foo> </c:set> <acme:atag att1="${att1}"/>

<c:set> may also be used to set the property of a JavaBeans object, or add or set a specific element in a java.util.Map object. For example:

<!-- set property in JavaBeans object --> <c:set target="${cust.address}" property="city" value="${city}"/> <!-- set/add element in Map object --> <c:set target="${preferences}" property="color" value="${param.color}"/>

Syntax. Syntax 1: Set the value of a scoped variable using attribute value:

http://java.boot.by/wcd-guide/wcd-guide.html 140 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<c:set value="value" var="varName" [scope={page|request|session|application}]/>

Syntax 2: Set the value of a scoped variable using body content:

<c:set var="varName" [scope="{page|request|session|application}"]> body content </c:set>

Syntax 3: Set a property of a target object (JavaBean object with setter property property, or a java.util.Map object) using attribute value:

<c:set value="value" target="target" property="propertyName"/>

Syntax 4: Set a property of a target object (JavaBean object with setter property property, or a java.util.Map object) using body content:

<c:set target="target" property="propertyName"> body content </c:set>

The <c:remove> action removes a scoped variable. If attribute scope is not specified, the scoped variable is removed according to the semantics of PageContext.removeAttribute(varName). If attribute scope is specified, the scoped variable is removed according to the semantics of PageContext.removeAttribute(varName, scope). Syntax:

<c:remove var="varName" [scope="{page|request|session|application}"]/>


http://java.boot.by/wcd-guide/wcd-guide.html 141 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Conditional tags. A simple conditional execution action evaluates its body content only if the test condition associated with it is true. In the following example, a special greeting is displayed only if this is a users first visit to the site:

<c:if test="${user.visitCount == 1}"> This is your first visit. Welcome to the site! </c:if>

If the test condition evaluates to true, the JSP container processes the body content (JSP) and then writes it to the current JspWriter. Syntax: Syntax 1: Without body content:

<c:if test="testCondition" var="varName" [scope="{page|request|session|application}"]/>

Syntax 2: With body content:

<c:if test="testCondition" [var="varName"] [scope="{page|request|session|application}"]> body content (JSP) </c:if>

The name of the exported scoped variable var for the resulting value of the test condition. The type of the scoped variable is Boolean.

http://java.boot.by/wcd-guide/wcd-guide.html 142 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

The <c:choose> tag works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <c:choose> tag has <c:when> tags. In a switch statement, you can specify a default clause to specify a default action in case none of the cases match. The <c:choose> equivalent of default is <c:otherwise> (optional), but note, it MUST be the LAST action nested within <c:choose>. Syntax:

<c:choose> body content (<when> and <otherwise> subtags) </c:choose>

<c:when test="testCondition"> body content </c:when>

<c:otherwise> conditional block </c:otherwise>

Iterator tags. The <c:forEach> action repeats its nested body content over the collection of objects specified by the items attribute. For example, the JSP code below creates an HTML table with one column that shows the default display value of each item in the collection:

<table> <c:forEach var="customer" items="${customers}"> <tr><td>${customer}</td></tr> </c:forEach> </table>

http://java.boot.by/wcd-guide/wcd-guide.html 143 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

A large number of collection types are supported by <c:forEach>, including all implementations of java.util.Collection (includes List, LinkedList, ArrayList, Vector, Stack, Set), and java.util.Map (includes HashMap, Hashtable, Properties, Provider, Attributes). Arrays of objects as well as arrays of primitive types (e.g. int) are also supported. For arrays of primitive types, the current item for the iteration is automatically wrapped with its standard wrapper class (e.g. Integer for int, Float for float, etc.). If the items attribute is of type java.util.Map, then the current item will be of type java.util.Map. Entry, which has the following two properties: key - the key under which this item is stored in the underlying Map; value - the value that corresponds to this key. Syntax. Syntax 1: Iterate over a collection of objects:

<c:forEach [var="varName"] items="collection" [varStatus="varStatusName"] [begin="begin"] [end="end"] [step="step"]> body content (JSP) </c:forEach>

Syntax 2: Iterate a fixed number of times:

<c:forEach [var="varName"] [varStatus="varStatusName"] begin="begin" end="end" [step="step"]> body content (JSP) </c:forEach>

If specified, begin must be >= 0. If end is specified and it is less than begin, the loop is simply not executed. If specified, step must be >= 1. If items is null, it is treated as an empty collection, i.e.,
http://java.boot.by/wcd-guide/wcd-guide.html 144 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

no iteration is performed. If begin is greater than OR EQUAL to the size of items, NO iteration is performed. Examples:

<c:forEach var="i" start="1" end="10"> Item <c:out value="${i}/><p> </c:forEach>

<c:forEach var="emp" items="employees"> Employee: <c:out value="${emp.name}"/> </c:forEach>

<c:forTokens> iterates over tokens, separated by the supplied delimiters. The items attribute specifies the string to tokenize and the delimiters attribute specifies a list of delimiters (similar to the way java.util.StringTokenizer works). Syntax:

<c:forTokens items="stringOfTokens" delims="delimiters" [var="varName"] [varStatus="varStatusName"] [begin="begin"] [end="end"] [step="step"]> body content </c:forTokens>

For example:

<c:forTokens items="moe,larry,curly" delimiters="," var="stooge"> <c:out value="${stooge}/><p>

http://java.boot.by/wcd-guide/wcd-guide.html 145 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

</c:forTokens>

URL Related tags. JSTL provides several tags for handling URLs and accessing Web resources. URLs can be difficult to work with when you must worry about URL rewriting (to insert the session ID when the browser doesn't support cookies), URL encoding of parameters, and referencing resources from a separate servlet context within the same servlet container. The <c:url> tag formats a URL into a string and stores it into a variable. The <c:url> tag automatically performs URL rewriting when necessary. The var attribute specifies the variable that will contain the formatted URL. The optional scope attribute specifies the scope of the variable (page is the default). The value attribute specifies the URL to be formatted. Syntax. Syntax 1: Without body content:

<c:url value="value" [context="context"] [var="varName"] [scope="{page|request|session|application}"]/>

Syntax 2: With body content to specify query string parameters:

<c:url value="value" [context="context"] [var="varName"] [scope="{page|request|session|application}"]> <c:param> subtags </c:url>

As a security precaution, the URL is only rewritten for relative URLs.

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

http://java.boot.by/wcd-guide/wcd-guide.html 146 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<c:param name="name"> parameter value </c:param>

Examples:

<c:url var="trackURL" value="/tracking.html"/>

<c:url var="trackURL" value="/track.jsp" context="/tracking"/>

<c:url value="/track.jsp" var="trackingURL"> <c:param name="trackingId" value="1234"/> <c:param name="reportType" value="summary"/> </c:url>

The <c:import> tag is similar to the <jsp:import> tag, but it is much more powerful. For example, the <jsp:import> tag usually just imports resources from within the same servlet container. The <jsp:import> tag can import data from other servers as well as from within the same container. Also, the <jsp:import> tag automatically inserts the imported content directly into the JSP. Although the <c:import> tag can automatically insert content, it can also return the content as either a STRING or a READER. The only required attribute in the <c:import> tag is url, which specifies the URL to be imported. As with the <c:url> tag, the URL may be a relative URL, a context-relative URL, or an absolute URL. Syntax. Syntax 1: Resource content inlined or exported as a String object:

http://java.boot.by/wcd-guide/wcd-guide.html 147 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<c:import url="url" [context="context"] [var="varName"] [scope="{page|request|session|application}"] [charEncoding="charEncoding"]> optional body content for <c:param> subtags </c:import>

Syntax 2: Resource content exported as a Reader object:

<c:import url="url" [context="context"] varReader="varReaderName" [charEncoding="charEncoding"]> body content where varReader is consumed by another action </c:import>

Examples:

<c:import var="data" url="/data.xml"/> <c:out value="${data}/>

is equivalent to:

<c:import url="/data.xml"/>

Using of reader:

http://java.boot.by/wcd-guide/wcd-guide.html 148 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<c:import url="/data.xml" varReader="dataReader" scope="session"/>

<c:redirect> sends an HTTP redirect to the client. Syntax. Syntax 1: Without body content:

<c:redirect url="value" [context="context"] />

Syntax 2: With body content to specify query string parameters:

<c:redirect url="value" [context="context"]> <c:param> subtags </c:redirect>

Chapter 10. Building a Custom Tag Library

Describe the semantics of the "Classic" custom tag event model when each event method (doStartTag, doAfterBody, and doEndTag) is executed, and explain what the return value for each event method means; and write a tag handler class.
The classes and interfaces used to implement classic tag handlers are contained in the javax. servlet.jsp.tagext package. Classic tag handlers implement either the Tag, IterationTag, or BodyTag interface. Interfaces can be used to take an existing Java object and make it a tag handler. For newly created classic tag handlers, you can use the TagSupport and BodyTagSupport classes as base classes. These classes and interfaces are contained in the javax.servlet.jsp.tagext package. Tag handler methods defined by the Tag and BodyTag interfaces are called by the JSP page's servlet at various points during the evaluation of the tag. When the start element of a custom tag is encountered, the JSP page's servlet calls methods to initialize the appropriate handler and then invokes the handler's doStartTag method. When the end element of a custom tag is encountered, the handler's doEndTag method is invoked for all but simple tags. Additional methods are invoked in between when a tag handler needs to manipulate the body of the tag.
http://java.boot.by/wcd-guide/wcd-guide.html 149 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Table 10.1. Tag Handler Methods


Tag Type Basic Attributes Body Body, iterative evaluation Body, manipulation Interface Tag Tag Tag IterationTag BodyTag doStartTag, doEndTag doStartTag, doEndTag, setAttribute1, ..., setAttributeN , release doStartTag, doEndTag, release doStartTag, doAfterBody, doEndTag, release doStartTag, doInitBody, doAfterBody, doEndTag, release Methods

A tag handler has access to an API that allows it to communicate with the JSP page. The entry points to the API are two objects: the JSP context (javax.servlet.jsp.JspContext) for simple tag handlers and the page context (javax.servlet.jsp.PageContext) for classic tag handlers. JspContext provides access to implicit objects. PageContext extends JspContext with HTTP-specific behavior. A tag handler can retrieve all the other implicit objects (request, session, and application) accessible from a JSP page through these objects. In addition, implicit objects can have named attributes associated with them. Such attributes are accessed using [set|get]Attribute methods. The Tag interface defines the basic protocol between a tag handler and a JSP page's servlet. It defines the life cycle and the methods to be invoked when the start and end tags are encountered. The JSP page's servlet invokes the setPageContext, setParent, and attribute setting methods before calling doStartTag. The JSP page's servlet also guarantees that release will be invoked on the tag handler before the end of the page. Here is a typical tag handler method invocation sequence:

ATag t = new ATag(); t.setPageContext(...); t.setParent(...); t.setAttribute1(value1); t.setAttribute2(value2); t.doStartTag(); t.doEndTag(); t.release();

The BodyTag interface extends Tag by defining additional methods that let a tag handler access its body. The interface provides three new methods:
http://java.boot.by/wcd-guide/wcd-guide.html 150 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

setBodyContent - Creates body content and adds to the tag handler doInitBody - Called before evaluation of the tag body doAfterBody - Called after evaluation of the tag body

A typical invocation sequence is:

t.doStartTag(); out = pageContext.pushBody(); t.setBodyContent(out); // perform any initialization needed after body content is set t.doInitBody(); t.doAfterBody(); // while doAfterBody() returns EVAL_BODY_AGAIN we // iterate body evaluation ... t.doAfterBody(); t.doEndTag(); out = pageContext.popBody(); t.release();

If the tag handler does not need to manipulate the body, the tag handler should implement the Tag interface. If the tag handler implements the Tag interface and the body of the tag needs to be evaluated, the doStartTag method needs to return Tag.EVAL_BODY_INCLUDE; otherwise it should return Tag.SKIP_BODY. If a tag handler needs to iteratively evaluate the body, it should implement the IterationTag interface. The tag handler should return IterationTag.EVAL_BODY_AGAIN from doAfterBody method if it determines that the body needs to be evaluated again. If the tag handler needs to manipulate the body, the tag handler must implement BodyTag (or be derived from BodyTagSupport). When a tag handler implements the BodyTag interface, it must implement the doInitBody and the doAfterBody methods. These methods manipulate body content passed to the tag handler by the JSP page's servlet. Body content supports several methods to read and write its contents. A tag handler can use the body content's getString or getReader methods to extract information from the body, and the writeOut(out) method to write the body contents to an out stream. The writer supplied to the writeOut method is obtained using the tag handler's getPreviousOut method. This method is used to ensure that a tag handler's results are available to an enclosing tag handler.

http://java.boot.by/wcd-guide/wcd-guide.html 151 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

If the body of the tag needs to be evaluated, the doStartTag method needs to return BodyTag. EVAL_BODY_BUFFERED; otherwise, it should return Tag.SKIP_BODY. The doInitBody method is called after the body content is set but before it is evaluated. You generally use this method to perform any initialization that depends on the body content. The doAfterBody method is called AFTER the body content is evaluated. doAfterBody must return an indication of whether to continue evaluating the body. Thus, if the body should be evaluated again, as would be the case if you were implementing an iteration tag, doAfterBody should return IterationTag.EVAL_BODY_AGAIN; otherwise, doAfterBody should return Tag.SKIP_BODY. The following example reads the content of the body (which contains a SQL query) and passes it to an object that executes the query. Since the body does not need to be reevaluated, doAfterBody returns Tag.SKIP_BODY:

public class QueryTag extends BodyTagSupport { public int doAfterBody() throws JspTagException { BodyContent bc = getBodyContent(); // get the bc as string String query = bc.getString(); // clean up bc.clearBody(); try { Statement stmt = connection.createStatement(); result = stmt.executeQuery(query); } catch (SQLException e) { throw new JspTagException("QueryTag: " + e.getMessage()); } return SKIP_BODY; } }

When you extend TagSupport, the doStartTag and doEndTag methods use the following return values (defined as constants):

doStartTag returns one of the following values:


r

Tag.EVAL_BODY_INCLUDE - Allow body text (including JSP code) between the start and end tags. Note, however, that body text is not available to the doEndTag method. Tag.SKIP_BODY - Ignore body text. Any text between the start and end tags is not evaluated or displayed.

http://java.boot.by/wcd-guide/wcd-guide.html 152 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

doEndTag returns one of the following values:


r r

Tag.EVAL_PAGE - Continue evaluating the page. Tag.SKIP_PAGE - Ignore the remainder of the page.

The following tag handler outputs messages from the doStartTag and doEndTag methods. These messages form the contents of the tag in the JSP page:

import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.IOException; public class SimpleTag extends TagSupport { /** * Executes when the tag is started. */ public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello from doStartTag()"); // Allow text in the body of the tag. return EVAL_BODY_INCLUDE; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } /** * Executes with the end tag. */ public int doEndTag() throws JspException { try { pageContext.getOut().print("Hello from doEndTag()"); // Continue evaluating the page. return EVAL_PAGE; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } }

If your custom tag must modify body content, extend the BodyTagSupport class. It implements BodyTag. Provides the doInitBody and doAfterBody methods. Extend this class when your tag handler must modify body content. The doStartTag method can return BodyTag.
http://java.boot.by/wcd-guide/wcd-guide.html 153 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

EVAL_BODY_BUFFERED in addition to Tag.EVAL_BODY_INCLUDE and Tag.SKIP_BODY. The BodyContent object is a subclass of JspWriter. JspWriter is the writer used internally for the JSP out variable. The BodyContent object is available to doInitBody, doAfterBody, and doEndTag through the bodyContent variable. You can integrate this object's contents with the original JspWriter in the doEndTag method. The BodyContent object contains methods that you use to write output as well as methods to read, clear, and retrieve its contents. For example, you can use bodyContent.getString() to retrieve the writer's contents, optionally modifying the contents before integrating them with the original JspWriter. The servlet container invokes the doInitBody method if the doStartTag method returns BodyTag. EVAL_BODY_BUFFERED. Use this method to initialize the body content, if necessary. Then the tag handler processes the body, and invokes the doAfterBody method. The doAfterBody method returns Tag.SKIP_BODY or IterationTag.EVAL_BODY_AGAIN. If it returns IterationTag.EVAL_BODY_AGAIN, the servlet container loops back and re-executes the body. This lets you loop over repetitive data, such as enumerations and database result sets. The following example shows using the doInitBody and doAfterBody methods. It also shows how to integrate bodyContent output with the output stream:

public class TestBody extends BodyTagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print("doStartTag()"); return EVAL_BODY_BUFFERED; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } public void doInitBody() throws JspException { try { // Note, that this is a different writer than the one // you have in doStartTag and doEndTag. bodyContent.print("doInitBody()"); } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } public int doAfterBody() throws JspException { try { // Note, that this is a different writer than the one // you have in doStartTag and doEndTag.
http://java.boot.by/wcd-guide/wcd-guide.html 154 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

bodyContent.print("doAfterBody()"); // return IterationTag.EVAL_BODY_AGAIN; // Use this to loop return SKIP_BODY; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } public int doEndTag() throws JspException { try { // Write from bodyContent writer to original writer. pageContext.getOut().print(bodyContent.getString()); // Now we're back to the original writer. pageContext.getOut().print("doEndTag()"); return EVAL_PAGE; } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } } }

Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes.
A PageContext is an object that provides a context to store references to objects used by the page, encapsulates implementation-dependent features, and provides convenience methods. A JSP page implementation class can use a PageContext to run unmodified in any compliant JSP container while taking advantage of implementation-specific improvements like high performance JspWriters. The PageContext provides a number of facilities to the page/component author and page implementor, including:

a single API to manage the various scoped namespaces a number of convenience API's to access various public objects a mechanism to obtain the JspWriter for output a mechanism to manage session usage by the page a mechanism to expose page directive attributes to the scripting environment mechanisms to forward or include the current request to other active components in the application a mechanism to handle errorpage exception processing

http://java.boot.by/wcd-guide/wcd-guide.html 155 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

public abstract class JspContext { public abstract void setAttribute(String name, Object value); public abstract void setAttribute(String name, Object value, int scope); public abstract Object getAttribute(String name); public abstract Object getAttribute(String name, int scope); public abstract Object findAttribute(String name); public abstract void removeAttribute(String name); public abstract void removeAttribute(String name, int scope); public abstract int getAttributesScope(String name); public abstract Enumeration getAttributeNamesInScope(int scope); public abstract JspWriter getOut(); }

public abstract class PageContext extends JspContext { public abstract javax.servlet.http.HttpSession getSession(); public abstract java.lang.Object getPage(); public abstract javax.servlet.ServletRequest getRequest(); public abstract javax.servlet.ServletResponse getResponse(); public abstract java.lang.Exception getException(); public abstract javax.servlet.ServletConfig getServletConfig(); public abstract javax.servlet.ServletContext getServletContext(); public abstract void forward(java.lang.String relativeUrlPath) throws javax.servlet.ServletException, java.io.IOException; public abstract void include(java.lang.String relativeUrlPath) throws javax.servlet.ServletException, java.io.IOException; public abstract void handlePageException(java.lang.Exception e) throws javax.servlet.ServletException, java.io.IOException; }

Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.
An object created by the enclosing tag handler of a group of nested tags is available to all inner tag handlers. This form of object sharing has the advantage that it uses a private namespace for the objects, thus reducing the potential for naming conflicts. To access an object created by an enclosing tag, a tag handler must first obtain its enclosing tag with the static method TagSupport.

http://java.boot.by/wcd-guide/wcd-guide.html 156 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

findAncestorWithClass(from, class) or the TagSupport.getParent() method. The former method should be used when a specific nesting of tag handlers cannot be guaranteed. Once the ancestor has been retrieved, a tag handler can access any statically or dynamically created objects. Statically created objects are members of the parent. Private objects can also be created dynamically. Such objects can be stored in a tag handler with the setValue method and retrieved with the getValue method. The following example illustrates a tag handler that supports both the named and private object approaches to sharing objects. In the example, the handler for a query tag checks whether an attribute named connectionId has been set. If the connection attribute has been set, the handler retrieves the connection object from the page context. Otherwise, the tag handler first retrieves the tag handler for the enclosing tag, and then retrieves the connection object from that handler:

public class QueryTag extends BodyTagSupport { public int doStartTag() throws JspException { String cid = getConnectionId(); Connection connection; if (cid != null) { // there is a connection id, use it connection =(Connection)pageContext.getAttribute(cid); } else { ConnectionTag ancestorTag = (ConnectionTag) findAncestorWithClass(this, ConnectionTag.class); if (ancestorTag == null) { throw new JspTagException("A query without a connection attribute must be nested within a connection tag."); } connection = ancestorTag.getConnection(); ... } } }

The query tag implemented by this tag handler could be used in either of the following ways:

<tt:connection cid="con01" ... > ... </tt:connection> <tt:query id="balances" connectionId="con01">


http://java.boot.by/wcd-guide/wcd-guide.html 157 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

SELECT account, balance FROM acct_table WHERE customer_number = ? <tt:param value="${requestScope.custNumber}" /> </tt:query> <tt:connection ... > <tt:query cid="balances"> SELECT account, balance FROM acct_table WHERE customer_number = ? <tt:param value="${requestScope.custNumber}" /> </tt:query> </tt:connection>

The TLD for the tag handler indicates that the connectionId attribute is optional with the following declaration:

<tag> ... <attribute> <name>connectionId</name> <required>false</required> </attribute> </tag>

Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag.
JSP 2.0 introduces a new type of tag extension called a Simple Tag Extension. Simple Tag Extensions can be written in one of two ways:

In Java, by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface. This class is intended for use by advanced page authors and tag library developers who need the flexibility of the Java language in order to write their tag handlers. The javax. servlet.jsp.tagext.SimpleTagSupport class provides a default implementation for all methods in SimpleTag. In JSP, using tag files. This method can be used by page authors who do not know Java. It can also be used by advanced page authors or tag library developers who know Java

http://java.boot.by/wcd-guide/wcd-guide.html 158 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

but are producing tag libraries that are presentation-centric or can take advantage of existing tag libraries. In addition to being simpler to work with, Simple Tag Extensions do not directly rely on any servlet APIs, which allows for potential future integration with other technologies. This is facilitated by the JspContext class, which PageContext now extends. JspContext provides generic services such as storing the JspWriter and keeping track of scoped attributes, whereas PageContext has functionality specific to serving JSPs in the context of servlets. Whereas the Tag interface relies on PageContext, SimpleTag only relies on JspContext. Unlike classic tag handlers, SimpleTag does not extend Tag.

package javax.servlet.jsp.tagext; public interface SimpleTag extends JspTag { public void doTag()throws JspException, java.io.IOException; public void setParent(JspTag parent); public JspTag getParent(); public void setJspContext(JspContext pc); public void setJspBody(JspFragment jspBody); }

Most SimpleTag handlers should extend javax.servlet.jsp.tagext.SimpleTagSupport. This is the convenience class, similar to TagSupport or BodyTagSupport. There are also some helpful methods included in this class that include:

public JspFragment getJspBody() - returns the body passed in by the container via setJspBody. The JspFragment encapsulates the body of the tag. If the JspFragment is null, it indicates that tag has a body content type of empty. public static final JspTag findAncestorWithClass(JspTag from, java.lang.Class klass) - finds the instance of a given class type that is closest to a given instance. This method uses the getParent() method from the Tag and/or SimpleTag interfaces. This method is used for coordination among cooperating tags. While traversing the ancestors, for every instance of TagAdapter (used to allow collaboration between classic Tag handlers and SimpleTag handlers) encountered, the tag handler returned by TagAdapter.getAdaptee() is compared to klass. In a case where the tag handler matches this class, and not its TagAdapter, is returned.

The body of a Simple Tag, if present, is translated into a JSP Fragment and passed to the setJspBody method. The tag can then execute the fragment as many times as needed. Because JSP fragments do not support scriptlets, the <body-content> of a SimpleTag cannot be "JSP". A TLD is invalid if it specifies "JSP" as the value for <body-content> for a tag whose handler implements the SimpleTag interface. JSP containers are recommended to but not required to produce an error if "JSP" is specified in this case. During the translation phase, various pieces of the page are translated into implementations of
http://java.boot.by/wcd-guide/wcd-guide.html 159 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

the javax.servlet.jsp.tagext.JspFragment abstract class, before being passed to a tag handler. JSP fragments are pieces of JSP code. Written using standard JSP syntax, a fragment is translated into an implementation of the interface JspFragment for use by tag handlers. A JSP fragment is used to represent the body of a tag for use with a SimpleTag handler. The JspFragment interface declares only two methods: invoke and getJspContext.

package javax.servlet.jsp.tagext; public abstract class JspFragment { public abstract void invoke(java.io.Writer out) throws JspException, java.io.IOException; public abstract JspContext getJspContext(); }

invoke causes the fragment to be executed, writing the output produced to the Writer passed to it. You can invoke a fragment as many times as needed. invoke can throw a SkipPageException, which signals that the fragment has determined that the remainder of the page doesn't need to be evaluated. The following example shows the simple custom tag:

public class MySimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().write("Hello, World !"); } }

The lifecycle of a Simple Tag Handler is straightforward and is not complicated by caching semantics. Once a Simple Tag Handler is instantiated by the Container, it is executed and then discarded. The same instance must not be cached and reused. The following lifecycle events take place for the simple tag handler (in the same order): 1. A new tag handler instance is created each time the tag is encountered by the container. This is done by calling the zero argument constructor on the corresponding implementation class. It is important to note that a new instance must be created for each tag invocation. 2. The setJspContext() and setParent() methods are invoked on the tag handler. If the value being passed is 'null', then the setParent() method need not be called. In the case of tag files, a JspContext wrapper is created so that the tag file can appear to have its own page scope. Calling getJspContext() must return the wrapped JspContext. 3. The container calls the setters for each attribute defined for this tag in the order in which
http://java.boot.by/wcd-guide/wcd-guide.html 160 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

they appear in the JSP page or Tag File. If the attribute value is an expression language expression or a runtime expression, it gets evaluated first and is then passed on to the setter. On the other hand if the attribute is a dynamic-attribute then setDynamicAttribute() is called. 4. The setJspBody() method is called by the container to set the body of this tag, as a JspFragment. A value of null is passed to setJspBody() if the tag is declared to have a <bodycontent> of empty. 5. The doTag() method is called by the container. All tag logic, iteration and body evaluations occur in this method. 6. All variables are synchronized after the doTag() method returns. The following example simply writes the body to the output stream. When the Writer given to invoke is null, the output from invoke goes to the JspWriter associated with the JspContext of the tag handler:

import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class MySimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspBody().invoke(null); } }

The invoke method directs all output to a supplied writer or to the JspWriter returned by the getOut method of the JspContext associated with the tag handler if the writer is null.

<%@ taglib uri="/mytag" prefix="mytag" %> <html> <body> <mytag:MySimpleTag> Hello, World ! </mytag:MySimpleTag> </body> </html>

SimpleTagSupport provides the convenience method getJspBody() to return the JspFragment generated for the body content. The following example demonstrates that a SimpleTag can

http://java.boot.by/wcd-guide/wcd-guide.html 161 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

obtain a copy of the body so that it can use or MANIPULATE it:

public class MySimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { StringWriter sw = new StringWriter(); getJspBody().invoke(sw); getJspContex().getOut().write(sw.toString()); } }

is equivalent to:

public class MySimpleTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { StringWriter sw = new StringWriter(); jspBody().invoke(sw); getJspContex().getOut().write(sw.toString()); } }

Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag.
Writing a traditional custom tag requires two steps:

Writing and compiling a tag handler. Defining the tag that is associated with the tag handler.

Tag files simplify the process. First, tag files don't need to be compiled. They are compiled as they are invoked. Also, tag files allow tag extensions to be written using only JSP syntax. This means someone who does not know Java can also write tag extensions. Secondly, a tag element in a tag library descriptor describes the name to be used in a JSP page to reference the custom action. Using tag files, the name of a custom action is the same as the tag file representing the action. Therefore, you don't need a tag library descriptor at all. A tag file looks like a JSP page. It can have directives, scripts, EL expressions, and standard and custom tags. A tag file has the . tag or .tagx extension and can also include other files that contain a common resource. An include file for a tag file has a .tagf extension. To work, tag files must be placed in the WEB-INF/tags directory under your application directory OR a subdirectory under it. The container converts each tag file found in (or uder) WEB-INF/tags
http://java.boot.by/wcd-guide/wcd-guide.html 162 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

into a tag handler. A number of implicit objects are available from inside of a tag file. You can access these objects from a script or an EL expression: Table 10.2. The Tag Files implicit objects
Object request response out session application config jspContext Type javax.servlet.http.HttpServletRequest javax.servlet.http.HttpServletResponse javax.servlet.jsp.JspWriter javax.servlet.http.HttpSession javax.servlet.ServletContext javax.servlet.ServletConfig javax.servlet.jsp.JspContext

This is the example of a tag library in which the tag file simply writes a String to the implicit out object:

<% WEB-INF/tags/myExample.tld %> <% out.println("Hello, World !"); %>

In JSP you need the taglib directive as usual, with the prefix attribute to identify your tag library throughout the page. NOTE, instead of a uri attribute, you have a tagdir attribute. The tagdir attribute refers to the WEB-INF/tags directory OR ANY subdirectory below WEB-INF/tags:

<%@ taglib prefix="simpleTag" tagdir="/WEB-INF/tags" %> <simpleTag:myExample />

http://java.boot.by/wcd-guide/wcd-guide.html 163 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

Combined with the expression language (EL), you can really build a scriptless JSP page very rapidly. The following example accepts an attribute from a calling JSP page and converts it to the upper case:

<% WEB-INF/tags/myExample2.tld %> <%@ attribute name="someAttribute" %> <% someAttribute = someAttribute.toUpperCase(); out.println(someAttribute); %>

The following JSP page that uses the tag file:

<%@ taglib prefix="simpleTag" tagdir="/WEB-INF/tags" %> <simpleTag:myExample2 someAttribute="hello" />

example, which is Java-code-free:

<% WEB-INF/tags/myExample3.tag %> <%@ variable name-given="myVar" scope="AT_BEGIN" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="myVar" value="3"/> After: ${myVar} <jsp:doBody/>

To use the tag file, use the following JSP page:

http://java.boot.by/wcd-guide/wcd-guide.html 164 / 166 2004/6/13 12:08:16

SCWCD 1.4 Study Guide

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="sampleTag" tagdir="/WEB-INF/tags" %> <c:set var="myVar" value="1"/> Before: ${myVar} <br> <simpleTag:myExample3/>

Chapter 11. J2EE Patterns

Given a scenario description with a list of issues, select a pattern that would solve the issues. The list of patterns you must know are: Intercepting Filter, Model-ViewController, Front Controller, Service Locator, Business Delegate, and Transfer Object.

Intercepting Filter. Model-View-Controller. Front Controller. Service Locator. Business Delegate. Transfer Object.

see: http://java.sun.com/blueprints/corej2eepatterns/

Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-ViewController, Front Controller, Service Locator, Business Delegate, and Transfer Object.

Intercepting Filter. Model-View-Controller. Front Controller. Service Locator. Business Delegate. Transfer Object.

see: http://java.sun.com/blueprints/corej2eepatterns/

http://java.boot.by/wcd-guide/wcd-guide.html 165 / 166 2004/6/13 12:08:17

SCWCD 1.4 Study Guide

Appendixes
Appendix A. First Appendix

First Section
sdsds

Second Section
sdsds

Third Section
sdsds

Bibliography
[Servlet_2.4] Java Servlet Specification Version 2.4 (http://java.sun.com/products/servlet). [JSP_2.0] JavaServer Pages Specification Version 2.0 (http://java.sun.com/products/jsp). [JavaRanch] JavaRanch.com forum for SCWCD Certification. [HTTP-1.0] Internet RFC: HTTP/1.0 - RFC 1945 (ftp://ftp.isi.edu/in-notes/rfc1945.txt) . [HTTP-1.1] Internet RFC: HTTP/1.1 - RFC 2616 (ftp://ftp.isi.edu/in-notes/rfc2616.txt) .

http://java.boot.by/wcd-guide/wcd-guide.html 166 / 166 2004/6/13 12:08:17

Você também pode gostar