Browse by

1 - java platform, enterprise edition

1 - JAVA PLATFORM, ENTERPRISE EDITION
1.1 the state of java EE
The Java EE 6 is the current Java Enterprise Edition specification (as of Oct. 2010). Compared to the previous specification, it introduces several new features:
•

Profiles, configurations of the Java EE platform targeted at specific classes of applications. Specifically, the Java EE 6 platform introduces a Web Profile targeted at web applications, as well as a Full Profile that contains all Java EE technologies. New technologies, including the following:
• • •

New features for Enterprise JavaBeansTM (EJBTM) components New features for servlets New features for JavaServer TM Faces components

1.2 the application model
The application model starts with the Java programming language and the Java Virtual Machine. This combination provides high portability, scalability and developing efficiency. Java EE is designed to support applications that implement enterprise services for customers, employees, suppliers, partners, and others who make demands on or contributions to the enterprise. Such applications are inherently complex, potentially accessing data from a variety of sources and distributing applications to a variety of clients. To better control and manage these applications, the business functions to support these various users are conducted in the middle tier. The middle tier represents an environment that is closely controlled by an enterprise's information technology department. The middle tier is typically run on dedicated server hardware and has access to the full services of the enterprise. The Java EE application model defines an architecture for implementing services as multi-tier applications that deliver the scalability, accessibility, and manageability needed by enterpriselevel applications. This model partitions the work needed to implement a multi-tier service into two parts: the business and presentation logic to be implemented by the developer, and the standard system services provided by the Java EE platform. The developer can rely on the platform to provide solutions for the hard systems-level problems of developing a multi-tier service.

1

1 - java platform, enterprise edition

1.3 distributed multitiered applications
The Java EE platform uses a distributed multitiered application model for enterprise applications. Application logic is divided into components according to function, and the various application components that make up a Java EE application are installed on different machines depending on the tier in the multitiered Java EE environment to which the application component belongs. Figure 1.1 shows generic multitiered Java EE applications divided into the tiers described in the list below. The Java EE application parts shown in figure 1.1 are presented in the Java EE components section.
• • • •

client-tier components run on the client machine. web-tier components run on the Java EE server. business-tier components run on the Java EE server. enterprise information system (EIS)-tier software runs on the EIS server

Figure 1.1 Distributed multitiered applications
Although a Java EE application can consist of the three or four tiers shown in figure 1.1, Java EE multitiered applications are generally considered to be three-tiered applications because they are distributed over three locations: client machines, the Java EE server machine, and the database or legacy machines at the back end. Three-tiered applications that run in this way extend the standard two-tiered client and server model by placing a multithreaded application server between the client application and back-end storage.

2

1 - java platform, enterprise edition

1.4 java EE components
Java EE applications are made up of components. A Java EE component is a self-contained functional software unit that is assembled into a Java EE application with its related classes and files and that communicates with other components. The Java EE specification defines the following Java EE components:
• • •

Application clients and applets are components that run on the client. Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components are web components that run on the server. Enterprise JavaBeansTM (EJB) components (enterprise beans) are business components that run on the server.

Java EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between Java EE components and “standard” Java classes is that Java EE components are assembled into a Java EE application, are verified to be well formed and in compliance with the Java EE specification, and are deployed to production, where they are run and managed by the Java EE server.

1.5 java EE Clients
A Java EE client can be a web client or an application client.

1.5.1 Web Clients
A web client consists of two parts: (1) dynamic web pages containing various types of markup language (HTML, XML, and so on), which are generated by web components running in the web tier, and (2) a web browser, which renders the pages received from the server. A web client is sometimes called a thin client. Thin clients usually do not query databases, execute complex business rules, or connect to legacy applications. When you use a thin client, such heavyweight operations are off-loaded to enterprise beans executing on the Java EE server, where they can leverage the security, speed, services, and reliability of Java EE server-side technologies.

1.5.2 Applets
A web page received from the web tier can include an embedded applet. An applet is a small client application written in the Java programming language that executes in the Java virtual machine installed in the web browser. However, client systems will likely need the Java Plug-in and possibly a security policy file in order for the applet to successfully execute in the web browser. Web components are the preferred API for creating a web client program because no plug-ins or security policy files are needed on the client systems. Also, web components enable cleaner and more modular application design because they provide a way to separate applications programming from web page design. Personnel involved in web page design thus do not need to understand Java programming language syntax to do their jobs.

3

1 - java platform, enterprise edition 1.5.3 Application Clients
An application client runs on a client machine and provides a way for users to handle tasks that require a richer user interface than can be provided by a markup language. It typically has a graphical user interface (GUI) created from the Swing or the Abstract Window Toolkit (AWT) API, but a command-line interface is certainly possible. Application clients directly access enterprise beans running in the business tier. However, if application requirements warrant it, an application client can open an HTTP connection to establish communication with a servlet running in the web tier. Application clients written in languages other than Java can interact with Java EE 6 servers, enabling the Java EE 6 platform to interoperate with legacy systems, clients, and non-Java languages.

1.5.4 The JavaBeans Component Architecture
The server and client tiers might also include components based on the JavaBeans component architecture (JavaBeans components) to manage the data flow between an application client or applet and components running on the Java EE server, or between server components and a database. JavaBeans components are not considered Java EE components by the Java EE specification. JavaBeans components have properties and have get and set methods for accessing the properties. JavaBeans components used in this way are typically simple in design and implementation but should conform to the naming and design conventions outlined in the JavaBeans component architecture.

1.5.5 Java EE Server Communications
Figure 1.2 shows the various elements that can make up the client tier. The client communicates with the business tier running on the Java EE server either directly or, as in the case of a client running in a browser, by going through JSP pages or servlets running in the web tier. Your Java EE application uses a thin browser-based client or thick application client. In deciding which one to use, you should be aware of the trade-offs between keeping functionality on the client and close to the user (thick client) and off-loading as much functionality as possible to the server (thin client). The more functionality you off-load to the server, the easier it is to distribute, deploy, and manage the application; however, keeping more functionality on the client can make for a better perceived user experience.

4

or finance.java platform. is handled by enterprise beans running in the business tier. enterprise edition
Figure 1. like the client tier. and sends it back to the client program.
1. An enterprise bean also retrieves data from storage.3 shows how an enterprise bean receives data from client programs. Static HTML pages and applets are bundled with web components during application assembly but are not considered web components by the Java EE specification. are not considered web components. The web tier. like HTML pages.1 . might include a JavaBeans component to manage the user input and send that input to enterprise beans running in the business tier for processing. which is logic that solves or meets the needs of a particular business domain such as banking. Servlets are Java programming language classes that dynamically process requests and construct responses. processes it (if necessary). Server-side utility classes can also be bundled with web components and. and sends it to the enterprise information system tier for storage. Java Server Faces technology builds on servlets and JSP technology and provides a user interface component framework for web applications. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. processes it (if necessary).
5
. Figure 1.2 Server communication
1.7 business components
Business code.6 web components
Java EE web components are either servlets or pages created using JSP technology (JSP pages) and/or Java Server Faces technology. retail.

you are free to concentrate on solving the business problem at hand. Business and EIS Tiers
1. Before a web. or application client component can be executed. it must be assembled into a Java EE module and deployed into its container. enterprise edition
Figure 1. and other complex low-level details.
1. Java EE application components might need access to enterprise information systems for database connectivity. For example.
1. database systems.9 java EE Containers
Normally. In addition. resource pooling. multithreading. The component-based and platform-independent Java EE architecture makes Java EE applications easy to write because business logic is organized into reusable components.
6
.3 Web. thin-client multitiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management. and other legacy information systems.8 enterprise information system tier
The enterprise information system tier handles EIS software and includes enterprise infrastructure systems such as enterprise resource planning (ERP).1 Container Services
Containers are the interface between a component and the low-level platform-specific functionality that supports the component.9.java platform. the Java EE server provides underlying services in the form of a container for every component type. enterprise bean. mainframe transaction processing.1 . Because you do not have to develop these services yourself.

application components within the same Java EE application can behave differently based on where they are deployed. The Java EE remote connectivity model manages low-level communications between clients and enterprise beans.
7
.
1. The container also manages nonconfigurable services such as enterprise bean and servlet life cycles. Here are some of the highlights:
• • • •
The Java EE security model lets you configure a web component or enterprise bean so that system resources are accessed only by authorized users.
Because the Java EE architecture provides configurable services. JNDI lookup services provide a unified interface to multiple naming and directory services in the enterprise so that application components can access these services.1 . Java Naming and Directory Interface (JNDI) lookups. an enterprise bean can have security settings that allow it a certain level of access to database data in one production environment and another level of database access in another production environment. After an enterprise bean is created.9. Container settings customize the underlying support provided by the Java EE server. enterprise edition
The assembly process involves specifying container settings for each component in the Java EE application and for the Java EE application itself.4. and remote connectivity. including services such as security. The Java EE transaction model lets you specify relationships among methods that make up a single transaction so that all methods in one transaction are treated as a single unit. data persistence. transaction management.2 Container Types
The deployment process installs Java EE application components in the Java EE containers illustrated in figure 1. and access to the Java EE platform APIs. database connection resource pooling. a client invokes methods on it as if it were in the same virtual machine.java platform. For example.

test. a web service can use XML and a schema to produce price lists. These XML-based standards and protocols are introduced in the following sections. Enterprise JavaBeans (EJB) container .manages the execution of applets. Web components and their container run on the Java EE server. develop. A partner company might put the XML pricing information through a tool to create a marketing presentation. Enterprise beans and their container run on the Java EE server. extensible.manages the execution of enterprise beans for Java EE applications. video. A Java EE server provides EJB and web containers.the runtime portion of a Java EE product. enterprise edition Figure 1.10 support for web services
Web services are web-based enterprise applications that use open.manages the execution of application client components. No low-level programming is needed because the XML API implementations do the work of translating the application data to and from an XML-based data stream that is sent over the standardized XML-based transport protocols. you send documents containing the service data back and forth. To write web services and clients with the Java EE XML APIs. For example. or for document-oriented web services. maps.4 Java EE Server and Containers
• • • • •
Java EE server . computeraided design (CAD) documents and the like. The Java EE platform provides the XML APIs and tools you need to quickly design. all you do is pass parameter data to the method calls and process the data returned. Another company might read the XML pricing information into an application for processing. or any kind of binary data such as audio. Here are examples:
• • •
One company might put XML pricing information through a program to translate the XML to HTML so that it can post the price lists to its intranet. This does not necessarily mean that the data being transported includes XML tags because the transported data can itself be plain text. and companies that receive the price lists and schema can have their own stylesheets to handle the data in a way that best suits their needs. Application client container . The next section introduces XML and explains how parties doing business can use XML tags and schemas to exchange data in a meaningful way. Web container .1 . Application clients and their container run on the client. XML-based standards and transport protocols to exchange data with calling clients.
1. the parties are free to create their own tags to describe the data. set up schemas to specify which tags can be used in a particular kind of XML document.1 XML
XML is a cross-platform. and use XML stylesheets to manage the display and handling of the data. Consists of a web browser and Java Plug-in running on the client together.10.
8
. The translation of data to a standardized XML-based data stream is what makes web services and clients written with the Java EE XML APIs fully interoperable. Applet container . XML data.manages the execution of JSP page and servlet components for Java EE applications. and deploy web services and clients that fully interoperate with other web services and clients running on Java-based or non-Java-based platforms. program files. When XML data is exchanged between parties. text-based standard for representing data.
1.java platform.

WSDL service descriptions can be stored in UDDI registries or published on the web (or both). Discovery and Integration (UDDI) and ebXML.2 SOAP Transport Protocol
Client requests and web service responses are transmitted as Simple Object Access Protocol (SOAP) messages over HTTP to enable a completely interoperable exchange between clients and web services.10.
1.
9
.11 java EE 6 core technologies and APIs
Figure 1. The Sun Java System Application Server Platform Edition 8 provides a tool for generating the WSDL specification of a web service that uses remote procedure calls to communicate with clients.java platform.1 .
1. and SOAP is an XML-based protocol that follows the HTTP request-and-response model. such as Universal Description. The description includes the name of the service.10. and ways to communicate with the service. all running on different platforms and at various locations on the Internet. where the information can be readily and globally accessed by clients who want to do business.4 UDDI and ebXML Standard Formats
Other XML-based standards. make it possible for businesses to publish information on the Internet about their products and web services.10. The SOAP portion of a transported message handles the following:
• • •
Defines an XML-based envelope to describe what is in the message and how to process the message Includes XML-based encoding rules to express instances of application-defined data types within the message Defines an XML-based convention for representing the request to the remote service and the resulting response
1.3 WSDL Standard Format
The Web Services Description Language (WSDL) is a standardized XML format for describing network services. HTTP is a familiar request-and response standard for sending messages over the Internet. the location of the service. The following sections give a brief summary of the technologies required by the Java EE platform. and the APIs used in Java EE applications. enterprise edition 1.5 illustrates the availability of the Java EE 6 platform APIs in each Java EE container type.

