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

Java API for RESTful Web Services (JAX-RS) Contexts and Dependency Injection for the Java EE Platform (JSR-299), informally known as Web Beans Java Authentication Service Provider Interface for Containers (JASPIC)

• • •

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

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

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

transaction management. JNDI lookup services provide a unified interface to multiple naming and directory services in the enterprise so that application components can access these services.2 Container Types The deployment process installs Java EE application components in the Java EE containers illustrated in figure 1. 7 . 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. application components within the same Java EE application can behave differently based on where they are deployed. Because the Java EE architecture provides configurable services. database connection resource pooling. The container also manages nonconfigurable services such as enterprise bean and servlet life cycles. and remote connectivity.4. data persistence. a client invokes methods on it as if it were in the same virtual machine. 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. and access to the Java EE platform APIs.1 . Container settings customize the underlying support provided by the Java EE server.java platform. enterprise edition The assembly process involves specifying container settings for each component in the Java EE application and for the Java EE application itself. 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. The Java EE remote connectivity model manages low-level communications between clients and enterprise beans. including services such as security. 1. After an enterprise bean is created. For example.9. Java Naming and Directory Interface (JNDI) lookups.

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

4 UDDI and ebXML Standard Formats Other XML-based standards. 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.10. all running on different platforms and at various locations on the Internet. HTTP is a familiar request-and response standard for sending messages over the Internet.11 java EE 6 core technologies and APIs Figure 1.java platform. 1. and ways to communicate with the service. The following sections give a brief summary of the technologies required by the Java EE platform.10.3 WSDL Standard Format The Web Services Description Language (WSDL) is a standardized XML format for describing network services. and SOAP is an XML-based protocol that follows the HTTP request-and-response model. and the APIs used in Java EE applications. Discovery and Integration (UDDI) and ebXML. 1. The description includes the name of the service.10. 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. enterprise edition 1. such as Universal Description.5 illustrates the availability of the Java EE 6 platform APIs in each Java EE container type. where the information can be readily and globally accessed by clients who want to do business. WSDL service descriptions can be stored in UDDI registries or published on the web (or both). the location of the service.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. 9 . make it possible for businesses to publish information on the Internet about their products and web services.1 .

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

1 - java platform, enterprise edition
implementation of the tags is optimized. JSTL has iterator and conditional tags for handling flow control, tags for manipulating XML documents, internationalization tags, tags for accessing databases using SQL, and commonly used functions.

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

The Java Persistence API The query language Object/relational mapping metadata

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.

1.11.23 Simplified Systems Integration
The Java EE platform is a platform-independent, full systems integration solution that creates

14

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. it can be changed without the need to modify the source code. Deployment typically involves using a platform’s deployment tool to specify location-specific information. enterprise edition an open marketplace in which every vendor can sell to every customer. it is ready to be deployed. Such a marketplace encourages vendors to compete. A Java EE application is delivered in an Enterprise Archive (EAR) file. 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. better tools. Because deployment descriptor information is declarative. servlet. a standard Java Archive (JAR) file with an . At runtime.java platform.ear extension. SAAJ. Once deployed on a local platform. or better customer support. module. and JNDI 1. a module. the Java EE server reads the deployment descriptor and acts upon the application. Using EAR files and modules makes it possible to assemble a number of different Java EE applications using some of the same components. JSP page.1 .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. An EAR file contains Java EE modules and deployment descriptors. or component accordingly. A deployment descriptor is an XML document with an . 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. 15 . JTA. No extra coding is needed. it is only a matter of assembling (or packaging) various Java EE modules into Java EE EAR files. such as better performance. such as a list of local users that can access it and the name of the local database. or a component. the application is ready to run. Each unit contains: • • A functional component or components (such as an enterprise bean.xml extension that describes the deployment settings of an application. or applet) An optional deployment descriptor that describes its content Once a Java EE unit has been produced.

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

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

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

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

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

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

the server closes the socket. </body> </html> After sending the response. 22 .2 .HTTP .

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

permitted in the declaration NAMELEN 65536 -.increased -ATTSPLEN 65536 -.HTML DESCSET 0 9 11 13 14 32 127 128 160 55296 57344 CAPACITY 9 2 2 1 18 95 1 32 55136 2048 1056768 UNUSED 9 UNUSED 13 UNUSED 32 UNUSED UNUSED 160 UNUSED 57344 150000 150000 150000 -.3 .Avoid fixed limits in actual PILEN 65536 -.implementations of HTML UA's TAGLVL 100 TAGLEN 65536 GRPGTCNT 150 GRPCNT 64 FEATURES MINIMIZE DATATAG OMITTAG RANK SHORTTAG LINK ----- NO YES NO YES 24 .SURROGATES -- SGMLREF TOTALCAP GRPCAP ENTCAP SCOPE DOCUMENT SYNTAX SHUNCHAR CONTROLS 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 127 BASESET "ISO 646IRV:1991//CHARSET International Reference Version (IRV)//ESC 2/8 4/2" DESCSET 0 128 0 FUNCTION RE RS SPACE TAB SEPCHAR LCNMSTRT UCNMSTRT LCNMCHAR UCNMCHAR NAMECASE 13 10 32 9 NAMING "" "" ".-_:" ".-_:" GENERAL YES ENTITY NO DELIM GENERAL SGMLREF SHORTREF SGMLREF NAMES SGMLREF QUANTITY SGMLREF ATTCNT 60 -.These are the largest values LITLEN 65536 -.

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

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

3 .6 table related elements The specific elements defining a table. The intersection of any row and any column is called a cell. Here is their description and attributes. <TR>. <TH> and <TD>. 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 . columns. headers and cells are <TABLE>. its rows. the cells in the first row contain are called headers and consist of a brief description of the content of the corresponding column.HTML A table is a visual rectangular object consisting of several rows and columns. <THEAD>. Here is a an example of a table: 3. Usually.

allowing user input and parameter submittal.required. The <FORM> element has the following attributes: • ACTION . specifies the URL of the server side process that will receive the data 28 .7 forms A form is a basic component container.HTML • VALIGN the <TH> element attributes: • • • • • • ABBR AXIS CHAR CHAROFF HEADERS SCOPE the <TR> element attributes: • • • • • ALIGN BGCOLOR CHAR CHAROFF VALIGN the <TD> element attributes: • • • • • • • • • ABBR ALIGN CHAR CHAROFF COLSPAN ROWSPAN SCOPE VALIGN WIDTH 3.3 .

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

HTML • SELECTED Example of a <SELECT> element: <SELECT NAME="action" STYLE="font-family: '@Arial Unicode MS' font-size: 11pt"> <OPTION SELECTED>Select Action <OPTION>Make Payment <OPTION>Transfer a balance <OPTION>Change Mailing Address <OPTION>Change e-mail Address <OPTION>Change User Name/Password <OPTION>View Account Activity </SELECT> 30 .3 .

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

the others are the standalone programs – Java applications. A java applet is a java class that extends the standard Applet class.4. as follows: java [-options] class [args] Where main options are: • • -cp <directories and jar files separated by “. namely: • • • CODE – identifies the (compiled) class file of the applet WIDTH HEIGHT A java application is a collection of java classes.”> : cp = classpath -D <name>=<value> : set a system property To execute a . each class is implemented in a source file having the same name as the class itself and whose extension is . In general. This binary relation is specified in the declaration of the derived class B using the keyword extends. 4.jar file. The first type are embedded in web pages – applets. or is derived from A. Generally. or that it extends A). use the command: java –jar [-options] jarfile [args] 4.4 .java.4. The <APPLET> element has 3 mandatory attributes. A Java class B inherits another class A (or is a subclass of A.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.JAVA PRIMER There exist 2 types of programs that can be written in Java.2 inheritance Inheritance is a partial order relation in the set of all Java classes. Exactly one of these classes must implement a method called main().4 object oriented concepts 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). an applet is inserted in a HTML page by an <APPLET> tag or by an <OBJECT> tag. An example: 32 .

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

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

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

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

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

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

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

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

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

txt+="Click OK to continue. alert(txt).1 alert Box An alert box is often used if you want to make sure information comes through to the user.5 .7.6 operators The only new one is the comparison operator === (equal values and same type). txt+="Error description: " + err. 5.description + "\n\n". } catch(err) { txt="There was an error on this page.\n\n".\n\n". Syntax: 42 . the user will have to click "OK" to proceed. strings can be added (concateneted) using the + operator. When an alert box pops up. Also. } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html> 5.7 popup boxes 5.javaScript // handle errors here } Example <html> <head> <script type="text/javascript"> var txt="" function message() { try { adddlert("Welcome guest!").

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

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

