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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 .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 -.-_:" GENERAL YES ENTITY NO DELIM GENERAL SGMLREF SHORTREF SGMLREF NAMES SGMLREF QUANTITY SGMLREF ATTCNT 60 -.permitted in the declaration NAMELEN 65536 -.-_:" ".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 "" "" ".These are the largest values LITLEN 65536 -.increased -ATTSPLEN 65536 -.3 .Avoid fixed limits in actual PILEN 65536 -.

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

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

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

The <FORM> element has the following attributes: • ACTION .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.required.3 . specifies the URL of the server side process that will receive the data 28 . allowing user input and parameter submittal.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5 . searching backwards from the specified position in a string Displays a string as a hyperlink Searches for a specified value in a string Replaces some characters with some other characters in a string Searches a string for a specified value Extracts a part of a string and returns the extracted part in a new string Displays a string in a small font Splits a string into an array of strings Displays a string with a strikethrough Displays a string as subscript Extracts a specified number of characters in a string. IE: Internet Explorer Property constructor prototype Methods Method Date() Description Returns today's date and time F F 1 N 2 I E 3 Description Returns a reference to the Date function that created the object Allows you to add properties and methods to the object F F 1 1 N 4 3 I E 4 4 47 . 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. N: Netscape.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.11.2 the Date object The JavaScript Date object is used to work with dates and times.

Use getFullYear() instead !! Takes a date string and returns the number of milliseconds since midnight of January 1.5 . as a four-digit number. as a two-digit or a three/four-digit number.javaScript getDate() getDay() 6) getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCMonth() getUTCFullYear() getUTCHours() getUTCMinutes() getUTCSeconds() getUTCMilliseconds() getYear() Returns the year. 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. 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 . depending on the browser. 1970 Returns the difference in minutes between local time and Greenwich Mean Time (GMT) Returns the day of the month from a Date object according to universal time (from 1-31) Returns the day of the week from a Date object according to universal time (from 0-6) Returns the month from a Date object according to universal time (from 0-11) Returns the four-digit year from a Date object according to universal time Returns the hour of a Date object according to universal time (from 0-23) Returns the minutes of a Date object according to universal time (from 0-59) Returns the seconds of a Date object according to universal time (from 0-59) Returns the milliseconds of a Date object according to universal time (from 0-999) Returns the year.

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

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

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 . Properties FF: Firefox.5 1 .5 the Boolean object The JavaScript Boolean object is an object wrapper for a Boolean value.11. 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 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. N: Netscape.5 1 1 4 4 5 Description F Converts the value of the object into an exponential notation Formats a number to the specified number of decimals 1 .5 .

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 . 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. 1.718) Returns the natural logarithm of 2 (approx.707) Returns the square root of 2 (approx.javaScript 5. 0.6 the Math Object The JavaScript Math object allows you to perform common mathematical tasks.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. 2.302) Returns the base-2 logarithm of E (approx. 0.11. 0. 1.y) min(x.442) Returns the base-10 logarithm of E (approx.14159) Returns the square root of 1/2 (approx. N: Netscape.x) ceil(x) cos(x) exp(x) floor(x) log(x) max(x. It includes several mathematical constants and functions.5 .y) pow(x.434) Returns PI (approx. 3.693) Returns the natural logarithm of 10 (approx. 2.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. Properties FF: Firefox.

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

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

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

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

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

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

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

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

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

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

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

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

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

frames. For elements. it fires when the target element or any of its content has been removed Fires when an object/image is stopped from loading before completely loaded Fires when an object/image/frame cannot be loaded properly Fires when a document view is resized Fires when a document view is scrolled Fires when a user selects some text in a text field. 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 .6 . including window. A keypress is defined as a keydown and keyup on the same key.Html DOM Fires when a key on the keyboard is "clicked". 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. objects and images. For elements. 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

service().UnavailableException The ServletException class extends java.lang.servlet. HttpServletResponse resp) protected void doOptions(HttpServletRequest req.lang.9 the servlet lifecycle Generally. The UnavailableException indicates to the web container that the servlet instance is unavaialble. 9.Exception and can be thrown by the init(). HttpServletResponse resp) protected void doTrace(HttpServletRequest req.servlet. HttpServletResponse resp) protected void doPut(HttpServletRequest req.SERVLETS HttpServletResponse resp) protected void doDelete(HttpServletRequest req. 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. It also extends the java. a servlet instance goes through the following stages: 84 .Exception class.9 . 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.8 servlet exceptions The Java servlet API specifies two servlet specific exceptions: javax.ServletException javax. HttpServletResponse resp) 9. doXXX() and destroy() methods of the Servlet interface implementations.

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

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

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

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

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

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

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

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

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

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

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

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