If the client terminates.5 Java EE Platform APIs 1. or enterprise bean. There are two kinds of enterprise beans: session beans and message-driven beans. the persistence manager ensures that the entity data is saved. A message-driven bean combines features of a session bean and a message listener.2 Java Servlet Technology
Java servlet technology lets you define HTTP-specific servlet classes. You can think of an enterprise bean as a building block that can be used alone or with other enterprise beans to execute business logic on the Java EE server. entity beans have been replaced by Java persistence API entities.3 JavaServer Pages Technology
JavaServer Pages (JSP) technology lets you put snippets of servlet code directly into a textbased document. An entity represents persistent data stored in one row of a database table. which determine how the page constructs dynamic content.11. In Java EE 5.4 JavaServer Pages Standard Tag Library
The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to many JSP applications.11.1 .
1. Instead of mixing tags from numerous vendors in your JSP applications.java platform.1 Enterprise JavaBeans Technology
An Enterprise JavaBeans (EJB) component. you employ a single.
1. WML.
1. This standardization allows you to deploy your applications on any JSP container that supports JSTL and makes it more likely that the
10
. When the client finishes executing. standard set of tags. enterprise edition
Figure 1.11. or if the server shuts down. allowing a business component to receive messages asynchronously. A session bean represents a transient conversation with a client. Although servlets can respond to any type of request. and XML) and JSP elements. Commonly.11. they are commonly used to extend the applications hosted by web servers. A servlet class extends the capabilities of servers that host applications that are accessed by way of a request-response programming model. these are Java Message Service (JMS) messages. A JSP page is a text-based document that contains two types of text: static data (which can be expressed in any text-based format such as HTML. is a body of code having fields and methods to implement modules of business logic. the session bean and its data are gone.

1.11.5 JavaServer Faces
JavaServer Faces technology is a user interface framework for building web applications. The main components of JavaServer Faces technology are as follows:
• •

A GUI component framework. A flexible model for rendering components in different kinds of HTML or different markup languages and technologies. A Renderer object generates the markup to render the component and converts the data stored in a model object to types that can be represented in a view. A standard RenderKit for generating HTML/4.01 markup. Input validation Event handling Data conversion between model objects and components Managed model object creation Page navigation configuration

•

The following features support the GUI components:
• • • • •

All this functionality is available via standard Java APIs and XML-based configuration files.

1.11.6 Java Message Service API
The Java Message Service (JMS) API is a messaging standard that allows Java EE application components to create, send, receive, and read messages. It enables distributed communication that is loosely coupled, reliable, and asynchronous.

1.11.7 Java Transaction API
The Java Transaction API (JTA) provides a standard interface for demarcating transactions. The Java EE architecture provides a default auto commit to handle transaction commits and rollbacks. An auto commit means that any other applications that are viewing data will see the updated data after each database read or write operation. However, if your application performs two separate database access operations that depend on each other, you will want to use the JTA API to demarcate where the entire transaction, including both operations, begins, rolls back, and commits.

1.11.8 JavaMail API
Java EE applications use the JavaMail API to send email notifications. The JavaMail API has two parts: an application-level interface used by the application components to send mail, and a service provider interface. The Java EE platform includes JavaMail with a service provider that allows application components to send Internet mail.

1.11.9 JavaBeans Activation Framework
The JavaBeans Activation Framework (JAF) is included because JavaMail uses it. JAF provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to

11

1 - java platform, enterprise edition
perform those operations.

1.11.10 Java API for XML Processing
The Java API for XML Processing (JAXP), part of the Java SE platform, supports the processing of XML documents using Document Object Model (DOM), Simple API for XML (SAX), and Extensible Stylesheet Language Transformations (XSLT). JAXP enables applications to parse and transform XML documents independent of a particular XML processing implementation. JAXP also provides namespace support, which lets you work with schemas that might otherwise have naming conflicts. Designed to be flexible, JAXP lets you use any XML-compliant parser or XSL processor from within your application and supports the W3C schema. You can find information on the W3C schema at this URL: http://www.w3.org/XML/Schema.

1.11.11 Java API for XML Web Services (JAX-WS)
The JAX-WS specification provides support for web services that use the JAXB API for binding XML data to Java objects. The JAX-WS specification defines client APIs for accessing web services as well as techniques for implementing web service endpoints. The Web Services for J2EE specification describes the deployment of JAX-WS-based services and clients. The EJB and servlet specifications also describe aspects of such deployment. It must be possible to deploy JAX-WS-based applications using any of these deployment models. The JAX-WS specification describes the support for message handlers that can process message requests and responses. In general, these message handlers execute in the same container and with the same privileges and execution context as the JAX-WS client or endpoint component with which they are associated. These message handlers have access to the same JNDI java:comp/env namespace as their associated component. Custom serializers and deserializers, if supported, are treated in the same way as message handlers.

1.11.12 Java API for RESTful Web Services (JAX-RS)
The Java API for RESTful Web Services (JAX-RS) defines APIs for the development of Web services built according to the Representational State Transfer (REST) architectural style. A JAXRS application is a web application that consists of classes that are packaged as a servlet in a WAR file along with required libraries. The JAX-RS API is new to the Java EE 6 platform.

1.11.13 Java Architecture for XML Binding (JAXB)
The Java Architecture for XML Binding (JAXB) provides a convenient way to bind an XML schema to a representation in Java language programs. JAXB can be used independently or in combination with JAX-WS, where it provides a standard data binding for web service messages. All Java EE application client containers, web containers, and EJB containers support the JAXB API.

1.11.14 SOAP with Attachments API for Java
The SOAP with Attachments API for Java (SAAJ) is a low-level API on which JAX-WS and JAXR depend. SAAJ enables the production and consumption of messages that conform to the SOAP 1.1 specification and SOAP with Attachments note. Most developers do not use the SAAJ API, instead using the higher-level JAX-WS API.

1.11.15 Java API for XML Registries
The Java API for XML Registries (JAXR) lets you access business and general-purpose registries over the web. JAXR supports the ebXML Registry and Repository standards and the

12

1 - java platform, enterprise edition
emerging UDDI specifications. By using JAXR, developers can learn a single API and gain access to both of these important registry technologies. Additionally, businesses can submit material to be shared and search for material that others have submitted. Standards groups have developed schemas for particular kinds of XML documents; two businesses might, for example, agree to use the schema for their industry's standard purchase order form. Because the schema is stored in a standard business registry, both parties can use JAXR to access it.

1.11.16 J2EE Connector Architecture
The J2EE Connector architecture is used by tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged in to any Java EE product. A resource adapter is a software component that allows Java EE application components to access and interact with the underlying resource manager of the EIS. Because a resource adapter is specific to its resource manager, typically there is a different resource adapter for each type of database or enterprise information system. The J2EE Connector architecture also provides a performance-oriented, secure, scalable, and message-based transactional integration of Java EE-based web services with existing EISs that can be either synchronous or asynchronous. Existing applications and EISs integrated through the J2EE Connector architecture into the Java EE platform can be exposed as XML-based web services by using JAX-WS and Java EE component models. Thus JAX-WS and the J2EE Connector architecture are complementary technologies for enterprise application integration (EAI) and end-to-end business integration.

1.11.17 Java Database Connectivity API
The Java Database Connectivity (JDBC) API lets you invoke SQL commands from Java programming language methods. You use the JDBC API in an enterprise bean when you have a session bean access the database. You can also use the JDBC API from a servlet or a JSP page to access the database directly without going through an enterprise bean. The JDBC API has two parts: an application-level interface used by the application components to access a database, and a service provider interface to attach a JDBC driver to the Java EE platform.

1.11.18 Java Persistence API
The Java Persistence API is a new all Java standards based solution for persistence. Persistence uses an object-relational mapping approach to bridge the gap between an object oriented model and a relational database. Java Persistence consists of three areas:
• • •

1.11.19 Java Naming and Directory Interface
The Java Naming and Directory Interface (JNDI) provides naming and directory functionality, enabling applications to access multiple naming and directory services, including existing naming and directory services such as LDAP (Lightweight Directory Access Protocol), NDS (Novell Directory Services), DNS, and NIS (Network Information services). It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a Java EE application can store and retrieve any type of named Java object, allowing Java EE applications to coexist with many legacy applications and systems.

13

1 - java platform, enterprise edition
Java EE naming services provide application clients, enterprise beans, and web components with access to a JNDI naming environment. A naming environment allows a component to be customized without the need to access or change the component's source code. A container implements the component's environment and provides it to the component as a JNDI naming context. A Java EE component can locate its environment naming context using JNDI interfaces. A component can create a javax.naming.InitialContext object and looks up the environment naming context in InitialContext under the name java:comp/env. A component's naming environment is stored directly in the environment naming context or in any of its direct or indirect subcontexts. A Java EE component can access named system-provided and user-defined objects. The names of system-provided objects, such as JTA UserTransaction objects, are stored in the environment naming context, java:comp/env. The Java EE platform allows a component to name user-defined objects, such as enterprise beans, environment entries, JDBC DataSource objects, and message connections. An object should be named within a subcontext of the naming environment according to the type of the object. For example, enterprise beans are named within the subcontext java:comp/env/ejb, and JDBC DataSource references in the subcontext java:comp/env/jdbc.

1.11.20 Java Authentication and Authorization Service
The Java Authentication and Authorization Service (JAAS) provides a way for a Java EE application to authenticate and authorize a specific user or group of users to run it. JAAS is a Java programming language version of the standard Pluggable Authentication Module (PAM) framework, which extends the Java Platform security architecture to support userbased authorization.

1.11.21 Java Authorization Service Provider Contract for Containers (Java ACC)
The Java ACC specification defines a contract between a Java EE application server and an authorization policy provider. All Java EE containers support this contract. The Java ACC specification defines java.security.Permission classes that satisfy the Java EE authorization model. The specification defines the binding of container access decisions to operations on instances of these permission classes. It defines the semantics of policy providers that employ the new permission classes to address the authorization requirements of the Java EE platform, including the definition and use of roles.

1.11.22 Java Authentication Service Provider Interface for Containers (JASPIC)
The Java Authentication Service Provider Interface for Containers (JASPIC) specification defines a service provider interface (SPI) by which authentication providers that implement message authentication mechanisms may be integrated in client or server message processing containers or runtimes. Authentication providers integrated through this interface operate on network messages provided to them by their calling container. They transform outgoing messages so that the source of the message may be authenticated by the receiving container, and the recipient of the message may be authenticated by the message sender. They authenticate incoming messages and return to their calling container the identity established as a result of the message authentication.

better tools. A deployment descriptor is an XML document with an . An EAR file contains Java EE modules and deployment descriptors. Deployment typically involves using a platform’s deployment tool to specify location-specific information. At runtime. SAAJ. or better customer support. the application is ready to run. or a component. such as better performance. or applet) An optional deployment descriptor that describes its content
Once a Java EE unit has been produced. a standard Java Archive (JAR) file with an . JTA. Because deployment descriptor information is declarative. or component accordingly. a module. it is only a matter of assembling (or packaging) various Java EE modules into Java EE EAR files. it is ready to be deployed. No extra coding is needed. and JNDI
1.
15
. JSP page.java platform. module. servlet. Once deployed on a local platform. such as a list of local users that can access it and the name of the local database.1 . the Java EE server reads the deployment descriptor and acts upon the application.12 java EE application assembly and deployment
A Java EE application is packaged into one or more standard units for deployment to any Java EE platform-compliant system. A Java EE application is delivered in an Enterprise Archive (EAR) file. and JAX-WS Simplified interoperability with the J2EE Connector architecture Easy database connectivity with the JDBC API Enterprise application integration with message-driven beans and JMS. it can be changed without the need to modify the source code.xml extension that describes the deployment settings of an application.ear extension. Using EAR files and modules makes it possible to assemble a number of different Java EE applications using some of the same components. not by trying to lock customers into their technologies but instead by trying to outdo each other in providing products and services that benefit customers. Each unit contains:
• •
A functional component or components (such as an enterprise bean. Such a marketplace encourages vendors to compete. enterprise edition
an open marketplace in which every vendor can sell to every customer. The Java EE 6 APIs enable systems and applications integration through the following:
• • • • • • •
Unified application model across tiers with enterprise beans Simplified request-and-response mechanism with JSP pages and servlets Reliable security model with JAAS XML-based data interchange integration with JAXP.

declares transaction attributes and security authorizations for an enterprise bean.war (Web ARchive) extension. Together. these implement the Connector architecture (see J2EE Connector Architecture) for a particular EIS. GIF and HTML files. native libraries. which contain servlet class files. The Application Server runtime deployment descriptors are named sunmoduleType. For example. EJB modules are packaged as JAR files with a . Resource adapter modules are packaged as JAR files with an .
• •
16
. supporting class files. JSP files. A Java EE module consists of one or more Java EE components for the same container type and one component deployment descriptor of that type. classes. The four types of Java EE modules are as follows:
• •
EJB modules. which contain class files for enterprise beans and an EJB deployment descriptor. such as caching directives.6 EAR file structure
There are two types of deployment descriptors: Java EE and runtime. and other documentation. A Java EE deployment descriptor is defined by a Java EE specification and can be used to configure deployment settings on any Java EE-compliant implementation.jar extension. A Java EE module without an application deployment descriptor can be deployed as a stand-alone module. the mapping of portable names of an application’s resources to the server’s resources. and Application Server implementation-specific parameters. An enterprise bean module deployment descriptor. the Sun Java System Application Server Platform Edition 9 runtime deployment descriptor contains information such as the context root of a web application. Application client modules. which contain all Java interfaces.xml and are located in the same META-INF directory as the Java EE deployment descriptor.rar (resource adapter archive) extension. Web modules are packaged as JAR files with a . for example. A runtime deployment descriptor is used to configure Java EE implementation-specific parameters. along with the resource adapter deployment descriptor. which contain class files and an application client deployment descriptor. Web modules. and a web application deployment descriptor. enterprise edition
Figure 1.java platform. Application client modules are packaged as JAR files with a .jar extension. Resource adapter modules.1 .

RFC 2617 (06/99) and RFC 2774 (02/00). It quickly evolved into the preferred communication protocol over the internet. we recommend www.HTTP
2. RFC 2616 (06/99).1.0 – dates from 05/95 and is the object of RFC 1945 (www. as follows: 1.. was the object of several RFCs. so far) version.) a file specification (path) (the part of the URL after the host name)
17
.3 the initial request line
Contains 3 elements.2 .HTTP
2 . namely HTTP 1.jmarshall. HTTP was created by by Tim Berners-Lee in 1990 at CERN as a mean to store scientific data.w3. It is authored by Tim Berners-Lee.1 what is http
HTTP stands for HyperText Transfer Protocol while hypertext means text contatining links to another text.apps.2 the structure of http transactions
HTTP follows the client – server model. Headern: valuen <optional data block>
2.. These messages may have different contents. The server answers with a response message.com/easy/http. an optional message body <initial line> Header1: value1 . . The second (and last. For a complete specification of the different HTTP versions. a blank line (CR/LF) 4. As a site for understanding how HTTP works. The first oficial version – HTTP 1. but they also have some common structural elements.html). POST. The client sends a request message to the server. Roy Fielding and Henrik Nielsen..ietf.org/Protocols .. separated by spaces:
• •
a command (method) name (like GET. zero or more header lines 3.org/rfc/rfc1945. of which we mention RFC 2068 (01/97). an initial line 2.
2. HEAD. check the official HTTP site – www.

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. HEAD 3.0).1. unless that text happens to be the output of the process.html HTTP/1. TRACE Three other commands are listed. GET /path/to/the/file/index. The only difference is that the response must not have a body. it is the produced data which shall be returned as the entity in the response and not the source text of the process. .0
Here is an example of an initial request line:
2. All the information requested is returned in the header section of the response. HTTP/1.4 http commands (methods)
As of HTTP 1. PUT 8. DELETE 6. GET 2. OPTIONS 7. as well. in the HTTP 1.1 specification. These commands are: • • • LINK UNLINK PATCH
The HEAD command is identical to the GET command in all respects but one.2 .Posting a message to a bulletin board.Annotation of existing resources. newsgroup. but lack of support makes them obsolete.HTTP
•
the HTTP version (usually.
2.
18
. Here is their list: 1. there are 8 HTTP commands (methods) that are widely supported. POST 4.5 the GET and POST methods
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. POST is designed to allow a uniform method to cover the following functions: . CONNECT 5. mailing list.

or ordering a product. or a record is subordinate to a database. or in the message body.7 the initial response (status) line
Contains 3 elements. The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI. while POST may involve anything. When used for form data submission.
2. In this case. depending on whether or not the response includes an entity that describes the result. a news article is subordinate to a newsgroup to which it is posted.HTTP
or similar group of articles. such as the result of submitting a form. . . The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory containing it. 3. (encoded as multipart/form-data). GET attaches this data to the URL of the request.
2. or sending E-mail 2.Extending a database through an append operation. A POST request requires an extra transmission to retrieve the message body. The action performed by the POST method might not result in a resource that can be identified by a URI.2 . like storing or updating data.Providing a block of data. to a data-handling process. separated by spaces (although the reason phrase may contain spaces.8 the status code
A three-digit integer. while a GET request allows data sent via the URL to be processed immediately. where the first digit identifies the general category of response:
•
1xx indicates an informational message only
19
. form data submitted by POST may be encoded either as above (using application/x-www-form-urlencoded content type). as a sequence of “name=value” pairs.6 differences between GET and POST
1. as well):
• • •
the HTTP version of the response a response status code (a number) a response status reason phrase (a human readable response status)
Here is an example of an initial response line: HTTP/1.0 404 Not Found
2.” On the other side. after the “?” character. The method GET is intended for getting (retrieving) data. either 200 (OK) or 204 (No Content) is the appropriate response status. separated by the character “&” or “.

the requested resource doesn't exist.the resource has moved to another URL (given by the Location: response header).0. the Content-Length: header gives the number of bytes in the body. and the resulting resource (e. file or script output) is returned in the message body. The most common cause is a server-side script that has bad syntax. header name and header value. or otherwise can't run correctly. In a request. 301 Moved Permanently 302 Moved Temporarily 303 See Other (HTTP 1. one (Host) is mandatory. 500 Server Error . In particular. and section 10 for HTTP 1. where the requested resource is returned to the client.
2. or perhaps explanatory text if there's an error.10 the message body
An HTTP message may have a body of data sent after the header lines.1). and should be automatically retrieved by the client. The HTTP 1. The most common use of the message body is in a response.
The most common status codes are:
• • • • •
•
A complete list of status codes is in the HTTP specification (the URL was mentioned in the firs section of this chapter) (section 9 for HTTP 1. none of them mandatory.an unexpected server error.the request succeeded. such as text/html or image/jpg. the header lines of the message are used to describe the body.HTTP
• • • •
2xx indicates success of some kind 3xx redirects the client to another URL 4xx indicates an error on the client's part 5xx indicates an error on the server's part 200 OK .
• •
the Content-Type: header gives the MIME-type of the data in the body.g. fails.9 header lines
A header line consists of two parts.0Gold Last-Modified: Fri.1 only) .1 version specifies 46 of them. If an HTTP message includes a body.
2. out of which. this is where user-entered data or uploaded files are sent to the server.2 . separated a semicolon. while the HTTP 1. 31 Dec 1999 23:59:59 GMT Header lines which begin with spaces or tabs are parts of the previous header line. A couple of examples of header lines: User-agent: Mozilla/3. that is.0 version specifies 16 headers.
20
. header values are. 404 Not Found . This is often used by a CGI script to redirect the browser to an existing file. Although the header names are not case sensitive.

with subtype mpeg
2. with subtypes octet-stream. application. Each extension consists of a type and a subtype. . audio. together with the subtypes defined in this particular RFC. RFC 1521 (www.info. alternative.0 [blank line here] The server should respond with something like the following. image. 1. digest.ietf. although the list of admissible subtypes is much longer. multipart.html HTTP/1.info. with subtypes jpeg. with subtypes mixed. port 80 (use the default port of 80 because none is specified in the URL).uvt.ro/path/file. message.HTTP
2. partial.11 mime types/subtypes
MIME stands for Multipurpose Internet Mail Extensions. sent back through the same socket: HTTP/1. text.html first open a socket to the host web.0 From: someuser@yahoo.com User-Agent: HTTPTool/1. parallel 3. external-body 4.0 200 OK Date: Fri. video. send something like the following through the socket: GET /path/file. gif 6.
21
.org/rfc/rfc1521. with subtype basic 7. with subtype plain 2.uvt. 31 Dec 1999 23:59:59 GMT Content-Type: text/html Content-Length: 1354 <html> <body> <h1>Happy birthday!</h1> (more file contents) . Here is the list of the seven types.html) defines 7 types and several subtypes. with subtypes rfc822.2 .12 an example of an http transaction
To retrieve the file at the URL http://web. postscript 5.ro.apps. Then.

Originally named Web Applications 1. A newer standard.2 (3.org/Markup . The latest version (XHTML 2. using a variety of tags and their related attributes.0 and was accepted in December 1997.was approved as a standard in September 1995 (as RFC 1866 (http://www. The SGML declaration of the latest version of HTML (4.com/tutors. a working draft for the next major revision. HTML describes how text. Other helpful sites .HTML
3.apps.1 what is html?
HTML stands for HyperText Markup Language.0. namely HTML 1. www. As a practical reference site use – www.01 With support for the first 17 planes of ISO 10646 and increased limits for tag and literal lengths etc.html) and was widely supported. Version 4.2 language definition
HTML is a system for describing documents. However.org/rfc/rfc1866.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.htmlgoodies.0. From 1999 on. appeared in summer 1991 and was supported by the first popular web browser. we can afford to have a look at this declaration. An SGML declaration – what characters and delimiters may appear. It is a special version of SGML (Standard Generalized Markup Language – an ISO standard (ISO 8879)). namely HTML 5 was published in January 2008. -CHARSET BASESET "ISO Registration Number 177//CHARSET ISO/IEC 10646-1:1993 UCS-4 with implementation level 3//ESC 2/5 2/15 4/6"
23
. check the official HTML site – www. The first official version – HTML 2. HTML 3.w3c. <!SGML "ISO 8879:1986" -SGML Declaration for HyperText Markup Language version HTML 4.01) can be found at this address: http://www.3 .0) dates from 08. Mosaic. The newest version of HTML is 4.0 was not widely accepted) appeared a W3C recommendation in January 1997.0 introduces the Cascading Style Sheets.html.HTML
3 .www. Since it fits in a couple of pages. the specification includes several ideas of the WHAT (Web Hypertext Application Technology) working group. It might take several years before the specification reaches final Recommendation status.
3.0 .01.02 and is not intended to be backwards compatible.blooberry. All markup languages defined in SGML are called SGML applications and are characterized by: 1. It is a revision of 4. For a complete specification of the different HTML versions.ietf. The XHTML 1.w3.com/indexdot/html . images and other components are to be displayed in a browser.jmarshall. HTML is part of a new specification – XHTML. The first version of HTML.0 draft was released in 01.com/easy/html .99.

3 .3 html elements
An HTML element consists of: • • • a start tag a content an end tag
One exception. three DTDs (HTML 4. Other optional attributes of the <IMG> element. A comment section in an HTML document starts with <!-. You get the point. An example:
<IMG SRC=”/images/logo.gif” ALT=”logo” HEIGHT=40 WIDTH=120>
declares an image element.org/TR/REC-html40/sgml/dtd.
3. Document instances containing data (content) and markup." (in hexadecimal) .0 Frameset DTD) and a list of character references. CONTROLS. look at these examples: “&lt”. with the required (mandatory) attributes SRC and ALT and the optional attributes HEIGHT and WIDTH. A Document Type Definition (DTD) – defines the syntax of markup constructs. BORDER. Check the address http://www.html for the latest version of the HTML DTD. Each instance contains a reference to the DTD to be used to interpret it.w3. A specification that describes the semantics to be ascribed to the markup and character entity references. 3.and end at the first occurrence of -->. An example: <!-. though. VSAPCE are omitted. …. This section deals with some of the most common elements. The start tag of the element contains the values of the (required or optional) attributes of the element. <><> -->
25
. HTML 4.01 specification.0 contains an SGML declaration.the chinese character for water. There are 91 elements defined in the HTML 4. Overall. HTML 4. This specification adds new syntactic restrictions which cannot be defined within the frame of the DTD. 4.0 Strict DTD. If you wonder what a character reference is. the element <BR> has no content and no end tag. DYNSRC.acesta este un comentariu. like ALIGN. “&quot”. "&#x6C34. the specification of HTML 4.HTML
SIMPLE NO IMPLICIT NO EXPLICIT NO OTHER CONCUR NO SUBDOC NO FORMAL YES APPINFO NONE
>
2.0 Transitional DTD.

3.5 tables
26
.HTML
3.uvt.ro/webmail/src/login.4 the minimal structure of an html document
All HTML documents start with the <HTML> tag and end with the corresponding end tag </HTML>. NAME. specifies the text to be displayed in case source is not found SRC – required. Main attributes: • • HREF – specifies the absolute or relative URL of the hyperlink NAME – assigns a symbolic name to the enclosed object (text. image. An HTML document consists of the parts: • • the <HEAD> part the <BODY> part
A minimal HTML document example:
<HTML> <HEAD>My Page </HEAD> <BODY>Empty Body </BODY> </HTML>
3.php”>Login to web mail</A>
3.3 . indicates the URL to reference the graphic HEIGHT WIDTH
3.2 The <IMG> element
Main attributes: • • • • ALT – required.3. etc.1 The <A> element
Must contain one of the 2 attributes – HREF.info.
Example:
<A HREF=”http://web.) in order to use it as a destination in a hyperlink or another URL call.

<TR>. Here is their description and attributes. headers and cells are <TABLE>. Here is a an example of a table:
3. The intersection of any row and any column is called a cell. <TH> and <TD>. <THEAD>. the <TABLE> element attributes:
• • • • • • • • • • • •
BORDER CELLSPACING CELLPADDING WIDTH ALIGN VALIGN TBODY BORDERCOLOR FRAME RULES COLORGROUP BACKGROUND
the <THEAD> element attributes:
• • • •
ALIGN BGCOLOR CHAR CHAROFF
27
. Usually.HTML
A table is a visual rectangular object consisting of several rows and columns. the cells in the first row contain are called headers and consist of a brief description of the content of the corresponding column. its rows.6 table related elements
The specific elements defining a table. columns.3 .

Main attributes:
29
. Other possible values for this attribute: "multipart/form-data" .8.3 . the browser appends the values to the URL. "reset".info.maximum number of options visible to the user. data is sent as a single document with multiple sections.:.uvt. "text/plain"
•
•
3. specifies the parameter name.required. "password". Example: http://web. however. "file".2 the <SELECT> element
Used to create a list of choices.
•
3. Each of the listed choices is an OPTION element. Default value:
•
"application/x-www-form-urlencoded" . specifies how data will be sent to the server.8 form related elements
3.3 the <OPTION> element
Used inside a <SELECT> element to list the selection choices. NAME . "GET" . where 'HH' is the hexadecimal ASCII code of the character.used with forms that contain a file-selection field.if specified. "radio".required.8.ro/servlet/MyServlet?a=12&b=25
•
ENCTYPE . SIZE . Possible values for this attribute:
• •
"POST".sends the form values in 2 steps: contacts first the server then the form values are sent in a separate transmission.HTML
•
METHOD .& or (sometimes) by semicolon .?. "image". The pairs name=value are separated by ampersand . since it converts spaces to '+' and non-alphanumerical to '%HH'.sends the form values in a single transmission. "button". may have the values GET or POST. "submit". "checkbox". Main attributes: • TYPE . specifies the type of the input which can have one of the following values: "text". "hidden". Main attributes: • • • NAME MULTIPLE .
3. after a quotation mark . allows multiple selections from the choice list.specifies the encoding type of the of the form content. either as a drop-down menu or as a list box.1 the <INPUT> element
Defines input fields for the form.8.the default value.required.

94 and was officially announced at Sun World in 05. Java source – a file with extension .. pretty much comparable to that of a binary executable. allows the compilation of the Java source into machine-dependent binary executable. The first commercial version was delivered to the first customer (Netscape.0. project started in 12.90.2 java the interpreter.class 3.2 version.class. a tool named Just In Time compiler.java. The java compiler (javac) translates it to bytecode – prog1. Inc. with the following main options:
• • • •
-classpath <path> -sourcepath <path> -d <directory> : specifies where to put the .95. The Java interpreter (which is part of the Java Virtual Machine) parses and executes the Java bytecode. Example: Edit the file prog1. -g : generate all debugging info. Early versions of Java were released in 12. which accounts for a pretty slow execution. but next time execution is much faster. The java compiler is (in general) a command line tool. a Java interpreted program is about 10 times slower than a compiled and linked one.95. javac -classpath .2004) of Java 2 Platform Standard Edition is J2SE 5.C:\TW\myPackages -g login. the compilation process occurs.JAVA PRIMER
4. Java bytecode – a file with extension .
4. In terms of execution time.4.C:\TW\mySource. The first time a class is loaded. following the 1.2010) of Java Platform Enterprise Edition is Java EE 6 Update 21. The current version (as of 10.) in 08.class file. The current version (as of 10.1 history
The initial name of this language was OAK and was developed as part of the GREEN project at Sun.JAVA PRIMER
4 . To overcome this significant shortage. A java program goes thru the following phases: 1.java
One example of command line compilation:
4. The java interpreter (as part of the JVM) parses and executes the prog1.java 2.4 .3 java applications
31
. jit
From source to execution.class file.

or is derived from A. use the command:
java –jar [-options] jarfile [args]
4.java.”> : cp = classpath -D <name>=<value> : set a system property
To execute a . as follows:
java [-options] class [args]
Where main options are: • • -cp <directories and jar files separated by “. or that it extends A).2 inheritance
Inheritance is a partial order relation in the set of all Java classes. In general. An example:
32
. The first type are embedded in web pages – applets. Exactly one of these classes must implement a method called main().
4. The <APPLET> element has 3 mandatory attributes.jar file.4. namely: • • • CODE – identifies the (compiled) class file of the applet WIDTH HEIGHT
A java application is a collection of java classes. A Java class B inherits another class A (or is a subclass of A.4 object oriented concepts
4. This binary relation is specified in the declaration of the derived class B using the keyword extends. Generally. each class is implemented in a source file having the same name as the class itself and whose extension is . the others are the standalone programs – Java applications. A java applet is a java class that extends the standard Applet class.4 . This method is the entry point in the application and must have the following signature:
public static void main(String[] args)
A compiled java application (class) may be executed from the command line using an executable called java (the java interpreter).1 encapsulation
This is a fancy word for the tendency of hiding the implementation of the methods of some class and exposing only the interface of its public (and to some degree – its protected) methods. an applet is inserted in a HTML page by an <APPLET> tag or by an <OBJECT> tag.4.JAVA PRIMER
There exist 2 types of programs that can be written in Java.

5 java as programming language
integer data types:
• • • •
byte short int long float double boolean . provided that the types (and order) of its parameters are different. all classes in Java are (by default) subclasses of a universal base class. but it also can override the implementation of any method in the base class.JAVA PRIMER
public class CaineComunitar extends Caine { … }
In this case. Boolean. namely: Byte.3 Polymorphism
Polymorphism means the ability of a variable of a given (base) type (class) to be used to reference objects of different (derived) types (classes).
4.1 bit char . Long. Therefore.
4.Unicode (16 bits)
floating point data types:
• •
other types:
• •
All basic types have associated classes which extend their functionality. a class can have more than one method with the same name. the forest we mentioned is actually a tree.4. providing its own implementation. all variables and methods of the base class A are automatically variables and methods of the derived class B.
33
.4 Method overloading
A method (which has to be declared in some class (or interface)) is identified by its name and the type sequence of its parameters. Therefore. called Object.4.4 . a Java class can extend a single base class.
4. Double. In fact. this is called method overloading. with the root the class Object. Integer. That means that the graph of the direct inheritance relation is a forest (its connected components are trees). and automatically call the method specific to the type (derived class) of the object that the variable references. Float. The return type of a method is not part of this signature. In OO jargon. Short. The derived class B can use (for free) all the methods of the base class. Character. While C++ allows multiple inheritance.

the class is visible from any class. A final variable (method.6 access specifiers and modifiers in java
The access attributes of a member variable or method of a class are specified by the access specifiers.accessible from any class in the same package an any subclass anywhere
While the above specifiers apply to the variables and the methods of a class.servlet. inherited)..
4. class) is one which cannot be modified (overridden.does not have any subclasses.the default value allows access from any class in the same package public . The declaration: abstract class myFirstClass extends javax. the specifiers for the class itself can be taken from the following list:
• • •
no specifier .HttpServlet and which implements the Serializable interface.http.. rather than at class instance.the class is abstract (some of its methods (inherited or specified by some interface) are to be implemented by some of its subclasses)
An example. } declares an abstract class.all variables referenced in the function body are static variables.the method implementation cannot be overriden by some subclass. class .the default value makes the class visible only to the classes in the same package public . has the same value for all class instances. no templates.
34
. which extends the class javax. A final:
• • •
variable .
• • • •
no specifier .
Static variables and methods can be referenced (invoked) using either the name of the class or the name of a class instance. The modifiers of the variables and methods of a class specify their range and stability. automatic garbage collection.access from any class anywhere private .4 .http. Except for the "package" concept. A static variable or method is one which is implemented at class level.HttpServlet implements Serializable { . More precisely: A static (or class):
• •
variable . method . which is visible only to the classes in the same package. anywhere abstract . they have the same basic meaning as in C++.one which is constant method .servlet.no access from outside the class itself protected .JAVA PRIMER
Other peculiarities: no pointers (only references).one which is defined at class level.

4. Exception categories: 1. All the standard exceptions are derived from 2 direct subclasses of Throwable. Linkage Error and VirtualMachineError.1 The Error class
Represent conditions which are not expected to be caught in our code.JAVA PRIMER
4.
4. All exceptions (even programmer defined) must inherit from the standard class Throwable.3 RuntimeException Exceptions
Usually. array index out of bounds.like invalid cast. due to a variety of execution factors or due to programming errors. namely class Error and the class Exception.7. code or data errors . The subclasses of the RuntimeException class.4 .ThreadDeath. these exceptions take place because of serious code errors and they are supposed to be fixed in the coding phase.2 The Exception class
Except for the RuntimeException exceptions. all then exceptions in this category must be caught in our code.
4. not at execution time. In Java. division by 0. an exception is an object which is created when the abnormal situation occurs.7.7.JVM execution errors (mostly caused by programming errors).lang package are:
• • • • • • • • • • •
ArithmeticException IndexOutOfBoundException NegativeArraySizeException NullPointerException ArrayStoreException ClassCastException IllegalArgumentException SecurityException IllegalMonitorStateException IllegalStateException UnsupportedOperationException
4. Therte are 3 direct subclasses of the class Error .7 exceptions in java
An exception signals an abnormal situation or an error in an application. standard method exceptions 3.7. as defined in the java. java errors .4 Handling Exceptions
There are 2 ways to deal with exceptions:
35
. 2. programmer defined exceptions 4.

java. Each class belongs to a package (even if a package name is not specified.support for user interface java.rmi java. is a subdirectory of a directory called bank11). The names in a package are qualified by the package name. rather) defined in the java source must be stored in a directory called servlets.class file. finally construct.util.net java. date and time info java.geom . string analyzers. the class (the .awt.awt .support for event handling java. they have to be unique inside a package.awt.
4.lang (automatically available).util .servlets.Properties. don't have to import java. ignore it (pass it to the code that called the method) .4 .util. All other packages must be explicitly imported.this can be done by providing a try. An example: package com. In the example above.event . which is a subdirectory of ccards (which itself.1 Package names
The default package has no name.default. the package statement is the first one in a java source file.8 java packages
A Java package is a named collection of classes. catch.zip . import.support for data collections.8. The package containing the standard classes is java.lang .sql java.. As a general rule.bank11.support for operations with 2D geometric figures java.
4. . followed by a comma separated list of exceptions after the parameter list of the method.ccards. followed by the import statements. therefore. the default package is used).security
36
.9 standard Java packages
• • • • • • • • • • • • java.
4.support for java archives creation java. The name of the package is directly linked to the directory structure in which it is stored.by adding the key word throws.JAVA PRIMER
• •
supply then code to deal with the exception inside the method . import javax.io java.*..sql.nio java.

accessibility javax.
37
. All methods declared in an interface are (by default) public and abstract.swing.event . While multiple inheritance is forbidden in Java (a class can be the subclass of a single base class).JAVA PRIMER
• • • • java. If a class is declared as implementing an interface but omits some of its methods.10 interfaces
An interface in Java corresponds to the abstract class concept in C++. constants) of an interface are automatically (by default) public.swing .swing GUI components (minimal dependence on native code) java.support for event handling
4. Java classes can implement zero or more interfaces.4 . All variables (actually. An interface is a collection of constants and "abstract" functions.text javax. static and final. it must be declared as abstract.

A JavaScript can be used to validate form data before it is submitted to a server.JAVASCRIPT
5. Adaptations of the ECMA standard for other applications.A JavaScript can be used to detect the visitor's browser.A JavaScript can be set to execute when something happens. other
38
. as JavaScript. then LiveScript and finally. Sometimes we want to execute a script when a page loads. the general public knows it only by the name given by its creator – JavaScript.HTML authors are normally not programmers. ECMA stands for European Computer Manufacturers Association and is an organization founded in 1961 to standardize computer systems in Europe.javaScript
5 . like QtScript or ActionScript.3 how and where?
JavaScripts in a page will be executed immediately while the page loads into the browser. and . like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements .
• • • •
A scripting language is a lightweight programming language A JavaScript source consists of lines of executable computer code A JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
The initial official name of this language was ECMAscript. This is not always what we want. This saves the server from extra processing JavaScript can be used to detect the visitor's browser . However.A JavaScript statement like this: document. and was originally developed by Brendan Eich of Netscape under the names Mocha. but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page . The origins of this language date back to 1995.5 . Subsequently.
5. like KDE or Adobe Flash bear different names.A JavaScript can be used to store and retrieve information on the visitor's computer
5.depending on the browser .write("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript can react to events .A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data .1 so what is JavaScript?
JavaScript is a scripting language designed to add interactivity to HTML pages.load another page specifically designed for that browser JavaScript can be used to create cookies .2 what can a JavaScript do?
•
• •
• • •
•
JavaScript gives HTML designers a programming tool . JavaScript was standardized by ECMA in June 1997 under the name ECMAScript.

When you place a script in the head section.js file in the "src" attribute of the <script> tag: <html> <head> <script src="myScript. you will ensure that the script is loaded before anyone uses it.js file extension.
5.. go in the head section. Save the external JavaScript file with a . </script> </body>
5.5 . When you place a script in the body section it generates the content of the page.javaScript
times when a user triggers an event..3. To simplify this.js"> </script> </head> <body> </body> </html>
5. point to the . or when an event is triggered..1 scripts in the head section
Scripts to be executed when they are called.4 javaScript variables and expressions
A variable is a "container" for some information whose value can change during the script..3 using an external JavaScript
Sometimes you might want to run the same JavaScript on several pages.3.2 scripts in the body section
Scripts which are to be executed when the page loads go in the body section. you can write a JavaScript in an external file...
39
. Here is an example: <html> <head> <script type="text/javascript"> . <html> <head> </head> <body> <script type="text/javascript"> . without having to write the same script on every page. Note: The external script cannot contain the <script> tag! To use the external script. </script> </head>
5.3.

in loop is executed once for each element/property..4.4. The type of the variable is determined by any assignment of a value to that variable.
5... else.4 variable types
A variable declaration in JavaScript does not contain a type declaration.in statement is used to loop (iterate) through the elements of an array or through the properties of an object. while()..5 ..1 variable names
Rules for variable names:
• •
Variable names are case sensitive They must begin with a letter or the underscore character
5.. continue. break.. This means that the type of the variable can change during the execution of a JavaScript script. switch().5.3 variable assignment
A value can be assigned to a variable at declaration time: var strnum = "Morii 771" Or just use a plain assignment: strname = "Morii 771"
5. while() it is worth mentioning the for .2 variable declaration
A variable can be declared or even created with the var statement: var strnum = "2157 Sunrise Blvd".. in and the try .. The code in the body of the for .
5..1 JavaScript for..5 javaScript flow control
Apart from the usual flow control constructs..javaScript 5. for(). catch constructs. or strnum = "2157 Sunrise Blvd".
5.4.In statement
The for.4. Syntax for (variable in object) { code to be executed }
40
. namely – if .

for (x in mycars) { document. There are two ways of catching errors in a Web page:
• •
By using the try.0.. This chapter will teach you how to trap and handle JavaScript error messages.3 try. Example Using for.in to loop through an array: <html> <body> <script type="text/javascript"> var x.5.write(mycars[x] + "<br />"). var mycars = new Array().. an array element..5.javaScript
The variable argument can be a named variable.. } </script> </body> </html>
5. or a property of an object. mycars[0] = "Saab".catch statement (available in IE5+. Error message like this may be useful for developers but not for users.. we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". and the catch block contains the code to be executed if an error occurs. mycars[2] = "BMW".. Syntax try { // run some code here } catch(err) {
41
. so you don't lose your audience.catch statement
The try.catch statement allows you to test a block of code for errors.2 catching errors
When browsing Web pages on the internet.. The try block contains the code to be run. they often leave the Web page. This is the old standard solution to catch errors (available since Netscape 3)
5. and Netscape 6) By using the onerror event.. mycars[1] = "Volvo". When users see errors.5 . Mozilla 1.

The syntax for creating a function is:
43
.3 prompt Box
A prompt box is often used if you want the user to input a value before entering a page. in the example above had not been written within a function. in the <head> section. If the user clicks "Cancel". the box returns true. Example: <html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!") } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" > </form> </body> </html> If the line: alert("Hello world!!").7. Now. Syntax: confirm("sometext")
5. the user will have to click either "OK" or "Cancel" to proceed after entering an input value."defaultvalue")
5..5 .8. the box returns false. If the user clicks "Cancel".javaScript
alert("sometext")
5. Syntax: prompt("sometext".js file). A function can be called from anywhere within the page (or even from other pages if the function is embedded in an external . When a prompt box pops up. Functions are defined at the beginning of a page. If the user clicks "OK". We have added an onClick event to the button that will execute the function displaymessage() when the button is clicked.2 confirm Box
A confirm box is often used if you want the user to verify or accept something. If the user clicks "OK" the box returns the input value. it would have been executed as soon as the line was loaded.1 function definition
A function contains some code that will be executed only by an event or by a call to that function. the script is not executed before the user hits the button. the box returns null.7. the user will have to click either "OK" or "Cancel" to proceed. When a confirm box pops up.8 functions
5.

The next pages will explain each built-in JavaScript object in detail. and how they are used.b) { x=a*b return x } When you call the function above. function functionname() { some code } Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters. otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name. and will be stored in the variable called product.
5.2 properties
Properties are the values associated with an object.. functions that are going to return a value must use the return statement.8. </script> The output of the code above will be: 12
44
.javaScript
function functionname(var1.2 the return statement
The return statement is used to specify the value that is returned from the function. etc are variables or values passed into the function. you must pass along two parameters: product=prod(2.9.
5.var2. So. We will start by looking at the built-in JavaScript objects.varX) { some code } var1.9 javaScript objects
5. document. An example is the function below should return the product of two numbers (a and b): function prod(a.3) The returned value from the prod() function is 6.5 . In the following example we are using the length property of the String object to return the number of characters in a string: <script type="text/javascript"> var txt="Hello World!". An OOP language allows you to define your own objects and make your own variable types.9..length).write(txt. var2.
5..1 object oriented programming
JavaScript is an Object Oriented Programming (OOP) language. The { and the } defines the start and end of the function..

3 methods
Methods are the actions that can be performed on objects.9.toUpperCase()). In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters: <script type="text/javascript"> var str="Hello world!".
45
. document. which will be specified in the next section. The first class consists of browser specific objects.10 the hierarchy of javaScript browser objects
There are two major classes of built-in javascript objects. The other class are the language specific objects.5 .write(str. </script>
5.javaScript 5.

1 the String object
The String object is used to manipulate a stored piece of text. check the site http://www. At its most basic level. or when the user interacts with a Web page. IE: Internet Explorer Property constructor length prototype Methods Method anchor() big() blink() bold() charAt() charCodeAt() concat() fixed() fontcolor() fontsize() fromCharCode() Description F Creates an HTML anchor Displays a string in a big font Displays a blinking string Displays a string in bold Returns the character at a specified position Returns the Unicode of the character at a specified position Joins two or more strings Displays a string as teletype text Displays a string in a specified color Displays a string in a specified size Takes the specified Unicode values and returns a string 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 4 4 2 2 2 4 3 3 4 4 3 3 3 4 F N E 3 3 I Description F A reference to the function that created the object Returns the number of characters in a string Allows you to add properties and methods to the object 1 1 1 4 2 2 F N E 4 3 4 I
46
.11. every Link on the page is an Object. Objects may also have certain Events that are associated with them. Properties FF: Firefox. every Image on the page is an Object. When an event message has been triggered. Even this Document itself is an Object. This is achieved through the use of Event Handlers.javaScript
We can think of each Web page as a collection of several individual elements. as well). you need a way to intercept the message and react to it. For example.asp
5.11 javaScript language built in objects
5. Objects are storage containers that have Properties (data values associated with Objects) and Methods (functions associated with Objects) that operate on that data. N: Netscape.w3schools. JavaScript allows you to control the appearance of many of the Objects that make up a Web page as we previously saw.5 . Events are special signals or messages which occur when certain pre-defined actions take place within a Web browser. For an exhaustive list of properties and methods of the above objects (and for the built in objects.com/jsref/default. which are called Objects.

11. Properties FF: Firefox. from a start index Extracts the characters in a string between two specified indices Displays a string as superscript Displays a string in lowercase letters Displays a string in uppercase letters Represents the source code of an object Returns the primitive value of a String object 1 1 1 2 2 2 3 3 3
link() match() replace() search() slice() small() split() strike() sub() substr() substring() sup() toLowerCase() toUpperCase() toSource() valueOf()
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 4 4 4 4 2 4 2 2 4 2 2 2 2 4 2
3 4 4 4 4 3 4 3 3 4 3 3 3 3 4
5.javaScript
indexOf() italics() lastIndexOf() Returns the position of the first occurrence of a specified string value in a string Displays a string in italic Returns the position of the last occurrence of a specified string value.2 the Date object
The JavaScript Date object is used to work with dates and times. N: Netscape. searching backwards from the specified position in a string Displays a string as a hyperlink Searches for a specified value in a string Replaces some characters with some other characters in a string Searches a string for a specified value Extracts a part of a string and returns the extracted part in a new string Displays a string in a small font Splits a string into an array of strings Displays a string with a strikethrough Displays a string as subscript Extracts a specified number of characters in a string. IE: Internet Explorer Property constructor prototype Methods Method Date() Description Returns today's date and time F F 1 N 2 I E 3 Description Returns a reference to the Date function that created the object Allows you to add properties and methods to the object F F 1 1 N 4 3 I E 4 4
47
.5 .

1970 Sets the day of the month in a Date object (from 1-31) Sets the year in a Date object (four digits) Sets the hour in a Date object (from 0-23) Sets the milliseconds in a Date object (from 0-999) Set the minutes in a Date object (from 0-59) Sets the month in a Date object (from 0-11) Sets the seconds in a Date object (from 0-59) Calculates a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1.5 . from a Date object Returns the hour of a Date object (from 0-23) Returns the milliseconds of a Date object (from 0-999) Returns the minutes of a Date object (from 0-59) Returns the month from a Date object (from 0-11) Returns the seconds of a Date object (from 0-59) Returns the number of milliseconds since midnight Jan 1. as a two-digit or a three/four-digit number.javaScript
getDate() getDay() 6) getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCMonth() getUTCFullYear() getUTCHours() getUTCMinutes() getUTCSeconds() getUTCMilliseconds() getYear() Returns the year. Use getFullYear() instead !! Takes a date string and returns the number of milliseconds since midnight of January 1. 1970 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 2 2 2 2 2 4 4 4 4 4 4 4 4 2 4 3 4 3 3 3 3 3 4 4 4 4 4 4 4 4 3 Returns the day of the month from a Date object (from 1-31) Returns the day of the week from a Date object (from 01 1 2 2 3 3
parse() setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime()
1 1 1 1 1 1 1 1 1
2 2 4 2 4 2 2 2 2
3 3 4 3 4 3 3 3 3
48
. as a four-digit number. depending on the browser. 1970 Returns the difference in minutes between local time and Greenwich Mean Time (GMT) Returns the day of the month from a Date object according to universal time (from 1-31) Returns the day of the week from a Date object according to universal time (from 0-6) Returns the month from a Date object according to universal time (from 0-11) Returns the four-digit year from a Date object according to universal time Returns the hour of a Date object according to universal time (from 0-23) Returns the minutes of a Date object according to universal time (from 0-59) Returns the seconds of a Date object according to universal time (from 0-59) Returns the milliseconds of a Date object according to universal time (from 0-999) Returns the year.

according to Greenwich time.5 .11. 1970 according to universal time Returns the primitive value of a Date object 1 1 4 2 4 3 1 1 1 1 1 1 2 4 4 2 4 2 3 4 4 3 4 1 1 1 1 1 1 1 1 4 4 4 4 4 4 4 2 4 4 4 4 4 4 4 3
valueOf()
1
2
4
5. according to local time. N: Netscape. according to local time. Use setFullYear() instead !! Returns the date portion of a Date object in readable form Converts a Date object. to a string and returns the date portion Converts a Date object. to a string.javaScript
setUTCDate() setUTCMonth() setUTCFullYear() setUTCHours() setUTCMinutes() setUTCSeconds() setUTCMilliseconds() setYear() toDateString() toGMTString() toLocaleDateString() toLocaleTimeString() toLocaleString() toSource() toString() toTimeString() toUTCString() UTC() Sets the day of the month in a Date object according to universal time (from 1-31) Sets the month in a Date object according to universal time (from 0-11) Sets the year in a Date object according to universal time (four digits) Sets the hour in a Date object according to universal time (from 0-23) Set the minutes in a Date object according to universal time (from 0-59) Set the seconds in a Date object according to universal time (from 0-59) Sets the milliseconds in a Date object according to universal time (from 0-999) Sets the year in the Date object (two or four digits). to a string Represents the source code of an object Converts a Date object to a string Returns the time portion of a Date object in readable form Converts a Date object.3 the Array object
The JavaScript Array object is used to store a set of values in a single variable name. IE: Internet Explorer Property Description F F N I E
49
. according to universal time. to a string and returns the time portion Converts a Date object. Properties FF: Firefox. Use toUTCString() instead !! Converts a Date object. according to local time. to a string Takes a date and returns the number of milliseconds since midnight of January 1.

Properties FF: Firefox.5 4 . var myNum=new Number(number).javaScript
constructor index input length prototype Methods Method concat() join() pop() push() reverse() shift() slice() sort() splice() toSource() toString() unshift() valueOf() Description F Joins two or more arrays and returns the result Puts all the elements of an array into a string.5 4 3 4 2 4 6 4 4 4 5 4 5 5 F N E 4 4 5 I Sets or returns the number of elements in an array Allows you to add properties and methods to the object Returns a reference to the array function that created the object 1 1 1 1 1 2 3 3 2 2 4 4 4 4 4
5.11.4 the Number object
The Number object is an object wrapper for primitive numeric values.5 4 3 4 . The elements are separated by a specified delimiter Removes and returns the last element of an array Adds one or more elements to the end of an array and returns the new length Reverses the order of the elements in an array Removes and returns the first element of an array Returns selected elements from an existing array Sorts the elements of an array Removes and adds new elements to an array Represents the source code of an object Converts an array to a string and returns the result Adds one or more elements to the beginning of an array and returns the new length Returns the primitive value of an Array object 1 1 1 1 1 1 1 1 1 1 1 1 1 4 3 4 . Syntax for creating a new Number object.5 3 4 .5 . IE: Internet Explorer Property constructor Description Returns a reference to the Number function that created the object F F 1 E 4 I
50
.

IE: Internet Explorer Property constructor prototype Methods Method toSource() toString() valueOf() Description F Returns the source code of the object Converts a Boolean value to a string and returns the result Returns the primitive value of a Boolean object 1 1 1 4 4 4 F N E 4 4 I Description Returns a reference to the Boolean function that created the object Allows you to add properties and methods to the object F F 1 1 N 2 2 I E 4 4
51
.javaScript
MAX_VALUE MIN_VALUE NaN NEGATIVE_INFINIT Y POSITIVE_INFINITY prototype Methods Method toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf() Converts a number into an exponential notation if it has more digits than specified Converts the Number object into a string Returns the value of the Number object 1 . N: Netscape.5 1 1 4 4 5 Description F Converts the value of the object into an exponential notation Formats a number to the specified number of decimals 1 .11.5 1 . Properties FF: Firefox.5 .5 the Boolean object
The JavaScript Boolean object is an object wrapper for a Boolean value.5 5 F E 5 I Represents a value that is greater than MAX_VALUE Allows you to add properties and methods to the object 1 1 4 4 Returns the largest possible value in JavaScript Returns the smallest possible value in JavaScript Represents "Not-a-number" value Represents a value that is less than MIN_VALUE 1 1 1 1 4 4 4 4
5.

write(personObj.you can give it properties named firstname.3 create a direct instance of an object
The following code creates an instance of an object and adds four properties to it: personObj=new Object(). All persons have these properties. personObj.5 .
53
. personObj. age.eyecolor="blue".
5. The persons' methods could be eat().methodName() There are different ways to create a new object:
5.javaScript
toSource() valueOf() Represents the source code of an object Returns the primitive value of a Math object 1 1 4 2 4
5. Methods are the actions that can be performed on objects. lastname. weight. age.12.age=50.firstname="John". work().firstname="John".age=30.lastname="Doe". and eyecolor as follows: personObj.1 Properties
The syntax for accessing a property of an object is: objName. The code above will generate the following output: John
5. eye color. Let's illustrate with an example: A person is an object. play(). height. sleep().eyecolor="blue". etc. Objects also have methods. but the values of those properties will differ from person to person.firstname).12 how to create your own objects
An object is just a special kind of data.12. Properties are the values associated with the object. personObj.propName You can add properties to an object by simply giving it a value. The persons' properties include name.2 Methods
An object can also contain methods. personObj. with a collection of properties and methods. personObj. personObj. document. etc. skin tone. Assume that the personObj already exists . You can call a method with the following syntax: objName. personObj.lastname="Doe".12.

like this: myFather=new person("John".eyecolor=eyecolor.12.age=age. this.firstname=firstname.48.lastname=new_lastname.propertyName.lastname=lastname.eyecolor) { this.age=age. myMother=new person("Sally".age.
54
. } Note that methods are just functions attached to objects.50.5 ."blue").newlastname=newlastname.eat=eat.
5. this. you can create new instances of the object."green"). The following code adds a method called eat() to the personObj: personObj.4 create a template of an object
The template defines the structure of an object: function person(firstname. } Notice that the template is just a function. Then we will have to write the newlastname() function: function newlastname(new_lastname) { this."Doe". The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). this."Rally".age. this. this.eyecolor=eyecolor. That's what "this" is: the instance of the object at hand.firstname=firstname. this.lastname=lastname.lastname. This is also done inside the template: function person(firstname.javaScript
Adding a method to the personObj is also simple. this. Inside the function you need to assign things to this. Once you have the template.eyecolor) { this.
You can also add some methods to the person object.lastname.

0 was the ability to let HTML events trigger actions in the browser.". Examples of events:
● ● ● ● ● ●
A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input box in an HTML form Submitting an HTML form A keystroke
Note: Events are normally used in combination with functions. F Loading of an image is interrupted An element loses focus The user changes the content of a field Mouse clicks an object Mouse double-clicks an object An error occurs when loading a document or an image An element gets focus A keyboard key is pressed A keyboard key is pressed or held down A keyboard key is released A page or an image is finished loading
F 1 1 1 1 1 1 1 1 1 1 1
N E 3 2 2 2 4 3 2 4 4 4 2
I 4 3 3 3 4 4 3 3 3 3 3
55
.5 ..javaScript
} The newlastname() function defines the person's new last name and assigns that to the person. Netscape an Internet Explorer for each such event. like starting a JavaScript when a user clicks on an HTML element. JavaScript knows which person you're talking about by using "this.newlastname("Doe")..13 JavaScript Events
New to HTML 4. and the function will not be executed before the event occurs! Tne following table contains an exhaustive list of events together with the support version of FireFox.
5. For example. we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. So. now you can write: myMother. Every element on a web page has certain events which can trigger JavaScript functions. We define the events in the HTML tags.
Event onabort onblur onchange onclick ondblclick onerror onfocus onkeydown onkeypress onkeyup onload
The event occurs when.

w3schools.13. Next time the visitor arrives at your page. the submit should be cancelled.13. you could have another popup saying something like: "Welcome John Doe!".
5. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: <a href="http://www.javaScript
onmousedown onmousemove onmouseout onmouseover onmouseup onreset onresize onselect onsubmit onunload A mouse button is pressed The mouse is moved The mouse is moved off an element The mouse is moved over an element A mouse button is released The reset button is clicked A window or frame is resized Text is selected The submit button is clicked The user exits the page 1 1 1 1 1 1 1 1 1 1 4 6 4 2 4 3 4 2 2 2 4 3 4 3 4 4 4 3 3 3
5. onBlur and onChange events are often used in combination with validation of form fields. and load the proper version of the web page based on the information.4 onMouseOver and onMouseOut
onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of how to use the onSubmit event.2 onFocus. Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.13.5 .13.3 onSubmit
The onSubmit event is used to validate ALL form fields before submitting it. The name is then stored in a cookie.htm" onsubmit="return checkForm()">
5. The checkForm() function will be called when the user clicks the submit button in the form. you could have a popup asking for the user's name upon his first arrival to your page. Below is an example of how to use the onChange event. For example.com" onmouseover="alert('An onMouseOver
56
. otherwise the submit will be cancelled: <form method="post" action="xxx. If it returns true the form will be submitted. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()">. The function checkForm() returns either true or false. If the field values are not accepted.
5. The onload event is often used to check the visitor's browser type and browser version. onBlur and onChange
The onFocus.1 onload and onUnload
The onload and onUnload events are triggered when the user enters or leaves the page.

and a standard interface for accessing and manipulating them. or WebAPI being among them.6 . after the completion of the DOM Level 3 Recommendations. If the application is strictly sequential and one-pass. However. In other words. The existing vendor-specific interfaces were dubbed intermediate DOMs. an implementation must at least buffer the document that has been read so far (or some parsed form of it). Hence the DOM is likely to be best suited for applications where the document must be accessed repeatedly or out of sequence order. SAX provides a mechanism for reading data from an XML document. the Document Object Model is the way JavaScript sees its containing HTML page and browser state. Although the W3C never produced a specification for DOM 0.defines a standard set of objects for any structured document XML DOM . W3C began development of the DOM in the mid-1990s.. particularly those used in Web browsers. Several W3C Working Groups have since taken the lead in maintaining and continuing to develop standard APIs for the Web since then. the SAX model is likely to be faster and use less memory. DOM 3 was released in April 2004 and is the current release of the DOM specification.defines a standard set of objects for HTML documents
A web browser is not obliged to use DOM in order to render an HTML document. and style of a document. structure. XML. the Document Object Model activity is closed. SVG. The Document Object Model Working Group was closed in the Spring of 2004.g.1 what is the DOM?
The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content. 2010). Right now (oct.defines a standard set of objects for XML documents HTML DOM . and HTML) and different levels (DOM Level 1/2/3):
• • •
Core DOM . It is a popular alternative to the Document Object Model (DOM). the DOM is required by JavaScript scripts that wish to inspect or modify a web page dynamically. As of January 2008.HTML DOM
6. HTML. The W3C DOM provides a standard set of objects for HTML and XML documents. By October 1998. CSS.Html DOM
6 . DOM 2 was issued in November 2000. Because the DOM supports navigation in any direction (e.2 history
The World Wide Web Consortium (W3C) developed the W3C Document Object Model in response to the development of various proprietary models for HTML. what drives the DOM Specifications is the WebApps WG. The W3C DOM is separated into different parts (Core. with specifics on the style sheet object model and style information manipulation. parent and previous sibling) and allows for arbitrary modifications. it was nonetheless a partially documented model and was included in the specification of HTML 4. SAX (Simple API for XML) is a sequential access parser API for XML.
6. the first specification of DOM (DOM 1) was released. The W3C
58
.

and a standard way to access and manipulate HTML documents.
6. The Window object represents a browser window. large parts of W3C DOM were well-supported by common JavaScript-enabled Web browsers. since it allows browser compatibility with a large audience. because non-conformant browsers such as Internet Explorer 4.Html DOM
Document Object Model (DOM) Document Object Model (DOM) Level 3 Working Group Notes: • Document Object Model (DOM) • Document Object Model (DOM) • Document Object Model (DOM) Working Draft • Window Object 1. A common DOM promised substantial simplification of the development of complex Web applications.6 javaScript specific objects
In addition to the built-in JavaScript objects.5 web browsers implementation
Earlier. The standardization effort did not bring forth an immediate change. In order to be cross-browser compatible. interoperability problems were numerous.x and Netscape 4. when each Web browser exclusively supported its own intermediate DOM. you can also access and manipulate all of the HTML DOM objects with JavaScript. Web developers are starting to rely mostly or solely on W3C DOM. large parts of Dynamic HTML code had to be rewritten for each browser to be supported. Gecko-based browsers (like Mozilla and Firefox). and Safari. W3C DOM Level 1 has been a recommendation since 1 October 1998. Opera. support multiple browsers.0
• •
Level 3 Load and Save Specification Level 3 Validation Specification Level 3 XPath Specification Level 3 Views and Formatting Specification Requirements
•
•
6. including Microsoft Internet Explorer (version 5 (1999) and version 6 (2001)). can be accessed through the
60
. Konqueror. that is. Object Window Description The top level object in the JavaScript hierarchy.6 .7 the HTML DOM
The HTML DOM defines a standard set of objects for HTML.x were still widely used in 2000. along with their containing text and attributes. A Window object is created automatically with every instance of a <body> or <frameset> tag Contains information about the client's browser Contains information about the client's display screen Contains the visited URLs in the browser window Contains information about the current URL
Navigator Screen History Location
6. Besides the generic objects listed bellow. All HTML elements. By 2005. the bulk of the HTML DOM objects are presented in the next paragraph.

and VBScript. The HTML DOM is platform and language independent. It can be used by any programming language like Java. and new elements can be created.6 . The contents can be modified or deleted.Html DOM
DOM. JavaScript. HTML DOM Objects
Object Document Anchor Area Base Body Button Event Form Frame Frameset Iframe Image Input button Input checkbox Input file Input hidden Input password Input radio Input reset Input submit Input text Link Meta Option Select Style Table TableData TableRow Textarea
Description Represents the entire HTML document and can be used to access all elements in a page Represents an <a> element Represents an <area> element inside an image-map Represents a <base> element (specifies a default address or a default target for all links on a page) Represents the <body> element Represents a <button> element Represents the state of an event Represents a <form> element Represents a <frame> element Represents a <frameset> element Represents an <iframe> element Represents an <img> element Represents a button in an HTML form Represents a checkbox in an HTML form Represents a fileupload in an HTML form Represents a hidden field in an HTML form Represents a password field in an HTML form Represents a radio button in an HTML form Represents a reset button in an HTML form Represents a submit button in an HTML form Represents a text-input field in an HTML form Represents a <link> element Represents a <meta> element Represents an <option> element Represents a selection list in an HTML form Represents an individual style statement Represents a <table> element Represents a <td> element Represents a <tr> element Represents a <textarea> element
61
.

1 DOM example
Look at the following HTML document: <html> <head> <title>DOM Tutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body> </html> The root node in the HTML above is <html>. the element node <title>. The <html> node has two child nodes. in the HTML DOM the value of the text node can be accessed by the innerHTML property.2 text is always stored in text nodes
A common error in DOM processing is to expect an element node to contain text. The tree structure is called a node-tree.
6.6 . However. the text of an element node is stored in a text node. In this example: <title>DOM Tutorial</title>. All other nodes in the document are contained within <html>. holds a text node with the value "DOM Tutorial".8.9.8 DOM nodes
According to the DOM.
62
.8.
6. everything in an HTML document is a node.Html DOM
6. <head> and <body>. The <body> node holds a <h1> and <p> node.9 the HTML DOM Node Tree
6.1 the Document Tree
The HTML DOM views a HTML document as a tree-structure. The DOM says:
• • • • •
The entire document is a document node Every HTML tag is an element node The text in the HTML elements are text nodes Every HTML attribute is an attribute node Comments are comment nodes
6. "DOM Tutorial" is not the value of the <title> element! However. The <head> node holds a <title> node.

Their contents can be modified or deleted. The length property defines the length of a node list (the number of nodes). except the root.9. By using the getElementById() method 2. By using the getElementsByTagName() method 3. the top node is called the root Every node.
63
.getElementsByTagName("p").
• • • • •
In a node tree. You can loop through a node list by using the length property: x=document. and siblings
The nodes in the node tree have a hierarchical relationship to each other. using the node relationships. and sibling are used to describe the relationships. has exactly one parent node A node can have any number of children A leaf is a node with no children Siblings are nodes with the same parent
6.Html DOM
All nodes can be accessed through the tree. and new elements can be created.getElementsByTagName("p"). and the connections between them. The node tree below shows the set of nodes. The following example returns a nodeList of all <p> elements that are descendants of the element with id="main": document.2 node parents. child.3 accessing nodes
You can access a node in three ways: 1. By navigating the node tree. Parent nodes have children.9.6 . The tree starts at the root node and branches out to the text nodes at the lowest level of the tree:
6.getElementById('main'). Children on the same level are called siblings (brothers or sisters). The terms parent. children.

document. }
6.Html DOM
for (i=0.6 .write(x[i].4 Node Properties
In the HTML Document Object Model (DOM).
• • •
nodeValue for element nodes is undefined nodeValue for text nodes is the text itself nodeValue for attribute nodes is the attribute value
the nodeType Property
The nodeType property returns the type of node and is read only. Objects have methods (functions) and properties (information about the object).write("<br />"). Three important HTML DOM node properties are:
• • •
nodeName nodeValue nodeType
the nodeName Property
The nodeName property specifies the name of a node.9.i++) { document.
• • • • •
nodeName is read-only nodeName of an element node is the same as the tag name nodeName of an attribute node is the attribute name nodeName of a text node is always #text nodeName of the document node is always #document
the nodeValue Property
The nodeValue property specifies the value of a node. The most important node types are:
Element type Element Attribute Text Comment Document
NodeType 1 2 3 8 9
64
.i<x.innerHTML). each node is an object. that can be accessed and manipulated by JavaScript.length.

txt=x.6 .
6. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is: • mousedown • mouseup • click Fires when the pointing device button is double clicked over an element Fires when the pointing device button is pressed over an element Fires when the pointing device button is released over an element Fires when the pointing device is moved onto an element Fires when the pointing device is moved while it is over an element Fires when the pointing device is moved away from an element
click
onclick
dblclick Mouse mousedown mouseup mouseover mousemove mouseout
ondblclick onmousedown onmouseup onmouseover onmousemove onmouseout
65
.firstChild.getElementById("intro").get the value of an element
The following code fragment retrieves the text node value of the first <p> element: x=document.10 HTML events
Common/W3C events
There is a huge collection of events that can be generated by most element nodes:
• • • • • •
Mouse events Keyboard events HTML frame/object events HTML form events User interface events Mutation events (notification of any changes to the structure of a document)
Note that the event classification above is not exactly the same as W3C's classification.9.
Category
Type
Attribute
Description Fires when the pointing device button is clicked over an element.Html DOM
6.5 example .nodeValue.

including input and textarea Fires when a control loses the input focus and its value has been modified since gaining focus Fires when a form is submitted Fires when a form is reset Fires when an element receives focus either via the pointing device or by tab navigation Fires when an element loses focus either via the pointing device or by tabbing navigation Similar to HTML focus event.Html DOM
Fires when a key on the keyboard is "clicked". A keypress is defined as a keydown and keyup on the same key. but can be applied to any focusable element
keypress Keyboard keydown keyup
onkeypress
onkeydown onkeyup
load
onload
unload HTML frame/object abort
onunload
onabort
error resize scroll select
onerror onresize onscroll onselect
change HTML form submit reset focus
onchange onsubmit onreset onfocus
blur User interface DOMFocusIn
onblur ondomfocusin
66
. including window. For elements.6 . objects and images. it fires when the target element and all of its content has finished loading Fires when the user agent removes all content from a window or frame. frames. For elements. it fires when the target element or any of its content has been removed Fires when an object/image is stopped from loading before completely loaded Fires when an object/image/frame cannot be loaded properly Fires when a document view is resized Fires when a document view is scrolled Fires when a user selects some text in a text field. The sequence of these events is: • keydown • keyup • keypress Fires when a key on the keyboard is pressed Fires when a key on the keyboard is released Fires when the user agent finishes loading all content within a document.

3. Mozilla. also supports these methods.
67
. This model is implemented in Netscape Navigator. This model is implemented in Internet Explorer and other browsers.Html DOM
DOMFocusOut ondomfocusout Similar to HTML blur event. there are two possible ways to handle it:
• •
Trigger the elements from outer to inner (event capturing). DOMNodeInserted. Safari and Opera also support readystatechange event for the XMLHttpRequest object. say "click". Events are first captured until it reaches the target element. Trigger the elements from inner to outer (event bubbling). but can be applied to any focusable element Similar to XUL command event. through a mouse click or a keypress. and/or by cancelling the default action for the event. Safari. an event can be responded to at any element in the path (an observer) in either phase by causing an action. Both have event handlers registered on the same event type. and/or by stopping the event (with method event.
6.6 . as of version 1. DOMNodeRemoved and DOMCharacterDataModified.stopPropagation() for Mozilla and command event. and then bubbled up. Fire when the subtree is modified Fires when a node has been added as a child of another node Fires when a node has been removed from a DOM-tree
DOMActivate
ondomactivate
DOMSubtreeModified DOMNodeInserted DOMNodeRemoved Mutation
onsubtreemodified onnodeinserted onnoderemoved
NodeInsertedIntoDoc onnodeinsertedinto Fires when a node is being ument document inserted into a document DOMAttrModified onattrmodified Fires when an attribute has been modified
DOMCharacterDataM oncharacterdatamo Fires when the character data odified dified has been modified Note that the events whose names start with “DOM” are currently not well supported. During the event flow. Mozilla also supports the beforeunload event using traditional event registration method (DOM Level 0).11 event flow
Consider the situation when there are 2 elements nested together. When the user clicks on the inner element. Also.
W3C takes a middle position in this struggle. but Internet Explorer for the Mac does not. Mozilla and Safari also support contextmenu. Fires when an element is activated. for instance. Mozilla and Opera support DOMAttrModified.cancelBubble = true for Internet Explorer).

Event properties Type DOMString EventTarget EventTarget unsigned short boolean boolean DOMTimeStamp Name type target currentTarget eventPhase bubbles cancelable timeStamp Description The name of the event (case-insensitive).Html DOM
6. there are very serious browser incompatibilities in this area. Specifies whether or not the event's default action can be prevented. including information about target element.12 the Event object
The Event object provides a lot of information about a particular event.
Event methods Name stopPropagation Argument type Argument name Description To prevent further propagation of an event during event flow. etc.6 . Used to indicate the EventTarget whose EventListeners are currently being processed. mouse button pressed. Used to indicate whether or not an event is a bubbling event.
preventDefault
68
. Used to specify the time (in milliseconds relative to the epoch) at which the event was created. meaning that any default action normally taken by the implementation as a result of the event will not occur. Used to indicate whether or not an event can have its default action prevented. mouse position. DOMString initEvent boolean boolean eventTypeArg canBubbleArg cancelableArg Specifies the event type. Specifies whether or not the event can bubble. key pressed. Used to indicate the EventTarget to which the event was originally dispatched. Hence only the W3C Event object is discussed here. To cancel the event if it is cancelable. Unfortunately. Used to indicate which phase of event flow is currently being evaluated.

etc. but also to save resources. But Ajax can selectively modify a part of a page displayed by the browser.AJAX
7. crunching numbers. The processing of web page formerly was only server-side.3 the basic architecture of ajax
The classic web application model works like this: most user actions in the interface trigger an HTTP request back to a web server.
7. fields of forms. JavaScript (ECMAScript) for local processing.2 why use ajax?
Mainly to build a fast.AJAX
7 . dynamic website.
7.7 . SOAP may be used to dialog with the server. without to wait and to freeze the display of the page. before the whole page was sent within the network. but rather a collection of existing technologies bound together by JavaScript. menus. The DomParser class may be used PHP or another scripting language may be used on the server. • • • • • • • HTML and CSS for presenting.1 what is ajax?
Ajax stands for Asynchronous JavaScript And XML.
optionally
XSL stands for EXtensible Stylesheet Language while XSLT stands for XSL Transformations The "Asynchronous" word. XML and XSLT to process the data if returned in Xml form. it is better to use the power of all the client computers rather than just an unique server and network. Ajax allows to perform processing on client computer (in JavaScript) with data taken from the server. It’s a model adapted from the Web’s original use as a hypertext medium. using web services or Php scripts.
69
. means that the response of the server will be processed when available. and update it without the need to reload the whole document with all images. may be processed and the result displayed immediately into the same page. For improving sharing of resources. and DOM (Document Object Model) to access data inside the page or to access elements of Xml file read on the server (with the getElementByTagName method for example) The XMLHttpRequest class read or send data on the server asynchronously. It is not a technology in itself. choices of user. For example. talking to various legacy systems — and then returns an HTML page to the client. but what makes the Web good for hypertext doesn’t necessarily make it good for software applications. The server does some processing — retrieving data.

Obviously. the user waits some more. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. we wouldn’t make users wait around. but it doesn’t make for a great user experience. While the server is doing its thing. the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. Once an interface is loaded. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf.AJAX
The traditional model for web applications (left) compared to the Ajax model (right) This approach makes a lot of technical sense. but the opposite is true. if we were designing the Web from scratch for applications. And at every step in a task. why should the user see the application go to the server at all? An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary — an Ajax engine — between the user and the server. waiting. why should the user interaction come to a halt every time the application needs something from the server? In fact. what’s the user doing? That’s right. waiting around for the server to do something.
70
. Instead of loading a web page.7 . It seems like adding a layer to the application would make it less responsive. at the start of the session. So the user is never staring at a blank browser window and an hourglass icon.

loading additional interface code.7 .AJAX
The synchronous interaction pattern of a traditional web application (top) compared with the asynchronous pattern of an Ajax application (bottom) Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax engine instead. If the engine needs something from the server in order to respond — if it’s submitting data for processing.
71
. and even some navigation — the engine handles on its own. usually using XML. or retrieving new data — the engine makes those requests asynchronously. Any response to a user action that doesn’t require a trip back to the server — such as simple data validation. editing data in memory. without stalling a user’s interaction with the application.

4: finished.send: send a request to the server. boolean) .5 the XMLHttpRequest class
Here is a closer look to the XMLHttpRequest class.AJAX
7. the state of availability of data is given by the readyState attribute of XMLHttpRequest.for a simple text. the ajax engine uses the XMLHttpRequest object.4 how does it work?
Ajax uses a programming model with display and events.holds a Xml loaded file.
Attributes
readyState status responseText responseXml . It allows the interaction with the servers. they call functions associated to elements of the web page. DOM's method allows to extract data.responseXml . We have to wait for the data to be available to process it. Interactivity is achieved with forms and buttons. 2: request received. and in this purpose.for a Xml file or . . These events are user actions.holds loaded data as a string of characters.open: create a connection.returned by the server . . This object provides two methods: .url: the location of the file
72
. Take note that a new XMLHttpRequest object has to be created for each new file to load. GET or POST .the code successively changes value from 0 to 4 that means "ready".mode: type of request. 3: answer in process.200 is ok.
7. DOM allows to link elements of the page with actions and also to extract data from Xml files provided by the server. Data furnished by the server will be found in these attributes of the XMLHttpRequest object: . States of readyState follow (only the last one is really useful): 0: not initialized.7 .the name of the function invoked
Methods
open(mode. . To get data on the server. 404 if the page is not found .
onreadystatechange . 1: connection established.responseText . thanks to its methods and attributes. url.

. http_request.boolean: true (asynchronous) / false (synchronous) send("string") . if (window. step by step
First step: create an instance
This is just a classical instance of class.XMLHTTP").ActiveXObject) // ActiveX version { request = new ActiveXObject("Microsoft. http_request. OK } else { // wait. but two options must be tried.6 building a request. if (request.xul. . }
Third step: make the request itself
Two methods of XMLHttpRequest are used: .open: command GET or POST. URL of the document.open('GET'. for browser compatibility.XMLHttpRequest) // Object of the current windows { request = new XMLHttpRequest(). The request below reads a document on the server. 'http://www.
73
. request. true for asynchronous.fr/somefile. true).. // IE }
Second step: wait for the response
The response and further processing are included in a function and the return of the function will be assigned to the onreadystatechange attribute of the object previously created.send: with POST only.null for a GET command
7.xml'.AJAX
.send(null). Safari. the data to send to the server.onreadystatechange = function() { // instructions to process the response }.7 . // Firefox..readyState == 4) { // received.. } else if (window. .

7 - AJAX
document.ajax.dyn.value= element.firstChild.data; content of the element to the form // assign the

7.7.3 how to post a text
A text is sent to the server and is written into a file. The call to the "open" method changes, the argument is POST, and the "send" method also has now a value for argument. req.open("POST", "ajax-post.xml", true); req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.send(document.getElementById("dyn".value));

7.7.4 how to write to body
Now, the text read is put in the body of the page, and not into a textfield. The code below replaces the textfield form object and the second part replaces the assignment into the JavaScript function. <div id="zone"> ... some text to replace ... </div> document.getElementById("zone").innerHTML = "Received:" + xhr.responseText;

7.8 the ajax toolkit framework
It is an Eclipse add-on that provides tools for building IDE for Ajax runtimes, and testing Ajax applications. The AJAX Toolkit Framework (ATF) provides and extensible framework and exemplary tools for building IDEs for the many different AJAX runtime offerings (Dojo, Zimbra, Rico, etc) in the market. Tools built upon these frameworks will initially include: enhanced JavaScript editing features such as edit-time syntax checking; an embedded Mozilla web browser; an embedded DOM browser; and an embedded JavaScript debugger.

7.9 drawbacks of ajax
● ● ● ●

If JavaScript is not activated, Ajax can't work. The user must be asked to set JavaScript from within options of the browser, with the "noscript" tag. Since data to display are loaded dynamically, they are not part of the page, and the keywords inside are not used by search engines. The asynchronous mode may change the page with delays (when the processing on the server take some times), this may be disturbing. The back button may be deactivated (this is not the case in examples provided here).

8 - WEB APPLICATIONS
8.1 the structure of a web application
A web application is a collection of Java servlets, JSP pages, Java Server Faces, other helper classes and class libraries, other static resources (HTML, images, etc.) and an xml file, the deployment descriptor. A web application consists of 4 parts: 1. a public directory – containing html, jsp files and other public resources. This is the root directory of the application. 2. a WEB-INF/web.xml file – the deployment descriptor. 3. a WEB-INF/classes directory. 4. a WEB-INF/lib directory. Example: Assume that we use a Tomcat web server and that the environment variable %TOMCAT_HOME% is set to C:\TW\Tomcat. Then, the root directory of some web application can be: C:\TW\Tomcat\webapps\bank11\ccards and the mandatory directories are: C:\TW\Tomcat\webapps\bank11\ccards\WEB-INF\classes C:\TW\Tomcat\webapps\bank11\ccards\WEB-INF\lib

8.2 web containers
A web container is a Java runtime providing implementation of the Java servlet API and some other facilities to the JSP and JSF pages. It responsible for initializing, invoking and managing the life cycle of servlets, JSPs and JSFs. A web container may either implement the basic HTTP services or delegates these services to an external web server. Web containers can be part of an application or web server or a separate runtime. Here is a description of these situations. web container in a J2EE application server. Commercial implementations of the J2EE specifications, like WebLogic, Inprise Application Server or IBM's WebSphere include web containers. web container built into web servers. Most known cases are the Sun's (Oracle's) Java WebServer and the Jakarta Tomcat web server. web container as a separate runtime. Some web servers, like Apache or IIS require a separate runtime to run servlets and a web server plug-in to integrate this Java runtime

•

• •

77

8 - WEB APPLICATIONS
with the web server. Typical integration scenarios are Tomcat with Apache and JRun (of Allaire) with most of the J2EE application servers.

Web Application

Web Application

Java Servlets

Java Servlets

JSP Pages

JSP Pages

JavaServer Faces

JavaServer Faces

Java Classes

Deployment descriptor

Deployment descriptor

Java EE Web Container

8.3 container services
Containers are the interface between a component and the low-level platform-specific functionality that supports the component. Before a web, enterprise bean, or application client component can be executed, it must be assembled into a Java EE module and deployed into its container. The assembly process involves specifying container settings for each component in the Java EE application and for the Java EE application itself. Container settings customize the underlying support provided by the Java EE server, including services such as security, transaction management, Java Naming and Directory Interface (JNDI) lookups, and remote connectivity. Here are some of the highlights:
•

The Java EE security model lets you configure a web component or enterprise bean so that system resources are accessed only by authorized users.

78

. classes.
8.servlets. JSPs and Java Server Faces. 3. Security related entries – may specify which pages require login and the roles different users may have. 4. The deployment descriptor serves several purposes.xml file: <?xml version="1. precompiled JSP entities are declared (names. The Java EE remote connectivity model manages low-level communications between clients and enterprise beans. JSPs and Java Server Faces mappings. Servlet. Others. Servlet.bank11. but typical web. servlet classes. and access to the Java EE platform APIs. entries related to session configuration..
Because the Java EE architecture provides configurable services.ccards. JSPs and Java Server Faces definitions. The container also manages nonconfigurable services such as enterprise bean and servlet life cycles. like: 1. application components within the same Java EE application can behave differently based on where they are deployed.LoginServlet </servlet-class> </servlet> </web-app>
79
. descriptions).)> <web-app> <!-. database connection resource pooling. an enterprise bean can have security settings that allow it a certain level of access to database data in one production environment and another level of database access in another production environment. MIME types used by the web application. Here is a small. JNDI lookup services provide a unified interface to multiple naming and directory services in the enterprise so that application components can access these services. Initialization of parameters for servlets. 2.WEB APPLICATIONS
• • •
The Java EE transaction model lets you specify relationships among methods that make up a single transaction so that all methods in one transaction are treated as a single unit. a client invokes methods on it as if it were in the same virtual machine. welcome pages.class>com.Define the Bank 11 ccards Servlets --> <servlet> <servlet-name>Login</servlet-name> <servlet. web. For example. After an enterprise bean is created.xml) which allows the customization of the web application at deployment time.4 deployment descriptor
The deployment descriptor is an xml file (namely. data persistence.0" encoding="ISO-8859-1" ?> <!DOCTYPE web-app (View Source for full doctype. 6. 5.8 . like what pages are error.

The association between the name of the web application and the location of its base directory is made by a <context> element in the "%TOMCAT_HOME%\conf\server. This association is made in the file "%TOMCAT_HOME%\conf\web. However. To make anything work:
•
de-comment the following section: <servlet-mapping> <servlet-name>invoker</servlet-name> <url-pattern>/servlet/*</url-pattern> </servlet-mapping> in the configuration file "%TOMCAT_HOME%\conf\web.xml". Unfortunately. The "/Enroll" part of the URL identifies the servlet. Basicly. it is the alias of the real servlet class. For example. In general.WEB APPLICATIONS
8.servlets. basicly.ccards.servlets". 1.8 . whose name is rather long.bank11. for flexibility. like "http://localhost:8080/ccards/servlet/Enroll" there are 3 things which have to be fixed in order to make things work properly.servlets". in an UNIX environment) is set to "C:\TW\Tomcat".xml" file. if the base directory of the "/ccards" web application is "%TOMCAT_HOME %\webapps\vdumitrascu\cc".bank11. The "/servlet" part of the URL tells the web server (Tomcat.ccards. Then the "EnrollServlet.class" file must be located in the directory "%TOMCAT_HOME%\webapps\vdumitrascu\cc\WEBINF\classes\com.EnrollServlet </servlet-class> </servlet>
80
. This association between the (short) alias of the servlet and its real (long) name is made in the web. The "/ccards" part of the URL is. Behind a very benign URL. This subdirectory has (in general) the same name as the application itself.xml" file looks like: <context path="/ccards" docbase="vdumitrascu/cc" /> 3. Assume that we work with Tomcat and that the environment variable %TOMCAT_HOME% (or $TOMCAT_HOME.bank11. Let's say that this class is "EnrollServlet. then the corresponding <context> element in the "%TOMCAT_HOME%\conf\server.class" and that it is part of the package "com. the lines which deal with this issue are commented out in the latest version of Tomcat (for so-called "security issues"). the name of the web application. More exactly the corresponding <servlet> element should look like: <servlet> <servlet-name>Enroll</servlet-name> <servlet-class>com. the base directory of an application is a subdirectory of the "%TOMCAT_HOME%\webapps" directory.xml"
2. the location of the base directory of a web application may be any sub(sub)directory of "%TOMCAT_HOME%\webapps".xml file of the web application.5 practical deployment issues
There are several issues with the web applications deployment. in our case) to execute the invoker servlet.ccards.

Enhydra Winstone supports specification 2.2 servlet containers
The servlet does not communicate directly with the client. tjws spec 2. this is just a work in progress.2. now bought by Oracle Borland Enterprise Server GlassFish (open source).4.2 commercial servlet containers
• • • • • • •
BEA WebLogic Server or Weblogic Express. 2010. Java EE 6 SDK is intended to contain an implementation of the Java Servlet 3. platform independent programs. but through a web container. Web containers are implemented by various vendors. from BEA Systems. Technically speaking. small footprint. The current Java Servlet specification is 2.
9. As of oct.SERVLETS
9 .1 Noncommercial servlet containers
• • • • • • •
Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under the Apache Software License.4. but at this point. Jetty Jaminid contains a higher abstraction than servlets.9 .0 specification.SERVLETS
9.0 specification is available for public review. The Java Servlet API provides a simple frame for building web applications on web servers. which extend the functionality of the web server.1 the servlets as part of web applications
Java servlets – small. from Sun Microsystems (Oracle) JBoss (open source) JRun.2.5 and is in final state. the Java Servlet 3. a servlet is a Java class that extends the GenericServlet (or. from Sun Microsystems (Oracle) Java System Web Server . more often. The servlet lives within this container which provides an execution environment for the servlet class. from Adobe Systems (formerly developed by Allaire Corporation)
81
. in most cases as part of an application server. modular design
9. Apache Geronimo is a full Java EE implementation by Apache.
9. maintained by Oracle Java System Application Server . has a focus on minimal configuration and the ability to strip the container down to only what you need. the HttpServlet) class.

All classes extending the GenericServlet class should provide an implementation for the service() method. ServletConfig.9 . ServletResponse resp) public void service(HttpServletRequest req. before the servlet processes any HTTP request. Since this class implements the ServletConfig interface. Methods specific to this class: public void init() public void log(String msg) public void log(String msg.5 the GenericServlet class
public abstract class GenericServlet implements Servlet. The web container calls the service() method in response to any incoming request.
9.6 the HttpServlet class
It is very likely that the only implementation of the Servlet interface we'll ever use is one that processes an HTTP request. The servlet API provides such a specific class.SERVLETS
public String getServletInfo(). without having to obtain a ServletConfig object first.
83
. HttpServletResponse resp) protected void doPost(HttpServletRequest req. Serializable This class provides a basic implementation of the Servlet interface. public abstract class HttpServlet extends GenericServlet implements Serializable The HttpServlet provides an HTTP specific implementation of the Servlet interface. namely the HttpServlet class. arguments which implement the ServletRequest and ServletResponse interfaces. Throwable t)
9. The method performs all initialization required. the developer may call ServletConfig methods directly. respectively. This method has two arguments. After instantiating the servlet. This abstract class specifies the following methods: public void service(ServletRequest req. More on the servlet life cycle. The servlet specification insures that the init() method is called just once for any given instance of the servlet. HttpServletResponse resp) protected void doGet(HttpServletRequest req. the web container calls its init() method. as well. in a different section.

After instantiation. the web container creates a single instance of the servlet. method which performs the initialization of the servlet.SERVLETS
• • • • •
instantiation initialization service destroy unavailable
The container creates a servlet instance as first response to an incoming (HTTP) request or at container startup. The other two use the HttpSession and ServletContext objects. Typically.SingleThreadModel. this method contains JDBC driver loading. If the servlet does not implement the javax. But what is the difference between a parameter and an attribute? While the parameters of the request are part of the request itself. or to allow sending data from a servlet to another. which requires that the service() method be thread safe.
85
. respectively. Also. DB connection opening.
9.10 the ServletRequest interface
Here are some of the methods of this interface: public public public public public public public public public public public public Object getAttribute(String name) Object setAttribute(String name. JSP or JSF. the servlet's destroy() method will be called before the servlet itself is destroyed. The first one is to attach attributes to the request object. The purpose of attributes is to allow the container to provide additional data to a servlet. which will service all incoming requests. the attributes of the request are attached by the web containers or by the servlets/JSPs/JSFs. concurrent requests are serviced in more than one service thread. etc. Object attr) Enumeration getAttributeNames() int getContentLength() String getContentType() String getParameter(String name) Enumeration getParameterNames() String[] getParameterValues() String getServerName() int getServerPort() String getRemoteAddr() String getRemoteHost()
Most of the above methods are self explanatory. Typically. There are 3 different ways for attaching and retrieving attributes.9 . the container calls the init() method of the servlet. The web container makes sure that the init() method of the servlet will be completed before invoking its service() method.servlet.

Here are the most important ones: public ServletOutputStream getOutputStream() public PrintWriter getWriter() public void setContentLength(int len) public void setContentType(String type) public void setBufferSize(int size) public int getBufferSize() public void flushBuffer()
9. Here are some of them: public Cookie[] getCookies() public long getDateHeader() public String getHeader(String name) public Enumeration getHeaders(String name) public Enumeration getHeaderNames() public String getContextPath() public String getPathInfo() public String getQueryString() public String getRemoteUser()
9.13 the HttpServletResponse interface
This interface extends the ServletResponse interface and defines methods specific for constructing responses to HTTP requests.12 the ServletResponse interface
This interface defines methods for constructing responses to servlet requests. Here are the most important ones:
86
. One has to take in account the structure of an HTTP request when overviewing the most important methods of this interface.11 the HttpServletRequest interface
public interface HttpServletRequest extends ServletRequest This interface contains HTTP specific methods.SERVLETS
9.9 .

xml file.servlets. Each servlet context is rooted at a specific path in the web server. String value) public void setStatus(int statusCode)
9. The ServletContext interface abstracts the context of a web application.SERVLETS
public void addCookie(Cookie cookie) public String encodeURL(String url) public void sendError(int status) public void sendError(int status. The deployment of a web application involves adding an application specific <context> tag which associates the the name of the application with its root directory.15 the Enroll servlet
The Enroll servlet services the request sent by the web browser when we submit the Enroll form (file Enroll.14 the ServletContext interface
A servlet context defines servlet's view of the web application and provides access to resources common to all servlets of the web application. String value) public void addHeader(String headerName.bank11. This is done in server's (container's) server.9 .html) Here is its abbreviated form (topics which are DB related are postponed) of the "EnrollServlet. Object attr) public String removeAttribute(String name)
9.java" file: package com.io.
87
. import java. String message) public void setHeader(String headerName.ccards. A reference to an object of this type can be obtained by invoking the getServletContext() method of the HttpServlet object. public String getMIMEType(String fileName) public String getResource(String path) public ServletContext getContext(String urlPath) public String getInitParameter(String name) public Enumeration getInitParameterNames() public Object getAttribute(String name) public Enumeration getAttributeNames() public void setAttribute(String name.*.

10 . due to the multiple layers of indirection involved and to the limitations imposed to the JDBC layer by the ODBC frame.sql package.
10. which provides several server-side capabilities The JDBC API provides programmatic access from applications written in the Java programming language to standard SQL. the javax. The first release of the JDBC specification dates back to Feb.1 what is jdbc?
JDBC stands for Java Data Base Connectivity and is the Java version of ODBC (Open Data Base Connectivity).0 API consists of 2 packages: 1. It abstracts the vendor-specific details and offers support for the most common database access functions.0) JDBC specification is defined in JSR 221. The JDBC 4. It offers an API for SQL-compliant relational databases access.0 while the current (4. as recognized by the DB industry. JSR (Java Specification Request) 54 defines JDBC 3. the java.0.
89
. The standard JDK includes all classes for this bridge . After that.JdbcOdbcDriver . 1997. JDBC – ODBC Bridge The driver translates the JDBC calls into equivalent ODBC calls. Type 1. The JDBC API presents a standard API to access a wide range of underlying data sources or legacy systems. Both the JDBC and the JDBCODBC calls are invoked within the client application. A JDBC driver is a middleware layer that translates JDBC calls into vendor specific calls. JDBC evolution is part of the Java Community Process. These drivers fall into four standard categories. JDBC was part of Java Standard Edition (JSE). as part of the Java Development Kit (JDK) 1.1.JDBC
10 . This solution is inefficient.jdbc.sql package 2.sun.odbc.JDBC
10. Starting with version 3.2 jdbc drivers
Each database vendor offers its own version of DB access API.

Pure Java Drivers These are the most efficient drivers. The JDBC API calls are converted to direct network calls using vendor provided protocols. The driver translates JDBC specific calls into vendor specific API calls. Part Native Driver The drivers in this category use a combination of Java implementation and vendor specific APIs for DB access. The client application sends a JDBC call through a JDBC driver to the intermediate Database servers. like WebLogic (of BEA Systems) or Inprise Application Server (of Borland). These servers translate the call into a native driver call which handles the actual DB connection.JDBC
Type 2. The DB returns the result of the call to the API. because it eliminates one level of indirection. Intermediate Database Access Server Type 3 drivers are DataBase servers which act as intermediate tier between multiple clients and multiple Database servers. which in turn.10 . Part Java. forwards them to the JDBC driver.
Type 3. It is much faster than the Type 1 drivers.
90
. This type of drivers are implemented by several application servers.
Type 4. All major vendors provide type 4 JDBC drivers for their Database products.

sql. java.CallableStatement java.sql.sql.Date java.0).sql.sql package
This package contains the core JDBC API.sql. The document containing this specification is JSR 221 and can be viewed at http://jcp.0 API.SQLPermission java.sql.sql. defined in the JDBC 3.sql.Driver java.sql.ResultSetMetaData java.sql.Array java.org/en/jsr/detail?id=221.JDBC
10.SQLInput java.Time java.SQLOutput java.Timestamp java.SQLDataException java.Blob java.Statement java.PreparedStatement
java.Connection java.sql.sql.sql. An exhaustive list of the classes and interfaces of this package can be found in the latest JDBC specification (4.SQLWarning java.sql. let's remind some of the most important ones.ResultSet java.Clob java.sql.3 the java.DriverManager
java.Struct java.sql.sql.SQLXML java.sql.Wrapper
91
. Of the 80+ classes and interfaces defined in this specification.sql.Types
java.sql.10 .sql.sql.sql.SQLData java.sql.sql.SQLException java.

OracleDriver sun.DB2Driver oracle.datastore.net.jdbc.jdbc.jdbc.10 . Here are some examples of actual database driver names:
• • • • •
com.ibm.jdbc.sybase.DataStoreDriver com. A database driver is specified by the driver name.borland.db2.JdbcOdbcDriver
93
.JDBC
10.jdbc.odbc. The first one is loading a database driver.driver.5 loading a DB driver connecting to the database
There are two main steps in connecting to an existing database.SybDriver com.

subname – the syntax of this field is vendor specific and allows the identification
Here are some examples of JDBC driver URLs: jdbc:sybase:localhost:2025 jdbc:db2://db2. try { Class. the only protocol allowed in JDBC). let's have a better look in the next section at the DriverManager class.*.Driver"). The URL has 3 parts separated by colons.gjt. but let's take it for granted: import java.sql. passwd). the sub-protocol is used to identify the JDBC driver. Here is some sample code which shows how this is done: String connURL = "jdbc:mysql://localhost:3306/ccards".10 .com:50002/ccards jdbc:oracle:thin:@loclahost:1521:ORCL
• • •
The second step in connecting to an existing database is to open the connection. as follows: jdbc:<subprotocol>:subname
• • •
jdbc is the protocol name (actually.newInstance(). } catch (Exception e) { // driver not found e. String passwd = "root" Connection conn = DriverManager.forName("org.
94
. } The actual location of the database is specified by its URL (also known as connection URL).*. import java.mm.getConnection(connURL.printStackTrace(). Since we just used it. user.mysql.bank11. as specified by the driver vendor.JDBC
The Java code to load the driver name is somewhat obscure.util. by using the connection URL. String user = "root".

java. let's see an example of how to use the last of the three forms.getConnection(connURL.Properties info) throws SQLException While the first two forms of getConnection() are pretty straightforward. int resultSetConcurrency. "true"). Here they are: public static Connection getConnection(String connURL) throws SQLException public static Connection getConnection(String connURL.JDBC
10. Properties prp = new Properties(). The most important methods for creating statements: Statement createStatement() throws SQLException Statement createStatement(int resultSetType. String user. Each driver used by the application must be registered (loaded) before the DriverManager class tries to obtain a connection. int resultSetConcurrency) throws SQLException Statement createStatement(int resultSetType. int resultSetHoldability) PreparedStatement prepareStatement(String sql) throws SQLException CallableStatement prepareCall(String sql) throws SQLException
95
.7 the Connection interface
The Connection interface is part of then javax. prp. but we will restrict ourselves to creating SQL statements. There are 3 versions of the getConnection() method of the DriverManager class.10 . Once we get the hold of a Connection object. prp. String passwd) throws SQLException public static Connection getConnection(String connURL. prp).put("autocommit". we can use it for various purposes.6 the DriverManager class
This class belongs to the javax. "true").sql package.put("create". Connection conn = DriverManager.util.sql package and offers a common access layer on top of different JDBC drivers.
10.

as the argument. all this data about the DB schema (or metadata) can be retrieved using the ResultSetMetaData interface. An exception to this is that WebSphere currently changes the cursor holdability default so that cursors are implicitly closed when committed. The invocation of the getMetaData() method of a ResultSet object returns an object of ResultSetMetaData type. not at 0) or the column name.10 .JDBC
Most of these methods require the column index (which in SQL starts at 1. PreparedStatement. What if we don't have this knowledge? Fortunately. a concurrency of read only. and CallableStatement objects. Here are the most important methods specified by the ResultSetMetaData interface:
• • • • • • • • • • • • • • • • • • • •
getCatalogName() getTableName() getSchemaName() getColumnCount() getColumnName() getColumnLabel() getColumnType() getColumnTypeName() getColumnClassName() getColumnDisplaySize() getScale() getPrecision() isNullable() isCurrency() isSearchable() isCaseSensitive() isSigned() isAutoIncrement() isReadOnly() isDefinitelyWritable()
10. and cursors are held over commit boundaries.10 ResultSet characteristics
By default. A cursor comprises a control structure for the successive traversal (and potential processing) of records in a result set. One can think of a database cursor as an iterator over the collection of rows in the result set. The usage of these retrieval methods assumes the prior knowledge of the type and the index (or name) of a particular column. These characteristics are configurable through methods that are accessible on Statement. all created ResultSets have a type of forward only.
98
.

Whether the ResultSet is scrollable. The types of Java (TM) Database Connectivity (JDBC) ResultSets that are defined by constants on the ResultSet interface.

Definitions of these ResultSet types are as follows:

TYPE_FORWARD_ONLY
A cursor that can only be used to process from the beginning of a ResultSet to the end of it. This is the default type.

TYPE_SCROLL_INSENSITIVE
A cursor that can be used to scroll in various ways through a ResultSet. This type of cursor is insensitive to changes made to the database while it is open. It contains rows that satisfy the query when the query was processed or when data is fetched.

TYPE_SCROLL_SENSITIVE
A cursor that can be used to scroll in various ways through a ResultSet. This type of cursor is sensitive to changes made to the database while it is open. Changes to the database have a direct impact on the ResultSet data. JDBC 1.0 ResultSets are always forward only. Scrollable cursors were added in JDBC 2.0. Note: The blocking enabled and block size connection properties affect the degree of sensitivity of a TYPE_SCROLL_SENSITIVE cursor. Blocking enhances performance by caching data in the JDBC driver layer itself.

10.10.2 Concurrency
Concurrency determines whether the ResultSet can be updated. The types are again defined by constants in the ResultSet interface. The available concurrency settings are as follows:

CONCUR_READ_ONLY
A ResultSet that can only be used for reading data out of the database. This is the default setting.

CONCUR_UPDATEABLE
A ResultSet that allows you to make changes to it. These changes can be placed into the underlying database. JDBC 1.0 ResultSets are always forward only. Updateable ResultSets were added in JDBC 2.0. Note: According to the JDBC specification, the JDBC driver is allowed to change the ResultSet type of the ResultSet concurrency setting if the values cannot be used together. In such cases, the JDBC driver places a warning on the Connection object. There is one situation where the application specifies a TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATEABLE ResultSet. Insensitivity is implemented in the database engine by making a copy of the data. You are then not allowed to make updates through that copy to the underlying database. If you specify this combination, the driver changes the sensitivity to TYPE_SCROLL_SENSITIVE and create the warning indicating that your request has been changed.

10.10.3 Holdability
The holdability characteristic determines whether calling commit on the Connection object closes the ResultSet. The JDBC API for working with the holdability characteristic is new in version 3.0. However, the native JDBC driver has provided a connection property for several

99

10 - JDBC
releases that allows you to specify that default for all ResultSets created under the connection. The API support overrides any setting for the connection property. Values for the holdability characteristic are defined by ResultSet constants and are as follows:

HOLD_CURSOR_OVER_COMMIT
All open cursors remain open when the commit clause is called. This is the native JDBC default value.

CLOSE_CURSORS_ON_COMMIT
All open cursors are closed when commit clause is called.

10.12 the PreparedStatement interface
If an SQL statement is used several times and its different forms differ only with respect to the data they specify, a better choice is the usage of a PreparedStatement object. Prepared statements are parametrized and each parameter (usually, a field (column) value or name) is represented by a question mark '?'. The following lines of Java code give an example of how to use PreparedStatement objects: Statement stmt = con.createStatement(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO customer VALUES (?, ?, ?)"); stmt.executeUpdate("CREATE TABLE customer varchar(32) lastName varchar(24))"); // set parameters for preparedStatement pstmt.setInt(1, 1021); pstmt.setString(2, "Vasile"); pstmt.setString(3, "Dumitrascu"); int count = pstmt.executeUpdate(); (id int, firstName

1 and is related to the 2.tagext contains classes and interfaces for the definition of JavaServer Pages Tag Libraries.jsp and javax.servlet.servlet.11 .5 Java Servlet specification. The interface HttpJspPage is the interface that a JSP processor-generated class for the HTTP protocol must satisfy.servlet.HttpJspPage interface has a single method: public void jspService(HttpServletRequest req.3 the generated servlet – an example
106
. JSR 245 is the official document containing the current specification of JSP.jsp.jsp package contains a number of classes and interfaces that describe and define the contracts between a JSP page implementation class and the runtime environment provided for an instance of such a class by a conforming JSP container.tagext.servlet.JspPage interface
This interface has 2 methods: public void jspInit() public void jspDestroy() The javax.jsp.JSP
11 . A JSP is loaded by a JSP container and is converted (to servlet code).servlet.
11. The JspPage interface is the interface that a JSP processor-generated class must satisfy. HttpServletResponse resp) throws ServletException.
11.jsp defines two interfaces – JspPage and HttpJspPage. The current JSP specification is JSP 2. The JSP specific interfaces.jsp. the servlet code is regenerated. IOException The implementation of this method is generated by the web container – never by the developer.servlet. If the JSP is modified.servlet. The javax. The package javax.2 the java.JSP
11. The package javax. classes and exceptions are part of two packages.1 java server pages as part of web applications
A Java Server Page (JSP) is a standard HTML or XML file which contains new scripting tags. namely javax.

11.4 ordinary java beans
A java bean is a java class which: implements the java.io.Serializable interface provides a no-argument constructor for each of its properties, provides get and set methods implements a property change mechanism

in case of error
The include directive instructs the container to include inline the content of the resource specified by "fileName". These directives do not produce any client output and affect the whole JSP file. the buffer is flushed automatically if full isThreadSafe – "true" or "false" isErrorPage – "true" or "false" contentType – MIME type of the response info errorPage – the URL of an error page. It has the following format: <%@taglib uri="tagLibUri" prefix="tagPrefix" %> where the tagPrefix indicates a name scope.11 . include and taglib.. it is interpreted relative to the position of the current JSP
11. attrn="valn" %> Ther are three JSP directives: page. The format of this directive: <%@include file="fileName" %> The taglib directive allows the usage of custom tags (tag extensions).JSP
•
if the URL does not start with / . The general format of a JSP directive is as follows: <%@directive_name attr1="val1" ..
111
. the implicit session object is available buffer – buffering model for the output stream autoflush – if "true". %> attributes:
• • • • • • • • • • •
language – values: "java" extends – superclass of the generated class import – list of packages classes session – "true" or "false". The page directive format: <%@page attr1="val1" .6 jsp directives
The JSP directives are messages sent by the Java Server Page to the JSP container...

11 .1 declarations
<%! java vars and method declarations %> Basicly. a bloc of java code used to define class-wide variables and methods in the generated servlet. It is evaluated at request processing time and the result is converted to a string which is then displayed.7 scripting elements
11.
11.JSP
11.7.
11. A tag can be embedded into a JSP page.8 the useBean standard action
<jsp:useBean> Used to instantiate a Java bean or locate a bean instance.7.2 scriptlets
<% valid java statements %> Block of java code which is executed during request processing.7. In Tomcat.7. Assigns it to available name or id.3 expressions
<%= java expressions to be evaluated %> A scriptlet that sends a value of a Java expression to back to the client. The syntax for this action is: <jsp:useBean id="beanName" scope="sName" beandetails />
112
.
11. this code goes to inside the service() method.4 standard actions
Tags that affect the runtime behaviour of the JSP and the response to the client. The standard actions are detailed in the next paragraphs.
11.

Sets one Bean property to the value of one request parameter.JSP
where beandetails is one of the following:
• • • •
class="className" class="className" type="typeName" beanName="beanName" type="typeName" type="typeName"
11. and if so.Sets one Bean property to a specific value. The value can be a String or an Expression
•
•
11. The property names in the Bean must match the request parameters property="propertyName" [ param="parameterName" ] . you must specify param. property="propertyName" value="{ string | <%= expression %> }" . The syntax for this action is: <jsp:setProperty name="beanName" propertydetails /> where propertydetails is one of the following:
• • • •
property="*" property="propertyName" property="propertyName" param="parameterName" property="propertyName" value="propertyValue"
where propertyValue is a string or a scriptlet.stores all of the values in the request object parameters (called request parameters) in matching Bean properties.11 .9 the setProperty standard action
<jsp:setProperty> Used in conjunction with the <jsp:useBean> action to set the value of the bean properties.10 the getProperty standard action
<jsp:getProperty>
113
. Attributes description:
• • •
name .the name of a bean instance. The request parameter can have a different name than the Bean property. already defined in a <jsp:useBean> property – specifies the relationship between request parameters and corresponding bean properties property="*" .

The syntax for this action is: <jsp:include page="pageURL" flush="true" /> Attributes description:
• •
page . the <jsp:include> action is executed at request processing time and has static or dynamic content.13 the forward standard action
114
.the URL of the page. The syntax for this action is: <jsp:param name="paramName" value="paramValue" />
11.JSP
Used to access the properties of a bean. The syntax for this action is: <jsp:getProperty name="beanName" property="propName" /> Attributes description:
• •
name . An included page has access only to the JspWriter object and cannot set headers or cookies. converts them to string and displays the output to the client.name of the property to be retrieved
11.11 the param standard action
<jsp:param> Provide other tags with additional information in the form of name:value pairs.11 . flush . same format as the <%@include> directive.only the "true" value is supported. <jsp:plugin> actions. It is used in conjunction with the <jsp:include>. While the <%@include> directive is executed at compile time and has static content.12 the include standard action
<jsp:include> Used for the inclusion of a static or dynamic resource into the current JSP page at request processing time.the name of a bean instance whose property is to be retrieved property .
11. <jsp:forward>.

the type of object the plugin will execute. when we want to separate the application into different views..JSP
<jsp:forward> Used to forward the the request to another JSP. followed by the execution of the applet or JavaBeans component specified by the tag. You must include the . code="classFileName" .class extension in the name following code.11 . codebase="classFileDirectoryName" . If you do not supply a value. the path of the JSP file that calls <jsp:plugin> is used. name="instanceName" . as well.the name of the Java class file that the plugin will execute.
name . already defined in a <jsp:useBean> type="bean|applet" . It is used mainly.. The syntax for this action is: <jsp:plugin type="bean|applet" code="objCode" codeBase="objCodeBase" align="align" archive="archiveList" height="height" hspace="hSpace" jreversion="jreVersion" name="componentName" vspace="vSpace" width="width" nspluginurl="netscapeURL" iepluginurl="IEURL"> <jsp:params> <jsp:param name="paramName" value="paramValue" /> </jsp:params> </jsp:plugin> Attributes description:
• • •
. archive="URIToArchive.a comma-separated list of paths that locate archive files
•
•
•
115
.the name of a bean instance.. as this attribute has no default value.
11. You must specify either bean or applet.a name for the Bean or applet instance. which makes it possible for applets or Beans called by the same JSP file to communicate with each other. The syntax for this action is: <jsp:forward page="pageURL" /> The action may include several <jsp:param> tags. depending on request. .." . The filename is relative to the directory named in the codebase attribute. servlet or to a static resource.the absolute or relative path to the directory that contains the applet's code..14 the plugin standard action
<jsp:plugin> Used in pages to generate client browser specific HTML tags (<OBJECT> or <EMBED>) that result in download of Java plugins(if required).

it has java. 1. it has HttpServletResponse type and page scope 3.jsp.the positioning of the image displayed by the applet or Bean relative to the line in the JSP result page that corresponds to the line in the JSP file containing the <jsp:plugin> tag.1. height="displayPixels" width="displayPixels" .an object with request scope is bound to the HttpServletRequest object.15 implicit objects
JSP provides several implicit objects. based on the servlet API.it is an instance of the page's implementation of the servlet class.JSP
to be preloaded with a class loader located in the directory named in codebase.
•
align="bottom|top|middle|left|right" . The value is a full URL. objects which are automaticly available. config . request . session . it is of type ServletConfig and has page scope 8. to the left and right (or top and bottom) of the image the applet or Bean displays.represents the object that triggered the service() method invokation and has type HttpServletRequest with scope request 2. pageContext . Must be a small nonzero number. of the image the applet or Bean displays. in pixels.16 scopes
1.1" .the initial height and width.represents server's response to the request. and domain name.the URL where the user can download the JRE plugin for Netscape Navigator.provides a single point of access to attributes and shared data within the page. it has javax. hspace="leftRightPixels" vspace="topBottomPixels" .it has HttpSession type and session scope 5.the amount of space. not counting any windows or dialog boxes the applet or Bean brings up. application .JspWriter type and scope page 7.PrintWriter.servlet. with a protocol name. the object can be accessed by invoking the getAttribute() method on the implicit
116
. iepluginurl="URLToPlugin"
•
•
• •
•
11. out .it represents the buffered version of java. page . in pixels.11 .it is the SevletConfig for the current JSP page. nspluginurl="URLToPlugin" . request . it has type PageContext with scope page 4. it has type ServletContext and scope application 6.represents the servlet context. response . The default value is 1.lang.io. optional port number.Object type and scope page
11. writes to the output stream to the client. jreversion="JREVersionNumber|1.the version of the Java Runtime Environment (JRE) the applet or Bean requires.

colors]". The primitive values must be wrapped by a Float and a Boolean in order to be stored as resources.string]". "An option must be selected" }. SimpleBeanResources. the form's name and the processor's name.18.number]".ListResourceBundle
{
private static final Object[][] contents = { { "[DEFAULT_VALUE. "One or more items must be selected" }.list]". The list of optional properties has a single element. new String[] {
123
. "One or more colors must be selected" }. The default values are defined for a String. { "[ERROR_MESSAGE. new Boolean(true) }. The form's name and the processor's name are used by the JSP handler described in the next section. No error is signaled if the user doesn't provide a value for this property. new Float(0.examples.list]". new int[] { 2.util. The default values for the properties of the contained bean could have been defined in another resource bundle called SimpleSubBeanResources.123) }. a float.number" SIZE="20"> <P> <INPUT TYPE="SUBMIT" VALUE="Submit"> <INPUT TYPE="RESET" VALUE="Reset"> </FORM> </BODY> </HTML>
11. It has been included here just for demonstrative purposes.simple. { "[ERROR_MESSAGE. error messages. There are three error messages. "abc" }.integer]". { "[DEFAULT_VALUE. { "[DEFAULT_VALUE.mapping. a boolean and an int[]. 3 } }. { "[OPTIONAL_PROPERTIES]". The mapping framework contains default error messages for each type of form element. These two resources aren't accessed by the mapping utilities. { "[DEFAULT_VALUE. the list of optional properties.java: package com.JSP
<P> String (subBean) <BR> <INPUT TYPE="TEXT" NAME="subBean. { "[ERROR_MESSAGE.3 bean resources
The SimpleBeanResources class is a resource bundle containing optional information that is useful to the mapping process: default values. public class SimpleBeanResources extends java. the processing order.11 .flag]".devsphere. Their role is to help the users to correct the input errors.string" SIZE="20"> <P> Number (subBean) <BR> <INPUT TYPE="TEXT" NAME="subBean. The processing order isn't necessary to this example.

examples.JSP
"optional" } }. The error messages that occur during the mapping process are stored in a Hashtable. { "[PROC_NAME]".FormUtils sets the bean properties to the values of the request parameters (form data).devsphere.11 . a later section of this chapter lists two JSPs that perform the mapping and build the HTML form without using the framework.jsp handler is based on a template that was described in a previous chapter.jsp: <%@ page language="java" %> <%@ page import="com.SimpleBean"/> <% // Get the bean resources java. It inserts a VALUE attribute for text elements. For a better understanding of this example. "SimpleForm. string values are converted to numbers.FormUtils inserts the bean data and the error messages into the HTML form. a CHECKED attribute for checkboxes and radio buttons that must be selected and a SELECTED attribute for the list items that must be highlighted. The formToBean() method of com.simple. "number".devsphere. The beanToForm() method of com. "integer".devsphere.4 JSP Handler
The SimpleHndl. "colors".devsphere.jsp" } }.mapping. "optional".mapping.ResourceBundle beanRes
124
. If necessary. public Object[][] getContents() { return contents. A boolean property is set to true if the request parameter is present no matter what its value is (except "false").logging.mapping.mapping. "SimpleProc.html" }. "flag".*" %> <jsp:useBean id="simpleBean" scope="request" class="com. com.devsphere. new String[] { "string". { "[PROCESSING_ORDER]". "list". "subBean" } }. } }
11. { "[FORM_NAME]".18.util.*. SimpleHndl.

jsp uses 150 lines of Java-JSP mixture to set the properties of a bean object to the values of the request parameters.append("}"). In addition. The localization of the Complex*. It uses 120 lines of Java-JSP-HTML mixture to generate a 40 lines HTML form.jsp files.util.toString(list[0]). for (int i = 0.toString().toString().length.length == 0) return "". } %>
11.append("}").append(" "). StringBuffer strbuf = new StringBuffer(). return strbuf.beanToForm() can do the same using a pure HTML file.SimpleBean"/> <jsp:useBean id="errorTable" scope="request" class="java. if (list.examples. A later chapter shows how to build internationalized applications using the framework.18. In addition. Using the framework you separate the HTML code from the Java/JSP code. ComplexForm. return strbuf. default values and error messages are kept in localizable resource bundles. i++) { strbuf. The adding/removing of a bean property requires changes in both Complex*.append(list[i]). A single call to FormUtils. } public static String toString(int list[]) { if (list == null || list. } strbuf. ComplexHndl.JSP
if (list[i] != null) { strbuf.formToBean() call.jsp generates the HTML form dynamically and inserts default values and error messages. you only have to add/remove a form element to/from a pure HTML file. strbuf.11 . i < list.mapping. strbuf. beanToForm() handles and logs many types of application errors. strbuf.6 without using the devsphere framework
ComplexForm.append(list[i]).length == 1) return Integer.simple. This is the equivalent of a single FormUtils. Using the framework.append("{ ").jsp: <%@ page language="java" %> <jsp:useBean id="simpleBean" scope="request" class="com. } strbuf.jsp files to other languages requires a lot of work and could make the maintenance very hard.devsphere. making the testing and the debugging easier.append(" ").Hashtable"/> <HTML> <HEAD><TITLE>Without using the framework</TITLE></HEAD>
127
.

} if (isPostMethod && errorTable.jsp.11 .mapping.setString(""). simpleBean.jsp"/> <% } %> <%! void setErrorMessage(java.put(property.jsp handler is basically a Java scriptlet.BeanDispatcher SimpleHndl.simple. } } catch (NumberFormatException e) { setErrorMessage(errorTable. That was a simple and compact way to present a handler.xml: SimpleHndl.18.Hashtable errorTable.number".helpers. String property. The JSP handler can be replaced by only a few lines that are added to servlets.\
133
.examples. simpleBean. errorTable.properties or web.mapping. simpleBean.initparams=\ BEAN_NAME=com.JSP
filled").123f). simpleSubBean.code=com.isEmpty()) { %> <jsp:forward page="SimpleProc.devsphere. "subBean.setNumber(0.devsphere. String message) { message = "<FONT COLOR=\"#FF0000\">" + message + "</FONT><BR>". A more elegant solution is the replacement of the JSP handler with a general Java servlet. The com.setString("abc").setFlag(true).setList(new int[] { 2.jsp"/> <% } else { %> <jsp:forward page="ComplexForm.helpers. simpleBean.setOptional("").SimpleBean.devsphere.7 using the framework with servlets and JSPs
The SimpleHndl.
} } else { simpleBean.util. "Must be a
number").mapping package contains an abstract class called GenericHandler. The Java code could easily be moved to a utility class. which is the bean-independent equivalent of SimpleHndl. message). } %>
11. This class is extended by BeanDispatcher. 3 }).

A standard servlet engine running on a single JVM will instantiate the servlet class once for each servlet declaration.
11.properties (or web. The previous section showed how to declare a BeanDispatcher servlet.devsphere.mapping. If your Web application contains many forms/beans.devsphere.xml) file: ServletName.AnotherBean. Users invoke the servlet by requesting a URL like this: http://www.code=com.devsphere.code=com.properties: AnotherHndl.host.examples. you could add a few other lines to servlets.helpers.com/AppName/servlet/SimpleHndl http://www.com/AppName/servlet/AnotherHndl
134
.\ BASE_PATH=/another The two servlets that share the same code could be invoked with something like this http://www.BeanDispatcher</servlet-class> <init-param> <param-name>BEAN_NAME</param-name> <paramvalue>com.\ BASE_PATH=/simple or <servlet> <servlet-name>SimpleHndl</servlet-name> <servletclass>com.devsphere.ClassName There is nothing that can stop you associating many servlets with the same class. You may use the same class to declare one servlet for each bean component.18.11 .examples. you have to declare the bean within a <jsp:useBean> tag. you have to provide a JSP handler for each bean. All requests to one of the declared servlets will be serviced by the same instance of the servlet class.BeanDispatcher AnotherHndl. a servlet is identified with its class.mapping. In many cases. If you have another bean-form pair.simple.mapping.another.8 why using servlets?
Using a JSP. A servlet can be made bean-independent.host.mapping.\ BEAN_ID=anotherBean.company.helpers.host.com/AppName/servlet/ServletName The servlet engine associates a servlet to a class in the servlets.JSP
BEAN_ID=simpleBean.SimpleBean</param-value> </init-param> <init-param> <param-name>BEAN_ID</param-name> <param-value>simpleBean</param-value> </init-param> <init-param> <param-name>BASE_PATH</param-name> <param-value>/simple</param-value> </init-param> </servlet> GenericHandler and BeanDispatcher were presented in a previous chapter.initparams=\ BEAN_NAME=com.

11 .JSP
135
.

Requests are processed by the FacesServlet. This technology includes: 1. like input fields. built in Ajax support and built in support for bookmarking & page-load actions. builds a component tree. There are five JSF specific tag libraries defined in this specification. Version 2.JAVASERVER FACES
12. A JavaServer Pages (JSP) custom tag library for expressing a JavaServer Faces interface within a JSP page. processes events.12 .0 supersedes version 1.2 javaServer Faces Technology 2. released through the Java Community Process under Java Specification Request (JSR) 314.0
The latest version (as of november 2010) of JavaServer Faces technology is version 2. which loads the appropriate view template.1 what are javaServer faces?
JavaServer Faces technology is a server-side user interface component framework for Java based web applications. JSF is a request-driven MVC web framework based on component driven UI design model. using XML files called view templates or Facelets views. buttons.0. and renders the response (typically HTML) to the client. namely
• • • • •
JSF HTML Tag Library JSF Core Tag Library JSTL Core Tag Library JSTL Functions Tag Library JSF Facelets Tag Library
136
.javaserver faces
12 .
12. links UI components management events handling input validation error handling page navigation specification support for internationalization and accessibility. Version 2.
2. A set of APIs for:
• • • • • • •
representing UI components.0 is part of the Java Enterprise Edition 6 platform.2 and brings in mandatory support for Facelets as the view technology for JSF pages.

JSP pages are compiled into servlets but it’s not the case with Facelets because Facelet pages are XML compliant and its framework uses a fast SAXbased compiler to build views.4.2 of the JFS specification. here is an exhaustive list of the JSF HTML tags:
• • • • • • • • • • • • •
column commandButton commandLink dataTable form graphicImage inputHidden inputSecret inputText inputTextArea message messages outputFormat
137
. there are 25 HTML JSF tags.javaserver faces
12. Facelets can make changes to pages immediately so developing JSF applications with Facelets is simply faster.12 .1 the list of JSF HTML Tags
For reference. The HTML tags can be grouped in the following categories:
• • • • • • •
inputs outputs commands selections layouts data table errors and messages
12. As of version 1.4 the html JSF tags
This tag library contains JavaServer Faces component tags for all UIComponent + HTML RenderKit Renderer combinations defined in the JavaServer Faces specification.3 facelets
Facelet is a view technology for Java Server Faces (JSF) that allows building composite views more quickly and easily than with JSP which is the default view technology for JSF.
12.

4. see the column tag documentation.01 compliant table element that can be associated with a backing bean to obtain its data as well as for event handling purposes. columns and rows. can be accomplished quite easily with this tag. The table can be customized extensively using cascading stylesheet (CSS) classes and definitions to enhance the appearance of the table's headers. A column component is rendered as a single "td" element.items}" var="item"> <f:facet name="header"> <h:outputText value="Your Shopping Cart" /> </f:facet> <h:column> <f:facet name="header"> <h:outputText value="Item Description" /> </f:facet> <h:outputText value="#{item. These are rendered as a single "th" element in a row at the top of the table and as a single "td" element in a row at the bottom of the table. For more information about columns.2 h:dataTable
The dataTable tag renders an HTML 4. The dataTable tag typically contains one or more column tags that define the columns of the table.description}" /> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Price" />
138
. Common formatting techniques. Example: <h:dataTable id="table1" value="#{shoppingCartBean. footers. A dataTable tag can also contain header and footer facets. respectively.
12. we'll have a closer look at some of these tags. such as alternating row colors.javaserver faces
• • • • • • • • • • • •
outputLabel outputLink outputText panelGrid pnelGroup selectBooleanCheckbox selectManyCheckbox selectManyListbox selectManyMenu selectOneListbox selectOneMenu selectOneRadio
In the next paragraphs.12 .

00</td></tr> </tbody> <tfoot> <tr><td colspan="2">Total: $15.javaserver faces
</f:facet> <h:outputText value="#{item.checkoutLabel}" action="#{shoppingCartBean. Example: <h:form id="form1"></h:form> HTML Output <form id="form1" name="form1" method="post" action="/demo/form. If your application requires the use of the GET method for form submission.4.4 h:commandButton
The commandButton tag renders an HTML submit button that can be associated with a backing bean or ActionListener class for event handling purposes. The display value of the button can also be obtained from a message bundle to support internationalization (I18N). The use of the POST method is also required and it is not possible to use the GET method for forms generated by this tag.4. binding request parameters to backing bean properties. Example: <h:commandButton id="button1" value="#{bundle.00</td></tr> </tfoot> </table>
12.00</td></tr> <tr><td>Juicy Orange</td><td>$5.12 .total}" /> </f:facet> </h:dataTable> HTML Output <table id="table1"> <thead> <tr><th scope="colgroup" colspan="2">Your Shopping Cart</th></tr> <tr><th>Item Description</th><th>Price</th></tr> </thead> <tbody> <tr><td>Delicious Apple</td><td>$5. JSF forms use the "post-back" technique to submit form data back to the page that contains the form.3 h:form
The form tag renders an HTML form element. your options include using plain HTML forms.checkout}" />
139
. and using the outputLink tag to generate dynamic hyperlinks.jsp" enctype="application/x-www-form-urlencoded"></form>
12.00</td></tr> <tr><td>Tasty Melon</td><td>$5.price}" /> </h:column> <f:facet name="footer"> <h:outputText value="Total: #{shoppingCartBean.

such as one of the HTML select or text input components.4 f:valueChangeListener
The ValueChangeListener tag registers a ValueChangeListener instance on the component associated with the enclosing tag. This tag accepts one value matching the validator ID you assigned to your validator class in your Faces configuration file.customer. The body content of this tag must be empty. Example: <h:inputText id="emailAddress" value="#{customerBean. A component fires a value change event when its input changes.
12. and validateLongRange tags) but the Validator interface can be implemented by classes that provide custom validation for your application.3 f:validator
The Validator tag registers a named Validator instance on the component associated with the enclosing tag. the user must manually submit the form to invoke the ValueChangeListener. You can register several ValueChangeListeners with a component and they will be invoked in the order that they are registered.emailAddress}"> <f:validator validatorId="emailAddressValidator" /> </h:inputText> <h:message for="emailAddress" /> HTML Output <input id="form:emailAddress" name="form:emailAddress" type="text" value="fake@email"/> Invalid email address. Example: <h:selectOneMenu id="optionMenu" value="#{optionBean. Any component that receives user input. can publish value change events.mycompany.optionList}" /> <f:valueChangeListener type="com. but only if the new input is validated successfully. The ValueChangeListener interface should be implemented by classes that you want to register with components that publish value change events.12 .javaserver faces 12.5.selectedOption}" onchange="submit()"> <f:selectItems value="#{optionBean. Notice in the example below the use of the JavaScript onchange() event to trigger form submission when the list selection changes. The JavaServer Faces framework includes three standard validators (see the validateDoubleRange. validateLength.MyValueChangeListenerImpl" /> </h:selectOneMenu> HTML Output <select name="form:optionMenu" size="1" onchange="submit()"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select>
142
.5. An alternative to this tag is to use a method-binding expression pointing at a value change listener method of a backing bean on the component tag itself. Without this JavaScript event.

This information could later be stored in a cookie and/or a database to identify which locale is preferred by your user. myJSFapp
143
.jsp (French) Bienvenue à notre site!
12. By default the JSF framework will attempt to select the best view for your user based on the Accept-Language header sent to the server from the user's browser as part of the HTTP request for your page. JSF will use the default locale for the Java Virtual Machine serving your application. Another option is to obtain the locale dynamically through user interaction.5. The directory myJSFapp is the base directory of the application.jsp (French) <f:view locale="fr"> <f:loadBundle basename="com.jsp (English) Welcome to our site! welcome_fr. for each locale you wish to support. This tag is useful for internationalization (I18N) purposes.welcomeMessage}" /> </f:view> HTML Output welcome_en. the JSF framework will use the default locale specified in your Faces configuration file. JSF will set that locale for the view and will display the messages for that locale defined in the locale's message bundle. If you have not specified a default locale.12 . The locale attribute accepts a value-binding expression that could resolve to the desired locale. including images and styles.jsp (English) <f:view locale="en"> <f:loadBundle basename="com.6 the structure of a JSF application
Here is a typical directory structure for a JSP application.welcomeMessage}" /> </f:view> welcome_fr. It provides you with several options for presenting your user with localized views of your application.MessageBundle" var="bundle" /> <h:outputText value="#{bundle. Example: welcome_en.mycompany. If your application supports the locale requested by the user.javaserver faces 12.5 f:view
The View tag is the container for all JavaServer Faces component tags used on a page. If the locale requested by the user is not supported by your application. You can wrap the root element of the structured markup language used in your document with this tag to ensure that all child tags are part of the same view.MessageBundle" var="bundle" /> <h:outputText value="#{bundle. This allows you to design localized versions of each page.mycompany. You can also specify the locale for which the view is to be rendered by explicitly setting the locale attribute of the view tag.

xml /pages Comments on this structure:
• • • • • • • • • • •
myJSFapp – application base directory with application name /ant – directory containing Ant build scripts with a default build.contains libraries required by the application. static resources.exadel.xml /JavaSource /WebContent /WEB-INF /classes /lib jsf-impl.12 .7 how does JSF work? a first example
Example taken from http://www.jar – files included in the /lib directory. Let's have a look at the steps needed to build a JSF application: 1. A JSF application is nothing else but a servlet/JSP application.xml web. Define navigation rules 3.jar.xml file /JavaSource – application specific java source classes and properties files /WebContent – contains the Web application files used by the application server or by the web container /WEB-INF – contains files used as part of the runtime Web application /classes – compiled Java classes and properties files copied from the /JavaSource directory /lib . custom tag libraries. included in the /WEB-INF directory faces-config. Create JSP pages 2.xml – the deployment descriptor of the application. JSP pages.com/tutorial/jsf/jsftutorial-kickstart. included in the /WEB-INF directory /pages – directory containing JSP and HTML presentation pages
12. The way the application behaves is controlled by an event listener class. and so on. jsf-api.jar jsf-api. like third party jar files jsf-impl.xml – the JSF configuration file. Create managed beans 4. It has a deployment descriptor. mandatory for any JSF application web.jar faces-config.html.javaserver faces
/ant build. Create properties files
144
. What makes it different is that a JSF application is event-driven.

As a diagram. Edit JSP pages 6.jsp file 7. <navigation-rule> <from-view-id>/pages/inputname.jsp and greeting.jsp files in WebContent/pages/. In our application.javaserver faces
5. Create an index.
12. it would look something like this:
Image from Exadel Studio Pro The navigation rule shown in the picture is defined below. We will complete the content of the files a little bit later. Now that we have the two JSP pages. we just want to go from inputname. The navigation rule for this application is described in the faces-config. And that's all there is to this.jsp is greeting. You only need to create the JSP files. These files will act as place holders for now.xml file.7. we can create a navigation rule.12 . This file already exists in the skeleton directory structure.jsp. Deploy and run the application
12. Compile the application 8.1 creating JSP Pages
Create the inputname.jsp to greeting.2 navigation
Navigation is the heart of JavaServer Faces.jsp.jsp</to-view-id> </navigation-case> </navigation-rule>
145
.jsp go to the view (page) greeting. if the "outcome" of executing inputname. The directory structure already exists.7.jsp</from-view-id> <navigation-case> <from-outcome>greeting</from-outcome> <to-view-id>/pages/greeting. You just need to create its contents. The rule says that from the view (page) inputname.

The bean simply captures the name entered by a user after the user clicks the submit button. of course. myJFSapp.java file.java
Put this code in the file: package myJFSapp. the second part of faces-config. To read more about navigation rules. This section defines a bean name PersonBean. we will create a PersonBean. The next line is the full class name.javaserver faces
This is.3.xml
Your final faces-config.3.7.xml describes our Java bean that we created in the previous steps. request sets the bean scope in the application. } /** * @param Person Name */ public void setPersonName(String name) { personName = name.3.7.12 . <managed-bean> <managed-bean-name>personBean</managed-bean-name> <managed-bean-class>myJFSapp. a very simple navigation rule.2 declaring the Bean in faces-config. we will create a myJFSapp folder inside the JavaSource folder. } } Later you will see how to "connect" this bean with the JSP page.3 faces-config. Inside this myJFSapp folder.PersonBean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>
12. This way the bean provides a bridge between the JSP page and the application logic.1 PersonBean.7. visit the JSP Navigation Example forum item.)
12.7.xml
Now.3 creating the Managed Bean
Next. public class PersonBean { String personName. It's a simple Java bean with one attribute and setter/getter methods. (Please note that the field name in the JSP file must exactly match the attribute name in the bean. /** * @return Person Name */ public String getPersonName() { return personName.
12.PersonBean. This class is straight-forward.
12. You can easily create more complex ones.xml file should look like this:
146
.

dtd"> <faces-config> <navigation-rule> <from-view-id>/pages/inputname.properties
Put this text in the properties file: inputname_header=JSF KickStart prompt=Tell us your name: greeting_text=Welcome to JSF button_text=Say Hello sign=! We now have everything to create the JSP pages. We use the messages stored in the properties file in our JSP pages. this properties file will be copied to the classes folder where the runtime can find it.com/jsf/core" prefix="f" %>
147
.jsp</from-view-id> <navigation-case> <from-outcome>greeting</from-outcome> <to-view-id>/pages/greeting.5.7.
12.sun.12 . Inc.4.jsp
Put the following coding into this file: <%@ taglib uri="http://java.sun.1 messages.com/dtd/web-facesconfig_1_1.PersonBean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> </faces-config>
12.1//EN" "http://java.javaserver faces
<?xml version="1.//DTD JavaServer Faces Config 1.0"?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems. Keeping the messages separate from the JSP page allows us to quickly modify the messages without editing the JSP page. We need to place it in the JavaSource folder so that during project compilation.
12.4 creating a Properties File (Resource Bundle)
A properties file is just a file with param=value pairs. Let's create a bundle folder in the JavaSource/myJFSapp folder and then a messages.7.sun.1 inputname.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.7.7.properties file in the bundle folder.5 editing the JSP Pages
Two pages should already have been created in myJFSapp/WebContent/pages.
12.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>personBean</managed-bean-name> <managed-bean-class>myJFSapp.

inputname_header}"/> </h1> <h:form id="helloForm"> <h:outputText value="#{msg.sun. One can also add a line like <f:validateLength minimum="2" maximum="10"/> to make sure that the length of this field is reasonable long.messages" var="msg"/> <html> <head> <title>enter your name page</title> </head> <body> <f:view> <h1> <h:outputText value="#{msg.javaserver faces
<f:loadBundle basename="myJFSapp.bundle. The third line loads our properties file (resource bundle) that holds messages that we want to display in our JSP page.prompt}"/> <h:inputText value="#{personBean.12 .prompt}"/> 3 <h:inputText value="#{personBean. Then. look up the value for inputname_header in that file and print it here. The required attribute of the h:inputText tag insures that an empty name will not be sent.personName}" required=”true”> <f:validateLength minimum="2" maximum="10"/> </h:inputText> <h:commandButton action="greeting" value="#{msg. <%@ taglib uri="http://java. <h:inputText value="#{msg.com/jsf/core" prefix="f" %> <f:loadBundle basename="myJFSapp.bundle.button_text}" /> </h:form> </f:view> </body> </html> Now. let's explain the important sections in this file after displaying the code for each section starting from the top.messages" var="msg"/> The first line of these three is a directive that tells us where to find JSF tags that define HTML elements and the second directive tells us where to find JSF tags that define core JSF elements. 1 <h:form id="helloForm"> 2 <h:outputText value="#{msg.sun.inputname_header}" required=”true”> This tag simply tells us to look in the resource bundle that we defined at the top of the page.button_text}" /> 7 </h:form>
148
.personName}" required=”true”> 4 <f:validateLength minimum="2" maximum="10"/> 5 </h:inputText> 6 <h:commandButton action="greeting" value="#{msg.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.

specifically the bean attribute personName.12 . you will see something like this: Welcome to JSF.6 creating the index. Having an index.bundle.com/jsf/core" prefix="f" %> <f:loadBundle basename="myJFSapp. In the value attribute we connect (bind) this field to the managed bean attribute that we created before.7.. The button's value is being retrieved from the properties file. Create the index.messages" var="msg"/> <html> <head> <title>greeting page</title> </head> <body> <f:view> <h3> <h:outputText value="#{msg.5. It uses a JSP tag to "forward" to the inputname. While the button's action attribute is set to greeting which matches the navigation-outcome in faces-config. Lines 3-5..personName}" /> <h:outputText value="#{msg.jsp file will allow us to start the application like this: http://localhost:8080/myJFSapp/
149
. Theses lines import JSF tag libraries and our properties file (resource bundle) with the messages.jsp page.sun.jsp File
We will now create a third JSP file that doesn't actually function as a presentation page.xml file. Creates an HTML input text box.
12. name!
12. <h:outputText value="#{personBean. Once this page is displayed in a Web browser.2 greeting.jsp
Put this coding inside the second JSP file: <%@ taglib uri="http://java.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sign}" /> </h3> </f:view> </body> </html> This page is very simple. JSF tags for the HTML form's submit button.7. Line 2.greeting_text}" />. Prints a message from the properties file using the value of prompt. The first three lines are identical to our first page. The first line will take a message from the resource bundle and print it on the page.</h3> tags.jsp file inside the WebContent folder. Note that this file is not created in the pages folder like the previous JSP files. That's how JSF knows where to go next. Line 6. The main code of interest to us is between the <h3>.sun. Creates an HTML form using JSF tags. The second line will access a Java bean. and also print its contents on the page.javaserver faces
Line 1.