9.5 . document. 45 .javaScript 5.10 the hierarchy of javaScript browser objects There are two major classes of built-in javascript objects. </script> 5. The first class consists of browser specific objects.toUpperCase()). which will be specified in the next section.write(str. 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!". The other class are the language specific objects.3 methods Methods are the actions that can be performed on objects.

com/jsref/default. as well). Properties FF: Firefox.1 the String object The String object is used to manipulate a stored piece of text. Events are special signals or messages which occur when certain pre-defined actions take place within a Web browser. which are called Objects.5 . For an exhaustive list of properties and methods of the above objects (and for the built in objects.asp 5. When an event message has been triggered. Objects are storage containers that have Properties (data values associated with Objects) and Methods (functions associated with Objects) that operate on that data. Even this Document itself is an Object.11. Objects may also have certain Events that are associated with them. check the site http://www.w3schools. every Image on the page is an Object. you need a way to intercept the message and react to it. 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 . At its most basic level. JavaScript allows you to control the appearance of many of the Objects that make up a Web page as we previously saw.javaScript We can think of each Web page as a collection of several individual elements.11 javaScript language built in objects 5. or when the user interacts with a Web page. N: Netscape. every Link on the page is an Object. This is achieved through the use of Event Handlers. For example.

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 . N: Netscape.11. 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. Properties FF: Firefox.2 the Date object The JavaScript Date object is used to work with dates and times. 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.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. as a four-digit number. depending on the browser. 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. 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 . 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.5 .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.

3 the Array object The JavaScript Array object is used to store a set of values in a single variable name. 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. N: Netscape. 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.5 . according to universal time.11.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). according to Greenwich time. according to local time. 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. to a string Takes a date and returns the number of milliseconds since midnight of January 1. IE: Internet Explorer Property Description F F N I E 49 . Use toUTCString() instead !! Converts a Date object. to a string. according to local time. to a string and returns the time portion Converts a Date object. Properties FF: Firefox.

5 3 4 . var myNum=new Number(number). 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 .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.5 4 3 4 .11. Syntax for creating a new Number object.4 the Number object The Number object is an object wrapper for primitive numeric values. IE: Internet Explorer Property constructor Description Returns a reference to the Number function that created the object F F 1 E 4 I 50 .5 4 . Properties FF: Firefox.5 .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 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 .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. Properties FF: Firefox. N: Netscape.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 .5 the Boolean object The JavaScript Boolean object is an object wrapper for a Boolean value. 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 .5 1 .11.5 .

It includes several mathematical constants and functions.6 the Math Object The JavaScript Math object allows you to perform common mathematical tasks. 0.434) Returns PI (approx. 2.707) Returns the square root of 2 (approx. IE: Internet Explorer Property E LN2 LN10 LOG2E LOG10E PI SQRT1_2 SQRT2 Methods Method abs(x) acos(x) asin(x) atan(x) atan2(y. Properties FF: Firefox. 0. N: Netscape.718) Returns the natural logarithm of 2 (approx. 3.693) Returns the natural logarithm of 10 (approx.11. 2.y) min(x. 1. 1.javaScript 5.y) random() round(x) sin(x) sqrt(x) tan(x) Description F Returns the absolute value of a number Returns the arccosine of a number Returns the arcsine of a number Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians Returns the angle theta of an (x.y) pow(x.5 .14159) Returns the square root of 1/2 (approx.414) F F 1 1 1 1 1 1 1 1 N E I 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 52 .x) ceil(x) cos(x) exp(x) floor(x) log(x) max(x. 0.302) Returns the base-2 logarithm of E (approx.y) point as a numeric value between -PI and PI radians Returns the value of a number rounded upwards to the nearest integer Returns the cosine of a number Returns the value of Ex Returns the value of a number rounded downwards to the nearest integer Returns the natural logarithm (base E) of a number Returns the number with the highest value of x and y Returns the number with the lowest value of x and y Returns the value of x to the power of y Returns a random number between 0 and 1 Rounds a number to the nearest integer Returns the sine of a number Returns the square root of a number Returns the tangent of an angle 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 F N I E 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 Description Returns Euler's constant (approx.442) Returns the base-10 logarithm of E (approx.

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

The following code adds a method called eat() to the personObj: personObj."blue").firstname=firstname. } Notice that the template is just a function."Rally". myMother=new person("Sally". this.javaScript Adding a method to the personObj is also simple.5 .age. this.lastname=lastname. this.firstname=firstname.eyecolor) { this.eyecolor=eyecolor.12. This is also done inside the template: function person(firstname.4 create a template of an object The template defines the structure of an object: function person(firstname.age. Once you have the template.eat=eat. this.lastname. Then we will have to write the newlastname() function: function newlastname(new_lastname) { this.lastname=lastname.eyecolor) { this. } Note that methods are just functions attached to objects. like this: myFather=new person("John". That's what "this" is: the instance of the object at hand.eyecolor=eyecolor."green"). 5.age=age. 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. this.age=age. 54 .lastname=new_lastname. this.48. You can also add some methods to the person object.50.lastname. Inside the function you need to assign things to this.newlastname=newlastname. you can create new instances of the object.propertyName."Doe".

Event onabort onblur onchange onclick ondblclick onerror onfocus onkeydown onkeypress onkeyup onload The event occurs when. So.newlastname("Doe").13 JavaScript Events New to HTML 4. We define the events in the HTML tags. Every element on a web page has certain events which can trigger JavaScript functions. 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. 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..javaScript } The newlastname() function defines the person's new last name and assigns that to the person.. now you can write: myMother. 5. JavaScript knows which person you're talking about by using "this. 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 .0 was the ability to let HTML events trigger actions in the browser.5 . we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button.". Netscape an Internet Explorer for each such event. like starting a JavaScript when a user clicks on an HTML element. For example.

An alert box appears when an onMouseOver event is detected: <a href="http://www. 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. The checkForm() function will be called when the user clicks the submit button in the form. For example. Below is an example of an onMouseOver event. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()">. If the field values are not accepted. the submit should be cancelled. onBlur and onChange events are often used in combination with validation of form fields.4 onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. Next time the visitor arrives at your page. The function checkForm() returns either true or false. 5.13. Below is an example of how to use the onChange event.13.3 onSubmit The onSubmit event is used to validate ALL form fields before submitting it. The name is then stored in a cookie. 5. and load the proper version of the web page based on the information. Below is an example of how to use the onSubmit event.5 .13. If it returns true the form will be submitted.2 onFocus. onBlur and onChange The onFocus.w3schools.com" onmouseover="alert('An onMouseOver 56 .13. you could have another popup saying something like: "Welcome John Doe!". otherwise the submit will be cancelled: <form method="post" action="xxx. The onload event is often used to check the visitor's browser type and browser version.htm" onsubmit="return checkForm()"> 5. you could have a popup asking for the user's name upon his first arrival to your page.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.1 onload and onUnload The onload and onUnload events are triggered when the user enters or leaves the page.

return false"> <img src="w3schools.javaScript event').gif" width="100" height="30"> </a> 57 .5 .

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

Level 3 Consists of 6 different specifications: 1. including a new revision of DOM Level 3 Events.4 specifications • • • Document Object Model (DOM) Level 1 Specification Level 2 Recommendations: • Document Object Model (DOM) Level 2 Core Specification • Document Object Model (DOM) Level 2 Views Specification • Document Object Model (DOM) Level 2 Events Specification • Document Object Model (DOM) Level 2 Style Specification • Document Object Model (DOM) Level 2 Traversal and Range Specification • Document Object Model (DOM) Level 2 HTML Specification Level 3 Recommendations: • Document Object Model (DOM) Level 3 Core Specification 59 .3 levels The W3C DOM specifications are divided into levels. To claim to support a level.Html DOM Web Applications Working Group has taken over responsibility for the Document Object Model specifications. a new DOM Core specification. 4. Level 0 The application supports an intermediate DOM. 2. DOM Level 3 Core. Level 2 XML namespace support. 5. As of 2005. each of which contains required and optional modules. Examples include the DHTML Object Model or the Netscape intermediate DOM. filtered views and events. Level 1 Navigation of DOM (HTML and XML) document (tree structure) and content manipulation (includes adding elements). an application must implement all the requirements of the claimed level and the levels below it. Level 1. 3. which further enhances the DOM 6. DOM Level 3 Views and Formatting. Level 2.6 . 6. DOM Level 3 XPath. DOM Level 3 Load and Save. DOM Level 3 Requirements. DOM Level 3 Validation. An application may also support vendor-specific extensions which don't conflict with the W3C standards. and 6. HTML-specific elements are included as well. which existed before the creation of DOM Level 1. and some modules of Level 3 are W3C Recommendations which means they have reached their final form. Level 0 is not a formal specification published by the W3C but rather a shorthand that refers to what existed before the standardization process. and potentially any errata on older DOM specifications.

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

and VBScript.Html DOM DOM. The contents can be modified or deleted. and new elements can be created. JavaScript.6 . It can be used by any programming language like Java. The HTML DOM is platform and language independent. 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 .

9 the HTML DOM Node Tree 6. "DOM Tutorial" is not the value of the <title> element! However. 62 .2 text is always stored in text nodes A common error in DOM processing is to expect an element node to contain text.8. in the HTML DOM the value of the text node can be accessed by the innerHTML property. 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. The <body> node holds a <h1> and <p> node.Html DOM 6. In this example: <title>DOM Tutorial</title>.9.8. everything in an HTML document is a node. 6. All other nodes in the document are contained within <html>.1 the Document Tree The HTML DOM views a HTML document as a tree-structure. However. The tree structure is called a node-tree. The <head> node holds a <title> node.6 . the text of an element node is stored in a text node.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>. 6.8 DOM nodes According to the DOM. the element node <title>. <head> and <body>. holds a text node with the value "DOM Tutorial". The <html> node has two child nodes.

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

each node is an object.9.write(x[i]. that can be accessed and manipulated by JavaScript. document.4 Node Properties In the HTML Document Object Model (DOM).6 . Three important HTML DOM node properties are: • • • nodeName nodeValue nodeType the nodeName Property The nodeName property specifies the name of a node. • • • 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. } 6. Objects have methods (functions) and properties (information about the object). • • • • • 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.Html DOM for (i=0.i<x.length.innerHTML).write("<br />"). The most important node types are: Element type Element Attribute Text Comment Document NodeType 1 2 3 8 9 64 .i++) { document.

Category Type Attribute Description Fires when the pointing device button is clicked over an element. txt=x.6 .9.firstChild.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. 6.get the value of an element The following code fragment retrieves the text node value of the first <p> element: x=document.5 example . 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 .getElementById("intro").nodeValue.Html DOM 6.

objects and images. For elements. A keypress is defined as a keydown and keyup on the same key. 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. 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 . 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.6 . including window. For elements.Html DOM Fires when a key on the keyboard is "clicked". 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. 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.

DOMNodeInserted. W3C takes a middle position in this struggle. Fires when an element is activated. for instance. This model is implemented in Internet Explorer and other browsers. but Internet Explorer for the Mac does not.Html DOM DOMFocusOut ondomfocusout Similar to HTML blur event. Events are first captured until it reaches the target element. and then bubbled up. Mozilla. Mozilla and Safari also support contextmenu.cancelBubble = true for Internet Explorer).stopPropagation() for Mozilla and command event. 6. 67 . Safari and Opera also support readystatechange event for the XMLHttpRequest object. an event can be responded to at any element in the path (an observer) in either phase by causing an action. Mozilla also supports the beforeunload event using traditional event registration method (DOM Level 0). as of version 1. 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.3. When the user clicks on the inner element.11 event flow Consider the situation when there are 2 elements nested together. Also. and/or by cancelling the default action for the event.6 . Safari. also supports these methods. Mozilla and Opera support DOMAttrModified. through a mouse click or a keypress. Trigger the elements from inner to outer (event bubbling). Both have event handlers registered on the same event type. DOMNodeRemoved and DOMCharacterDataModified. This model is implemented in Netscape Navigator. During the event flow. say "click". but can be applied to any focusable element Similar to XUL command event. there are two possible ways to handle it: • • Trigger the elements from outer to inner (event capturing). and/or by stopping the event (with method event.

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

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

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

71 .7 . usually using XML. If the engine needs something from the server in order to respond — if it’s submitting data for processing.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. and even some navigation — the engine handles on its own. loading additional interface code. without stalling a user’s interaction with the application. Any response to a user action that doesn’t require a trip back to the server — such as simple data validation. or retrieving new data — the engine makes those requests asynchronously. editing data in memory.

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

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

2 how to get from xml To get data from a xml file we have just to replace this line: document.XMLHTTP). }.XMLHttpRequest) req = new XMLHttpRequest(). else if (window. else document. } </script> </head> <body> <FORM method="POST" name="ajax" action=""> <INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()"> <INPUT type="text" name="dyn" value=""> </FORM> </body> </html> 7.setRequestHeader("Content-Type". if(window. "application/x-www-form-urlencoded").7 examples 7.item(0).1 How to get a text <html> <head> <script> function submitForm() { var req = null.responseText. req. // read the first element with a dom's method 74 . true). req.onreadystatechange = function() { if(req.xml".7 .send(null).ajax.readyState == 4) if(req.7. req. by this code: var doc = req.AJAX 7. req.dyn="Received:" + req.ActiveXObject) req = new ActiveXObject(Microsoft.status.getElementsByTagName('root').ajax.responseXML.7.ajax.dyn="Error code " + req.status == 200) document.dyn=""Received:" + req.open("GET". // assign the Xml file to a var var element = doc. "data.responseText.

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