Objects implementing the Connection interface are mainly used for SQL queries execution.ResultSet object which is available to the user and allows access to the data retrieved.". Here is a typical example: Statement stmt = conn.10 .. 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 . 10.JDBC The Statement interfaces also support the same methods for transaction support as the Connection objects.9 the ResultSet interface The result of a query by a Statement object is a java.executeUpdate(sqlString). The interface ResultSet is implemented by driver vendors.createStatement()..sql. stmt.

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

Big Decimal Object float 10. There are three types of implementations: 1.10 .Time java.sql package.Big Decimal none double double int Object byte[] String null java. It is part of the javax. This interface is. basicly.math.0 optional package. secs date. the DriverManager interface is replaced by the DataSource interface as main method of obtaining DB connections. Basic implementation -.produces a Connection object that will 103 . nanoseconds 8 bit integer variable length binary value variable length char string TIME TIMESTAMP TINYINT none VARCHAR java. the new mechanism uses a centralized JNDI service to locate a javax. While the DriverManager interface was used at run time to load explicitly a JDBC driver.produces a standard Connection object 2.sql.sql.sql.14 JDBC Data Sources In the JDBC 2. Connection pooling implementation -.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.math. a factory for creating DB connections.DataSource object. time. The DataSource interface is implemented by a driver vendors.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. mins.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

11 .JSP colors list optional subBean.number SimpleForm.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 .string subBean.

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

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

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

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

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

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

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

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

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

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

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

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

11 .JSP 135 .

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

12 . Facelets can make changes to pages immediately so developing JSF applications with Facelets is simply faster. 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. The HTML tags can be grouped in the following categories: • • • • • • • inputs outputs commands selections layouts data table errors and messages 12.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. there are 25 HTML JSF tags. 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 .javaserver faces 12.4. As of version 1.1 the list of JSF HTML Tags For reference.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.2 of the JFS specification.

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

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

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

The Facet tag registers a named facet on the component associated with the enclosing tag.5.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. 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. For example. you can create a header and a footer facet for a dataTable component. Example: <h:dataTable id="reportTable" value="#{reportBean.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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Its properties appear in the Properties view.jsp and then on the icon for success. select Navigation Case. notice that the warning triangle disappears. from the palette at left. then click first on the icon for login. 6. and is represented by an arrow. This is shown below: 157 . /pages/success. add 3 more pages.jsp. then click on the newly-added forward-action icon to select it. and set them to /pages/login. This inserts a forward-action between the two pages.jsp 4.jsp and /pages/error. You can also change it on the diagram directly (select the page and click once more). in the Properties view.jsp. 5. change the value of path to /index.jsp.jsp.12 . "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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