We will use null (link) deployment to deploy the application in-place. launch a web browser and enter: http://localhost:8080/myJFSapp.xml file. put this coding into the file: <html> <body> <jsp:forward page="/pages/inputname. we need to deploy it.
12.
150
. To build the application run the build. Your setup. might possibly be different).
12.jsp. (Port 8080 is the default port in Tomcat.xml file for the application *.sourceforge. because in the web.jp/docs/FacesIDE/SampleJSFApp.jsf and not .1 Overview
This is a tutorial in which we create a simple JSF application to demonstrate FacesIDE's functionality.bat in Tomcat's bin directory).jsf" /> </body> </html> If you look at the path for the forward. insert this code: <Context debug="0" docBase="Path_to_WebContent" path="/myJFSapp" reloadable="true"/> near the end of the server. This is used here.xml script from the ant folder: ant build
12.8 creating a JSF application in eclipse with the facesIDE plugin
Example taken from http://amateras.xml file within the Host element just before the closing </Host> tag. you'll notice the file suffix is .javaserver faces
Now.7 Compiling
An Ant build script is provided for you. which asks an user for an ID and password.jsf is the URL pattern used to signal that the forwarded page should be handled by the JavaServer Faces servlet within Tomcat. C:/examples/myJFSapp/WebContent). start the Tomcat server (probably using the script startup.7. This is a "login" application.html . Of course. To do this.
12. When Tomcat is done loading.7. Path_to_WebContent needs to be replaced with the exact path on your system to the WebContent folder inside the myJFSapp folder (for example.
12. though. verifies the information.9 Running
Next.8 Deploying
Before you can run this application within the servlet container.8. We are almost done with this example.12 . and forwards the user to a success or error page.7. To do this we need to register a context in Tomcat's {TomcatHome}\conf\server.

say. make sure FacesIDE and required plugins have been installed. From the menu bar select File/New/Project. click Next. select Amateras/JSF/Add JSF Support. note that Root: has automatically been set to /webroot. a. Create the source folder: select the Java Build Path node. click Yes through messages that appear. Your folder structure should now be as follows: jsf-login | +-. 7.12 . We don't assume that a J2EE server-specific plugin. and set up folders for a web application.. click Add Folder.webroot | +-..xml Editor)
As a prerequisite for the tutorial. from the menubar select File/New/Other. Select the Amateras node.. click OK to dismiss the properties dialog. Select Java Project. in Package Explorer select the jsf-login project b. This folder will contain all "functional" pages. and from its context menu select File/New/Folder. select the Source tab. and to add JSF libraries to the project. click Next d. 1. in the dialog that appears create a folder named src directly under the project folder (jsf-login). 9. Enter project name. jsf-login. see Installing & Uninstalling.xml Editor (see faces-config.. c. enter jsflogin/webroot/WEB-INF/classes. 10.8. Create the web root folder: in Package Explorer select the jsf-login project.
12..WEB-INF
151
. name the folder webroot 5.. The folder structure created is simply one that works for this author. name the folder pages. From the menubar open Project/Properties 8.javaserver faces
The application will use a few JSP pages with JSF elements. your mileage may vary. click Finish 4. Create the web pages folder: in Package Explorer select the webroot folder.2 Creating A Project
Here we create an Eclipse project. 3. make sure all checkboxes are checked. for Web Application Root enter /jsflogin/webroot. click Next. make sure HTML validation and DTD/XSD validation are enabled. in the wizard that appears. Use FacesIDE to add JSF support: we use a FacesIDE wizard to create J2EEprescribed folders and files in webroot. Along the way we'll use the following FacesIDE functionality:
• • • •
add JSF support to a project use the New JSF/JSP file wizard use the JSP Editor (see HTML/JSP/XML Editor) use the faces-config. and from the menubar select File/New/Folder. 6.src | +-.Set the output folder: in the Default output folder textbox at the bottom. The New Project wizard appears. in the Add JSF Support page. 2.. and a session-scoped managed bean to coordinate their interactions. such as the Sysdeo Tomcat plugin has been installed..

the New File wizard appears. We will have 4 pages: a start page (index.jsp. All pages except login. b. <!-. then close the editor
12.jsp: create this file similarly to index.webroot/pages/success. but in webroot/pages.webroot/index. click Finish.4 Creating JSP Pages
Here we create the JSP pages that make up the application's user interface.12 . index. Create success.jsp --> <html> <head> <title>jsf-login</title> </head> <body> <h2>Error!</h2> The user-id and or password were invalid. c.jsp. but in webroot/pages. 1.jsp using a FacesIDE wizard.jsp.8.jsp and error. in Package Explorer select webroot. from the menubar select File/Save. save the file and close the editor. e. Enter the following code: <!-.jsp --> <html> <body> <jsp:forward page="faces/pages/login. for File name enter index. and its sole function is to forward users to the login page.jsp). enter the following code.jsp: a.jsp).jsp: create this file similarly to index. using the Workbench's standard file-creation facilities.jsp are simple pages with static content.webroot/pages/error. again. Enter the following code: <!-. from its context menu select New/File.javaserver faces
session. success. the JSP Editor opens. Then we create login.jsp.jsp is placed directly in webroot. and 3 content pages (login. Content pages are placed in webroot/pages. so we create them first. </body>
Please try
153
.jsp" /> </body> </html> 2. Create error. Create index.jsp --> <html> <head> <title>jsf-login</title> </head> <body> <h2>Success!</h2> </body> </html> 3. make sure that the parent folder is set to /jsflogin/webroot.

com/jsf/core" prefix="f" %> <html> <head> <meta http-equiv="Content-Type" content="text/html.completion.javaserver faces
</html> 4. this inserts the corresponding JSF element at the cursor location. expand the JSF HTML panel in the palette. and dock it along the right. and uses them for code completion as well. and the JSP Editor can help with code.
154
..sun. the FacesIDE JSP Editor opens.. enter jsf-login e. and click on the icon for <h:inputText>. <%@ page contentType="text/html.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java. for File name enter login. d. g. Create login. place the cursor between the <title></title> elements. with the following template code. Open the JSF palette. create a few blank lines between the <h:form> elements. charset=Cp1252"/> <title></title> </head> <body> <f:view> <h:form> </h:form> </f:view> </body> </html> We will now edit this page to contain our input widgets. click Next c. as shown below. and choose default for Template. Note: the JSP editor is aware of referenced tag libraries. now we want to add attributes to this element.12 . in Package Explorer select webroot/pages. place your cursor in one of these lines. a code-completion window pops up. etc. make sure that Container is set to /jsflogin/webroot/pages. you would get a popup window of JSF HTML elements. charset=Cp1252" %> <%@ taglib uri="http://java. b. select Amateras/JSF/Faces JSP File. and hit CTRL + Spacebar. Thus if you were to type <h: and hit CTRL + Spacebar. the New wizard appears. from its context menu select New/Other.jsp: a. and that Use MyFaces Tomahawk components and Use MyFaces SandBox components are unchecked. click Finish..jsp. place the cursor inside the <h:inputText> element. To see this in action.sun. (See Show View Dialog) f.

select userID from the code-completion window. place the cursor between the quotes in value="".sun..) j. enter #{mgr. This is shown below:
(Recall that we configured LoginManager as a managed bean called mgr. and hit CTRL + Spacebar.password}" l. charset=Cp1252" %> <%@ taglib uri="http://java. with bean properties available in mgr.javaserver faces
h. insert another <h:inputText> element. i.sun. and its action to the value binding expression #{mgr. with the barest presentational formatting. is shown below: <%@ page contentType="text/html. complete the expression with the closing { k.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java. this inserts value="" at the cursor. in the code-completion window scroll down to value. and hit Enter. set its value to Login.loginAction} The final code.com/jsf/core" prefix="f" %> <html>
155
. FacesIDE can provide code completion here as well. insert a <h:commandButton> element. We will now bind this to the userID property of LoginManager. a code-completion window pops up.12 . set its value binding expression to value="#{mgr.

then click inside the editor window.5 Creating Navigation Rules
Here we create navigation rules among pages. Select the Navigation tab 3. this inserts a page icon into the editor. This is shown below. from the Navigation panel in the palette at left. click on Page. 2.javaserver faces
<head> <title>jsf-title</title> </head> <body> <f:view> <h:form> UserID: <h:inputText value="#{mgr.12 .xml. 1.userID}"/> <br/>Password: <h:inputText value="#{mgr.loginAction}"/> </h:form> </f:view> </body> </html>
12. and the page's properties appear in the Workbech's Properties view.xml Editor. it should open in the faces-config. Open faces-config.
Note that the icon has a small triangle overlay--this indicates that something is wrong.8.password}"/> <br/><h:commandButton value="Login" action="#{mgr.
156
. using a FacesIDE editor.

notice that the warning triangle disappears. add 3 more pages. Arrange them as shown below:
Now we'll add navigation rules among the pages.jsp.jsp. and set them to /pages/login. "Decharge" the mouse pointer by clicking on the pointer icon in the palette. 6. from the palette at left.javaserver faces
specifically that FacesIDE could not locate a page at path /page1. This is shown below:
157
. Its properties appear in the Properties view. in the Properties view.jsp 4.jsp. You can also change it on the diagram directly (select the page and click once more).jsp. /pages/success. This inserts a forward-action between the two pages. 5. then click on the newly-added forward-action icon to select it. and is represented by an arrow.jsp and then on the icon for success. select Navigation Case. change the value of path to /index.jsp and /pages/error.12 . then click first on the icon for login.

jsp to error. and you should be sent to the success page. scroll to the bottom and look for the comment <!-. and we'll then be ready to deploy the application.xml. change the value of fromoutcome to loginPass. in the Properties view (or direct editing on the diagram). 1. As it turns out. and you should be automatically forwarded to login.
12.xml is indicate the Faces Servlet mapping.Faces Servlet Mapping --> 2.xml. open web. We want virtual path-based mapping. Deployment to some servers is described below:
158
. and set its fromoutcome to loginFail We're done with setting up navigation rules. or leave it as-is. any other id/password should send you to the error page. You may comment out the entry for extension-based mapping.8. all we need do in web. so uncomment it.javaserver faces
7. by default virtual path-based mapping is commented out. You can also change values by direct-editing (select once and re-click) in the diagram 8. We'll set some properties in web. Similarly add a forward-action from login. Recall that this is the success-value returned by LoginManager's loginAction method. Use UserID/Password of foo/bar.xml
Here we edit web.jsp. The application is now complete.jsp.jsp.6 Editing web. since we have such a trivial application. Once deployed browse to index. and extension-based mapping is turned on.12 . and you should be able to deploy it to your server of choice.xml for the specifics of our application.

7 Deploying To Tomcat 5.faces javax. that factory is used.javaserver faces 12.CONFIG_FILES
159
.convert javax.application javax.model javax.faces.faces.component javax.faces.component. click Deploy 3. If the JavaServer Faces configuration files named by the javax.el javax.webapp
12. Click on its link to launch the application. For a given factory class name.faces.8. for Context path enter /jsf-login. start Tomcat. for WAR or Directory URL enter the path to webroot.12 . we'll deploy our app by providing its directory.faces. a corresponding implementation class is searched for based on the following algorithm.. scroll down to Deploy. open its Manager application in a browser. the Manager application should reload. the default URL for this is http://localhost:8080/manager/html 2. Items are listed in order of decreasing search precedence:
• •
If the JavaServer Faces configuration file bundled into the WEB-INF directory of the webapp contains a factory entry of the given factory class name.event javax.context javax. leave XML Configuration File URL blank.faces.faces package
Contains 2 classes – FactoryFinder and FacesException public final class FactoryFinder extends Object FactoryFinder implements the standard discovery algorithm for all factory objects specified in the JavaServer Faces APIs.9 packges in the JavaServer Faces API
The classes and interfaces of the JavaServer Faces API are grouped in several packages. and you should see /jsf-login in the list of running applications.0
1..faces.10 the javax.render javax.faces.faces. namely:
• • • • • • • • • • • • •
javax.faces.
12.validator javax.html javax..faces.faces.lifecycle javax.faces. as file:///.

Implementations of JavaServer Faces must provide at least a default implementation of Application. and supporting internationalization and accessibility. those factories are used. which is typically associated with a particular component in the view.javaserver faces
ServletContext init parameter contain any factory entries of the given factory class name. ViewHandlerWrapper .a factory object that creates (if needed) and returns Application instances.
•
•
public class FacesException extends RuntimeException This class encapsulates general JavaServer Faces exceptions. its first line is read and assumed to be the name of the factory implementation class to use. A FacesMessage instance may be created based on a specific messageId.A set of APIs for representing UI components and managing their state. This allows for implementations to support different response generation technologies. the JavaServer Faces implementation specific class is used. If none of the above steps yield a match. FacesMessage . NavigationHandler – An object of this type is passed the outcome string returned by an application action invoked for this application.the pluggablity mechanism for allowing implementations of or applications using the JavaServer Faces specification to provide their own handling of the activities in the Render Response and Restore View phases of the request processing lifecycle.11 the javax.directs the process of saving and restoring the view between requests.represents a single validation (or other) message.used to represent message severity levels in a typesafe enumeration.
12.12 . the factory entries of the given factory class name in those files are used.faces.
•
If there are any JavaServer Faces configuration files bundled into the META-INF directory of any jars on the ServletContext's resource paths. defining page navigation. ApplicationFactory . with the last one taking precedence. ViewHandler . StateManagerWrapper .Severity . FacesMessage. The default implementation of all methods is to call through to the wrapped StateManager.Provides a simple implementation of ViewHandler that can be
•
•
• •
• •
•
•
160
.application package
Contains the following classes:
•
Application .Provides a simple implementation of StateManager that can be subclassed by developers wishing to provide specialized behavior to an existing StateManager instance. handling events and input validation. and will use this (along with related state information) to choose the view to be displayed next. with the last one taking precedence. as well as alternative strategies for saving and restoring the state of each view. If a META-INF/services/{factory-class-name} resource is visible to the web application class loader for the calling application (typically as a result of being present in the manifest of a JAR file). StateManager .

extends ActionSource and provides a JavaBeans property analogous to the "action" property on ActionSource.12 . Here they are:
• •
UIColumn .an interface that must be implemented by any UIComponent that wants to be a naming container.
•
•
161
.faces. when activated by the user. as well as access data in the model tier via a value binding expression. String) results in failure on postback.interface implemented by classes that need to save their state between requests.
•
•
• • • •
The classes in this package are all UI related. ActionSource2 . The set of UIComponent instances associated with a particular request and response are organized into a component tree under a UIViewRoot that represents the entire content of the request or response.12 the javax. UIComponentBase .an interface that may be implemented by any concrete UIComponent that wishes to be a source of ActionEvents. including the ability to invoke application actions via the default ActionListener mechanism. triggers an application specific "command" or "action".
12. EditableValueHolder . String. The difference is the type of this property is a MethodExpression rather than a MethodBinding. NamingContainer .a UIComponent that represents a single column of data within a parent UIData component.javaserver faces
subclassed by developers wishing to provide specialized behavior to an existing ViewHandler instance.
•
ViewExpiredException . and support conversion between String and the model tier data's native data type.implementations must throw this FacesException when attempting to restore the view StateManager.faces. Such a component is typically rendered as a push button. The interfaces defined in this package are:
•
ActionSource . StateHolder .a UIComponent that represents a user interface component which.context. or a hyperlink. a menu item. ValueHolder .restoreView(javax. The default implementation of all methods is to call through to the wrapped ViewHandler. ContextCallBack . UICommand . UIComponent .a convenience base class that implements the default concrete behavior of all methods defined by UIComponent. including ValueChangeEvents and Validators.FacesContext.A simple callback interace that enables taking action on a specific UIComponent (either facet or child) in the view while preserving any contextual state for that component instance in the view.an interface that may be implemented by any concrete UIComponent that wishes to support a local value.the base class for all user interface components in JavaServer Faces.an extension of ValueHolder that describes additional features supported by editable components. This allows the ActionSource concept to leverage the new Unified EL API.component package
Defines both a set of interfaces and classes.

The user cannot manipulate this component. identified by a clientId. UIParameter . This component has no rendering. it is for display purposes only. which is the current value of this component itself (typically established via a ValueBinding).a UIComponent that represents an optionally named configuration parameter for a parent component. UIForm .12 .a UIComponent that represents an input form to be presented to the user.a UIComponent that displays a graphical image to the user.
•
• •
• • • •
• • • •
•
•
•
12. It is most commonly rendered as a checkbox. UIInput . The user can modify the selected values. optionally retrieved from a model tier bean via a value binding expression.a UIComponent that represents the user's choice of a zero or more items from among a discrete set of available options.html package
162
. During iterative processing over the rows of data in the data model. that is displayed to the user. the component can be preconfigured with zero or more currently selected items. UIGraphic .a convenience base class for components that wish to implement NamingContainer functionality. UIViewRoot .a UIComponent that has a value. and causes the addition of a SelectItem instance to the list of available options for the parent component. UIMessage . UIOutput . and whose child components represent (among other things) the input fields to be included when the form is submitted.The renderer for this component is responsible for obtaining the messages from the FacesContext and displaying them to the user. the object for the current row is exposed as a request attribute under the key specified by the var property. The user can modify the selected value. by storing it as the value property of the component.a UIComponent that represents a component that both displays output to the user (like UIOutput components do) and processes request parameters on the subsequent request that need to be decoded.a UIComponent that represents a single boolean (true or false) value. The user cannot directly modify the rendered value. Optionally. UIPanel .component. Optionally.a UIComponent that manages the layout of its child components. it is for display purposes only.13 the java. by storing them as an array in the value property of the component.javaserver faces
•
UIData . UINamingContainer .faces. UISelectMany . the component can be preconfigured with a currently selected item.This component is generally rendered as a select box or a group of checkboxes.a UIComponent that represents the user's choice of zero or one items from among a discrete set of available options. UISelectOne . UIMessages . it just serves as the root of the component tree.This component is responsible for displaying messages for a specific UIComponent.a UIComponent that supports data binding to a collection of data objects represented by a DataModel instance.a component that may be nested inside a UISelectMany or UISelectOne component. UISelectBoolean .the UIComponent that represents the root of the UIComponent tree. UISelectItem .

This is useful in scenarios where a parent component is expecting a single component to be present. or not. HtmlInputHidden .represents an HTML textarea element. HtmlInputSecret . HtmlGraphicImage .represents an HTML label element. HtmlInputTextarea .javaserver faces
Contains HTML related classes.represents an HTML input element of type hidden. used to define an accessible label for a corresponding input element. HtmlCommandButton .represents an HTML input element of type checkbox. the rendererType property must be set to "javax. HtmlOutputFormat .represents a column that will be rendered in an HTML table element. render a span element and pass them through as attributes on the span. HtmlPanelGroup .represents an HTML input element of type password. Child input components will be submitted unless they have been disabled. used to retrieve and render a graphical image. HtmlOutputLink .represents an HTML a (hyperlink) element that may be used to link to an arbitrary URL defined by the value property. HtmlMessages . based on the value of the value
• • •
• • • • •
• • •
•
•
• • • • •
•
163
. HtmlSelectBooleanCheckbox . HtmlForm . HtmlColumn . optionally uses it as a MessageFormat pattern string and substitutes in parameter values from nested UIParameter components. On a redisplay.represents an HTML a element for a hyperlink that acts like a submit button.represents a set of repeating data (segregated into columns by child UIColumn components) that will be rendered in an HTML table element.renders the component value as text.by default.Message". and renders the result. but the application wishes to render more than one. HtmlMessage .represents an HTML input element for a button of type submit or reset. If the "dir" or "lang" attributes are present.by default.represents a component that looks up a localized message in a resource bundle.represents an HTML img element. HtmlPanelGrid . The checkbox will be rendered as checked.causes all child components of this component to be rendered.renders child components in a table. This component must be placed inside a form.Messages" This value can be changed by calling the setRendererType() method. optionally wrapping in a span element if CSS styles or style classes are specified. the rendererType property must be set to "javax. starting a new row after the specified number of columns. This value can be changed by calling the setRendererType() method. any previously entered value will not be rendered (for security reasons) unless the redisplay property is set to true.faces.faces. HtmlOutputLabel . The label text is specified by the component value. HtmlDataTable .represents an HTML input element of type text. HtmlOutputText . and requires JavaScript to be enabled in the client.12 . HtmlCommandLink .represents an HTML form element. HtmlInputText .

14 the java.a factory object that creates (if needed) and returns new FacesContext instances.faces.12 . HtmlSelectOneRadio . each phase of the request processing lifecycle. FacesContextFactory .represents a single-selection component that is rendered as an HTML select element. FacesContext . and the rendering of the corresponding response.represents a single-selection component that is rendered as an HTML select element. showing a single available option at a time. HtmlSelectOneListbox . initialized for the processing of the specified request and response objects. and potentially modified by. HtmlSelectOneMenu . HtmlSelectManyMenu . It is passed to. The default implementation of all methods is to call through to the wrapped ResponseWriter.
• •
HtmlSelectManyCheckbox .allows the Faces API to be unaware of the nature of its containing application environment. HtmlSelectManyListbox . showing a single available option at a time. ResponseWriter .represents a multiple-selection component that is rendered as an HTML select element.represents a single-selection component that is rendered as a set of HTML input elements of typeradio.an interface describing an adapter to an underlying output mechanism for binary output.15 the java.convert package
164
.provides a simple implementation of ResponseWriter that can be subclassed by developers wishing to provide specialized behavior to an existing ResponseWriter instance. showing either all available options or the specified number of options.represents a multiple-selection component that is rendered as a set of HTML input elements of type checkbox.faces. showing either all available options or the specified number of options.context package
Contains the following classes: ExternalContext . In particular.contains all of the per-request state information related to the processing of a single JavaServer Faces request.
• •
• •
12.
•
•
•
• • •
12. ResponseStream . this class allows JavaServer Faces based applications to run in either a Servlet or a Portlet environment.javaserver faces
property.represents a multiple-selection component that is rendered as an HTML select element.an abstract class describing an adapter to an underlying output mechanism for character-based output. ResponseWriterWrapper .

PropertyResolver .javaserver faces 12.an object that can be used to access the property represented by an action or value binding expression.
•
• • •
165
. to indicate that the requested conversion cannot be performed.represents a pluggable mechanism for resolving a top-level variable reference at evaluation time. on an instance that is acquired by evaluatng the leading portion of a method binding expression via a ValueBinding.
12.an exception thrown by the getAsObject() or getAsText() method of a Converter.an object that can be used to call an arbitrary public method.1 the interface Converter
Converter is an interface describing a Java class that can perform Object-to-String and Stringto-Object conversions between model data objects and a String representation of those objects that is suitable for rendering.12 .faces. VariableResolver . ValueBinding . Classes: MethodBinding .represents a pluggable mechanism for accessing a "property" of an underlying Java object instance.el package
Contains classes and interfaces for evaluating and processing reference expressions.15. The classes implementing this interface within this package are:
• • • • • • • • • • • • •
BigDecimalConverter BigIntegerConverter BooleanConverter ByteConverter CharacterConverter DateTimeConverter DoubleConverter EnumConverter FLoatConverter IntegerConverter LongConverter NumberConverter ShortConverter
The package also contains one exception:
•
ConverterException .16 the java.

for the request encapsulated by the specified FacesContext.listener interface for receiving ActionEvents.interface implemented by objects that wish to be notified at the beginning and ending of processing for each standard phase of the request processing lifecycle.a notification that the local value of the source component has been change as a result of user interface activity.
• • •
• •
One exception .
166
.AbortProcessingException .thrown by event listeners to terminate the processing of the current event.listener interface for receiving ValueChangeEvents.
• • •
•
Classes: ActionEvent .a generic base interface for event listeners for various types of FacesEvents.an exception reporting a syntax error in a method binding expression or value binding expression.17 the java.javaserver faces
Exceptions: EvaluationException .faces. ReferenceSyntaxException .represents the activation of a user interface component (such as a UICommand).typesafe enumeration of the legal values that may be returned by the getPhaseId() method of the FacesEvent interface. PhaseId . MethodNotFoundException .an exception caused by a property name that cannot be resolved against a base object. and event implementation classes.
• • • •
12.an exception reporting an error that occurred during the evaluation of an expression in a MethodBinding or ValueBinding. PropertyNotFoundException . ValueChangeListener .event package
Contains interfaces describing events and event listeners. FacesEvent .12 .represents the beginning or ending of processing for a particular phase of the request processing lifecycle. PhaseListener .an exception caused by a method name that cannot be resolved against a base object. FacesListener . PhaseEvent .the base class for user interface and application events that can be fired by UIComponents. ValueChangeEvent . Interfaces: ActionListener .

model package
Contains the interface DataModelListener and several classes providing standard model data beans for JavaServer Faces. The Lifecycle class manages the processing of the entire lifecycle of a particular JavaServer Faces request.a convenience implementation of DataModel that wraps an array of Java objects. Renderer .a convenience implementation of DataModel that wraps a ResultSet of Java objects.a convenience implementation of DataModel that wraps an List of Java objects. Classes: ArrayDataModel .a convenience implementation of DataModel that wraps a JSTL Result object.
12.represents a single item in the list of supported items associated with a UISelectMany or UISelectOne component.converts the internal representation of UIComponents into the output stream
•
167
. The LifecycleFactory class is a factory object that creates (if needed) and returns Lifecycle instances.faces. SelectItemGroup . DataModel .12 .18 the java. ResultSetDataModel .a convenience implementation of DataModel that wraps an individual Java object.render package
Contains classes defining the rendering model.an abstraction around arbitrary data binding technologies that can be used to adapt a variety of data sources for use by JavaServer Faces components that support per-row processing for their child components (such as UIData). ScalarDataModel .represents an event of interest to registered listeners that occurred on the specified DataModel.javaserver faces
12. depending upon the requirements of the UISelectMany or UISelectOne renderer that is actually used.faces.faces.
• •
• • •
• • • •
12. SelectItem . DataModelEvent . typically representing the results of executing an SQL query via JSTL tags.19 the java. ResultDataModel . Note that the specified ResultSet MUST be scrollable.20 the java.lifecycle package
This package contains 2 classes.a subclass of SelectItem that identifies a set of options that will be made available as a subordinate "submenu" or "options list". ListDataModel .

AttributeTag . and concrete validator implementation classes.a base class for all JSP custom actions that create and register a Converter instance on the ValueHolder associated with our most immediate
•
•
168
. LongRangeValidator . including a standard servlet.12 .a Validator that checks the value of the corresponding component against specified minimum and maximum values. Typically. Implementations of JavaServer Faces must provide at least a default implementation of RenderKit. and concrete tag implementations for core tags.the helper class to StateManager that knows the specific rendering technology being used to generate the response.javaserver faces
(or writer) associated with the response we are creating for a particular request.
12. Each Renderer knows how to render one or more UIComponent types (or classes).a Validator that checks the number of characters in the String representation of the value of the associated component.22 the java. RenderKitFactory . know how to render JavaServer Faces UIComponent instances for a specific client. as well.
•
•
12. which perform the actual rendering process for each component.
•
RenderKit . ConverterTag .faces. A ValidatorException is an exception thrown by the validate() method of a Validator to indicate that validation failed.a factory object that registers and returns RenderKit instances.21 the java. ResponseStateManager .validator package
Interface defining the validator model.Tag implementation that adds an attribute with a specified name and String value to the component whose tag it is nested inside.faces. if the component does not already contain an attribute with the same name. A Validator implementation is a class that can perform validation (correctness checks) on a EditableValueHolder. base classes for JSP custom component tags.webapp package
Contains classes required for integration of JavaServer Faces into web applications.
The package contains an exception. Implementation classes:
• • •
DoubleRangeVlidator . together. RenderKits are specialized for some combination of client device type. A RenderKit also acts as a Factory for associated Renderer instances. and advertises a set of render-dependent attributes that it recognizes for each supported UIComponent.a Validator that checks the value of the corresponding component against specified minimum and maximum values LengthValidator . markup language. and/or user Locale.represents a collection of Renderer instances that.

A JSP page source is compiled into a page implementation class.23 the JSF lifecycle
Regardless of whether you are using JSF with JSP pages. When using JSF.12 . telling the model to update its data. When other pages are included or the request is forwarded. related to a UIComponent. which passes the request to the page class. Because this does not involve JSF in any way. telling the view to update its presentation.a base class for all JSP custom actions that create and register a Validator instance on the EditableValueHolder associated with our most immediate surrounding instance of a tag whose implementation class is a subclass of UIComponentTag. servlets. but basically. This is because the core of JSF is the MVC pattern. The JSF life cycle must handle this delay between event and event processing. Several kinds of request/response cycles can occur in a JSF-enabled application. the JSF system includes a phase for validating inputs and another for updating the model only after all inputs pass validation. the controller is the
169
. When the user takes some action with the presentation. UIComponentBodyTag . or some other web technology. The delivery of user actions or page events is delayed until a new connection is established. a small set of classes processes a request and sends back a response. the JSF life cycle does not apply. the life cycle is more complicated. the model is composed of business objects that are usually implemented as JavaBeans. You can have a request that comes from a previously rendered JSF page (a JSF request) and a request that comes from a non-JSF page (a non-JSF request). that request is passed to the container. you can also have a non-JSF request that generates a non-JSF response. which has several implications. UIComponentTag . Likewise.a servlet that manages the request processing lifecycle for web applications that are utilizing JavaServer Faces to construct the user interface.the base class for all JSP custom actions that correspond to user interface components in a page that is rendered by JavaServer Faces.the JSP mechanism for denoting a UIComponent is to be added as a facet to the component associated with its parent. We are concerned with these three request/response pairs:
• • •
Non-JSF request generates JSF response JSF request generates JSF response JSF request generates non-JSF response
Of course. the process includes a few more components or pages. When the model is updated. the controller sends a message to the view. In MVC. the JSF life cycle must ensure that the view is correct before rendering the view.a base class for all JSP custom actions.javaserver faces
surrounding instance of a tag whose implementation class is a subclass of UIComponentTag.
12. the controller sends a message to the model. To ensure that the business state is never invalid. The page class processes the request and then writes the response back to the client. User actions in JSF-generated views take place in a client that does not have a permanent connection to the server. In JSF. Also. the presentation of data (the view) is separate from its representation in the system (the model). each request/response flow that involves JSF follows a certain life cycle. or when an exception occurs. that need to process their tag bodies. FacetTag . JSP pages have a relatively simple life cycle. ValidatorTag . When a web server receives a request. you can have a JSF response or a non-JSF response.
• • • • •
FacesServlet .

or from request headers. Data can come from input fields in a web form. This is because if the JSF implementation began to update the business objects as data was validated. and the state of the UI view is saved for subsequent requests. These objects update their state with the data values. It updates only the UI components with the new data. The JSF life cycle has six phases as defined by the JSF specification: • Restore View: In this phase. • Apply Request Values: Any data that was sent as part of the request is passed to the appropriate UI objects that compose the view. If this is a subsequent request. any events that were generated during previous phases and that have not yet been handled are passed to the web application so that it can complete any other processing of the request that is required. the JSF implementation restores the objects and data structures that represent the view of the request. As with the previous phase. converting a String to a Date object). from cookies sent as part of the request. Data for some components. Conversion is needed when the data type of a property is not a String or a Java primitive. the JSF implementation must create the view. the saved UI view is retrieved for the processing of the current request. it creates UI objects for each view component. and a piece of data failed validation. the business objects that make up the application are updated with the validated data from the request. and what happens during the processing and response. the thread of execution for a request/response cycle can flow through each phase. For a JSF-enabled application. such as components that create HTML input fields. The state of the UI components is saved so that the component tree can be restored when the client sends another request. However. • Invoke Application: During this phase. depending on the request. the action method of any command button or link that was activated is called.12 . • Render Response: The response UI components are rendered.
170
. the model would be partially updated and in an invalid state. Note that this does not yet update the business objects that compose the model. • Process Validations: The data that was submitted with the form is validated (if it was not validated in the previous phase). not every request will flow through all six phases. in the order listed here and as shown in the figure below. • Update Model Values: After all validations are complete. this does not yet update the business objects in the application. When a JSF implementation creates and renders a JSFenabled page. if any of the data needs to be converted to a different format to update the model (for example. In addition. If this is the client’s first visit to a page. and the response is sent to the client. is validated at this time. the conversion occurs in this phase.javaserver faces
JSF implementation. The components are stored in a component tree. and the UI components are the view. In addition.

skipping any remaining phases.javaserver faces
In the above figure. the flow of execution can exit the life cycle without completing further phases. If data fails validation in either the Apply Request Values or Process Validations phase. if at any point in the life cycle the request processing is complete and a non-JSF response is to be sent to the client. One way this might occur is if input data is incorrect or invalid. information about the error is saved and processing proceeds directly to the Render Response phase.12 . you can see a number of optional paths through the life cycle. Also. the flow of execution transfers immediately to the Render Response phase. For example. if errors occur during any of the phases.
171
.

the UNIXTM file system's naming convention is that a file is named from its path relative to the root of the file system. names a file hello in the file directory usr.13 . Different naming and directory service providers can be plugged in seamlessly behind this common API. DNS.
13. A naming service allows you to look up an object given its name. such as addresses. It enables applications to access different. It is designed especially for the Java platform using Java's object model. relative to the DNS entry Wiz. names an entry with the name Wiz in the COM entry. you must supply its name. you are always naming one object or another. possibly multiple.JNDI
13.1 what is JNDI?
JNDI is an API specified in Java technology that provides naming and directory functionality to applications written in the Java programming language. JNDI is also defined independent of any specific naming or directory service implementation.Wiz. Using JNDI. These two examples also illustrate the wide range of scale at which naming services exist--from naming an object on the Internet to naming a file on the local file system.2. c:\bin\autoexec.com) to IP addresses (such as 192. A naming service's primary function is to map people-friendly names to objects. This syntax is sometimes called the naming system's naming convention. which is located in the root of the file system.COM. The UNIX pathname. The DNS entry Wiz. For example. Thus the DNS name sales."). JNDI provides methods for performing standard directory operations. The naming system determines the syntax that the name must follow. For example. the Internet Domain Name System (DNS) maps machine names (such as www.COM names a DNS entry with the name sales. as well as enabling the applications to coexist with legacy software and systems. When using almost any computer program or system.9. The DNS naming convention calls for components in the DNS name to be ordered from right to left and delimited by the dot character (".JNDI
13 .48. and NIS(YP). A file system maps a filename (for example. in turn. To access a file in the computer. /usr/hello.COM. such as LDAP.
172
. or objects typically used by computer programs. This enables Java technology-based applications to take advantage of information in a variety of existing naming and directory services. NDS. with each component in the path separated from left to right using the forward slash character ("/").1 names
To look up an object in a naming system. For example. when you use an electronic mail system. In addition. for example.bat) to a file handle that a program can use to access the contents of the file. naming and directory services using a common API.sun. identifiers. applications based on Java technology can store and retrieve named Java objects of any type.5).
13. such as associating attributes with objects and searching for objects using their attributes. you supply it the name of the object.2 naming concepts
A fundamental facility in any computing system is the naming service--the means by which names are associated with objects and and objects are found based on their names. you must provide the name of the recipient to whom you want to send mail.

Every context has an associated naming convention. A printer object.
13. such as its current queue and the amount of paper in the paper tray. Thus the LDAP name cn=Rosanna Lee.JNDI
The Lightweight Directory Access Protocol (LDAP) naming convention orders components from right to left. in a file directory /usr/bin.2. c=US names an LDAP entry cn=Rosanna Lee. a copy of the object cannot be placed inside the naming service. an airplane object might contain a list of the airplane's passengers and crew. in the an LDAP entry o=sun.COM. Typically.
173
. In another example.3 references and addresses
Depending on the naming service.
13. while the object itself might contain more state information. such as /usr. on the other hand. might contain the state of the printer. that is. a pointer or reference to the object is placed inside the naming service.13 . the DNS domain Sun is a subcontext of COM. that is. The LDAP has the further rule that each component of the name must be a name/value pair with the name and value separated by an equals character ("="). A name in one context object can be bound to another context object (called a subcontext) that has the same naming convention. A reference is information about how to access an object. unbinding names. Although in general a reference can contain any arbitrary information. Using the reference. An LDAP name is bound to an LDAP entry. it is a much more compact representation that can be used to communicate with the object. The DNS contains bindings that map machine names to IP addresses. relative to the entry o=Sun. That is. also called a file handle. an LDAP entry. A DNS domain named relative to another DNS domain is a subcontext. in the UNIX file system is a context. such as its print server name and printing protocol. might contain only information on how to reach the printer. For example. its flight plan. a file name is bound to a file. A file object. By contrast. the directory bin is a subcontext of usr.2 bindings
The association of a name with an object is called a binding. for example. Finally. this tutorial uses "object" to refer to both objects and object references when a distinction between the two is not required. such as COM. the entry o=sun is a subcontext of c=us. For example. it is useful to refer to its contents as addresses (or communication end points): specific information about how to access the object.
13. an airplane object reference might contain only its flight number and departure time. is relative to c=us.4 context
A context is a set of name-to-object bindings. is a context. and its flight number and departure time. a DNS domain.2. is accessed using a file reference.2. and listing bound names. A file directory named relative to another file directory is a subcontext (some UNIX users refer to this as a subdirectory). such as c=us.c=us. An LDAP entry named relative to another LDAP entry is a subcontext. For example. A printer object reference. The reference is a much more compact representation of information about the airplane object and can be used to obtain additional information. which in turn. is a context. For example. o=Sun. and fuel and instrument status. they must be stored by reference. For example. A context provides a lookup (resolution) operation that returns the object and may provide operations such as those for binding names. in the DNS domain Sun. you can contact the object and obtain more information about the object. for example. delimited by the comma character (". a file directory. Instead. some objects cannot be stored directly. For simplicity.").

A naming service is accessed through its own interface.3 directory services
Many naming services are extended with a directory service. and even the computer itself and other computers.
13. And it kind of makes sense. to represent a printer. A user might be represented by a directory object that has as attributes the user's e-mail address.3. two different computer
174
. however. A directory object contains attributes that describe the object that it represents. A system that communicates using the LDAP is a naming system.JNDI
If we imagine all the resources available for us as a collection of rooted trees. Going now back to the rationality of this chapter. various telephone numbers. and color. postal mail address. Thus. identify a web application with its root directory (a node in the file system directory tree). a printer might be represented by a directory object that has as attributes its speed. because we can. because it is available online and can be used to store a variety of information that can be utilized by users. For example. The LDAP namespace contains names of LDAP entries. The computer's directory service is much more powerful. in a first and raw approximation as a node in one of these trees. remember that a naming serviced associates names with real objects (resources).5 naming systems and namespaces
A naming system is a connected set of contexts of the same type (they have the same naming convention) and provides a common set of operations. programs. a person. It maps a subscriber's name to his address and phone number. This association between a name Which leads to a list of constraints:
•
within a given context. A naming system provides a naming service to its customers for performing naming-related operations. a name is unique
13. An attribute identifier is a token that identifies an attribute independent of its values. resolution. For example. the DNS offers a naming service that maps machine names to IP addresses. For example. A file system offers a naming service that maps filenames to files and directories. a system that implements the DNS is a naming system. you not only can look up an object by its name but also get the object's attributes or search for the object based on its attributes. A directory object can be used.
13. for example. to some extent. A computer's directory service is very much like a telephone company's directory service in that both can be used to store information such as telephone numbers and addresses. The LDAP offers a naming service that maps LDAP names to LDAP entries. An example is the telephone company's directory service.13 . For example.1 attributes
A directory object can have attributes. A directory object represents an object in a computing environment. a computer. For example. the UNIX file system has a namespace consisting of all of the names of files and directories in that file system. or a network. An attribute has an attribute identifier and a set of attribute values. A namespace is the set of names in a naming system. A directory service associates names with objects and also allows such objects to have attributes.2. The DNS namespace contains names of DNS domains and entries. one context can be viewed. and computer account information.

Directory-enabled Java applications and applets. the ability to access directory services will become essential. they play the role of naming contexts in addition to that of containers of attributes. "mail" is the attribute identifier.com".
13. The service is accessed through its own interface. Within the DIT. that is. When you search.
13. called a directory information tree (DIT). Many examples of directory services are possible.2 directories and directory services
A directory is a connected set of directory objects.113. might contain group objects that might in turn contain person objects. to store and retrieve attributes of directory objects. for example.4. A Java mail transfer agent program can use it to retrieve mail routing information.JNDI
accounts might have a "mail" attribute. and modifying the attributes associated with objects in a directory. an organization object. The query is called a search filter. An attribute value is the contents of the attribute. Similarly. you can query it to find all machines whose IP address starts with "192. When directory objects are arranged in this way. Network Information Service (NIS) is a directory service available on the Solaris operating system for storing system-related information. The directory service searches for and returns the objects that satisfy the search filter. such as the file and print services. This style of searching is sometimes called reverse lookup or content-based searching. adding.
13. For example. Alternatively.smith@somewhere. A directory service is a service that provides operations for creating. you can query the directory service to find all users that have the attribute "age" greater than 40 years.
13.50". The Novell Directory Service (NDS) is a directory service from Novell that provides information about many networking services. such as those based on the LDAP. By using a directory service. And a Java calendar program can use it to retrieve user preference settings. A Java mail client program. for example. networks.1 traditional use of the directory
A directory-enabled application is an application that uses a naming or directory service.13 .4 combining naming and directory services
Directories often arrange their objects in a hierarchy. such as that relating to machines.4 directory-enabled java applications
Directory service is a vital component of network computing.3.
13. can use the directory in the traditional way. for example. As the use of the Java programming language to write practical applications in a network environment increases. the LDAP arranges all directory objects in a tree.3. you can supply not a name but a query consisting of a logical expression in which you specify the attributes that the object or objects must have.3. might have an attribute identifier of "mail" and the attribute value of "john. printers. support the notion of searches. many directories.3 searches and search filters
You can look up a directory object by supplying its name to the directory service. For example. The email address. The SunONE Directory Server is a general-purpose directory service based on the Internet standard LDAP. you can simplify applications and their administration by centralizing the storage of shared information. removing. like any other program running on the network. and users.
175
. can use the directory as an address book for retrieving the addresses of mail recipients.

naming javax. Java applications can also use it as a repository for Java objects. Java applications use the JNDI API to access a variety of naming and directory services. that is to store and retrieve Java objects. v1.naming.3 includes three service providers for the following naming/directory services:
• • •
Lightweight Directory Access Protocol (LDAP) Common Object Request Broker Architecture (CORBA) Common Object Services (COS) name service Java Remote Method Invocation (RMI) Registry
Other service providers can be downloaded from the JNDI Web site or obtained from other vendors. v1. you must first download the JNDI classes and one or more service providers. more coherent and manageable.
13. This sharing makes applications that are deployed across the system.1 and Java 2 SDK. The JNDI is divided into five packages:
• • • •
javax. When using the JNDI as a Standard Extension on the JDK 1. It is also available as a Java Standard Extension for use with the JDK 1. thereby allowing the Java application using the JNDI API to access their services.event javax.JNDI
Applications can share the common infrastructure provided by the directory.
13.2 the directory as an object store In addition to using the directory in the traditional way.5.4. emerging. For example. It extends the v1.1 and v1.ldap
176
. v1. It is defined to be independent of any specific directory service implementation.13 . v1.3 and later releases. The Java 2 SDK.naming.naming.1 and the Java 2 SDK.2. Thus a variety of directories--new. The SPI enables a variety of naming and directory services to be plugged in transparently.2 packaging
The JNDI is included in the Java 2 SDK.
13.directory javax. a Java print client program should be able to look up a printer object from the directory and send a data stream to the printer object for printing. and already deployed--can be accessed in a common way.5 the JNDI API
The Java Naming and Directory Interface TM (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the Java TM programming language. and even the network.2 platforms to provide naming and directory functionality. To use the JNDI. you must have the JNDI classes and one or more service providers.
13.5. printer configuration and mail routing information can be stored in the directory so that it can be replicated and distributed for use by all printer-related and mailrelated applications and services.2.1 architecture
The JNDI architecture consists of an API and a service provider interface (SPI). For example.

A service that supports storing Java objects might support storing an object in its serialized form. For the methods in the Context interface. printer. Printer printer = (Printer)ctx.6.6. list() is similar to listBindings(). However. binding/unbinding. a
177
. except that it returns an enumeration of NameClassPair. such as those that simply read in a name and look up the corresponding object. Java programs are but one group of applications that access them.String name argument represents a composite name. renaming objects and creating and destroying subcontexts. You supply lookup() the name of the object you want to look up. Furthermore.JNDI
•
javax. and the object itself.lang. A Name argument of any other type represents a compound name.
13. Although listBindings() provides all of the same information.String name.1 context
The javax.6 the naming package
The javax.naming package contains classes and interfaces for accessing naming services.naming. The most commonly used operation is lookup() .spi
13. A java.
13. that is. the name of the object's class.3 bindings
listBindings() returns an enumeration of name-to-object bindings.) The overloads that accept Name are useful for applications that need to manipulate names.lang. Each binding is represented by an instance of the Binding class. (Names are covered in the Beyond the Basics trail. it is potentially a much more expensive operation.2 names
Every naming method in the Context interface has two overloads: one that accepts a Name argument and one that accepts a java. Name is an interface that represents a generic name--an ordered sequence of zero or more components.
13.String names are likely to be more useful for simple applications.naming package defines a Context interface. a Name argument that is an instance of CompositeName represents a composite name .lookup("treekiller"). so you can name an object using a name that spans multiple namespaces. In this case. for some objects in the directory.6. A binding is a tuple containing the name of the bound object. list() is useful for applications such as browsers that want to discover information about the objects bound within a context but that don't need all of the actual objects. The overloads that accept java.
13. and so on. comparing components. some naming and directory services do not support the storing of Java objects. NameClassPair contains an object's name and the name of the object's class. which is the core interface for looking up. For example.13 .6. composing them. the following code fragment looks up a printer and sends a document to the printer object to be printed.print(report).lang. and it returns the object bound to that name.4 references
Objects are stored in naming and directory services in different ways.

Other overloaded forms of search() support more sophisticated search filters.2 searches
DirContext contains methods for performing content-based searching of the directory.
13. In the simplest and most common form of usage. You use getAttributes() to retrieve the attributes associated with a directory object (for which you supply the name). This means that any directory object can also provide a naming context. the application specifies a set of attributes--possibly with specific values--to match and submits this attribute set to the search() method.7 directory package
The javax.13 .7.
13. Attributes are modified using modifyAttributes(). or remove attributes and/or attribute values using this operation.6 exceptions
The JNDI defines a class hierarchy for exceptions that can be thrown in the course of performing naming and directory operations.
13.naming package to provide functionality for accessing directory services in addition to naming services. Once you have an initial context. a directory object for a person might contain attributes about that person as well as provide a context for naming objects.5 the Initial context
In the JNDI. InitialContext. A reference might be a very compact representation of an object.7. This package allows applications to retrieve attributes associated with objects stored in the directory and to search for objects using specified attributes.
13.
178
. all naming and directory operations are performed relative to a context. It defines methods for examining and updating attributes associated with a directory object.naming.
13. Programs interested in dealing with a particular exception can catch the corresponding subclass of the exception. which provides a starting point for naming and directory operations.JNDI
serialized Java object might not be the most appropriate representation. DirContext also behaves as a naming context by extending the Context interface. You can add. you can use it to look up other contexts and objects. Therefore the JNDI defines an initial context. The JNDI defines the Reference class to represent a reference. For example. A reference contains information on how to construct a copy of the object. replace. such as the person's printers and file system relative to that person directory object. There are no absolute roots.6. Otherwise. The root of this class hierarchy is NamingException. whereas its serialized form might contain a lot more state (see the Naming Concepts lesson).1 the directory context
The DirContext interface represents a directory context. they should catch NamingException.6.directory package extends the javax. The JNDI will attempt to turn references looked up from the directory into the Java objects that they represent so that JNDI clients have the illusion that what is stored in the directory are Java objects.

3 unsolicited notifications
In addition to the normal request/response style of interaction between the client and server. A control may be defined by a standards organization such as the IETF or by a vendor. Events A NamingEvent represents an event that is generated by a naming/directory service." A NamingEvent also contains other information about the change.9. and vice versa. Listeners A NamingListener is an object that listens for NamingEvents.naming. To receive event notifications.JNDI
13." and those that do not. such as "object added.naming. called controls .2 controls
The LDAP v3 allows any request or response to be augmented by yet-to-be defined modifiers.
13.
13. Each category of event type has a corresponding type of NamingListener.ldap package contains classes and interfaces for using features that are specific to the LDAP v3 that are not already covered by the more generic javax.9. In fact.
13.naming.13 . Event notification is described in detail in the Beyond the Basics trail. This package is primarily for those applications that need to use "extended" operations. An "extended" operation may be defined by a standards organization such as the Internet Engineering Task Force (IETF) or by a vendor.naming. Once registered. a NamespaceChangeListener represents a listener interested in namespace change events and an ObjectChangeListener represents a listener interested in object change events. a listener must be registered with either an EventContext or an EventDirContext. such as information about the object before and after the change.9.naming. the LDAP v3 (RFC 2251) specifies a way to transmit yet-to-be defined operations between the LDAP client and the server. there need not be a response control for each request control sent. Request controls and response controls are not necessarily paired.event package contains classes and interfaces for supporting event notification in naming and directory services.ldap package at all.1 "extended" operation
In addition to specifying well-defined operations such as search and modify.directory package. This package defines classes for the Start TLS extension. event types are categorized into those that affect the namespace. that is. The event contains a type that identifies the type of event. controls. These operations are called "extended" operations. the LDAP v3 also specifies unsolicited notifications--messages that are sent from the server to the
179
. For example. most JNDI applications that use the LDAP will find the javax.8 event package
The javax. the listener will receive event notifications when the corresponding changes occur in the naming/directory service. For example.
13.directory package sufficient and will not need to use the javax. or unsolicited notifications. A control sent with a request is a request control and a control sent with a response is a response control .9 LDAP package
The javax. such as "object changed.

import javax. For example.JNDI
client asynchronously and not in response to any client request.
13.bind() and related methods can accept Java objects and store the objects in a format acceptable to the underlying naming/directory service.9.1 importing the JNDI classes
Using your favorite text editor.11 naming example
This example shows you how to write a program that looks up an object whose name is passed in as a command-line argument. It uses a service provider for the file system.lookup() and related methods to return Java objects that are natural and intuitive for the Java programmer. and receiving response controls.4 the LDAP context
The LdapContext interface represents a context for performing "extended" operations.spi package provides the means by which developers of different naming/directory service providers can develop and hook up their implementations so that the corresponding services are accessible from applications that use the JNDI. create a file named Lookup.java. This support is provided in the form of state factories. In the process of completing an operation.
13. This support is provided in the form of object factories.naming. sending request controls.spi package supports implementors of Context. These implementations include those for the initial context and for contexts that can be reached from the initial context.1 plug-In architecture
The javax. You can import either the entire package or only individual classes and interfaces. This package provides support for different providers to cooperate to complete JNDI operations. then you likely would expect to get back a printer object on which to operate.
13. That is.
13.10. if you look up a printer name from the directory.
13. You do not need to understand details about the service provider at this point.
13.3 multiple naming systems (federation)
JNDI operations allow applications to supply names that span multiple naming systems. This package also provides support for doing the reverse.naming.13 .10.naming.
13.2 java object support
The javax.naming. The following code imports each class that is used from the javax. implementors of Context.Context. one service provider might need to interact with another service provider.10. Examples of how to use these features are described in the Controls and Extensions lesson.naming package.11. Therefore the name that you supply to the program must be a filename.10 service provider package
The javax.
180
.spi package allows different implementations to be plugged in dynamically. for example to pass on the operation to be continued in the next naming system.

2 creating an initial context
In the main() method of the program. you must have access to the JNDI classes.11. you can include the classes either by setting the CLASSPATH variable to include the jndi.4 catching NamingException
The creation of the initial context and the lookup() method can throw a NamingException.InitialContext.
13. then the JNDI classes are already included. If the compilation fails. Here's the code fragment repeated with the try/catch clause.naming.lookup(name). then see the Common Problems lesson for help.jar as an installed extension. v1.naming. If you are still having problems. env. Indicate that you're using the file system service provider by setting the environment properties parameter (represented by a Hashtable class) to the InitialContext constructor.5 compiling the program
Next.class in the same directory (folder) as the Java source file (Lookup. } catch (NamingException e) { System.11. Object obj = ctx.out.
13. If the compilation succeeds. as follows. Hashtable env = new Hashtable().3. How to set up the parameters for this constructor is explained in more detail in The Basics trail.fscontext. If you are using the Java 2 SDK.jndi.err. you need to enclose these calls inside a try/catch clause. then the compiler will create a file named Lookup.INITIAL_CONTEXT_FACTORY.lookup(name). The following code looks up the object bound to the name supplied in the command line.println(name + " is bound to: " + obj).JNDI
import javax. Otherwise.11. use Context.println("Problem looking up " + name + ":" + e). Context ctx = new InitialContext(env).3 looking up an Object
Next. // Look up an object Object obj = ctx.NamingException.put(Context. create an initial context. you compile the source file using the Java compiler.13 . "com.java).
}
13. using the capitalization shown.11.RefFSContextFactory").
181
.jar that you downloaded from the JNDI Web site or by installing jndi. For this reason. import javax. // Print it System. See the Preparations lesson for details on how to install the JNDI classes and service providers.
13. try { // Create the initial context Context ctx = new InitialContext(env). then make sure that you typed in and named the program exactly as shown here. To compile to program.sun.lookup() to look up an object.

13. supply the name of a file in your file system.11.directory packages. either include them in your CLASSPATH variable or install them as extensions.2 creating an initial directory context
In the main() method of the program.class).java. javax.directory.JNDI 13.12. You can import either the entire package or only individual classes and interfaces.naming.1 importing the JNDI directory classes
Using your favorite text editor.Attributes.put(Context.sun.jndi.naming.jndi. then you will see something like the following.fscontext.put(Context.INITIAL_CONTEXT_FACTORY. This is similar to creating an initial context in the previous naming example. Finally. "com. and your example class (Lookup.directory.naming. javax. See the compilation step for instructions on including access to the JNDI classes. env.class file in your the CLASSPATH variable. import import import import import javax. except that you use the constructor for InitialDirContext. It uses an LDAP service provider to access an LDAP service.sun.NamingException.InitialDirContext.6 running the program
To run the program. # java Lookup /tmp /tmp is bound to: com.13 . then you will see something like this: /tmp/f is bound to: //tmp/f
13. To run the program.PROVIDER_URL. Note that these archive files are not included with the Java 2 SDK.naming. v1. as follows: # java Lookup /tmp Or as follows: # java Lookup \autoexec.naming. The following code imports each class that is used from the javax.12.LdapCtxFactory").jar and providerutil. "ldap://localhost:389/o=JNDITutorial").Context. create a file named Getattr. env.
13. To include the file system service provider classes (fscontext.ldap.DirContext.12 directory example
This example shows you how to write a program that retrieves attributes from a directory object. javax.RefFSContext@1dae083f If the name that you supplied is a file.bat If you supply a file directory.
182
.naming. javax.3. See the Preparations lesson for details on how to install the JNDI classes and service providers.jar). create an initial directory context. Hashtable env = new Hashtable().naming and javax. you need access to the JNDI classes.directory. include the directory that contains your Lookup. the file system service provider.

java).13 . you can ask for a particular attribute by using Attributes. you indicate that you're using the LDAP service provider by setting the Hashtable parameter to the InitialDirContext constructor appropriately. then see the Common Problems lesson for help. Similar to the naming example.12.
13.get("sn").3 getting a directory Object's attributes
Next.12. If the compilation fails.out. // Ask for all attributes of the object Attributes attrs = ctx.get() on it to get its value: attrs.get("sn"). } catch (NamingException e) { System. ou=People"). If the compilation succeeds. Instructions for setting up a sample LDAP server for this tutorial are given in the Preparations lesson. then the compiler creates a file named Getattr.5 catching NamingException
The method calls shown so far can throw a NamingException. For now.get()).JNDI
DirContext ctx = new InitialDirContext(env).get() and then from that attribute get its value.12. If you are still having problems.getAttributes("cn=Ted Geisel.println("Problem getting attribute:" + e).12.
}
13. the only thing to understand is that the program by default identifies an LDAP server on the local machine.6 compiling the program
Next. you need to wrap these calls inside a try/catch clause. // Find the surname attribute ("sn") and print it System.println("sn: " + attrs. Here's the code fragment repeated with the try/catch clause. For this reason. The following line first gets the surname attribute "sn" and then invokes Attribute. then you need to edit the LDAP URL ("ldap://localhost:389/o=JNDITutorial") accordingly. Details on how to set up the parameters for this constructor are given in The Basics trail. As with the naming example.class in the same directory (folder) as the Java source file (Getattr. use getAttributes() to get an object's attributes. to do this you need access to the JNDI classes. Attributes. ou=People": Attributes attrs = ctx.getAttributes("cn=Ted Geisel. compile the source file using the Java compiler. then make sure that you typed in and named the program exactly as shown here. using the capitalization shown.4 extracting the desired attribute
From a set of attributes.
183
. try { // Create the initial directory context DirContext ctx = new InitialDirContext(env).
ou=People").get().err.
13. The following code retrieves all of the attributes associated with the object bound to the name "cn=Ted Geisel. If your LDAP server is located on another machine or is using another port.
13.

If you are using the Java 2 SDK. v1. it extracts the surname attribute ("sn"). then see the Common Problems lesson. If you have any trouble running this example.
184
. With this configuration.jar).) It asks for the attributes of the entry "cn=Ted Geisel. serving the "o=JNDITutorial" namespace. You also need access to the LDAP service provider classes (ldap. (See the Preparations lesson for details on this configuration step.put(Context. then these classes are already included.13 .PROVIDER_URL.class. this command queries the LDAP server on machine localhost that is listening on port 389. Here's an example of a command line for running Getattr and the output it generates. Once it has the attributes. you need access to both the JNDI classes and your example class. ou=People". env.3.12. Getattr.7 running the program
As with the naming example. # java Getattr sn: Geisel Recall that the program was configured with the following property. "ldap://localhost:389/o=JNDITutorial").jar and providerutil.JNDI 13.

14 . JMS message .a JMS client that receives messages. The publisher has to create a subscription in order for clients to be able to subscribe.a JMS client that creates and sends messages. nor does the consumer need to be running at the time the message is sent Every message successfully processed is acknowledged by the consumer
The publish/subscribe model supports publishing messages to a particular message topic. Zero or more subscribers may register interest in receiving messages on a particular message topic. A good metaphor for it is anonymous bulletin board. the messages are delivered in the order sent.2 JMS models
The JMS API supports two models:
• •
point-to-point or queuing model publish and subscribe model
In the point-to-point or queuing model.a distribution mechanism for publishing messages that are delivered to multiple subscribers. The following are JMS elements:
•
• • • • •
JMS provider . JMS queue . JMS topic . JMS is a part of the Java Platform. A message is removed from the queue once it has been read. The following are characteristics of this model:
• •
Multiple consumers can get the message There is a timing dependency between publishers and subscribers. JMS client . a producer posts messages to a particular queue and a consumer reads messages from the queue. As the name queue suggests.JAVA MESSAGE SERVICE
14 . the producer knows the destination of the message and posts the message directly to the consumer's queue.an object that contains the data being transferred between JMS clients. The subscriber has to remain continuously active to receive messages.a staging area that contains messages that have been sent and are waiting to be read.JAVA MESSAGE SERVICE
14.An implementation of the JMS interface for a Message Oriented Middleware (MOM). neither the publisher nor the subscriber know about each other.an application or process that produces and/or consumes messages. Providers are implemented as either a Java JMS implementation or an adapter to a non-Java MOM. In this model.
•
14. Enterprise Edition. JMS producer . and is defined by a specification developed under the Java Community Process as JSR 914. It is characterized by following:
• • •
Only one consumer will get the message The producer does not have to be running at the time the consumer consumes the message. Here. unless it has established a durable
185
.1 JMS elements
The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. JMS consumer .

4 the JMS API
The JMS API is provided in the Java package javax. users will use either a queue connection factory or topic connection factory.14 .jms.
14. JMS clients access the connection factory through portable interfaces so the code does not need to be changed if the underlying implementation changes. JMS provides a way of separating the application from the transport layer of providing data.
14. Depending on the type of message.1 the ConnectionFactory interface
An administered object that a client uses to create a connection to the JMS provider.
186
. On the receiving side. In that case.3 the JMS API programming model
14. The classes first use a connection factory to connect to the queue or topic. Administrators configure the connection factory in the Java Naming and Directory Interface (JNDI) namespace so that JMS clients can look them up. Using Java. The same Java classes can be used to communicate with different JMS providers by using the JNDI information for the desired provider. and then use populate and send or publish the messages. the clients then receive or subscribe to the messages.4.JAVA MESSAGE SERVICE
subscription. messages published while the subscriber is not connected will be redistributed whenever it reconnects.

Before an application completes.4. JMS administered objects are normally placed in the jms naming subcontext.createConnection().2 the Connection interface
Once a connection factory is obtained. The JMS administrator creates these objects. the administrator can create two types of destinations: queues for Point-to-Point and topics for Publish/Subscribe. Before your application can consume messages. ConnectionFactory connectionFactory = (ConnectionFactory) ctx.4.close().lookup("jms/MyQueue"). you can use it to create a Connection: Connection connection = connectionFactory. A connection represents a communication link between the application and the messaging server. you must close any connections that you have created.14 . Connections implement the Connection interface. you usually perform a JNDI lookup of a connection factory. the following line of code performs a JNDI lookup of the previously created topic jms/MyTopic and casts and assigns it to a Destination object: Destination myDest = (Destination) ctx. The following line of code looks up a queue named jms/MyQueue and casts and assigns it to a Queue object: Queue myQueue = (Queue) ctx. The consumer can receive messages synchronously (blocking) or asynchronously (non-blocking) for both queue and
187
. connection. connections allow users to create sessions for sending and receiving messages from a queue or topic.3 the Destination interface
An administered object that encapsulates the identity of a message destination. If you want to stop message delivery temporarily without closing the connection. For example.lookup("jms/ConnectionFactory"). which is where messages are delivered and consumed. you call the stop() method. then cast and assign it to a ConnectionFactory object. Like the connection factory. It is either a queue or a topic. the following code fragment obtains an InitialContext object and uses it to look up a ConnectionFactory by name. In a J2EE application. For example.
14. When you have a ConnectionFactory object.
14. Closing a connection also closes its sessions and their message producers and message consumers.lookup("jms/MyTopic"). It receives messages sent to a destination.
14. and users discover them using JNDI. Depending on the connection type.4. you must call the connection's start() method. Failure to close a connection can cause resources not to be released by the JMS provider. Then it assigns it to a ConnectionFactory object: Context ctx = new InitialContext().JAVA MESSAGE SERVICE
At the beginning of a JMS client program.4 the MessageConsumer interface
An object created by a session. a connection to a JMS provider can be created.

you call the start() method on the Connection to begin message delivery. Message m = consumer. onMessage(). Moreover. however. and you can use it to receive messages.setMessageListener(myListener). a message listener object may be used. This method is valid only if you are using a topic. You use the Session. Message delivery does not begin until you start the connection you created by calling its start() method. you are likely to miss messages.start(). you define the actions to be taken when a message arrives.createDurableSubscriber() method to create a durable topic subscriber. if you define a class named Listener that implements the MessageListener interface.) When message delivery begins. the JMS provider automatically calls the message listener's onMessage() method whenever a message is delivered.createConsumer(myQueue).5 the MessageListener interface
A message listener is an object that acts as an asynchronous event handler for messages. In the onMessage() method. depending on the type of destination for which the message consumer was created. After you register the message listener. you use a Session to create a MessageConsumer for either a queue or a topic: MessageConsumer consumer = session. A message listener is not specific to a particular destination type.) You use the receive method to consume a message synchronously. The same listener can obtain messages from either a queue or a topic. forgetting to start the connection is one of the most common JMS programming errors.4. which contains one method.receive().receive(1000). A message listener does. you can register the message listener as follows: Listener myListener = new Listener(). This object implements the MessageListener interface. You can use the close() method for a MessageConsumer to make the message consumer inactive. For example. a message listener must either assume a particular destination type or obtain the destination type of the message and create a producer for that destination type. usually expect a specific message type and format.14 . (If you call start() before you register the message listener. // time out after a second To consume a message asynchronously.
14. Message m = consumer. (Remember always to call the start() method. The onMessage() method takes one argument of type Message.JAVA MESSAGE SERVICE
topic-type messaging. consumer. You can use this method at any time after you call the start method: connection. connection. which your implementation of the method can cast to any of the other message types.createConsumer(myTopic).start(). it becomes active. For example. if it needs to reply to messages.
188
. After you have created a message consumer. You register the message listener with a specific MessageConsumer by using the setMessageListener() method. MessageConsumer consumer = session.

you might use the following statements: TextMessage message = session. You must first create the messages.setText(msg_text). The message interface is extremely flexible and provides numerous ways to customize the contents of a message. For example: MessageProducer anon_prod = session. bytes message. to create and send a TextMessage.createProducer(myTopic).
14.JAVA MESSAGE SERVICE 14. that is. stream message. message).4. // msg_text is a String producer. You can use one or more getter methods to extract the message contents. anon_prod. and the second for the destination myTopic: MessageProducer producer = session.send(myQueue. A message body (optional): Allows users to create five types of messages (text message. Here.send(message).createTextMessage(). At the consuming end. from one application to another.createProducer(myQueue). For example. you do not specify a destination until you send a message. With an unidentified producer. The user can create a sender to a specific destination or create a generic sender that specifies the destination at the time the message is sent. It can be used to create custom fields or filters (selectors).14 . map message. you can use it to send messages by using the send method: producer. 3.4. The following code fragment uses the getText method: Message m = consumer.6 the MessageProducer interface
An object created by a session that sends messages to a destination. the first example creates a producer for the destination myQueue. message. if (m instanceof TextMessage) { TextMessage message = (TextMessage) m. a message arrives as a generic Message object and must be cast to the appropriate message type.send(message).7 the Message interface
An object that is sent between consumers and producers. and object message). The JMS API provides methods for creating messages of each type and for filling in their contents. if you created an unidentified producer. After you have created a message producer.createProducer(null). You use a Session to create a MessageProducer for a destination. A message has three main parts: 1.receive(). use an overloaded send method that specifies the destination as the first parameter. You can create an unidentified producer by specifying null as the argument to createProducer. A message header (required): Contains operational settings to identify and route messages 2. MessageProducer producer = session. A set of message properties (optional): Contains additional properties to support compatibility with other providers or users.
189
.

Before committing the transaction. the second indicates that message acknowledgment is not specified for transacted sessions. A session is singlethreaded so that messages are serialized. Session. then delivers the messages.14 . The first argument means that the session is not transacted. Sessions implement the Session interface.createSession(false. A session allows users to create message producers to send messages.
190
.4. The benefit of a session is that it supports transactions. the user can cancel the messages using a rollback operation. Here. the session context holds a group of messages until the transaction is committed. } else { // Handle error }
14. To create a transacted session.out.println("Reading message: " + message. use the following code: Session session = connection. 0).JAVA MESSAGE SERVICE
System. you use it to create a Session: Session session = connection. the first argument means that the session is transacted. meaning that messages are received one-by-one in the order sent.8 the Session interface
Represents a single-threaded context for sending and receiving messages. If the user selects transaction support.getText()).createSession(true.AUTO_ACKNOWLEDGE). the second means that the session automatically acknowledges messages when they have been received successfully. and message consumers to receive messages. After you create a Connection object.

15 . multiple clients can access it simultaneously while its life-span is the same as the data it represents. bundled into a single unit.1 enterprise java beans versus (ordinary) java beans
(Ordinary) Java beans provide a format for general-purpose components. It provides annotations for every type of metadata previously addressed by deployment descriptors. the container lives (in general) in an application server. especially if we have more databases and more access components data caching .ENTERPRISE JAVA BEANS
15.intended to be used by a single client (client extension on the server).2 the ejb container and its services
The EJB container provides an execution environment for a component. The component lives inside a container. The EJBs will run in an EJB container which is part of an application server.
15.logging. Version 1. improved performance security . message-driven beans
The 2. container which offers services to the component.consistent error handling framework .jar file into the application server. while the EJB (Enterprise Java Beans) architecture provides a format for highly specialized business logic components. component recovery scalability portability
191
.ENTERPRISE JAVA BEANS
15 .DB interaction transactions . Entity beans have been superseded by the Java Persistence API in EJB 3. What are Enterprise Java Beans? A collection of Java classes together with an xml file. so no XML descriptor is needed and beans deployment can be done just through a plain . On the other side.EJB access can be stated without extra coding error handling .0. Novelties in this specification try to make the development of EJBs easier.0 EJB specification adds another bean type:
•
The current EJB specification is 3.0. bean's life span can be no longer than client's entity beans . These services are:
• • • • • • •
persistence . server which provides an execution environment for containers. The Java classes must follow certain rules and must offer certain callback methods.no developer coding.1 of EJB specification provides two EJB types:
• •
session beans .transaction management can be complex. The main reason for using EJBs is to take advantage of the services provided by the container.object oriented representation of data in a DB.

the bean itself (the class that contains the business logic ) 2. returning the remote interface and throwing CreateException and RemoteException. the remote interface of the bean 4. It uses only argument types allowed by the RMI standard.ENTERPRISE JAVA BEANS
•
manageability
15. called ejb-jar. The methods specified by the EJBHome interface (not implemented (in general) by the programmer) are the following: public void remove(Handle han) throws RemoteException. Handle – abstraction for a network reference to an EJB. It provides methods named create() with application specific arguments.3 enterprise java beans architecture
An EJB consists of (at least) 3 classes and an xml file. RemoveException public EJBMetaData getEJBMetaData() throws RemoteException public HomeHandle getHomeHandle() throws RemoteException
192
.4 the home interface
The home interface of an ejb is an interface that extends the EJBHome interface. It is bean's programmer task to create them (at least). which is an xml file. as follows: 1. RemoveException public void remove(Object primaryKey) throws RemoteException.15 .xml
15. the deployment descriptor. the home interface of the bean 3.

15 . "localhost:1099"). The client gains access to the EJB through a remote interface. getting the InitialContext requires the usage of some server-side properties.PROVIDER_URL. getting an initial context if the client is another EJB executing in the same container and the bean to be used is declared as a resource in the deployment descriptor.NamingContextFactory". if the client executes outside the container. In the case of an web application. }
194
. how to create or find the bean 2. "org. Here are the main parts of the client code: authentication Client's authentication is done in a way which is server specific. Here is an example:
•
try { Properties prop = new Properties(). This object acts like a factory for EJBs. what methods to use (know its interface) 3. how to release its resources The client is able to create an EJB through an object implementing the EJBHome interface.ENTERPRISE JAVA BEANS
15.6 client programmer's viewpoint
For an EJB client application.INITIAL_CONTEXT_FACTORY. we need to know: 1. prop.interfaces. prop.jnp. this can be done (for example) through SSL.put(Context. Context ctx = new InitialContext(prop). the InitialContext is already available:
•
Context ctx = new InitialContext().put(Context. implemented by an object built by the EJB host in the deployment process. creating them for the client application.

that is part of CORBA standards. do implements the java.rmi. The underlying protocol that it is used for the communication is IIOP (Internet Inter ORB Protocol). Some languages. cast the home interface reference To make sure that the client works with the underlying communication protocol. more specifically. It is normally used to describe this communication system using the Java RMI over IIOP. MyBeanHome. This is done through the javax.lookup("MyBean"). The client only has a remote interface to this instance (i. and this means that there are some limitations. Java RMI-IIOP provides a mechanism to narrow the the Object you have received from your lookup.narrow(homeRef.lookup("java:comp/env/ejb/MyBean"). using the narrow() method. the client should use the narrow() method of javax. this cannot be done using the normal/explicit casting: MyBeanHome myHome = (MyBeanHome)returnedObject The reason has to do with CORBA.PortableRemoteObject: MyBeanHome myHome = (MyBeanHome)PortableRemoteObject. in fact. when we perform a lookup() on a Context object. the client has a stub).15 . to the appropriate type. but for generic languages. Why do we have to use the narrow() method? Usually. the method will return you an Object that needs to be casted to the home interface we've asked for.rmi. the code may look like:
•
Object homeRef = ctx.Remote interface). in fact. Problem is.rmi.PortableRemoteObject class and. It is JNDI's task to identify the resource associated to the name provided:
Object homeRef = ctx.e. IIOP has not been designed for Java.ENTERPRISE JAVA BEANS
find the home interface of the bean for a client executing inside the container. the communication between the server and the client is based on RMI (both remote and local interfaces. the bean can be associated to any name in the JNDI name space. Why? For EJB.. do not have the concept of casting.class).
195
. create an instance of the bean The instance of the bean is created on the server.
•
if the client executes outside the container.

the code implementing this class may look like this: package com.. String lastName. Assuming that our bean (called MyBean) is a session bean. we concentrate now on the bean class itself.15 .ENTERPRISE JAVA BEANS
Here is the code: MyBeanObject myObject = myHome.
15. import javax.7 bean programmer's viewpoint
Since the home interface and the remote interface have been detailed in the previous sections. as well). remove the bean instance myObject.bank11.create(). } public void deleteEntry(int custId) { // method implementation . "Vasile". int custId) { // method implementation .SessionBean { public void processEntry(String firstName.. } // mandatory methods for session beans // method implementations may be empty public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {}
196
. the bean class must implement (although the implementation itself may be empty) a certain set of methods.. set which is specific to each major type of beans (session or entity). public class MyBean implements javax. 1102).ccards.SessionContext.processEntry("Dumitrascu". call business methods on the bean myObject.ejb.remove()..ejbeans.ejb. Besides the implementation of the business methods (which were declared in the remote interface.

This reduces the number of instances maintained by the server. a new stateful instance is instantiated and populated from the passivated storage.9 container callbacks for session beans
There are 5 mandatory callbacks for classes implementing the SessionBean interface. namely stateful and stateless beans. the object is activated.1 illustrates the stages that a session bean passes through during its lifetime. public void ejbActivate() public void ejbPassivate() public void ejbCreate() public void ejbRemove() public void setSessionContext(SessionContext ctx) The first two methods will never be called for stateless session beans.8 session beans
There are two types of session beans. The bean is now ready to have its business methods invoked.
15.
197
. The EJB container instantiates the bean and then invokes the setSessionContext and ejbCreate methods in the session bean. the bean's state is serialized to a secondary storage.ENTERPRISE JAVA BEANS
public void ejbPassivate() {} public void setSessionContext(SessionContext ctx) {} } The deployment descriptor of the bean will be detailed in another section. it can evict stateful session beans from memory.
15. When a client invokes a method on the EJB object. that is. The client initiates the life cycle by invoking the create method. A stateless bean does not.
15. To passivate the bean and preserve its conversational state.15 . because the container will never activate a stateless session bean.10 the life cycle of a stateful session bean
Figure 15. A stateful session bean preserves data between client accesses. When an EJB server needs to conserve its resources.

If a client invokes a business method on the bean while it is in the passive stage. the EJB container uses a least-recentlyused algorithm to select a bean for passivation. calls the bean's ejbActivate method.2 illustrates the stages of a stateless session bean. its life cycle has only two stages: nonexistent and ready for the invocation of business methods. All other methods in Figure 15. or passivate. you might wish to connect to a database in the ejbCreate method. the EJB container may decide to deactivate.ENTERPRISE JAVA BEANS
Figure 15. and then moves it to the ready stage. and the EJB container calls the bean's ejbRemove method. For example.
198
. for example. allowing you to perform certain operations right after the bean is instantiated. The ejbCreate method. the EJB container activates the bean.1 Life Cycle of a Stateful Session Bean While in the ready stage. The bean's instance is ready for garbage collection.15 . Figure 15. Your code controls the invocation of only two life-cycle methods: the create and remove methods in the client.
15. (Typically.11 the life cycle of a stateless session bean
Because a stateless session bean is never passivated. is inside the bean class.) The EJB container invokes the bean's ejbPassivate method immediately before passivating it. the bean by moving it from memory to secondary storage.1 are invoked by the EJB container. At the end of the life cycle. the client invokes the remove method.

For BMPs:
• •
the primary key can be any legal RMI/IIOP type it must provide suitable implementations for hashCode(). The requirements that must be satisfied by the primary key are different for the two main types of entity beans.15 . support for concurrent access 3. This primary key must be represented by a primary key class.13 primary keys
Every entity bean has a primary key. providing all the persistence management code (no SQL code necessary) There are 2 main types of entity beans.
• •
CMPs (Container Managed Persistence) BMPs (Bean Managed Persistence) for which the bean developer provides the actual persistence (SQL) code
15.ENTERPRISE JAVA BEANS
Figure 15. maintaining a cache between transactions 4.2 Life Cycle of a Stateless Session Bean
15. container callbacks to manage caching within a transaction 2. equals()
199
.12 entity beans
Entity beans represent actual data (usually. stored in a Database). The EJB container provides the developer several persistence services: 1.

CreateException. namely ejbCreate() and ejbPostCreate(). This is transactional data that is accessible to multiple clients.bank11. as the parameters in the original create() method. an instance of that bean is created.CustomerID</prim-key-class> or <prim-key-class>java.lang.ccards. methods which have the same parameters. a Database) (we actually insert a record in a database). Each create() method from the Home interface of the bean has 2 correspondent methods in the bean implementation class.1 create
When a client calls a create() method on a session bean's home interface. when a client calls create() on an entity bean's home interface. the field is specified: <prim-key-field>sportsTeamID</prim-key-field>
15.
15. We can have more create() methods.ENTERPRISE JAVA BEANS
•
must have a unique value among beans of a particular type
For CMPs:
• •
the container must be able to create a primary key the key class must have a no argument constructor
The fully qualified name of the primary key is always specified in the deployment descriptor (except when it is not known until deployment) An example: <prim-key-class>com. an entity bean must implement (although this implementation may be left empty) the following methods: public void ejbActivate() public void ejbPassivate() public void setEntityContext(EntityContext ctx) public void unsetEntityContext() CRUD translates through Create. Update and Delete. These methods are mandatory for entity beans. Read. On the other side. in the same order.15 .14.
200
. all throwing RemoteException.String</prim-key-class> In the case of CMP using a simple type as primary key. state data is stored into data store (usually.14 mandatory callbacks for entity beans
Besides the CRUD callbacks which are discusses later in this section.

a client can invoke the remove method. On the second path. the updated data is to be stored immediately
15.ENTERPRISE JAVA BEANS
• •
the return type of the ejbCreate() is the same as the primary key.3 update
• •
ejbStore() in CMP. the entity bean moves to a pool of available instances. it calls the setEntityContext method of the entity bean class. causing the EJB container to call the ejbCreate and ejbPostCreate methods. ejbCreate() must have insertion SQL code and returns an instance of the primary key. the EJB container invokes the ejbActivate method. but in general. Second. in BMP.
201
. not null.14. All instances in the pool are identical. for BMP. There are two paths from the pooled stage to the ready stage. it's business methods can be invoked. the instance is not associated with any particular EJB object identity.14.
15. the client invokes the create method. but the developer returns null for CMP. the method can be used for preprocessing data to be stored. After the EJB container creates the instance.15 the life cycle of an entity bean
Figure 15.
15. There are also two paths from the ready stage to the pooled stage. First.4 delete
• •
the corresponding method in the bean implementation class is ejbRemove() data is deleted from DB (in the CMP case). for BMPs. but needs actual SQL code in BMP the bean's persistence implementation may choose to defer loading until it is used ejbLoad() may contain processing code
15. it is empty. left empty most of the time in CMP.14.2 read
• • •
ejbLoad(). the EJB container can invoke the ejbPassivate method. the programmer will create actual SQL code. which causes the EJB container to call the ejbRemove method. After instantiation. The setEntityContext method passes the entity context to the bean. The EJB container assigns an identity to an instance when moving it to the ready stage. actual SQL update code.15 . While an entity bean is in the ready stage. While in the pooled stage.3 shows the stages that an entity bean passes through during its lifetime. On the first path.

The messages may be sent by any J2EE component . If the primary key is incorrect. Message-driven beans currently process only JMS messages. the EJB container removes the instance from the pool and invokes the unsetEntityContext method.an application client. It acts as a JMS message listener. the ejbLoad and ejbStore methods cannot synchronize the instance variables with the database. it does not automatically set the primary key. In the pooled state. which is similar to an event listener except that it receives messages instead of events. the values of the instance variables are not needed.ENTERPRISE JAVA BEANS
Figure 15. an instance is not associated with any particular EJB object identity.3 Life Cycle of an Entity Bean At the end of the life cycle. In the pooled state. The ejbActivate method sets the primary key (id) as follows: id = (String)context. another enterprise bean.getPrimaryKey(). Therefore.15 . With bean-managed persistence. or a Web component .or by a JMS application or system that does not use J2EE technology.
202
. You can make these instance variables eligible for garbage collection by setting them to null in the ejbPassivate method. the ejbCreate and ejbActivate methods must assign a value to the primary key.
15. when the EJB container moves an instance from the pooled state to the ready state. but in the future they may be used to process other kinds of messages.16 message-driven beans
A message-driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously.

16. so that all operations within the onMessage method are part of a single transaction. a message-driven bean resembles a stateless session bean.
15. If this element is set to more than one. The container can pool these instances to allow streams of messages to be processed concurrently.ENTERPRISE JAVA BEANS 15. To avoid tying up server resources. a message-driven bean has only a bean class.
The instance variables of the message-driven bean instance can contain some state across the handling of client messages . max-beans-infree-pool. change the weblogic-ejb-jar.4 concurrent support for message-driven beans
Message-driven Beans support concurrent processing for both topics and queues. and therefore cannot be directly accessed by internal or external clients. When a message arrives. a single message-driven bean can process messages from multiple clients. To ensure concurrency. an open database connection.
• •
•
a message-driven bean's instances retain no data or conversational state for a specific client. by sending a message to a JMS Queue or Topic. To receive messages in an asynchronous manner. the container will spawn as many threads as specified.
203
. but not asynchronously. The onMessage method normally casts the message to one of the five JMS message types and handles it in accordance with the application's business logic. Clients interact with message-driven beans only indirectly. A message may be delivered to a message-driven bean within a transaction context.for example. all instances of a message-driven bean are equivalent. message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways:
• •
message-driven beans process multiple JMS messages asynchronously. or an object reference to an enterprise bean object. If message processing is rolled back. message-driven bean can be used. you may prefer not to use blocking synchronous receives in a server-side component.16. the container calls the message-driven bean's onMessage method to process the message.16.2 differences between message-driven beans and the other ejb's
The most visible difference between message-driven beans and session and entity beans is that clients do not access message-driven beans through interfaces.1 when to use message-driven beans
Session beans and entity beans allow you to send JMS messages and to receive them synchronously. Previously.xml deployment descriptor maxbeans-in-free-pool setting to >1. Unlike a session or entity bean. message-driven beans have no home or remote interface.3 differences between message-driven beans and stateless session EJBs
Although the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances. or it may invoke a session or entity bean to process the information in the message or to store it in a database.
15.16. In several respects. The onMessage method may call helper methods. For more information on this element see.
15. only concurrent processing for Queues was supported.15 . the message will be redelivered. a JMS API connection. rather than processing a serialized sequence of method calls. allowing the EJB container to assign a message to any message-driven bean instance.

. and it must not // accept parameters. and must take a single parameter of // type javax.. public void onMessage(javax. public void ejbRemove() {. See Creating and Removing Bean Instances.7 bean class requirements
The EJB 2.. Obtain a new bean instance.}.. 3. // The throws clause (if used) must not include an application //exception.} // onMessage() is required. ejbRemove() must not be declared as final or static. Note: These instances can be pooled. // The EJB class cannot define a finalize() method } Creating and Removing Bean Instances The WebLogic Server container calls the message-driven bean's ejbCreate() and ejbRemove() methods when creating or removing an instance of the bean class.16.Message MessageName) {.jms.0 specification: { public class MessageTraderBean implements javax.5 invoking a message-driven bean
When a JMS Queue or Topic receives a message. The following output shows the basic components of a message-driven bean class. call the bean's setMessageDrivenContext() to associate the instance with a container context. or create a new one.} // ejbRemove() is required and must not accept parameters.. The bean can utilize elements of this context as described in Using the Message-Driven Bean Context. onMessage() must not be // declared as final or static. If the bean cannot be located in the pool and a new one must be created. the ejbCreate() method in the bean class should prepare any resources that are
204
. and method declarations in bold are required as part of the EJB 2.MessageDrivenBean public MessageTraderBean() {. The constructor must not be declared as // final or abstract.0 specification provides detailed guidelines for defining the methods in a messagedriven bean class.Message..jms. See Implementing Business Logic with onMessage(). 2.
15. methods. The throws clause (if used) must not // include an application exception. As with other EJB types.0 specification.16.
15. Classes.6 developing message-driven beans
To create message-driven EJBs. you must follow certain conventions described in the JavaSoft EJB 2. as well as observe several general practices that result in proper bean behavior. Obtain a new bean instance from the connection pool if one already exists.16.ejb. Call the bean's onMessage() method to perform business logic. // An EJB constructor is required. finalize{}.ENTERPRISE JAVA BEANS 15.15 . use WebLogic Server to call an associated message-driven bean as follows: 1.

This is not a client context.9 implementing business logic with onMessage()
The message-driven bean's onMessage() method performs all of the business logic for the EJB.16. or by having the WebLogic Server container
205
.11 transaction services for message-driven beans
As with other EJB types. WebLogic Server immediately removes the EJB instance without calling ejbRemove(). If any method throws such an exception. passing the full JMS message object as an argument. It is the messagedriven EJB's responsibility to parse the message and perform the necessary business logic in onMessage().16. getRollbackOnly() .
15.
15.jms.
15. it cannot be assumed that the EJB receives messages in the order they were sent by the client. The ejbRemove() method should release those resources. WebLogic Server calls onMessage() when the EJB's associated JMS Queue or Topic receives a message. Message-driven beans should also perform some form of regular clean-up routine outside of the ejbRemove() method. if the EJB throws a runtime exception). For example. Make sure that the business logic accounts for asynchronous message processing. WebLogic Server provides the EJB with a container context. Instance pooling within the container means that messages are not received or processed in a sequential order. Note: Although getEJBHome() is also inherited as part of the MessageDrivenContext interface.MessageListener.The EJB can use this method only if it utilizes beanmanaged transaction demarcation.16.onMessage() for more information. getUserTransaction(). because future messages are forwarded to a new instance that WebLogic Server creates. although individual onMessage() calls to a given messagedriven bean instance are serialized.16. However. message-driven beans can demarcate transaction boundaries either on their own (using bean-managed transactions). Calling getEJBHome() from within a message-driven EJB instance yields an IllegalStateException. even in onMessage().
15.The EJB can use this method only if it utilizes containermanaged transaction demarcation. because the beans cannot rely on ejbRemove() being called under all circumstances (for example.ENTERPRISE JAVA BEANS
required for the bean's operation. message-driven EJBs do not have a home interface. the client context is not passed along with the JMS message.15 . See javax.The EJB can use this method only if it utilizes containermanaged transaction demarcation.10 handling exceptions
Message-driven bean methods should not throw an application exception or a RemoteException. so that they are freed before WebLogic Server removes the instance. from the client perspective the EJB still exists. whose properties can be accessed from within the instance by using the following methods from the MessageDrivenContext interface:
• • • • •
getCallerPrincipal() isCallerInRole() setRollbackOnly().8 using the message-driven bean context
WebLogic Server calls setMessageDrivenContext() to associate the message-driven bean instance with a container context.

Deploying Message-Driven Beans in WebLogic Server To deploy a message-driven bean on WebLogic Server. For EJBs that use container-managed transaction demarcation.12 message receipts
The receipt of a JMS message that triggers a call to an EJB's onMessage() method is not generally included in the scope of a transaction. WebLogic Server automatically acknowledges messages for EJBs with bean-managed transactions. a message-driven bean does not receive a transaction context from the client that sends a message. WebLogic Server always calls a bean's onMessage() method by using the transaction context specified in the bean's deployment descriptor. the message receipt is always outside the scope of the bean's transaction.0 specification. If the EJB uses bean-managed transactions.0 specification. as required by the EJB 2. you edit the XML file to create the deployment descriptors that associate the EJB with a configured JMS destination.xml. In either case. WebLogic Server automatically acknowledges a message when the EJB transaction commits.13 message acknowledgment
For message-driven beans that use container-managed transaction demarcation. Deployment Descriptors The deployment descriptor for a message-driven bean also specifies:
• • • •
Whether the EJB is associated with a JMS Topic or Queue Whether an associated Topic is durable or non-durable Transaction attributes for the EJB JMS acknowledgment semantics to use for beans that demarcate their own transactions
15. but the deployer can configure acknowledgment semantics using the jms-acknowledge-mode deployment parameter.16.xml as follows: <assembly-descriptor> <container-transaction> <method> <ejb-name>MyMessageDrivenBeanQueueTx</ejb-name> <method-name>*</method-name> </method> <trans-attribute>NotSupported</trans-attribute> </container-transaction> </assembly-descriptor>
15. Transaction attributes are defined in ejb-jar. For EJBs that use bean-managed transactions.14 deployment elements
The EJB 2. Because no client provides a transaction context for calls to a message-driven bean.ENTERPRISE JAVA BEANS
manage transactions (container-managed transactions). beans that use container-managed transactions must be deployed using the Required or NotSupported transaction attribute in ejb-jar.0 specification adds the following new XML deployment elements for deploying
206
. as described in the EJB 2.15 .
15. both the receipt and the acknowledgment of a message occur outside of the EJB transaction context.16.16. WebLogic Server includes the message receipt as part of the bean's transaction only if the bean's transaction attribute is set to Required.

subscription-durability specifies whether or not an associated Topic should be durable.MessageTraderBean</ejb-class> <transaction-type>Container</transaction-type> <message-driven-destination> <jms-destination-type> javax.ejb20.xml deployment file. It calls the setMessageDrivenContext method to pass the context object to the instance. For each instance. the EJB container instantiates the bean and performs these tasks: 1. as described in the EJB 2.4 illustrates the stages in the life cycle of a message-driven bean. It calls the instance's ejbCreate method.
•
•
These elements are defined in the ejb-jar.
207
.jms.xml elements. </message-driven> .ENTERPRISE JAVA BEANS
message-driven beans. </enterprise-beans> In addition to the new ejb-jar...15 .Topic </jms-destination-type> </message-driven-destination> . 2. jms-acknowledge-mode specifies the JMS acknowledgment semantics to use for beans that demarcate their own transaction boundaries. The EJB container usually creates a pool of message-driven bean instances.. the weblogic-ejb-jar. The following excerpt shows a sample XML stanza for defining a message-driven bean: <enterprise-beans> <message-driven> <ejb-name>exampleMessageDriven1</ejb-name> <ejb-class>examples. This element has two possible values: AUTO_ACKNOWLEDGE (the default) or DUPS_OK_ACKNOWLEDGE.
15.0 specification.message.xml file includes a new message-driven-descriptor stanza to associate the message-driven bean with an actual destination in WebLogic Server..17 the life cycle of a message-driven bean
Figure 15.
•
message-driven-destination specifies whether the EJB should be associated with a JMS Queue or Topic destination.

This information can be divided into two main categories:
• •
structural information related to a particular EJB. bean home name . security
208
. access control entries . session specific elements 9. isolation level. environment properties 6. here is a typical list of entries (elements) in a deployment descriptor: 1. EJB class name 5.ENTERPRISE JAVA BEANS
Figure 15. which users can access a bean or a particular method of a bean 2.18 the deployment descriptor
The deployment descriptor of an EJB contains information about the bean in relation to the application it belongs to.like transaction. application assembly information
Although not an exhaustive one. attributes . The bean's instance is then ready for garbage collection.security issues. the container calls the ejbRemove method.15 . At the end of the life cycle.4 Life Cycle of a Message-Driven Bean Like a stateless session bean. a message-driven bean is never passivated.specifies control attributes for transactions 4. control descriptors . entity specific elements 10.name under which the bean is registered under JNDI 3. the remote interface name 8. the home interface name 7.
15. and it has only two states: nonexistent and ready to receive messages.