75

7 - AJAX

7.10 Specifications
Ajax is based on these specifications:
● ● ●

XML 1, HTML 4.0, DOM 2, from W3C ECMAScript 1.5 (standard for JavaScript) from ECMA W3C draft specification for XMLHttpRequest.

76

8 - WEB APPLICATIONS

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

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

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

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

Enterprise Edition. from Oracle Corporation Orion Application Server . IOException.servlet package.servlet javax. from IronFlare Caucho's Resin Server ServletExec . from New Atlanta Communications WebObjects. while the second one. public ServletConfig getServletConfig(). namely: • • • • • • • • servlet implementation servlet configuration servlet exceptions request and responses session tracking servlet context servlet collaboration miscellaneous 9.http contains classes and interfaces which are HTTP specific. which are part of the Java Platform SDK. 82 . from Apple Inc.http The classes and interfaces defined in the javax. The classes and interfaces of the Java servlet API can be divided in several categories. from IBM 9.SERVLETS • • • • • • • LiteWebServer (open source) Oracle Application Server . public void destroy() throws ServletException.3 servlet packages and classes The Java servlet API consists of 2 packages. WebSphere. ServletResponse resp) throws ServletException.servlet package are protocol independent. It declares the following methods: public void init(ServletConfig config) throws ServletException.servlet. public void service(ServletRequest req.9 .4 the Servlet interface The Servlet interface is part of the javax.servlet. the javax. These packages are: • • javax.

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

containing web container information This interface specifies the following methods: public public public public String getInitParameter(String name) Enumeration getInitParameterNames() ServletContext getServletContext() String getServletName() 9.ServletException javax.9 .servlet.lang. HttpServletResponse resp) protected void doPut(HttpServletRequest req. HttpServletResponse resp) 9.Exception and can be thrown by the init().UnavailableException The ServletException class extends java.9 the servlet lifecycle Generally. service(). HttpServletResponse resp) protected void doOptions(HttpServletRequest req.SERVLETS HttpServletResponse resp) protected void doDelete(HttpServletRequest req.8 servlet exceptions The Java servlet API specifies two servlet specific exceptions: javax. a servlet instance goes through the following stages: 84 .lang.Exception class. It also extends the java. doXXX() and destroy() methods of the Servlet interface implementations. HttpServletResponse resp) protected void doTrace(HttpServletRequest req. 9. namely: • • • initialization parameters (as name-value pairs) the name of the servlet a ServletContext object.7 the ServletConfig interface This interface abstracts configuration information about the servlet. The UnavailableException indicates to the web container that the servlet instance is unavaialble.servlet.

concurrent requests are serviced in more than one service thread. etc. this method contains JDBC driver loading. respectively.SingleThreadModel. The web container makes sure that the init() method of the servlet will be completed before invoking its service() method. But what is the difference between a parameter and an attribute? While the parameters of the request are part of the request itself. 85 . method which performs the initialization of the servlet. Also. The first one is to attach attributes to the request object. which will service all incoming requests. There are 3 different ways for attaching and retrieving attributes. If the servlet does not implement the javax. After instantiation.9 . The purpose of attributes is to allow the container to provide additional data to a 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 attributes of the request are attached by the web containers or by the servlets/JSPs/JSFs.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. or to allow sending data from a servlet to another. Typically.servlet. the servlet's destroy() method will be called before the servlet itself is destroyed. the container calls the init() method of the servlet. 9. DB connection opening. The other two use the HttpSession and ServletContext objects. JSP or JSF. which requires that the service() method be thread safe. the web container creates a single instance of the servlet. 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.

SERVLETS 9.9 . Here are the most important ones: 86 . 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.11 the HttpServletRequest interface public interface HttpServletRequest extends ServletRequest This interface contains HTTP specific methods. One has to take in account the structure of an HTTP request when overviewing the most important methods of this interface.12 the ServletResponse interface This interface defines methods for constructing responses to servlet requests.

java" file: package com. Each servlet context is rooted at a specific path in the web server.ccards.SERVLETS public void addCookie(Cookie cookie) public String encodeURL(String url) public void sendError(int status) public void sendError(int status. import java. 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. Object attr) public String removeAttribute(String name) 9.*. String message) public void setHeader(String headerName. 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.bank11.html) Here is its abbreviated form (topics which are DB related are postponed) of the "EnrollServlet. String value) public void setStatus(int statusCode) 9. A reference to an object of this type can be obtained by invoking the getServletContext() method of the HttpServlet object.xml file.9 .servlets.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. This is done in server's (container's) server.io. The ServletContext interface abstracts the context of a web application. 87 .