When using the JNDI as a Standard Extension on the JDK 1.5.directory javax. It is defined to be independent of any specific directory service implementation.naming. and already deployed--can be accessed in a common way.2.ldap 176 . The SPI enables a variety of naming and directory services to be plugged in transparently.2. more coherent and manageable.1 and the Java 2 SDK. that is to store and retrieve Java objects. v1.4.2 packaging The JNDI is included in the Java 2 SDK.naming.2 the directory as an object store In addition to using the directory in the traditional way. v1. emerging.1 and Java 2 SDK.naming. you must have the JNDI classes and one or more service providers.2 platforms to provide naming and directory functionality. 13. and even the network. 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.JNDI Applications can share the common infrastructure provided by the directory. For example. To use the JNDI. 13.1 architecture The JNDI architecture consists of an API and a service provider interface (SPI).3 includes three service providers for the following naming/directory services: • • • Lightweight Directory Access Protocol (LDAP) Common Object Request Broker Architecture (CORBA) Common Object Services (COS) name service Java Remote Method Invocation (RMI) Registry Other service providers can be downloaded from the JNDI Web site or obtained from other vendors. v1.5.event javax.naming javax. thereby allowing the Java application using the JNDI API to access their services. Java applications use the JNDI API to access a variety of naming and directory services. For example. This sharing makes applications that are deployed across the system. Java applications can also use it as a repository for Java objects. v1.3 and later releases.13 . The Java 2 SDK. Thus a variety of directories--new. you must first download the JNDI classes and one or more service providers. 13. The JNDI is divided into five packages: • • • • javax.1 and v1. 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.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. It is also available as a Java Standard Extension for use with the JDK 1. It extends the v1. 13.

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

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

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

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

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

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

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

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

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

messages published while the subscriber is not connected will be redistributed whenever it reconnects. The classes first use a connection factory to connect to the queue or topic. In that case.jms.JAVA MESSAGE SERVICE subscription. 14. 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. On the receiving side. 186 . JMS provides a way of separating the application from the transport layer of providing data. users will use either a queue connection factory or topic connection factory.4.4 the JMS API The JMS API is provided in the Java package javax.1 the ConnectionFactory interface An administered object that a client uses to create a connection to the JMS provider. Depending on the type of message. Using Java. Administrators configure the connection factory in the Java Naming and Directory Interface (JNDI) namespace so that JMS clients can look them up. the clients then receive or subscribe to the messages.3 the JMS API programming model 14. and then use populate and send or publish the messages.14 . 14.

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

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

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

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

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

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

While the Remote interface declares no methods. RemoteException. } 15. import.*. 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.RemoteException. import.javax.rmi. public interface MyBeanHome extends EJBHome { MyBeanObject create() throws CreateException. String lastName.ENTERPRISE JAVA BEANS Code example for the a home interface.ejb. The developer does not implement this interface.javax. RemoveException Code example for a remote interface called MyBeanObject: package myBeans.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.15 .*. void deleteEntry(int custId) throws RemoteException.RemoteException. } 193 .rmi. import java. public interface MyBeanObject extends EJBObject { // assume that we have two business logic methods void processEntry(String firstName.ejb. int custId) throws RemoteException. import java. called MyBeanHome: package myBeans.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

bank11.AccountHome</home> <remote>com.bank11.bank11.ccards.bank11.Integer</prim-key-class> <reentrant>False</reentrant> <cmp-field> <field-name>accountNumber</field-name> 209 .ccards.Account</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.CCEnrollObject</remote> <ejb-class>com.Accountbject</remote> <ejb-class>com.ejb.ccards.1"?> <ejb-jar> <entrprise-beans> <session> <ejb-name>CCEnroll</ejb-name> <home>com.lang. here is how the deployment descriptor may look like: <?xnm version="1.15 .bank11.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.ccards.CCEnrollHome</home> <remote>com.bank11.ccards.AccountHome</home> <remote>com.ccards.ccards.bank11.ejb.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.ENTERPRISE JAVA BEANS Keeping in mind that the application assembler is to follow.bank11.ejb.

</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 .15 ..lang.Float</env-entry-type> <env-entry-value>2. Here is a very lean one: </ejb-jar> <enterprise-beans> ..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.

ENTERPRISE JAVA BEANS 211 .15 .

Sign up to vote on this title
UsefulNot useful