out. out.println("</html>").*. PrintWriter out = resp. out. out. HttpServletResponse resp) throws ServletException.init(config).servlet.*.println("<html>"). IOException { resp.setContentType(“text/html”). out. out.println("</head>"). out.println("</body>").println("<body>"). out.close(). import javax. out. } public void doPost(HttpServletRequest req.SERVLETS import javax. // output your page here out.http.println("<head>").servlet.println("<br>").println("merge").9 .println("<title>Servlet</title>"). } } 88 . public class EnrollServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.getWriter().

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

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

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

Blob java.sql.sql.sql.SQLTransientException java.sql. querying the database 4.ResultSet java.sql.sql.SQLTimeoutException java.sql.StatementEvent javax.sql package The figure below shows the interactions and relationships between the major classes and interfaces of the java.sql.sql.SQLInvalidAuthorizationSpecException java.SQLNonTransientConnectionException java.sql.sql.SQLSyntaxErrorException java.sql.sql.Wrapper javax.sql.Types java.sql. processing the result set 92 .sql.SQLNonTransientException java.4 interaction schema in the java.JDBC The following list contains all of the classes and interfaces new or updated in version 4.StatementEventListener 10.sql.sql.sql.sql.0. establishing a database connection 3.sql.sql.sql package.SQLException java.SQLOutput java.CommonDataSource javax.Connection java.sql. The main steps in communicating with a database are: 1.sql.Clob java.DatabaseMetaData java.sql.PreparedStatement java.SQLTransactionRollbackException java.SQLWarning java.10 .sql.sql.sql.sql.SQLClientInfoException java.RowIdLifeTime java.SQLInput java.Statement java.ClientinfoStatus java.NClob java. java.SQLDataException java.SQLTransientConnectionException java.CallableStatement java.sql.SQLFeatureNotSupportedException java.sql.sql.RowId java.SQLIntegrityConstraintViolationException java.sql.SQLXML java.sql. loading a database driver 2.

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

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

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

8 statement interfaces The objects we encountered in the previous section. Statement.10 . methods for result set concurrency and type: • • getResultSetConcurrency() getResultSetType() 6. other methods: • • • • • • setQueryTimeout() getQueryTimeout() setMaxFieldSize() getMaxFieldSize() cancel() getConnection() 96 . methods for executing statements: • • • execute() executeQuery() executeUpdate() 2. PreparedStatement and CallableStatement abstract regular SQL statements. methods for result set fetch size and direction: • • • • setFetchSize() getFetchSize() setFetchDirection() getFetchDirection() 4. methods for batch updates: • • • addBatch() executeBatch() clearBatch() 3. respectively. The Statement interface has (among others) the following methods: 1. method to get the current result set: • getResultSet() 5. namely.JDBC 10. prepared statements and stored procedures.

JDBC The Statement interfaces also support the same methods for transaction support as the Connection objects.sql. The interface ResultSet is implemented by driver vendors. Methods to retrieve data: • • • • • • • • • • • • • • • • • • • • getAsciiStream() getBoolean() getDate() getInt() getShort() getTimeStamp() getBinaryStream() getBytes() getFloat() getObject() getTime() getString() getByte() getDouble() getLong() getBigDecimal() getMetaData() getClob() getWarnings() getBlob() 97 . String sqlString = "CREATE TABLE customer . stmt.10 ..executeUpdate(sqlString). 10.. Objects implementing the Connection interface are mainly used for SQL queries execution.". Here is a typical example: Statement stmt = conn.ResultSet object which is available to the user and allows access to the data retrieved.createStatement().9 the ResultSet interface The result of a query by a Statement object is a java.

One can think of a database cursor as an iterator over the collection of rows in the result set. What if we don't have this knowledge? Fortunately. PreparedStatement. The usage of these retrieval methods assumes the prior knowledge of the type and the index (or name) of a particular column. not at 0) or the column name. and cursors are held over commit boundaries. The invocation of the getMetaData() method of a ResultSet object returns an object of ResultSetMetaData type. A cursor comprises a control structure for the successive traversal (and potential processing) of records in a result set. as the argument.10 . 98 . An exception to this is that WebSphere currently changes the cursor holdability default so that cursors are implicitly closed when committed. a concurrency of read only. 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 CallableStatement objects. These characteristics are configurable through methods that are accessible on Statement.10 ResultSet characteristics By default. all created ResultSets have a type of forward only.JDBC Most of these methods require the column index (which in SQL starts at 1. all this data about the DB schema (or metadata) can be retrieved using the ResultSetMetaData interface.

10 - JDBC 10.10.1 ResultSet types
The ResultSet type specifies the following about the ResultSet:
• •

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.11 example of data retrieval
// DisplayServlet.java package com.bank11.ccards.servlets; import import import import import java.sql.*; javax.servlet.*; javax.servlet.http.*; java.math.*; java.util.*;

public class DisplayServlet extends HttpServlet { Connection conn; // Initializes the servlet public void init(ServletConfig config) throws ServletException { super.init(config); String driverName = "org.gjt.mm.mysql.Driver"; try { Class.forName("org.gjt.mm.mysql.Driver"); } catch(ClassNotFoundException e) { e.printStackTrace(); } String connURL="jdbc:mysql://localhost:3306/ccards"; try { conn=DriverManager.getConnection(connURL,"root","root"); } catch (SQLException sqle) { sqle.printStackTrace(); } } // Destroys the servlet.

100

10 - JDBC
public void destroy() { } // Processes requests for both HTTP GET and POST methods. protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { String theCode = req.getParameter(“CODE”); String sql = “SELECT FIRST_NAME, LAST_NAME, ACCOUNT_NUM from CUSTOMERS where CNP=”+theCode+”;”; try { Statement stmt = conn.getStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { String firstName = rs.getString(“FIRST_NAME”); String lastName = rs.getString(“LAST_NAME”); BigDecimal accountNum = rs.getBigDecimal(“ACCOUNT_NUM”); } } catch (SQLException sqle) { sqle.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } resp.setContentType("text/html"); java.io.PrintWriter out = resp.getWriter(); // output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet</title>"); out.println("</head>"); out.println("<body>"); ... out.println("</body>"); out.println("</html>"); out.close(); } // Handles the HTTP GET method. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { processRequest(req, resp); } // Handles the HTTP POST method. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException {

101

10 - JDBC
processRequest(req, resp); } // Returns a short description of the servlet. public String getServletInfo() { return "Short description"; } }

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

10.13 jdbc and sql types and their corresponding java classes
JDBC Type ARRAY BIGINT BINARY BIT BLOB CHAR CLOB DATE Purpose SQL array 64 bit integer binary value one bit value binary large object char string character large object day, month, year SQL Type ARRAY BIGINT none BIT BLOB CHAR CLOB DATE Java Type java.sql.Array long byte[] boolean java.sql.Blob String java.sql.Clob java.sql.Date

102

sql.produces a Connection object that will 103 .sql package. basicly. This interface is. a factory for creating DB connections. The DataSource interface is implemented by a driver vendors.14 JDBC Data Sources In the JDBC 2.Big Decimal Object float 10.sql. While the DriverManager interface was used at run time to load explicitly a JDBC driver.sql.Times tamp short byte[] String 16 bit integer SMALLINT short Purpose decimal value distinct double precision double precision 32 bit integer stores Java objects variable length binary value variable length char string null values decimal value db specific types single precision SQL Type DECIMAL DISTINCT DOUBLE PRECISION FLOAT INTEGER none none none NULL NUMERIC none REAL Java Type java. mins.math.Time java. secs date. There are three types of implementations: 1. Basic implementation -. Connection pooling implementation -.Big Decimal none double double int Object byte[] String null java.DataSource object.produces a standard Connection object 2. the DriverManager interface is replaced by the DataSource interface as main method of obtaining DB connections. It is part of the javax.math. the new mechanism uses a centralized JNDI service to locate a javax. nanoseconds 8 bit integer variable length binary value variable length char string TIME TIMESTAMP TINYINT none VARCHAR java.10 .0 optional package. time.JDBC JDBC Type DECIMAL DISTINCT DOUBLE FLOAT INTEGER JAVA_OBJECT LONGVARBINARY LONGVARCHAR NULL NUMERIC OTHER REAL REF SMALLINT STRUCT TIME TIMESTAMP TINYINT VARBINARY VARCHAR hrs.

lookup(DATASOURCE_NAME).sql. javax.lookup("java:comp/env").JDBC automatically participate in connection pooling.servlet.*.produces a Connection object that may be used for distributed transactions and almost always participates in connection pooling.naming.*.getName()).*. private final static String DATASOURCE_NAME = "jdbc/ccards". import import import import import import java. } public void init() throws ServletException { if (theDataSource == null) { try { Context env = (Context) new InitialContext(). This implementation works with a middletier connection pooling manager.servlets.sql. javax.servlet.*.*.ccards. 104 . Main methods: public Connection getConnection() throws SQLException public Connection getConnection(String user. throws public class TestDataSource extends HttpServlet { private final static Logger log = Logger.io.class.http.*. private DataSource theDataSource. Distributed transaction implementation -.getLogger(TestDataSource. } public DataSource getDataSource() { return theDataSource. public void setDataSource(DataSource dataSource) { theDataSource = dataSource. theDataSource = (DataSource) env.bank11. This implementation works with a middle-tier transaction manager and almost always with a connection pooling manager. javax. java.10 . 3. String pwd) SQLException A servlet example using the DataSource interface: package com. javax.

} catch (NamingException e) { throw new ServletException(e)..JDBC if (theDataSource == null) throw new ServletException("`" + DATASOURCE_NAME + "' is an unknown DataSource"). } } } public void doGet(HttpServletRequest request. ServletException { .10 .. HttpServletResponse response) throws IOException. } } 105 .

The package javax.JSP 11 .jsp.HttpJspPage interface has a single method: public void jspService(HttpServletRequest req. The JspPage interface is the interface that a JSP processor-generated class must satisfy. namely javax. JSR 245 is the official document containing the current specification of JSP.servlet. classes and exceptions are part of two packages.jsp.servlet.servlet.servlet. If the JSP is modified. A JSP is loaded by a JSP container and is converted (to servlet code).servlet. IOException The implementation of this method is generated by the web container – never by the developer.servlet.5 Java Servlet specification.11 .JSP 11. The javax. The JSP specific interfaces.2 the java.JspPage interface This interface has 2 methods: public void jspInit() public void jspDestroy() The javax. The package javax. HttpServletResponse resp) throws ServletException. 11.1 and is related to the 2. The interface HttpJspPage is the interface that a JSP processor-generated class for the HTTP protocol must satisfy. The current JSP specification is JSP 2.tagext contains classes and interfaces for the definition of JavaServer Pages Tag Libraries.tagext.3 the generated servlet – an example 106 .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. the servlet code is regenerated.jsp and javax.jsp.jsp defines two interfaces – JspPage and HttpJspPage.servlet. 11.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.

11 - JSP
Even if we start with a very benign java server page, like the listed “hello world” example below, the generated servlet is still pretty complex. First, the original index.jsp file. <%-Document : index Created on : 08.11.2010, 08:17:39 Author : sm --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> </body> </html> The generated servlet follows. package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.Vector _jspx_dependants; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public Object getDependants() {

107

11 - JSP
return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("X-Powered-By", "JSP/2.1"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n"); out.write(" \"http://www.w3.org/TR/html4/loose.dtd\">\n"); out.write("\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); out.write(" <title>JSP Page</title>\n"); out.write(" </head>\n"); out.write(" <body>\n"); out.write(" <h1>Hello World!</h1>\n"); out.write(" </body>\n"); out.write("</html>\n");

108

11 - JSP
} catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } } A short comment. The class HttpJspBase is a vendor-implemented class, whose declaration clarifies its relationship with the standard JSP classes and interfaces. public abstract class HttpJspBase extends javax.servlet.http.HttpServlet implements javax.servlet.jsp.HttpJspPage

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

• • • •

Here is a typical example of a java bean. /* * NewBean.java */ import java.beans.*; import java.io.Serializable; /** * @author sm */ public class NewBean extends Object implements Serializable {

109

11 - JSP
public static final String PROP_SAMPLE_PROPERTY = "sampleProperty"; private String sampleProperty; private PropertyChangeSupport propertySupport; public NewBean() { propertySupport = new PropertyChangeSupport(this); } public String getSampleProperty() { return sampleProperty; } public void setSampleProperty(String value) { String oldValue = sampleProperty; sampleProperty = value; propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY, oldValue, sampleProperty); } public void addPropertyChangeListener(PropertyChangeListener listener) { propertySupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertySupport.removePropertyChangeListener(listener); } }

11.5 jsp tags
There are 3 categories of JSP tags (elements): 1. directives – affect the structure of the whole jsp 2. scripting elements – java code inserted in the JSP page 3. actions – special tags affecting the run time behaviour of the JSP Rules for JSP tags:
• •

attribute values are always quoted (single or double quotes) URLs follow the servlet conventions

110

It has the following format: <%@taglib uri="tagLibUri" prefix="tagPrefix" %> where the tagPrefix indicates a name scope. 111 . The format of this directive: <%@include file="fileName" %> The taglib directive allows the usage of custom tags (tag extensions). include and taglib. it is interpreted relative to the position of the current JSP 11...11 .6 jsp directives The JSP directives are messages sent by the Java Server Page to the JSP container. 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.JSP • if the URL does not start with / .. attrn="valn" %> Ther are three JSP directives: page.. 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 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. The general format of a JSP directive is as follows: <%@directive_name attr1="val1" . The page directive format: <%@page attr1="val1" .

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

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

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

the path of the JSP file that calls <jsp:plugin> is used. You must include the . as this attribute has no default value. .class extension in the name following code.a comma-separated list of paths that locate archive files • • • 115 . servlet or to a static resource. codebase="classFileDirectoryName" . followed by the execution of the applet or JavaBeans component specified by the tag. If you do not supply a value. 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: • • • . as well. The filename is relative to the directory named in the codebase attribute.the name of the Java class file that the plugin will execute. name . depending on request. code="classFileName" . which makes it possible for applets or Beans called by the same JSP file to communicate with each other..JSP <jsp:forward> Used to forward the the request to another JSP. name="instanceName" ... archive="URIToArchive. It is used mainly. when we want to separate the application into different views. 11.11 .the name of a bean instance.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). You must specify either bean or applet. already defined in a <jsp:useBean> type="bean|applet" .the absolute or relative path to the directory that contains the applet's code.the type of object the plugin will execute.. The syntax for this action is: <jsp:forward page="pageURL" /> The action may include several <jsp:param> tags.." .a name for the Bean or applet instance.

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

bank11. the object can be accessed by invoking the getValue() method on the implicit session object. session .JSP request object. Object value) method 2. Object value) method 4.an object with application scope is bound to the ServletContext object.invalidAcct()) { %> <jsp:forward page="retry. the generated servlet binds the object to HttpSession object using the setAttribute(String key. page .ccards. the object can be accessed by invoking the getAttribute() method on the implicit application object.jsp"> <jsp:param name="resolution" value="userExists"/> </jsp:forward> 117 .jsp"%> <jsp:useBean id="enrollBean" scope="session" class="com. application . the object can be accessed by invoking the getAttribute() method on the implicit pageContext object.beans.11 . <%@page contentType="text/html" errorPage="error.init(). Object value) method 3. the generated servlet binds the object to the ServletContext object using the setAttribute(String key.jsp"> <jsp:param name="resolution" value="invalidAcct"/> </jsp:forward> <% } else if (enrollBean. the generated servlet binds the object to HttpServletRequest object using the setAttribute(String key.userExists()) { %> <jsp:forward page="retry. if (enrollBean. the generated servlet binds the object to PageContext object using the setAttribute(String key.jsp file.jsp"> <jsp:param name="resolution" value="registeredAcct"/> </jsp:forward> <% } else if (enrollBean. Object value) method 11.17 a short example The following is the Enroll.an object with session scope is bound to the HttpSession object.EnrollBean" /> <jsp:setProperty name="enrollBean" property="*" /> <% enrollBean.an object with page scope is bound to the PageContext object.registeredAcct()) { %> <jsp:forward page="response.

mapping.18. private String optional. since the Java compiler generates one in the absence of any other constructors.jsp"> <jsp:param name="resolution" value="userEnrolled"/> </jsp:forward> <% } %> 11. // No-arg constructor public SimpleBean() { } // Gets the string property public String getString() { return this. an int.18 an extended example This example is provided by Devsphere.devsphere. SimpleBean. private boolean flag.examples. The public constructor could have been omitted. a software development and consulting company. has a no-arg constructor and provides accessors (get & set methods) for its properties. The SimpleBean class is declared public. a float.io. // Simple bean public class SimpleBean implements java. a boolean and another String). private int integer.11 . private SimpleSubBean subBean.Serializable { private String string.java: package com.JSP <% } else { enrollBean. } // Sets the string property public void setString(String value) { 118 . private int list[].simple. 11. private float number. %> <jsp:forward page="response. private String colors[].string.1 Data beans SimpleBean is a Java bean that contains several standard properties (a String.register(). two indexed standard properties (a String[] and an int[]) and another data bean (a SimpleSubBean).

} // Sets the flag property public void setFlag(boolean value) { this.flag = value. } // Sets the number property public void setNumber(float value) { this.JSP this. } // Sets the integer property public void setInteger(int value) { this.integer. } // Gets an element of the colors property public String getColors(int index) { return this.number.string = value. } // Gets the integer property public int getInteger() { return this. } // Gets the colors property public String[] getColors() { return this. } // Gets the flag property public boolean getFlag() { return this.integer = value.11 .colors.flag.colors = values. } // Gets the number property public float getNumber() { return this.colors[index]. } // Sets the colors property public void setColors(String values[]) { this.number = value. } 119 .

list[index] = value. } // Sets the optional property public void setOptional(String value) { this.11 .subBean = value. } // Gets the subBean property public SimpleSubBean getSubBean() { return this. String value) { this. } } 120 .subBean.list[index]. } // Sets the list property public void setList(int values[]) { this.JSP // Sets an element of the colors property public void setColors(int index. } // Gets the optional property public String getOptional() { return this.colors[index] = value. } // Gets the list property public int[] getList() { return this. } // Gets an element of the list property public int getList(int index) { return this.list = values. } // Sets the subBean property public void setSubBean(SimpleSubBean value) { this. int value) { this. } // Sets an element of the list property public void setList(int index.list.optional = value.optional.

Serializable { private String string.string.io.18.2 the HTML Form The properties of SimpleBean are mapped to the form elements of SimpleForm. } // Sets the number property public void setNumber(float value) { this.java: package com.JSP SimpleSubBean contains only two standard properties (a String and a float).string = value.11 . } // Gets the number property public float getNumber() { return this.devsphere.html: Name string number integer flag Property type String float int boolean Element type text text radio[] checkbox 121 . SimpleSubBean. } // Sets the string property public void setString(String value) { this.number = value. } } 11.mapping. // Simple sub-bean public class SimpleSubBean implements java.simple.examples. // No-arg constructor public SimpleSubBean() { } // Gets the string property public String getString() { return this.number. private float number.

11 .html: <HTML> <HEAD><TITLE>Simple form</TITLE></HEAD> <BODY> <H3>Simple Example</H3> <FORM METHOD="POST"> <P> String <BR> <INPUT TYPE="TEXT" NAME="string" SIZE="20"> <P> Number <BR> <INPUT TYPE="TEXT" NAME="number" SIZE="20"> <P> Integer <BR> <INPUT TYPE="RADIO" NAME="integer" VALUE="1">Option 1 <INPUT TYPE="RADIO" NAME="integer" VALUE="2">Option 2 <INPUT TYPE="RADIO" NAME="integer" VALUE="3">Option 3 <P> Flag <BR> <INPUT TYPE="CHECKBOX" NAME="flag">Flag <P> Colors <BR> <INPUT TYPE="CHECKBOX" NAME="colors" VALUE="red">Red <INPUT TYPE="CHECKBOX" NAME="colors" VALUE="green">Green <INPUT TYPE="CHECKBOX" NAME="colors" VALUE="blue">Blue <P> List <BR> <SELECT NAME="list" SIZE="3" MULTIPLE> <OPTION VALUE="1">Item 1</OPTION> <OPTION VALUE="2">Item 2</OPTION> <OPTION VALUE="3">Item 3</OPTION> </SELECT> <P> Optional <BR> <INPUT TYPE="TEXT" NAME="optional" SIZE="20"> String[] int[] String String float checkbox[] select text text text 122 .JSP colors list optional subBean.number SimpleForm.string subBean.

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

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

slashIndex+1) : "". simpleBean.Hashtable errorTable = FormUtils.getRealPath(formPath).lastIndexOf('/').substring(0.getTemplate(new java. // Process the valid data bean instance application.getMethod(). // Construct the form's path String formPath = basePath + beanRes. errorTable = HandlerUtils. // Get a new document FormDocument document = template. 125 .equals("POST"). logger).getRequestDispatcher(procPath).removeUserErrors(errorTable). // Wrap the form data FormData formData = new ServletFormData(request).File(formPath)).trim().getString("[FORM_NAME]").io.forward(request. formPath = application. response).getClass()).util. basePath = slashIndex != -1 ? basePath. // Get the form template FormTemplate template = FormUtils. // Construct the base path String basePath = request.JSP = HandlerUtils. // Create a logger that wraps the servlet context ServletLogger logger = new ServletLogger(application). if (isPostMethod && errorTable == null) { // Construct the processor's path String procPath = basePath + beanRes. } else { if (!isPostMethod) // Ignore the user errors if the form is requested with GET.trim().formToBean(formData.getServletPath(). // Determine the HTTP method boolean isPostMethod = request.getDocument(). int slashIndex = basePath.getBeanResources(simpleBean.getString("[PROC_NAME]").11 . // Form-to-bean mapping: request parameters are mapped to bean properties java.

11 . } %> 11. // Send the form document document.string = <%= simpleBean.getString() %> <P> subBean.jsp processor gets the beans that were validated by the JSP handler and prints the values of their properties.getList()) %> <P> optional = <jsp:getProperty name="simpleBean" property="optional"/> <P> subBean. i++) 126 .length == 1 && list[0] != null) return list[0]. i < list.mapping. strbuf.examples. errorTable. // Bean-to-form mapping: bean properties are mapped to form FormUtils. document.length == 0) return "".beanToForm(simpleBean. SimpleProc.getNumber() %> </BODY> </HTML> <%! public static String toString(String list[]) { if (list == null || list.getSubBean().5 JSP Processor The SimpleProc.getColors()) %> <P> list = <%= toString(simpleBean. StringBuffer strbuf = new StringBuffer().getSubBean().jsp: <%@ page language="java"%> <jsp:useBean id="simpleBean" scope="request" class="com.length.append("{ "). for (int i = 0.number = <%= simpleBean.simple.SimpleBean"/> <HTML> <HEAD><TITLE>Simple bean</TITLE></HEAD> <BODY> <H3>Simple Example</H3> <P><B> SimpleBean properties: </B> <P> string = <jsp:getProperty name="simpleBean" property="string"/> <P> number = <jsp:getProperty name="simpleBean" property="number"/> <P> integer = <jsp:getProperty name="simpleBean" property="integer"/> <P> flag = <jsp:getProperty name="simpleBean" property="flag"/> <P> colors = <%= toString(simpleBean.JSP elements logger).devsphere.18. if (list.send(out).

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

i++) { int value = i+1.equals(colorValues[i])) { checked = true. %> <INPUT TYPE="RADIO" NAME="integer" VALUE="<%= value %>" <%= checked ? "CHECKED" : "" %>> <%= integerLabels[i] %> <% } %> <P> Flag <BR> <%= getErrorMessage(errorTable. i < colorValues.getInteger() == value. "Green". "integer") %> <% String integerLabels[] = { "Option 1". 128 . "string") %> <INPUT TYPE="TEXT" NAME="string" VALUE="<jsp:getProperty name="simpleBean" property="string"/>"> <P> Number <BR> <%= getErrorMessage(errorTable. j++) if (colors[j]. "blue" }. boolean checked = simpleBean. if (colors != null) for (int j = 0.getFlag() ? "CHECKED" : "" %>> Flag <P> Colors <BR> <%= getErrorMessage(errorTable.length. "Option 2". "colors") %> <% String colors[] = simpleBean.length. String colorValues[] = { "red". j < colors. "Blue" }. "green". "Option 3" }. if (colors == null) colors = new String[0]. for (int i = 0.11 . "flag") %> <INPUT TYPE="CHECKBOX" NAME="flag" <%= simpleBean. i < integerLabels.JSP <BODY> <H3>Equivalent of Simple Example</H3> <FORM METHOD=POST> <P> String <BR> <%= getErrorMessage(errorTable. for (int i = 0. "number") %> <INPUT TYPE="TEXT" NAME="number" VALUE="<jsp:getProperty name="simpleBean" property="number"/>"> <P> Integer <BR> <%= getErrorMessage(errorTable.getColors(). String colorLabels[] = { "Red".length. i++) { boolean checked = false.

break.string") %> <INPUT TYPE="TEXT" NAME="subBean.getSubBean(). "Item 2".11 .getList(). String listItems[] = { "Item 1". j < list. i < listItems.string" VALUE="<%= simpleBean. i++) { int value = i+1.getString() %>"> <INPUT TYPE="CHECKBOX" NAME="colors" VALUE="<%= colorValues[i] <%= checked ? "CHECKED" : "" %>> <%= colorLabels[i] %> 129 . "list") %> <SELECT NAME="list" SIZE="3" MULTIPLE> <% int list[] = simpleBean. "optional") %> <INPUT TYPE="TEXT" NAME="optional" VALUE="<jsp:getProperty name="simpleBean" property="optional"/>"> <% if (simpleBean.SimpleSubBean()). for (int i = 0.setSubBean( new com. if (list != null) for (int j = 0. } %> %>" <% } %> <P> List <BR> <%= getErrorMessage(errorTable. } %> <OPTION VALUE = "<%= value %>" <%= selected ? "SELECTED" : "" %>> <%= listItems[i] %> <% } %> </SELECT> <P> Optional <BR> <%= getErrorMessage(errorTable. boolean selected = false. "Item 3" }.simple.length.devsphere. j++) if (list[j] == value) { selected = true. %> <P> String (subBean) <BR> <%= getErrorMessage(errorTable.length.JSP break.examples.mapping. if (list == null) list = new int[0].getSubBean() == null) simpleBean. "subBean.

SimpleBean"/> <jsp:useBean id="simpleSubBean" scope="page" class="com.getMethod().devsphere.jsp: <%@ page language="java" %> <jsp:useBean id="simpleBean" scope="request" class="com. String property) { String message = (String) errorTable.setString("abc").number") %> <INPUT TYPE="TEXT" NAME="subBean. } %> ComplexHndl.SimpleSubBean"/> <jsp:useBean id="errorTable" scope="request" class="java.getSubBean().11 .mapping.equals("POST"). return message.JSP <P> Number (subBean) <BR> <%= getErrorMessage(errorTable.length() == 0) { simpleBean.util.getString().getString() == null || simpleBean.Hashtable errorTable.number" VALUE="<%= simpleBean. "subBean. boolean isPostMethod = request. if (message == null) message = "".get(property).simple.examples.mapping.util.devsphere. if (isPostMethod) { //* string : text %> <jsp:setProperty name="simpleBean" property="string"/> <% if (simpleBean. 130 .getNumber() %>"> <P> <INPUT TYPE="SUBMIT" VALUE="Submit"> <INPUT TYPE="RESET" VALUE="Reset"> </FORM> </BODY> </HTML> <%! String getErrorMessage(java.setSubBean(simpleSubBean).examples.simple.Hashtable"/> <% simpleBean.

"Must be filled"). "number".getParameter("number"). if (numberValue != null && numberValue.JSP setErrorMessage(errorTable. "number".getColors().setNumber(new Float(numberValue).getInteger() == 0) { setErrorMessage(errorTable. } //* flag : checkbox String flagValue = request. } } catch (NumberFormatException e) { simpleBean. if (flagValue. } //* integer : radio group %> <jsp:setProperty name="simpleBean" property="integer"/> <% if (simpleBean.floatValue()). "integer". } //* number : text try { String numberValue = request.setNumber(0.getParameter("flag").123f).11 . "string".setNumber(0.length == 0) { 131 . if (flagValue != null) { flagValue = flagValue. } simpleBean.length() != 0) simpleBean.123f).setFlag(flagValue != null). setErrorMessage(errorTable.length() == 0 || flagValue.trim().getColors() == null || simpleBean. "An option must be selected").equals("false")) flagValue = null. "Must be a number"). else { simpleBean. setErrorMessage(errorTable. "Must be filled"). //* color : checkbox group %> <jsp:setProperty name="simpleBean" property="colors"/> <% if (simpleBean.

getString(). "Must be filled"). } //* list : select %> <jsp:setProperty name="simpleBean" property="list"/> <% if (simpleBean. "colors".string : text %> <jsp:setProperty name="simpleSubBean" property="string" param="subBean.11 .setOptional(""). 3 }).number : text try { String numberValue = request.length() == 0) { simpleSubBean. setErrorMessage(errorTable.number". "One or more colors must be selected").setString("").number").string"/> <% if (simpleSubBean. setErrorMessage(errorTable. //* subBean. "subBean. else { setErrorMessage(errorTable.getList(). "list". "subBean. "Must be } //* subBean. if (numberValue != null && numberValue.length() != 0) simpleSubBean.setList(new int[] { 2.floatValue()). } //* optional : text %> <jsp:setProperty name="simpleBean" property="optional"/> <% if (simpleBean. "One or more items must be selected").length == 0) { simpleBean.getOptional() == null) simpleBean.string". 132 .getParameter("subBean.setNumber(new Float(numberValue).getString() == null || simpleSubBean.JSP setErrorMessage(errorTable.getList() == null || simpleBean.

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

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

11 .JSP 135 .

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

The HTML tags can be grouped in the following categories: • • • • • • • inputs outputs commands selections layouts data table errors and messages 12. here is an exhaustive list of the JSF HTML tags: • • • • • • • • • • • • • column commandButton commandLink dataTable form graphicImage inputHidden inputSecret inputText inputTextArea message messages outputFormat 137 . 12. there are 25 HTML JSF tags. As of version 1. 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.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 .javaserver faces 12.1 the list of JSF HTML Tags For reference.2 of the JFS specification.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. Facelets can make changes to pages immediately so developing JSF applications with Facelets is simply faster.

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

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.00</td></tr> <tr><td>Juicy Orange</td><td>$5. 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.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. Example: <h:form id="form1"></h:form> HTML Output <form id="form1" name="form1" method="post" action="/demo/form.00</td></tr> </tbody> <tfoot> <tr><td colspan="2">Total: $15. The display value of the button can also be obtained from a message bundle to support internationalization (I18N). and using the outputLink tag to generate dynamic hyperlinks.checkoutLabel}" action="#{shoppingCartBean. If your application requires the use of the GET method for form submission.javaserver faces </f:facet> <h:outputText value="#{item. your options include using plain HTML forms.checkout}" /> 139 .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. Example: <h:commandButton id="button1" value="#{bundle.00</td></tr> </tfoot> </table> 12.12 .4.price}" /> </h:column> <f:facet name="footer"> <h:outputText value="Total: #{shoppingCartBean.00</td></tr> <tr><td>Tasty Melon</td><td>$5. binding request parameters to backing bean properties.jsp" enctype="application/x-www-form-urlencoded"></form> 12.

javaserver faces HTML Output <input id="form:button1" name="form:button1" type="submit" value="Check Out" onclick="someEvent().5 the core JSF tags The core JavaServer Faces tags define custom actions that are independent of any particular RenderKit.6 message Tag The message tag renders a message for a specific component. green for information) as well as the detail level of the message itself.user.</span> 12.username}" errorStyle="color:red"/> <h:message for="username" /> HTML Output <input type="text" id="form:username" name="form:username" value=""/> <span style="color:red">"username": Value is required. 12.username}" /> HTML Output <input id="form:username" name="form:username" type="text" /> 12.5 h:inputText The inputText tag renders an HTML input element of the type "text".12 .4.5." /> 12. red for error. Example: <h:inputText id="username" required="#{true}" value="#{userBean.1 the list of JSF Core Tags Here is an exhaustive list of the JSF core tags: • • • • • • actionListener attribute convertDateTime converter convertNumber facet 140 . You can customize the message generated by this component by applying different CSS styles to the message depending on its severity (eg.4. Example: <h:inputText id="username" value="#{userBean.user. You can also customize the standard error messages by overriding specific JSF properties in your message bundle.

12.javaserver faces • • • • • • • • • • • • loadBundle param selectItem selectItems subview validateDoubleRange validateLength validateLongRange validator valueChangeListener verbatim view Some of these tags will be detailed in the next paragraphs. you can create a header and a footer facet for a dataTable component. For example.dailyReport}" var="item"> <h:column> <f:facet name="header"> <h:outputText value="Daily Report" /> </f:facet> <h:outputText value="#{item}" /> </h:column> </h:dataTable> HTML Output <table id="reportTable"> <thead> <tr><th>Daily Report</th></tr> </thead> <tbody> <tr><td>Item 1</td></tr> <tr><td>Item 2</td></tr> <tr><td>Item 3</td></tr> </tbody> </table> 141 .12 . Example: <h:dataTable id="reportTable" value="#{reportBean.5. The Facet tag registers a named facet on the component associated with the enclosing tag.2 f:facet A facet represents a named section within a container component The JSF facets specify the requirements and constraints that apply to a JSF project.

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

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

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

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

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

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

prompt}"/> 3 <h:inputText value="#{personBean.inputname_header}" required=”true”> This tag simply tells us to look in the resource bundle that we defined at the top of the page. Then.personName}" required=”true”> <f:validateLength minimum="2" maximum="10"/> </h:inputText> <h:commandButton action="greeting" value="#{msg. <%@ taglib uri="http://java.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java. The third line loads our properties file (resource bundle) that holds messages that we want to display in our JSP page. let's explain the important sections in this file after displaying the code for each section starting from the top.bundle.button_text}" /> 7 </h:form> 148 .inputname_header}"/> </h1> <h:form id="helloForm"> <h:outputText value="#{msg.javaserver faces <f:loadBundle basename="myJFSapp. 1 <h:form id="helloForm"> 2 <h:outputText value="#{msg. The required attribute of the h:inputText tag insures that an empty name will not be sent.12 .prompt}"/> <h:inputText value="#{personBean.sun.bundle.sun. look up the value for inputname_header in that file and print it here.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. <h:inputText value="#{msg.button_text}" /> </h:form> </f:view> </body> </html> Now.personName}" required=”true”> 4 <f:validateLength minimum="2" maximum="10"/> 5 </h:inputText> 6 <h:commandButton action="greeting" value="#{msg.com/jsf/core" prefix="f" %> <f:loadBundle basename="myJFSapp. 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.

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

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

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

pages 12. for scope select 152 .equalsIgnoreCase("foo") && _pwd.8. 2. if ( _uid.LoginManager. The faces-config. for name enter mgr. In the Package field. click Managed Bean. else action = "loginFail". } void setPassword(String pwd) { _pwd = pwd.3 Creating & Configuring Managed Beans Here we create a class called LoginManager which will be used as a backing bean for the login process. We then configure it to be a managed bean. } void setUserID(String uid) { _uid = uid. from its context menu select New/Class.javaserver faces | | | +-. Click Finish.classes (not shown in Java perspective) | | | +-. } return action.12 . private String _pwd = "".java package login. } String getPassword() { return _pwd.xml editor opens.xml Editor. In Package Explorer select the src folder. Enter and save the following code for the LoginManager class: // LoginManager. The Java code editor opens.xml. for class enter login. c.lib | +-. public class LoginManager { private String _uid = "". 1. in the Name field enter LoginManager.equalsIgnoreCase("bar") ) action = "loginPass". along the bottom of the editor there are 3 tabs. public public public public String getUserID() { return _uid. } 4. click Add. enter login. from its context menu select Open With/faces-config. 3. Use FacesIDE to configure the bean: we use a FacesIDE editor to configure LoginManager as a session-scoped managed bean. in Package Explorer select jsf-login/webroot/WEB-INF/facesconfig. input widgets appear d. } public String loginAction() { String action = null. b. a. The New Java Class wizard appears.

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

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

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

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

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

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

. for Context path enter /jsf-login..model javax. scroll down to Deploy. for WAR or Directory URL enter the path to webroot.. a corresponding implementation class is searched for based on the following algorithm.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.faces.component javax.faces.faces.webapp 12.12 .faces.7 Deploying To Tomcat 5.faces. leave XML Configuration File URL blank.lifecycle javax. as file:///. that factory is used. the Manager application should reload.0 1. we'll deploy our app by providing its directory.10 the javax.9 packges in the JavaServer Faces API The classes and interfaces of the JavaServer Faces API are grouped in several packages.faces.validator javax.faces. click Deploy 3.context javax.application javax.html javax.faces. 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. the default URL for this is http://localhost:8080/manager/html 2. 12.faces. Click on its link to launch the application.faces.faces. namely: • • • • • • • • • • • • • javax.convert javax.faces javax.el javax.CONFIG_FILES 159 . For a given factory class name.8. start Tomcat.render javax.faces.javaserver faces 12.event javax.component. If the JavaServer Faces configuration files named by the javax. and you should see /jsf-login in the list of running applications.faces. open its Manager application in a browser.

StateManager . and supporting internationalization and accessibility. as well as alternative strategies for saving and restoring the state of each view. ApplicationFactory . which is typically associated with a particular component in the view.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. Implementations of JavaServer Faces must provide at least a default implementation of Application. with the last one taking precedence. FacesMessage .javaserver faces ServletContext init parameter contain any factory entries of the given factory class name.a factory object that creates (if needed) and returns Application instances. those factories are used.Severity . the factory entries of the given factory class name in those files are used. • If there are any JavaServer Faces configuration files bundled into the META-INF directory of any jars on the ServletContext's resource paths. • • public class FacesException extends RuntimeException This class encapsulates general JavaServer Faces exceptions. 12.faces. This allows for implementations to support different response generation technologies. ViewHandlerWrapper . A FacesMessage instance may be created based on a specific messageId.represents a single validation (or other) message. the JavaServer Faces implementation specific class is used. its first line is read and assumed to be the name of the factory implementation class to use. FacesMessage. and will use this (along with related state information) to choose the view to be displayed next.11 the javax.Provides a simple implementation of ViewHandler that can be • • • • • • • • 160 . ViewHandler .used to represent message severity levels in a typesafe enumeration. NavigationHandler – An object of this type is passed the outcome string returned by an application action invoked for this application. If none of the above steps yield a match.A set of APIs for representing UI components and managing their state. with the last one taking precedence. StateManagerWrapper .directs the process of saving and restoring the view between requests. handling events and input validation. defining page navigation. The default implementation of all methods is to call through to the wrapped StateManager.12 .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. 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).

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

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

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

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

16 the java. 12. • • • • 165 . Classes: MethodBinding .represents a pluggable mechanism for accessing a "property" of an underlying Java object instance. ValueBinding . to indicate that the requested conversion cannot be performed. 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 . on an instance that is acquired by evaluatng the leading portion of a method binding expression via a ValueBinding.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 . PropertyResolver .represents a pluggable mechanism for resolving a top-level variable reference at evaluation time. VariableResolver .el package Contains classes and interfaces for evaluating and processing reference expressions.javaserver faces 12.an exception thrown by the getAsObject() or getAsText() method of a Converter.an object that can be used to access the property represented by an action or value binding expression.15.an object that can be used to call an arbitrary public method.faces.

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

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

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

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

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

skipping any remaining phases. For example. 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. if errors occur during any of the phases. 171 .12 . the flow of execution can exit the life cycle without completing further phases.javaserver faces In the above figure. the flow of execution transfers immediately to the Render Response phase. If data fails validation in either the Apply Request Values or Process Validations phase. you can see a number of optional paths through the life cycle. 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. Also.

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

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

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

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

emerging.2 the directory as an object store In addition to using the directory in the traditional way. 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.1 architecture The JNDI architecture consists of an API and a service provider interface (SPI).naming javax. 13. The Java 2 SDK. 13. For example. you must first download the JNDI classes and one or more service providers. Java applications can also use it as a repository for Java objects. 13. you must have the JNDI classes and one or more service providers.naming. thereby allowing the Java application using the JNDI API to access their services. The JNDI is divided into five packages: • • • • javax. The SPI enables a variety of naming and directory services to be plugged in transparently. v1.2.13 . It extends the v1.event javax.2 platforms to provide naming and directory functionality.2 packaging The JNDI is included in the Java 2 SDK. It is defined to be independent of any specific directory service implementation. For example.2.1 and the Java 2 SDK.JNDI Applications can share the common infrastructure provided by the directory. Thus a variety of directories--new. v1.1 and Java 2 SDK. This sharing makes applications that are deployed across the system.1 and v1.5. that is to store and retrieve Java objects. To use the JNDI.naming.ldap 176 . Java applications use the JNDI API to access a variety of naming and directory services.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. and already deployed--can be accessed in a common way. 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. It is also available as a Java Standard Extension for use with the JDK 1.directory javax. v1.5. and even the network. v1. more coherent and manageable.naming.3 and later releases.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.4. 13. When using the JNDI as a Standard Extension on the JDK 1.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

called MyBeanHome: package myBeans.RemoteException.javax.javax. the EJBObject declares the following ones: public EJBHome getEJBHome() throws RemoteException public Object getPrimaryKey() throws RemoteException public Handle getHandle() throws RemoteException public boolean isIdentical(EJBObject obj) throws RemoteException public void remove() throws RemoteException. import.ejb.ENTERPRISE JAVA BEANS Code example for the a home interface. RemoteException.rmi. String lastName. } 193 . import.*.*. int custId) throws RemoteException. import java.15 . } 15.ejb.rmi. void deleteEntry(int custId) throws RemoteException. While the Remote interface declares no methods. import java. public interface MyBeanHome extends EJBHome { MyBeanObject create() throws CreateException.5 the remote interface The remote interface of a bean is a standard Java interface that extends the EJBObject and Remote interfaces and declares the business logic methods of the bean.RemoteException. The developer does not implement this interface. public interface MyBeanObject extends EJBObject { // assume that we have two business logic methods void processEntry(String firstName. RemoveException Code example for a remote interface called MyBeanObject: package myBeans.

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

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

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

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

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

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

Update and Delete.15 . in the same order. Read. On the other side.lang. all throwing RemoteException.14. state data is stored into data store (usually. when a client calls create() on an entity bean's home interface.14 mandatory callbacks for entity beans Besides the CRUD callbacks which are discusses later in this section. 200 . This is transactional data that is accessible to multiple clients. as the parameters in the original create() method. 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. methods which have the same parameters. the field is specified: <prim-key-field>sportsTeamID</prim-key-field> 15.CustomerID</prim-key-class> or <prim-key-class>java. Each create() method from the Home interface of the bean has 2 correspondent methods in the bean implementation class. a Database) (we actually insert a record in a database).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. We can have more create() methods.String</prim-key-class> In the case of CMP using a simple type as primary key. These methods are mandatory for entity beans. an instance of that bean is created.ccards.bank11.1 create When a client calls a create() method on a session bean's home interface. 15. CreateException. namely ejbCreate() and ejbPostCreate().

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

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

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

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

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

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. For EJBs that use bean-managed transactions. WebLogic Server includes the message receipt as part of the bean's transaction only if the bean's transaction attribute is set to Required. as described in the EJB 2. 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.13 message acknowledgment For message-driven beans that use container-managed transaction demarcation. beans that use container-managed transactions must be deployed using the Required or NotSupported transaction attribute in ejb-jar.0 specification.16.0 specification adds the following new XML deployment elements for deploying 206 .xml.14 deployment elements The EJB 2. If the EJB uses bean-managed transactions.ENTERPRISE JAVA BEANS manage transactions (container-managed transactions). both the receipt and the acknowledgment of a message occur outside of the EJB transaction context.16. For EJBs that use container-managed transaction demarcation. you edit the XML file to create the deployment descriptors that associate the EJB with a configured JMS destination. a message-driven bean does not receive a transaction context from the client that sends a message. but the deployer can configure acknowledgment semantics using the jms-acknowledge-mode deployment parameter.15 . Transaction attributes are defined in ejb-jar.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.0 specification.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. Because no client provides a transaction context for calls to a message-driven bean. 15. WebLogic Server automatically acknowledges a message when the EJB transaction commits. as required by the EJB 2. WebLogic Server automatically acknowledges messages for EJBs with bean-managed transactions. Deploying Message-Driven Beans in WebLogic Server To deploy a message-driven bean on WebLogic Server. In either case.

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

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

ccards.ejb.ccards.15 .ejb.bank11.Account</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.ccards.bank11.ccards.ejb.Accountbject</remote> <ejb-class>com.bank11.ccards.bank11.ccards.CCEnrollObject</remote> <ejb-class>com.lang.AccountHome</home> <remote>com.bank11.Integer</prim-key-class> <reentrant>False</reentrant> <cmp-field> <field-name>accountNumber</field-name> 209 .AccountObj</remote> </ejb-ref> <security-role-ref> <description> This role relates to cash advances from ATMs </description> <role-name>CashAdvATM</role-name> <security-role-ref> </session> <entity> <ejb-name>Account</ejb-name> <home>com.ejb.bank11.AccountHome</home> <remote>com. here is how the deployment descriptor may look like: <?xnm version="1.bank11.CCEnrollHome</home> <remote>com.1"?> <ejb-jar> <entrprise-beans> <session> <ejb-name>CCEnroll</ejb-name> <home>com.ENTERPRISE JAVA BEANS Keeping in mind that the application assembler is to follow.ccards.ccards.CCEnroll</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container<transaction-type> <ejb-ref> <ejb-ref-name>ejb/CCAccount</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <home>com.bank11.

Float</env-entry-type> <env-entry-value>2.lang. Here is a very lean one: </ejb-jar> <enterprise-beans> . </enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>CCEnroll</ejb-name> <method-name>*</method-name> </method> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar> 210 .5</env-entry-value> </env-entry> </entity> </enterprise-beans> </ejb-jar> The assembly descriptor combines EJBs into a deployable application.ENTERPRISE JAVA BEANS </cmp-field> <cmp-field> <field-name>userName</field-name> </cmp-field> <cmp-field> <field-name>customerID</field-name> </cmp-field> <cmp-field> <prim-key-field>accountNumber</prim-key-field> </cmp-field> <env-entry> <env-entry-name>env/minPaymentPerc</env-entry-name> <env-entry-type>java..15 ..

15 .ENTERPRISE JAVA BEANS 211 .

Sign up to vote on this title
UsefulNot useful