Вы находитесь на странице: 1из 237

1 - java platform, enterprise edition

1 - JAVA PLATFORM, ENTERPRISE


EDITION
1.1 the state of java EE

The Java EE 7 (released in august 2013) is the current Java Enterprise Edition specification.
Compared to the previous specification, Java EE 7 introduces several new features:
New technologies, including the following:
Batch Applications for the Java Platform
Concurrency Utilities for Java EE
Java API for JSON Processing (JSON-P)
Java API for WebSocket
New features for Enterprise JavaBeans ( EJB) components (see Enterprise JavaBeans
Technology for details)
New features for servlets (see Java Servlet Technology for details)
New features for JavaServer Faces components (see JavaServer Faces Technology for
details)
New features for the Java Message Service (JMS) (see Java Message Service API for
details)
The next release is Java EE 8 and it's final specification is scheduled for 2017. The Java EE 8
specification is part of JSR 366 and (as of sept. 2015) the following schedule is expected:
Q4 2015 - early draft
Q1 2016 - public review
Q3 2016 - proposed final draft
H1 2017 - final release

Novelties expected in the forthcoming release:


better support for HTML5
support for the emerging HTTP 2.0 standard
enhanced simplification and managed bean integration
improved infrastructure for applications running in the cloud.

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

1
1 - java platform, enterprise edition

users are conducted in the middle tier. 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 enterprise-level
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.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

2
1 - java platform, enterprise edition

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.

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

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

3
1 - java platform, enterprise edition

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 7 servers, enabling the Java EE 7 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 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 and off-
loading as much functionality as possible to the server. 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.

Figure 1.2 Server communication

4
1 - java platform, enterprise edition

1.6 web components

Java EE web components are either servlets or pages created using JSP technology (JSP pages)
and/or Java Server Faces technology. Servlets are Java programming language classes that
dynamically process requests and construct responses. JSP pages are text-based documents that
execute as servlets but allow a more natural approach to creating static content. Java Server Faces
technology builds on servlets and JSP technology and provides a user interface component framework
for web applications.
Static HTML pages and applets are bundled with web components during application assembly but
are not considered web components by the Java EE specification. Server-side utility classes can also
be bundled with web components and are not considered web components.
The web tier, like the client tier, might include a JavaBeans component to manage the user input
and send that input to enterprise beans running in the business tier for processing.

1.7 business components

Business code, which is logic that solves or meets the needs of a particular business domain such
as banking, retail, or finance, is handled by enterprise beans running in the business tier. Figure 1.3
shows how an enterprise bean receives data from client programs, processes it (if necessary), and
sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data
from storage, processes it (if necessary), and sends it back to the client program.

Figure 1.3 Web, Business and EIS Tiers

5
1 - java platform, enterprise edition

1.8 enterprise information system tier

The enterprise information system tier handles EIS software and includes enterprise infrastructure
systems such as enterprise resource planning (ERP), mainframe transaction processing, database
systems, and other legacy information systems. For example, Java EE application components might
need access to enterprise information systems for database connectivity.

1.9 java EE Containers

Normally, thin-client multitiered applications are hard to write because they involve many lines of
intricate code to handle transaction and state management, multithreading, resource pooling, and
other complex low-level details. The component-based and platform-independent Java EE
architecture makes Java EE applications easy to write because business logic is organized into
reusable components. In addition, the Java EE server provides underlying services in the form of a
container for every component type. Because you do not have to develop these services yourself, you
are free to concentrate on solving the business problem at hand.

1.9.1 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.
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.
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 Java EE remote connectivity model manages low-level communications between clients
and enterprise beans. After an enterprise bean is created, a client invokes methods on it as if
it were in the same virtual machine.
Because the Java EE architecture provides configurable services, application components within the
same Java EE application can behave differently based on where they are deployed. For example, an
enterprise bean can have security settings that allow it a certain level of access to database data in
one production environment and another level of database access in another production environment.
The container also manages nonconfigurable services such as enterprise bean and servlet life
cycles, database connection resource pooling, data persistence, and access to the Java EE platform
APIs.

1.9.2 Container Types


The deployment process installs Java EE application components in the Java EE containers
illustrated in figure 1.4.

6
1 - java platform, enterprise edition

Figure 1.4 Java EE Server and Containers

Java EE server - the runtime portion of a Java EE product. A Java EE server provides EJB
and web containers.
Enterprise JavaBeans (EJB) container - manages the execution of enterprise beans for Java
EE applications. Enterprise beans and their container run on the Java EE server.
Web container - manages the execution of JSP page and servlet components for Java EE
applications. Web components and their container run on the Java EE server.
Application client container - manages the execution of application client components.
Application clients and their container run on the client.
Applet container - manages the execution of applets. Consists of a web browser and Java
Plug-in running on the client together.

1.10 support for web services

Web services are web-based enterprise applications that use open, XML-based standards and
transport protocols to exchange data with calling clients. The Java EE platform provides the XML APIs
and tools you need to quickly design, develop, test, and deploy web services and clients that fully
interoperate with other web services and clients running on Java-based or non-Java-based platforms.
To write web services and clients with the Java EE XML APIs, all you do is pass parameter data to
the method calls and process the data returned; or for document-oriented web services, you send
documents containing the service data back and forth. 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. These XML-
based standards and protocols are introduced in the following sections.
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. This does not necessarily mean that the

7
1 - java platform, enterprise edition

data being transported includes XML tags because the transported data can itself be plain text, XML
data, or any kind of binary data such as audio, video, maps, program files, computer-aided design
(CAD) documents and the like. The next section introduces XML and explains how parties doing
business can use XML tags and schemas to exchange data in a meaningful way.

1.10.1 XML
XML is a cross-platform, extensible, text-based standard for representing data. When XML data is
exchanged between parties, the parties are free to create their own tags to describe the data, set up
schemas to specify which tags can be used in a particular kind of XML document, and use XML
stylesheets to manage the display and handling of the data.
For example, a web service can use XML and a schema to produce price lists, 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. Here are examples:
One company might put XML pricing information through a program to translate the XML to
HTML so that it can post the price lists to its intranet.
A partner company might put the XML pricing information through a tool to create a marketing
presentation.
Another company might read the XML pricing information into an application for processing.

1.10.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, all running on different platforms and at various locations on the Internet. HTTP is a
familiar request-and response standard for sending messages over the Internet, and SOAP is an
XML-based protocol that follows the HTTP request-and-response model.
The SOAP portion of a transported message handles the following:
Defines an XML-based envelope to describe what is in the message and how to process the
message
Includes XML-based encoding rules to express instances of application-defined data types
within the message
Defines an XML-based convention for representing the request to the remote service and the
resulting response

1.10.3 WSDL Standard Format


The Web Services Description Language (WSDL) is a standardized XML format for describing
network services. The description includes the name of the service, the location of the service, and
ways to communicate with the service. WSDL service descriptions can be stored in UDDI registries or
published on the web (or both). 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.10.4 UDDI and ebXML Standard Formats


Other XML-based standards, such as Universal Description, Discovery and Integration (UDDI) and
ebXML, make it possible for businesses to publish information on the Internet about their products and
web services, where the information can be readily and globally accessed by clients who want to do
business.

8
1 - java platform, enterprise edition

1.11 java EE 7 core technologies and APIs

Figure 1.5 illustrates the availability of the Java EE 6 platform APIs in each Java EE container type.
The following sections give a brief summary of the technologies required by the Java EE platform, and
the APIs used in Java EE applications.

Figure 1.5 Java EE Platform APIs

For Java EE 7, the following technologies have to be added:


At Application Client Container level : JSON-P
At Web container level:
WebSocket
Concurrency utilities
Batch
JSON-P
At EJB container level:
Concurrency utilities
Batch
JSON-P

1.11.1 Enterprise JavaBeans Technology


An Enterprise JavaBeans (EJB) component, or enterprise bean, is a body of code having fields and
methods to implement modules of business logic. 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.
There are two kinds of enterprise beans: session beans and message-driven beans. A session
bean represents a transient conversation with a client. When the client finishes executing, the session
bean and its data are gone. A message-driven bean combines features of a session bean and a

9
1 - java platform, enterprise edition

message listener, allowing a business component to receive messages asynchronously. Commonly,


these are Java Message Service (JMS) messages.
In Java EE 5, entity beans have been replaced by Java persistence API entities. An entity
represents persistent data stored in one row of a database table. If the client terminates, or if the
server shuts down, the persistence manager ensures that the entity data is saved.

1.11.2 Java Servlet Technology


Java servlet technology lets you define HTTP-specific servlet classes. A servlet class extends the
capabilities of servers that host applications that are accessed by way of a request-response
programming model. Although servlets can respond to any type of request, they are commonly used to
extend the applications hosted by web servers.
In Java EE 7, some of the new Servlet features include:
Non-blocking I/O
HTTP protocol upgrade
Java EE 7 requires Servlet 3.1.

1.11.3 JavaServer Pages Technology


JavaServer Pages (JSP) technology lets you put snippets of servlet code directly into a text-based
document. 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, WML, and XML) and JSP elements, which
determine how the page constructs dynamic content.
Java EE 7 requires JSP 2.3 but recommends the use of Facelets as the display technology in
new applications.

1.11.4 JavaServer Pages Standard Tag Library


The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to
many JSP applications. Instead of mixing tags from numerous vendors in your JSP applications, you
employ a single, standard set of tags. This standardization allows you to deploy your applications on
any JSP container that supports JSTL and makes it more likely that the 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.
Java EE 7 requires JSTL 1.2.

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.
The following features support the GUI components:
Input validation
Event handling

10
1 - java platform, enterprise edition

Data conversion between model objects and components


Managed model object creation
Page navigation configuration
All this functionality is available via standard Java APIs and XML-based configuration files.
New features in Java EE 7:
HTML 5 friendly markup
Faces Flows
Resource Library contracts
Java EE 7 requires JFS 2.2 and Expression Language 3.0.

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.
Java EE 7 requires JMS 2.0.

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 perform
those operations.

1.11.10 Java API for WebSocket


WebSocket is an application protocol that provides full-duplex communications between two peers
over TCP. The Java API for WebSocket enables Java EE applications to create endpoints using
annotations that specify the configuration parameters of the endpoint and designate its lifecycle
callback methods.
The WebSocket API is new to the Java EE 7 platform. The Java EE 7 platform requires Java API for
WebSocket 1.0.

11
1 - java platform, enterprise edition

1.11.11 JSON processing


JSON is a text-based data exchange format derived from JavaScript that is used in web services
and other connected applications. The Java API for JSON Processing (JSON-P) enables Java EE
applications to parse, transform, and query JSON data using the object model or the streaming model.
JSON-P is new to the Java EE 7 platform. The Java EE 7 platform requires JSON-P 1.0.

1.11.12 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.13 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.14 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 JAX-RS
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.15 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.16 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.

12
1 - java platform, enterprise edition

1.11.17 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 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.18 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.19 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.20 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
The Java Persistence Criteria API
Object/relational mapping metadata

1.11.21 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

13
1 - java platform, enterprise edition

named Java object, allowing Java EE applications to coexist with many legacy applications and
systems.
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.22 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 user-based
authorization.

1.11.23 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.24 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.25 Simplified Systems Integration


The Java EE platform is a platform-independent, full systems integration solution that creates an
open marketplace in which every vendor can sell to every customer. Such a marketplace encourages
vendors to compete, 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, such as better

14
1 - java platform, enterprise edition

performance, better tools, or better customer support.


The Java EE 7 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, SAAJ, 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, JTA, and JNDI

1.12 java EE application assembly and deployment

A Java EE application is packaged into one or more standard units for deployment to any Java EE
platform-compliant system. Each unit contains:
A functional component or components (such as an enterprise bean, JSP page, servlet, or
applet)
An optional deployment descriptor that describes its content
Once a Java EE unit has been produced, it is ready to be deployed. Deployment typically involves
using a platforms deployment tool to specify location-specific information, such as a list of local users
that can access it and the name of the local database. Once deployed on a local platform, the
application is ready to run.
A Java EE application is delivered in an Enterprise Archive (EAR) file, a standard Java Archive
(JAR) file with an .ear extension. Using EAR files and modules makes it possible to assemble a
number of different Java EE applications using some of the same components. No extra coding is
needed; it is only a matter of assembling (or packaging) various Java EE modules into Java EE EAR
files.
An EAR file contains Java EE modules and deployment descriptors. A deployment descriptor is
an XML document with an .xml extension that describes the deployment settings of an application, a
module, or a component. Because deployment descriptor information is declarative, it can be changed
without the need to modify the source code. At runtime, the Java EE server reads the deployment
descriptor and acts upon the application, module, or component accordingly.

15
1 - java platform, enterprise edition

Figure 1.6 EAR file structure

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

1.13 scripting versus application servers

16
1 - java platform, enterprise edition

In this section we attempt to answer a recurrent question why bother with servlets, java server
pages or java server faces when we can achieve faster the same results using a versatile language
like PHP? Without ignoring its major qualities, let's point out some of weaknesses of PHP, which are
inherent to its nature.
PHP scripts are tied to a the web server and require writing explicit database queries to generate
dynamic content. Even these queries are written in a way which is specific to a particular database
engine. In PHP, the application programmer writes the SQL queries and embeds them directly into the
script, mixing presentation and business logic in the process. No direct support is provided for the
management of component pooling and lifecycle management, client session management, database
connection pooling, persistence, transaction management, authentication, and access control. On the
other hand, all these may be achieved through an application server.
For those who want a deeper understanding of this debate, the following links may help.
http://stiri.rol.ro/dezbatere-forum-la-link-academy-php-vs-java-820468.html
http://www.cs.montana.edu/~tosun/phpvsjava.pdf
http://shootout.alioth.debian.org/u32q/benchmark.php?test=all&lang=java&lang2=php
http://raibledesigns.com/rd/entry/php_vs_java_which_is
http://brand-maestro.com/php-vs-java-programming-language-better-future/

17
2 - HTTP

2 - HTTP
2.1 what is http?

HTTP stands for HyperText Transfer Protocol while hypertext means text contatining links to
another text. HTTP was created by by Tim Berners-Lee in 1990 at CERN as a mean to store scientific
data. It quickly evolved into the preferred communication protocol over the internet.
The first official version HTTP 1.0 dates from 05/95 and is the object of RFC 1945
(www.apps.ietf.org/rfc/rfc1945.html). It is authored by Tim Berners-Lee, Roy Fielding and Henrik
Nielsen.
The second version, namely HTTP 1.1, was the object of several RFCs, of which we mention RFC
2068 (01/97), RFC 2616 (06/99), RFC 2617 (06/99) and RFC 2774 (02/00).
For a complete specification of the different HTTP versions, check the official HTTP site
www.w3.org/Protocols . As a site for understanding how HTTP works, we recommend
www.jmarshall.com/easy/http.
The next version of the HTTP specification is HTTP 2.0 (or HTTP/2) has been released as RFC
7540 in May 2015 - https://tools.ietf.org/html/rfc7540
The working group for HTTP/2 hopes to address the following issues and goals:
Negotiation mechanism that allows clients and servers to elect to use HTTP 1.1, 2.0, or
potentially other non-HTTP protocols.
Maintain high-level similarity with HTTP 1.1 (for example with methods, status codes, header
fields, and URIs, and most header fields)
Decrease latency to improve page load speed in web browsers by considering:
Data compression of HTTP headers
Server push technologies
Fixing the head-of-line blocking problem in HTTP 1
Loading page elements in parallel over a single TCP connection
Support common existing use cases of HTTP, such as desktop web browsers, mobile web
browsers, web APIs, web servers at various scales, proxy servers, reverse proxy servers,
firewalls, and content delivery networks

2.2 the structure of http transactions

HTTP follows the client server model. The client sends a request message to the server. The
server answers with a response message. These messages may have different contents, but they
also have some common structural elements, as follows:
1. an initial line
2. zero or more header lines
3. a blank line (CR/LF)
4. an optional message body

<initial line>
Header1: value1
...
Headern: valuen

18
2 - HTTP

<optional data block>

2.3 the initial request line

Contains 3 elements, separated by spaces:


a command (method) name (like GET, POST, HEAD, ...)
a file specification (path) (the part of the URL after the host name)
the HTTP version (usually, HTTP/1.0).
Here is an example of an initial request line:
GET /path/to/the/file/index.html HTTP/1.0

2.4 http commands (methods)

As of HTTP 1.1, there are 8 HTTP commands (methods) that are widely supported. Here is their list:
1. GET
2. HEAD
3. POST
4. CONNECT
5. DELETE
6. OPTIONS
7. PUT
8. TRACE

Three other commands are listed, as well, in the HTTP 1.1 specification, but lack of support makes
them obsolete. These commands are:
LINK
UNLINK
PATCH

The HEAD command is identical to the GET command in all respects but one. The only difference is
that the response must not have a body. All the information requested is returned in the header
section of the response.

2.5 the GET and POST methods

The GET method means retrieve whatever information (in the form of an entity) is identified by the
Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which
shall be returned as the entity in the response and not the source text of the process, unless that text
happens to be the output of the process.
The POST method is used to request that the origin server accept the entity enclosed in the request
as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is
designed to allow a uniform method to cover the following functions:

19
2 - HTTP

- Annotation of existing resources;


- Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
- Providing a block of data, such as the result of submitting a
form, to a data-handling process;
- Extending a database through an append operation.

The actual function performed by the POST method is determined by the server and is usually
dependent on the Request-URI. The posted entity is subordinate to that URI in the same way that a
file is subordinate to a directory containing it, a news article is subordinate to a newsgroup to which it is
posted, or a record is subordinate to a database.
The action performed by the POST method might not result in a resource that can be identified by a
URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending
on whether or not the response includes an entity that describes the result.

2.6 differences between GET and POST

1. The method GET is intended for getting (retrieving) data, while POST may involve anything, like
storing or updating data, or ordering a product, or sending E-mail
2. When used for form data submission, GET attaches this data to the URL of the request, after the
? character, as a sequence of name=value pairs, separated by the character & or ; On the
other side, form data submitted by POST may be encoded either as above (using
application/x-www-form-urlencoded content type), or in the message body,
(encoded as multipart/form-data).
3. A POST request requires an extra transmission to retrieve the message body, while a GET
request allows data sent via the URL to be processed immediately.

2.7 the initial response (status) line

Contains 3 elements, separated by spaces (although the reason phrase may contain spaces, as
well):
the HTTP version of the response
a response status code (a number)
a response status reason phrase (a human readable response status)
Here is an example of an initial response line:
HTTP/1.0 404 Not Found

2.8 the status code

A three-digit integer, where the first digit identifies the general category of response:
1xx indicates an informational message only
2xx indicates success of some kind
3xx redirects the client to another URL

20
2 - HTTP

4xx indicates an error on the client's part


5xx indicates an error on the server's part
The most common status codes are:
200 OK - the request succeeded, and the resulting resource (e.g. file or script output) is
returned in the message body.
404 Not Found - the requested resource doesn't exist.
301 Moved Permanently
302 Moved Temporarily
303 See Other (HTTP 1.1 only) - the resource has moved to another URL (given by the
Location: response header), and should be automatically retrieved by the client. This is often
used by a CGI script to redirect the browser to an existing file.
500 Server Error - an unexpected server error. The most common cause is a server-side
script that has bad syntax, fails, or otherwise can't run correctly.
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.0, and section 10 for HTTP 1.1).

2.9 header lines

A header line consists of two parts, header name and header value, separated a semicolon. The
HTTP 1.0 version specifies 16 headers, none of them mandatory, while the HTTP 1.1 version
specifies 46 of them, out of which, one (Host) is mandatory. Although the header names are not case
sensitive, header values are.
A couple of examples of header lines:
User-agent: Mozilla/3.0Gold
Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT
Header lines which begin with spaces or tabs are parts of the previous header line.

2.10 the message body

An HTTP message may have a body of data sent after the header lines. The most common use of
the message body is in a response, that is, where the requested resource is returned to the client, or
perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded
files are sent to the server.
If an HTTP message includes a body, the header lines of the message are used to describe the
body. In particular,
the Content-Type: header gives the MIME-type of the data in the body, such as text/html or
image/jpg.
the Content-Length: header gives the number of bytes in the body.

2.11 mime types/subtypes

MIME stands for Multipurpose Internet Mail Extensions. Each extension consists of a type and a
subtype. RFC 1521 (www.apps.ietf.org/rfc/rfc1521.html) defines 7 types and several subtypes,

21
2 - HTTP

although the list of admissible subtypes is much longer.


Here is the list of the seven types, together with the subtypes defined in this particular RFC.
1. text, with subtype plain
2. multipart, with subtypes mixed, alternative, digest, parallel
3. message, with subtypes rfc822, partial, external-body
4. application, with subtypes octet-stream, postscript
5. image, with subtypes jpeg, gif
6. audio, with subtype basic
7. video, with subtype mpeg

2.12 an example of an http transaction

To retrieve the file at the URL http://web.info.uvt.ro/path/file.html


first open a socket to the host web.info.uvt.ro, port 80 (use the default port of 80 because none is
specified in the URL). Then, send something like the following through the socket:
GET /path/file.html HTTP/1.0
From: someuser@yahoo.com
User-Agent: HTTPTool/1.0
[blank line here]
The server should respond with something like the following, sent back through the same socket:
HTTP/1.0 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/html
Content-Length: 1354

<html>
<body>
<h1>Happy birthday!</h1>
(more file contents)
.
.
</body>
</html>

After sending the response, the server closes the socket.

22
2 - HTTP

2.13 HTTP/2 protocol overview

HTTP/2 provides an optimized transport for HTTP semantics. HTTP/2 supports all of the core
features of HTTP/1.1 but aims to be more efficient in several ways.

The basic protocol unit in HTTP/2 is a frame. Each frame type serves a different purpose. For
example, HEADERS and DATA frames form the basis of HTTP requests and responses; other frame
types like SETTINGS, WINDOW_UPDATE, and PUSH_PROMISE are used in support of other
HTTP/2 features.

Multiplexing of requests is achieved by having each HTTP request/response exchange associated


with its own stream. Streams are largely independent of each other, so a blocked or stalled request or
response does not prevent progress on other streams.

Flow control and prioritization ensure that it is possible to efficiently use multiplexed streams.
Flow control helps to ensure that only data that can be used by a receiver is transmitted. Prioritization
ensures that limited resources can be directed to the most important streams first.

HTTP/2 adds a new interaction mode whereby a server can push responses to a client. Server
push allows a server to speculatively send data to a client that the server anticipates the client will
need, trading off some network usage against a potential latency gain. The server does this by
synthesizing a request, which it sends as a PUSH_PROMISE frame. The server is then able to send a
response to the synthetic request on a separate stream.

Because HTTP header fields used in a connection can contain large amounts of redundant data,
frames that contain them are compressed. This has especially advantageous impact upon request
sizes in the common case, allowing many requests to be compressed into one packet.

23
3 - HTML

3 - HTML
3.1 what is html?

HTML stands for HyperText Markup Language. HTML describes how text, images and other
components are to be displayed in a browser, using a variety of tags and their related attributes.
The first version of HTML, namely HTML 1.0, appeared in summer 1991 and was supported by the
first popular web browser, Mosaic. The first official version HTML 2.0 - was approved as a standard
in September 1995 (as RFC 1866 (http://www.apps.ietf.org/rfc/rfc1866.html) and was widely
supported. A newer standard, HTML 3.2 (3.0 was not widely accepted) appeared a W3C
recommendation in January 1997.
Version 4.0 introduces the Cascading Style Sheets.
The latest version of HTML as SGML application is 4.01. It is a revision of 4.0 and was accepted in
December 1997. However, a working draft for the next major revision, namely HTML 5 was published
in January 2008. Originally named Web Applications 1.0, the specification includes several ideas of
the WHAT (Web Hypertext Application Technology) working group. It might take several years (a
formal target has been set for 2014) before the specification reaches final Recommendation status.
From 1999 on, HTML is part of a new specification XHTML. The XHTML 1.0 draft was released in
01.99 and mirrors the HTML 4.01 specification. The latest version (XHTML 2.0) was a working draft
but was abandoned in 2009 in favor of work on XHTML5, which is being defined alongside HTML5.
For a complete specification of the different HTML versions, check the official HTML site
www.w3c.org/Markup . As a practical reference site use www.blooberry.com/indexdot/html . Other
helpful sites - www.htmlgoodies.com/tutors, www.jmarshall.com/easy/html .

3.2 language definition

HTML is a system for describing documents. It is a special version of SGML (Standard Generalized
Markup Language an ISO standard (ISO 8879)). All markup languages defined in SGML are called
SGML applications and are characterized by:
1. An SGML declaration what characters and delimiters may appear. The SGML declaration of
the latest version of HTML (4.01) can be found at this address:
http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html. Since it fits in a couple
of pages, we can afford to have a look at this declaration.

<!SGML "ISO 8879:1986"


--
SGML Declaration for HyperText Markup Language version HTML 4.01

With support for the first 17 planes of ISO 10646 and increased
limits for tag and literal lengths etc.
--

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"
DESCSET 0 9 UNUSED
9 2 9
11 2 UNUSED
13 1 13

24
3 - HTML

14 18 UNUSED
32 95 32
127 1 UNUSED
128 32 UNUSED
160 55136 160
55296 2048 UNUSED -- SURROGATES --
57344 1056768 57344

CAPACITY SGMLREF
TOTALCAP 150000
GRPCAP 150000
ENTCAP 150000

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 13
RS 10
SPACE 32
TAB SEPCHAR 9

NAMING LCNMSTRT
""
UCNMSTRT
""
LCNMCHAR
".-_:"
UCNMCHAR
".-_:"
NAMECASE
GENERAL YES
ENTITY NO
DELIM GENERAL SGMLREF
SHORTREF SGMLREF
NAMES SGMLREF
QUANTITY SGMLREF
ATTCNT 60 -- increased --
ATTSPLEN 65536 -- These are the largest values --
LITLEN 65536 -- permitted in the declaration --
NAMELEN 65536 -- Avoid fixed limits in actual --
PILEN 65536 -- implementations of HTML UA's --
TAGLVL 100
TAGLEN 65536
GRPGTCNT 150
GRPCNT 64

FEATURES
MINIMIZE
DATATAG NO
OMITTAG YES
RANK NO
SHORTTAG YES
LINK
SIMPLE NO
IMPLICIT NO
EXPLICIT NO
OTHER
CONCUR NO

25
3 - HTML

SUBDOC NO
FORMAL YES
APPINFO NONE
>

2. A Document Type Definition (DTD) defines the syntax of markup constructs. Check the
address http://www.w3.org/TR/REC-html40/sgml/dtd.html for the latest version of the HTML
DTD.
3. A specification that describes the semantics to be ascribed to the markup and character entity
references. This specification adds new syntactic restrictions which cannot be defined within
the frame of the DTD.
4. Document instances containing data (content) and markup. Each instance contains a
reference to the DTD to be used to interpret it.
Overall, the specification of HTML 4.0 contains an SGML declaration, three DTDs (HTML 4.0 Strict
DTD, HTML 4.0 Transitional DTD, HTML 4.0 Frameset DTD) and a list of character references. If you
wonder what a character reference is, look at these examples: &lt, &quot, "&#x6C34;" (in
hexadecimal) - the chinese character for water. You get the point.

3.3 html5

As of December 2012, HTML5 is a candidate recommendation of the World Wide Web Consortium
(W3C). Its core aims have been to improve the language with support for the latest multimedia while
keeping it easily readable by humans and consistently understood by computers and devices (web
browsers, parsers, etc.). HTML5 is intended to subsume not only HTML 4, but also XHTML 1 and
DOM Level 2 HTML.
In October 2014, the HML5 specification was finalized and published as a W3C Recommendation.
It includes detailed processing models to encourage more interoperable implementations; it
extends, improves and rationalises the markup available for documents, and introduces markup and
application programming interfaces (APIs) for complex web applications.
HTML5 adds many new syntactic features. These include the new <video>, <audio> and <canvas>
elements, as well as the integration of scalable vector graphics (SVG) content (that replaces the uses
of generic<object> tags) and MathML for mathematical formulas. These features are designed to
make it easy to include and handle multimedia and graphical content on the web without having to
resort to proprietary plugins and APIs. Other new elements, such as <section>, <article>, <header>
and <nav>, are designed to enrich the semantic content of documents. New attributes have been
introduced for the same purpose, while some elements and attributes have been removed.

3.4 html elements

An HTML element consists of:


a start tag
a content
an end tag

One exception, though; the element <BR> has no content and no end tag.
There are 91 elements defined in the HTML 4.01 specification. This section deals with some of the
most common elements.
The start tag of the element contains the values of the (required or optional) attributes of the

26
3 - HTML

element. An example:

<IMG SRC=/images/logo.gif ALT=logo HEIGHT=40 WIDTH=120>

declares an image element, with the required (mandatory) attributes SRC and ALT and the optional
attributes HEIGHT and WIDTH. Other optional attributes of the <IMG> element, like ALIGN,
BORDER, CONTROLS, DYNSRC, , VSAPCE are omitted.
A comment section in an HTML document starts with <!-- and end at the first occurrence of -->. An
example:

<!-- acesta este un comentariu. <><> -->

3.4.1 The <A> element


Must contain one of the 2 attributes HREF, NAME. Main attributes:
HREF specifies the absolute or relative URL of the hyperlink
NAME assigns a symbolic name to the enclosed object (text, image, etc.) in order to use it
as a destination in a hyperlink or another URL call.

Example:
<A HREF=http://web.info.uvt.ro/webmail/src/login.php>Login to
web mail</A>

3.4.2 The <IMG> element


Main attributes:
ALT required; specifies the text to be displayed in case source is not found
SRC required; indicates the URL to reference the graphic
HEIGHT
WIDTH

3.5 the minimal structure of an html document

All HTML documents start with the <HTML> tag and end with the corresponding end tag </HTML>.
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>

27
3 - HTML

</HTML>

3.6 tables

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, 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 a an example of
a table:

3.7 table related elements

The specific elements defining a table, its rows, columns, headers and cells are <TABLE>,
<THEAD>, <TR>, <TH> and <TD>. Here is their description and attributes.
the <TABLE> element
attributes:
BORDER
CELLSPACING
CELLPADDING
WIDTH
ALIGN
VALIGN
TBODY
BORDERCOLOR
FRAME
RULES
COLORGROUP
BACKGROUND

the <THEAD> element


attributes:
ALIGN
BGCOLOR
CHAR
CHAROFF
VALIGN

28
3 - HTML

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

A form is a basic component container, allowing user input and parameter submittal.
The <FORM> element has the following attributes:
ACTION - required, specifies the URL of the server side process that will receive the data
METHOD - required, may have the values GET or POST, specifies how data will be sent to the
server. Possible values for this attribute:
"POST"- sends the form values in 2 steps: contacts first the server then the form values are
sent in a separate transmission.
"GET" - sends the form values in a single transmission, the browser appends the values to the
URL, after a quotation mark - ?. The pairs name=value are separated by ampersand - & or
(sometimes) by semicolon - :.
Example:
http://web.info.uvt.ro/servlet/MyServlet?a=12&b=25

29
3 - HTML

ENCTYPE - specifies the encoding type of the of the form content. Default value:
"application/x-www-form-urlencoded" - the default value; however, since it converts spaces to '+'
and non-alphanumerical to '%HH', where 'HH' is the hexadecimal ASCII code of the character.
Other possible values for this attribute:
"multipart/form-data" - used with forms that contain a file-selection field, data is sent as a single
document with multiple sections.
"text/plain"

3.9 form related elements

3.9.1 the <INPUT> element


Defines input fields for the form. Main attributes:
TYPE - required, specifies the type of the input which can have one of the following values:
"text", "password", "checkbox", "radio", "submit", "image", "reset", "button", "hidden", "file".
NAME - required, specifies the parameter name.

3.9.2 the <SELECT> element


Used to create a list of choices, either as a drop-down menu or as a list box. Each of the listed
choices is an OPTION element.
Main attributes:
NAME
MULTIPLE - if specified, allows multiple selections from the choice list.
SIZE - maximum number of options visible to the user.

3.9.3 the <OPTION> element


Used inside a <SELECT> element to list the selection choices. Main attributes:
SELECTED

Example of a <SELECT> element:

<SELECT NAME="action" STYLE="font-family: '@Arial Unicode MS'


font-size: 11pt">
<OPTION SELECTED>Select Action
<OPTION>Make Payment
<OPTION>Transfer a balance
<OPTION>Change Mailing Address
<OPTION>Change e-mail Address
<OPTION>Change User Name/Password
<OPTION>View Account Activity
</SELECT>

30
3 - HTML

31
4 - JAVA PRIMER

4 - JAVA PRIMER
4.1 history

The initial name of this language was OAK and was developed as part of the GREEN project at
Sun, project started in 12.90. Early versions of Java were released in 12.94 and was officially
announced at Sun World in 05.95. The first commercial version was delivered to the first customer
(Netscape, Inc.) in 08.95. The current version (as of 10.2004) of Java 2 Platform Standard Edition is
J2SE 5.0, following the 1.4.2 version. The current version (as of 10.2014) of Java Platform Enterprise
Edition is Java EE 7.

4.2 java the interpreter, jit

From source to execution, A java program goes thru the following phases:
1. Java source a file with extension .java
2. Java bytecode a file with extension .class
3. The Java interpreter (which is part of the Java Virtual Machine) parses and executes the Java
bytecode.

Example:
Edit the file prog1.java. The java compiler (javac) translates it to bytecode prog1.class. The java
interpreter (as part of the JVM) parses and executes the prog1.class file.
In terms of execution time, a Java interpreted program is about 10 times slower than a compiled
and linked one. To overcome this significant shortage, a tool named Just In Time compiler, allows the
compilation of the Java source into machine-dependent binary executable. The first time a class is
loaded, the compilation process occurs, which accounts for a pretty slow execution, but next time
execution is much faster, pretty much comparable to that of a binary executable.
The java compiler is (in general) a command line tool, with the following main options:
-classpath <path>
-sourcepath <path>
-d <directory> : specifies where to put the .class file.
-g : generate all debugging info.
One example of command line compilation:
javac -classpath .;C:\TW\mySource;C:\TW\myPackages -g login.java

4.3 java applications

There exist 2 types of programs that can be written in Java. The first type are embedded in web
pages applets, the others are the standalone programs Java applications.
A java applet is a java class that extends the standard Applet class.
In general, an applet is inserted in a HTML page by an <APPLET> tag or by an <OBJECT> tag. The
<APPLET> element has 3 mandatory attributes, namely:
CODE identifies the (compiled) class file of the applet

32
4 - JAVA PRIMER

WIDTH
HEIGHT
A java application is a collection of java classes. Generally, each class is implemented in a source
file having the same name as the class itself and whose extension is .java. Exactly one of these
classes must implement a method called main(). 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), as follows:

java [-options] class [args]

Where main options are:


-cp <directories and jar files separated by ;> : cp = classpath
-D <name>=<value> : set a system property

To execute a .jar file, use the command:

java jar [-options] jarfile [args]

4.4 object oriented concepts

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

4.4.2 inheritance
Inheritance is a partial order relation in the set of all Java classes. A Java class B inherits another
class A (or is a subclass of A, or is derived from A, or that it extends A). This binary relation is
specified in the declaration of the derived class B using the keyword extends. An example:

public class CaineComunitar extends Caine


{

}

In this case, all variables and methods of the base class A are automatically variables and methods
of the derived class B.
The derived class B can use (for free) all the methods of the base class, but it also can override the
implementation of any method in the base class, providing its own implementation.
While C++ allows multiple inheritance, a Java class can extend a single base class. That means
that the graph of the direct inheritance relation is a forest (its connected components are trees). In
fact, all classes in Java are (by default) subclasses of a universal base class, called Object. Therefore,

33
4 - JAVA PRIMER

the forest we mentioned is actually a tree, with the root the class Object.

4.4.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), and automatically call the method specific to the type
(derived class) of the object that the variable references.

4.4.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. The return type of a method is not part of this signature. Therefore, a
class can have more than one method with the same name, provided that the types (and order) of its
parameters are different. In OO jargon, this is called method overloading.

4.5 java as programming language

integer data types:


byte
short
int
long
floating point data types:
float
double
other types:
boolean - 1 bit
char - Unicode (16 bits)

All basic types have associated classes which extend their functionality, namely: Byte, Short,
Integer, Long, Float, Double, Boolean, Character.
Other peculiarities: no pointers (only references), automatic garbage collection, no templates.

4.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. Except for the "package" concept, they have the same basic meaning as in C++.
no specifier - the default value allows access from any class in the same package
public - access from any class anywhere
private - no access from outside the class itself
protected - 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, the specifiers for the
class itself can be taken from the following list:
no specifier - the default value makes the class visible only to the classes in the same package
public - the class is visible from any class, anywhere
abstract - the class is abstract (some of its methods (inherited or specified by some interface)
are to be implemented by some of its subclasses)

34
4 - JAVA PRIMER

An example. The declaration:


abstract class myFirstClass extends javax.servlet.http.HttpServlet
implements Serializable
{
...
}
declares an abstract class, which is visible only to the classes in the same package, which extends
the class javax.servlet.http.HttpServlet and which implements the Serializable
interface.

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, rather than at class instance. A final
variable (method, class) is one which cannot be modified (overridden, inherited). More precisely:
A static (or class):
variable - one which is defined at class level, has the same value for all class instances.
method - all variables referenced in the function body are static variables.
Static variables and methods can be referenced (invoked) using either the name of the class or the
name of a class instance.
A final:
variable - one which is constant
method - the method implementation cannot be overriden by some subclass.
class - does not have any subclasses.

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.
In Java, an exception is an object which is created when the abnormal situation occurs.
Exception categories:
1. code or data errors - like invalid cast, array index out of bounds, division by 0.
2. standard method exceptions
3. programmer defined exceptions
4. java errors - JVM execution errors (mostly caused by programming errors).
All exceptions (even programmer defined) must inherit from the standard class Throwable.
All the standard exceptions are derived from 2 direct subclasses of Throwable, namely class Error
and the class Exception.

4.7.1 The Error class


Represent conditions which are not expected to be caught in our code. Therte are 3 direct
subclasses of the class Error - ThreadDeath, Linkage Error and VirtualMachineError.

4.7.2 The Exception class


Except for the RuntimeException exceptions, all then exceptions in this category must be caught in
our code.

35
4 - JAVA PRIMER

4.7.3 RuntimeException Exceptions


Usually, these exceptions take place because of serious code errors and they are supposed to be
fixed in the coding phase, not at execution time.
The subclasses of the RuntimeException class, as defined in the java.lang package are:
ArithmeticException
IndexOutOfBoundException
NegativeArraySizeException
NullPointerException
ArrayStoreException
ClassCastException
IllegalArgumentException
SecurityException
IllegalMonitorStateException
IllegalStateException
UnsupportedOperationException

4.7.4 Handling Exceptions


There are 2 ways to deal with exceptions:
supply then code to deal with the exception inside the method - this can be done by providing a
try, catch, finally construct.
ignore it (pass it to the code that called the method) - by adding the key word throws, followed
by a comma separated list of exceptions after the parameter list of the method.

4.8 java packages

A Java package is a named collection of classes. Each class belongs to a package (even if a
package name is not specified, the default package is used). The names in a package are qualified by
the package name, therefore, they have to be unique inside a package.

4.8.1 Package names


The default package has no name. The package containing the standard classes is java.lang
(automatically available). All other packages must be explicitly imported. As a general rule, the
package statement is the first one in a java source file, followed by the import statements. An
example:

package com.bank11.ccards.servlets;
import javax.sql.*;
import.java.util.Properties;
...
The name of the package is directly linked to the directory structure in which it is stored. In the
example above, the class (the .class file, rather) defined in the java source must be stored in a
directory called servlets, which is a subdirectory of ccards (which itself, is a subdirectory of a directory
called bank11).

36
4 - JAVA PRIMER

4.9 standard Java packages

java.lang - default, don't have to import


java.io
java.awt - support for user interface
java.awt.event - support for event handling
java.awt.geom - support for operations with 2D geometric figures
java.net
java.nio
java.rmi
java.util - support for data collections, string analyzers, date and time info
java.util.zip - support for java archives creation
java.sql
java.security
java.text
javax.accessibility
javax.swing - swing GUI components (minimal dependence on native code)
java.swing.event - support for event handling

4.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), Java classes can implement
zero or more interfaces.
An interface is a collection of constants and "abstract" functions.
All variables (actually, constants) of an interface are automatically (by default) public, static and final.
All methods declared in an interface are (by default) public and abstract.
If a class is declared as implementing an interface but omits some of its methods, it must be
declared as abstract.

37
5 - javaScript

5 - JAVASCRIPT
5.1 so what is JavaScript?

JavaScript is a scripting language designed to add interactivity to HTML pages.

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. ECMA stands for European Computer
Manufacturers Association and is an organization founded in 1961 to standardize computer systems in
Europe. The origins of this language date back to 1995, and was originally developed by Brendan Eich
of Netscape under the names Mocha, then LiveScript and finally, as JavaScript. Subsequently,
JavaScript was standardized by ECMA in June 1997 under the name ECMAScript. However, the
general public knows it only by the name given by its creator JavaScript. Adaptations of the ECMA
standard for other applications, like KDE or Adobe Flash bear different names, like QtScript or
ActionScript.
The version history of ECMAScript starts with version 1.0 from 03.1996, continuing with 1.1 in
08.1996, , version 1.5 in 11.2000 and the latest one, 1.8.5 dating back to 07.2010, but the whole
concept of versioning seems to be on verge of removal.

5.2 what can a JavaScript do?

JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, 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 - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data
before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page specifically
designed for that browser
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer

5.3 how and where?

JavaScripts in a page will be executed immediately while the page loads into the browser. This is
not always what we want. Sometimes we want to execute a script when a page loads, other times

38
5 - javaScript

when a user triggers an event.

5.3.1 scripts in the head section


Scripts to be executed when they are called, or when an event is triggered, go in the head section.
When you place a script in the head section, you will ensure that the script is loaded before anyone
uses it. Here is an example:

<html>
<head>
<script type="text/javascript">
....
</script>
</head>

5.3.2 scripts in the body section


Scripts which are to be executed when the page loads go in the body section. When you place a
script in the body section it generates the content of the page.

<html>
<head>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>

5.3.3 using an external JavaScript


Sometimes you might want to run the same JavaScript on several pages, without having to write the
same script on every page. To simplify this, you can write a JavaScript in an external file.
Save the external JavaScript file with a .js file extension.

Note: The external script cannot contain the <script> tag!

To use the external script, point to the .js file in the "src" attribute of the <script> tag:

<html>
<head>
<script src="myScript.js">
</script>
</head>
<body>
</body>
</html>

5.4 javaScript variables and expressions

A variable is a "container" for some information whose value can change during the script.

5.4.1 variable names


Rules for variable names:

39
5 - javaScript

Variable names are case sensitive


They must begin with a letter or the underscore character

5.4.2 variable declaration


A variable can be declared or even created with the var statement:

var strnum = "2157 Sunrise Blvd";


or
strnum = "2157 Sunrise Blvd";

5.4.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.4.4 variable types


A variable declaration in JavaScript does not contain a type declaration. The type of the variable is
determined by any assignment of a value to that variable. This means that the type of the variable can
change during the execution of a JavaScript script.

5.5 javaScript flow control

Apart from the usual flow control constructs, namely if ... else, switch(), for(), while(), break,
continue, while() it is worth mentioning the for ... in and the try ... catch constructs.

5.5.1 JavaScript for...In statement


The for...in statement is used to loop (iterate) through the elements of an array or through the
properties of an object.
The code in the body of the for ... in loop is executed once for each element/property.
Syntax

for (variable in object)


{
code to be executed
}

The variable argument can be a named variable, an array element, or a property of an object.
Example
Using for...in to loop through an array:

40
5 - javaScript

<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>

5.5.2 catching errors


When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there
is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for
developers but not for users. When users see errors, they often leave the Web page.
This chapter will teach you how to trap and handle JavaScript error messages, so you don't lose
your audience.
There are two ways of catching errors in a Web page:
By using the try...catch statement (available in IE5+, Mozilla 1.0, and Netscape 6)
By using the onerror event. This is the old standard solution to catch errors (available since
Netscape 3)

5.5.3 try...catch statement


The try...catch statement allows you to test a block of code for errors. The try block contains the
code to be run, and the catch block contains the code to be executed if an error occurs.
Syntax

try
{
// run some code here
}
catch(err)
{
// handle errors here
}

Example

<html>

41
5 - javaScript

<head>
<script type="text/javascript">
var txt=""
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>

5.6 operators

The only new one is the comparison operator === (equal values and same type). Also, strings can
be added (concateneted) using the + operator.

5.7 popup boxes

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

Syntax:
alert("sometext")

5.7.2 confirm Box


A confirm box is often used if you want the user to verify or accept something. When a confirm box
pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box
returns true. If the user clicks "Cancel", the box returns false.

42
5 - javaScript

Syntax:
confirm("sometext")

5.7.3 prompt Box


A prompt box is often used if you want the user to input a value before entering a page. When a
prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an
input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel", the box
returns null.

Syntax:
prompt("sometext","defaultvalue")

5.8 functions

5.8.1 function definition


A function contains some code that will be executed only by an event or by a call to that function. A
function can be called from anywhere within the page (or even from other pages if the function is
embedded in an external .js file). Functions are defined at the beginning of a page, in the <head>
section. 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!!"), in the example above had not been written within a function, it would
have been executed as soon as the line was loaded. Now, the script is not executed before the user
hits the button. We have added an onClick event to the button that will execute the function
displaymessage() when the button is clicked..

The syntax for creating a function is:


function functionname(var1,var2,...,varX) { some code }

var1, var2, etc are variables or values passed into the function. The { and the } defines the start and
end of the function.

function functionname() { some code }

Note: Do not forget about the importance of capitals in JavaScript! The word function must be

43
5 - javaScript

written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a
function with the exact same capitals as in the function name.

5.8.2 the return statement


The return statement is used to specify the value that is returned from the function. So, functions
that are going to return a value must use the return statement. An example is the function below
should return the product of two numbers (a and b):

function prod(a,b) { x=a*b return x }

When you call the function above, you must pass along two parameters:

product=prod(2,3)

The returned value from the prod() function is 6, and will be stored in the variable called product.

5.9 javaScript objects

5.9.1 object oriented programming


JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to
define your own objects and make your own variable types.
We will start by looking at the built-in JavaScript objects, and how they are used. The next pages will
explain each built-in JavaScript object in detail.

5.9.2 properties
Properties are the values associated with an object.
In the following example we are using the length property of the String object to return the number of
characters in a string:

<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>

The output of the code above will be:


12

5.9.3 methods
Methods are the actions that can be performed on 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!";
document.write(str.toUpperCase());
</script>

44
5 - javaScript

5.10 the hierarchy of javaScript browser objects

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

45
5 - javaScript

5.11 javaScript language built in objects

5.11.1 the String object


The String object is used to manipulate a stored piece of text.

Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
Property Description F N I
F E
constructor A reference to the function that created the object 1 4 4
length Returns the number of characters in a string 1 2 3
prototype Allows you to add properties and methods to the object 1 2 4

Methods
Method Description F N I
F E
anchor() Creates an HTML anchor 1 2 3
big() Displays a string in a big font 1 2 3
blink() Displays a blinking string 1 2
bold() Displays a string in bold 1 2 3
charAt() Returns the character at a specified position 1 2 3
charCodeAt() Returns the Unicode of the character at a specified position 1 4 4
concat() Joins two or more strings 1 4 4
fixed() Displays a string as teletype text 1 2 3
fontcolor() Displays a string in a specified color 1 2 3
fontsize() Displays a string in a specified size 1 2 3
fromCharCode() Takes the specified Unicode values and returns a string 1 4 4
indexOf() Returns the position of the first occurrence of a specified string 1 2 3
value in a string
italics() Displays a string in italic 1 2 3
lastIndexOf() Returns the position of the last occurrence of a specified string 1 2 3
value, searching backwards from the specified position in a string
link() Displays a string as a hyperlink 1 2 3
match() Searches for a specified value in a string 1 4 4
replace() Replaces some characters with some other characters in a 1 4 4
string
search() Searches a string for a specified value 1 4 4
slice() Extracts a part of a string and returns the extracted part in a 1 4 4
new string
small() Displays a string in a small font 1 2 3
split() Splits a string into an array of strings 1 4 4

46
5 - javaScript

strike() Displays a string with a strikethrough 1 2 3


sub() Displays a string as subscript 1 2 3
substr() Extracts a specified number of characters in a string, from a 1 4 4
start index
substring() Extracts the characters in a string between two specified 1 2 3
indices
sup() Displays a string as superscript 1 2 3
toLowerCase() Displays a string in lowercase letters 1 2 3
toUpperCase() Displays a string in uppercase letters 1 2 3
toSource() Represents the source code of an object 1 4 -
valueOf() Returns the primitive value of a String object 1 2 4

5.11.2 the Date object


The JavaScript Date object is used to work with dates and times.

Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
F I
Property Description N
F E
constructor Returns a reference to the Date function that created the 1 4 4
object
prototype Allows you to add properties and methods to the object 1 3 4

Methods
F I
Method Description N
F E
Date() Returns today's date and time 1 2 3
getDate() Returns the day of the month from a Date object (from 1- 1 2 3
31)
getDay() Returns the day of the week from a Date object (from 0-6) 1 2 3
getFullYear() Returns the year, as a four-digit number, from a Date 1 4 4
object
getHours() Returns the hour of a Date object (from 0-23) 1 2 3
getMilliseconds() Returns the milliseconds of a Date object (from 0-999) 1 4 4
getMinutes() Returns the minutes of a Date object (from 0-59) 1 2 3
getMonth() Returns the month from a Date object (from 0-11) 1 2 3
getSeconds() Returns the seconds of a Date object (from 0-59) 1 2 3
getTime() Returns the number of milliseconds since midnight Jan 1, 1 2 3
1970
getTimezoneOffset() Returns the difference in minutes between local time and 1 2 3
Greenwich Mean Time (GMT)
getUTCDate() Returns the day of the month from a Date object according 1 4 4
to universal time (from 1-31)

47
5 - javaScript

getUTCDay() Returns the day of the week from a Date object according 1 4 4
to universal time (from 0-6)
getUTCMonth() Returns the month from a Date object according to 1 4 4
universal time (from 0-11)
getUTCFullYear() Returns the four-digit year from a Date object according to 1 4 4
universal time
getUTCHours() Returns the hour of a Date object according to universal 1 4 4
time (from 0-23)
getUTCMinutes() Returns the minutes of a Date object according to universal 1 4 4
time (from 0-59)
getUTCSeconds() Returns the seconds of a Date object according to 1 4 4
universal time (from 0-59)
getUTCMilliseconds() Returns the milliseconds of a Date object according to 1 4 4
universal time (from 0-999)
getYear() Returns the year, as a two-digit or a three/four-digit 1 2 3
number, depending on the browser. Use getFullYear()
instead !!
parse() Takes a date string and returns the number of milliseconds 1 2 3
since midnight of January 1, 1970
setDate() Sets the day of the month in a Date object (from 1-31) 1 2 3
setFullYear() Sets the year in a Date object (four digits) 1 4 4
setHours() Sets the hour in a Date object (from 0-23) 1 2 3
setMilliseconds() Sets the milliseconds in a Date object (from 0-999) 1 4 4
setMinutes() Set the minutes in a Date object (from 0-59) 1 2 3
setMonth() Sets the month in a Date object (from 0-11) 1 2 3
setSeconds() Sets the seconds in a Date object (from 0-59) 1 2 3
setTime() Calculates a date and time by adding or subtracting a 1 2 3
specified number of milliseconds to/from midnight January 1,
1970
setUTCDate() Sets the day of the month in a Date object according to 1 4 4
universal time (from 1-31)
setUTCMonth() Sets the month in a Date object according to universal time 1 4 4
(from 0-11)
setUTCFullYear() Sets the year in a Date object according to universal time 1 4 4
(four digits)
setUTCHours() Sets the hour in a Date object according to universal time 1 4 4
(from 0-23)
setUTCMinutes() Set the minutes in a Date object according to universal 1 4 4
time (from 0-59)
setUTCSeconds() Set the seconds in a Date object according to universal 1 4 4
time (from 0-59)
setUTCMilliseconds() Sets the milliseconds in a Date object according to 1 4 4
universal time (from 0-999)
setYear() Sets the year in the Date object (two or four digits). Use 1 2 3
setFullYear() instead !!
toDateString() Returns the date portion of a Date object in readable form
toGMTString() Converts a Date object, according to Greenwich time, to a 1 2 3
string. Use toUTCString() instead !!

48
5 - javaScript

toLocaleDateString() Converts a Date object, according to local time, to a string 1 4 4


and returns the date portion
toLocaleTimeString() Converts a Date object, according to local time, to a string 1 4 4
and returns the time portion
toLocaleString() Converts a Date object, according to local time, to a string 1 2 3
toSource() Represents the source code of an object 1 4 -
toString() Converts a Date object to a string 1 2 4
toTimeString() Returns the time portion of a Date object in readable form
toUTCString() Converts a Date object, according to universal time, to a 1 4 4
string
UTC() Takes a date and returns the number of milliseconds since 1 2 3
midnight of January 1, 1970 according to universal time
valueOf() Returns the primitive value of a Date object 1 2 4

5.11.3 the Array object


The JavaScript Array object is used to store a set of values in a single variable name.

Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
F I
Property Description N
F E
constructor Returns a reference to the array function that created the object 1 2 4
index 1 3 4
input 1 3 4
length Sets or returns the number of elements in an array 1 2 4
prototype Allows you to add properties and methods to the object 1 2 4

Methods
Method Description F N I
F E
concat() Joins two or more arrays and returns the result 1 4 4
join() Puts all the elements of an array into a string. The elements are 1 3 4
separated by a specified delimiter
pop() Removes and returns the last element of an array 1 4 5
.5
push() Adds one or more elements to the end of an array and returns 1 4 5
the new length .5
reverse() Reverses the order of the elements in an array 1 3 4
shift() Removes and returns the first element of an array 1 4 5
.5
slice() Returns selected elements from an existing array 1 4 4
sort() Sorts the elements of an array 1 3 4
splice() Removes and adds new elements to an array 1 4 5
.5

49
5 - javaScript

toSource() Represents the source code of an object 1 4 -


toString() Converts an array to a string and returns the result 1 3 4
unshift() Adds one or more elements to the beginning of an array and 1 4 6
returns the new length
valueOf() Returns the primitive value of an Array object 1 2 4

5.11.4 the Number object


The Number object is an object wrapper for primitive numeric values.
Syntax for creating a new Number object.

var myNum=new Number(number);

Properties
FF: Firefox, IE: Internet Explorer
F I
Property Description
F E
constructor Returns a reference to the Number function that created the 1 4
object
MAX_VALUE Returns the largest possible value in JavaScript 1 4
MIN_VALUE Returns the smallest possible value in JavaScript 1 4
NaN Represents "Not-a-number" value 1 4
NEGATIVE_INFINITY Represents a value that is less than MIN_VALUE 1 4
POSITIVE_INFINITY Represents a value that is greater than MAX_VALUE 1 4
prototype Allows you to add properties and methods to the object 1 4

Methods
Method Description F I
F E
toExponential() Converts the value of the object into an exponential notation 1 5
.5
toFixed() Formats a number to the specified number of decimals 1 5
.5
toLocaleString()
toPrecision() Converts a number into an exponential notation if it has more 1 5
digits than specified .5
toString() Converts the Number object into a string 1 4
valueOf() Returns the value of the Number object 1 4

5.11.5 the Boolean object


The JavaScript Boolean object is an object wrapper for a Boolean value.

Properties
FF: Firefox, N: Netscape, IE: Internet Explorer

50
5 - javaScript

F I
Property Description N
F E
constructor Returns a reference to the Boolean function that created the 1 2 4
object
prototype Allows you to add properties and methods to the object 1 2 4

Methods
Method Description F N I
F E
toSource() Returns the source code of the object 1 4 -
toString() Converts a Boolean value to a string and returns the result 1 4 4
valueOf() Returns the primitive value of a Boolean object 1 4 4

5.11.6 the Math Object


The JavaScript Math object allows you to perform common mathematical tasks. It includes several
mathematical constants and functions.

Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
F I
Property Description N
F E
E Returns Euler's constant (approx. 2.718) 1 2 3
LN2 Returns the natural logarithm of 2 (approx. 0.693) 1 2 3
LN10 Returns the natural logarithm of 10 (approx. 2.302) 1 2 3
LOG2E Returns the base-2 logarithm of E (approx. 1.442) 1 2 3
LOG10E Returns the base-10 logarithm of E (approx. 0.434) 1 2 3
PI Returns PI (approx. 3.14159) 1 2 3
SQRT1_2 Returns the square root of 1/2 (approx. 0.707) 1 2 3
SQRT2 Returns the square root of 2 (approx. 1.414) 1 2 3

Methods
Method Description F N I
F E
abs(x) Returns the absolute value of a number 1 2 3
acos(x) Returns the arccosine of a number 1 2 3
asin(x) Returns the arcsine of a number 1 2 3
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and 1 2 3
PI/2 radians
atan2(y,x) Returns the angle theta of an (x,y) point as a numeric value 1 2 3
between -PI and PI radians
ceil(x) Returns the value of a number rounded upwards to the nearest 1 2 3
integer
cos(x) Returns the cosine of a number 1 2 3

51
5 - javaScript

exp(x) Returns the value of Ex 1 2 3


floor(x) Returns the value of a number rounded downwards to the nearest 1 2 3
integer
log(x) Returns the natural logarithm (base E) of a number 1 2 3
max(x,y) Returns the number with the highest value of x and y 1 2 3
min(x,y) Returns the number with the lowest value of x and y 1 2 3
pow(x,y) Returns the value of x to the power of y 1 2 3
random() Returns a random number between 0 and 1 1 2 3
round(x) Rounds a number to the nearest integer 1 2 3
sin(x) Returns the sine of a number 1 2 3
sqrt(x) Returns the square root of a number 1 2 3
tan(x) Returns the tangent of an angle 1 2 3
toSource() Represents the source code of an object 1 4 -
valueOf() Returns the primitive value of a Math object 1 2 4

5.12 how to create your own objects

An object is just a special kind of data, with a collection of properties and methods.
Let's illustrate with an example: A person is an object. Properties are the values associated with the
object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All
persons have these properties, but the values of those properties will differ from person to person.
Objects also have methods. Methods are the actions that can be performed on objects. The persons'
methods could be eat(), sleep(), work(), play(), etc.

5.12.1 Properties
The syntax for accessing a property of an object is:

objName.propName

You can add properties to an object by simply giving it a value. Assume that the personObj already
exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";
document.write(personObj.firstname);

The code above will generate the following output:


John

5.12.2 Methods
An object can also contain methods.
You can call a method with the following syntax:
objName.methodName()

52
5 - javaScript

There are different ways to create a new object:

5.12.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();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";

Adding a method to the personObj is also simple. The following code adds a method called eat() to
the personObj:

personObj.eat=eat;

5.12.4 create a template of an object


The template defines the structure of an object:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

Notice that the template is just a function. Inside the function you need to assign things to
this.propertyName. 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). That's what "this" is: the instance of the
object at hand.
Once you have the template, you can create new instances of the object, like this:

myFather=new person("John","Doe",50,"blue");
myMother=new person("Sally","Rally",48,"green");

You can also add some methods to the person object. This is also done inside the template:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

53
5 - javaScript

this.newlastname=newlastname;
}

Note that methods are just functions attached to objects. Then we will have to write the
newlastname() function:

function newlastname(new_lastname)
{
this.lastname=new_lastname;
}

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.". So, now you can write:
myMother.newlastname("Doe").

5.13 JavaScript Events

New to HTML 4.0 was the ability to let HTML events trigger actions in the browser, like starting a
JavaScript when a user clicks on an HTML element.
Every element on a web page has certain events which can trigger JavaScript functions. For
example, we can use the onClick event of a button element to indicate that a function will run when a
user clicks on the button. We define the events in the HTML tags.

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, 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, Netscape an Internet Explorer for each such event.

Event The event occurs when... F N I


F E
onabort Loading of an image is interrupted 1 3 4
onblur An element loses focus 1 2 3
onchange The user changes the content of a field 1 2 3
onclick Mouse clicks an object 1 2 3
ondblclick Mouse double-clicks an object 1 4 4
onerror An error occurs when loading a document or an image 1 3 4

54
5 - javaScript

onfocus An element gets focus 1 2 3


onkeydown A keyboard key is pressed 1 4 3
onkeypress A keyboard key is pressed or held down 1 4 3
onkeyup A keyboard key is released 1 4 3
onload A page or an image is finished loading 1 2 3
onmousedown A mouse button is pressed 1 4 4
onmousemove The mouse is moved 1 6 3
onmouseout The mouse is moved off an element 1 4 4
onmouseover The mouse is moved over an element 1 2 3
onmouseup A mouse button is released 1 4 4
onreset The reset button is clicked 1 3 4
onresize A window or frame is resized 1 4 4
onselect Text is selected 1 2 3
onsubmit The submit button is clicked 1 2 3
onunload The user exits the page 1 2 3

5.13.1 onload and onUnload


The onload and onUnload events are triggered when the user enters or leaves the page.

The onload event is often used to check the visitor's browser type and browser version, and load the
proper version of the web page based on the information.
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. For example, you could have a popup asking for the user's
name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor
arrives at your page, you could have another popup saying something like: "Welcome John Doe!".

5.13.2 onFocus, onBlur and onChange


The onFocus, onBlur and onChange events are often used in combination with validation of form
fields.
Below is an example of how to use the onChange event. The checkEmail() function will be called
whenever the user changes the content of the field:

<input type="text" size="30" id="email" onchange="checkEmail()">;

5.13.3 onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.
Below is an example of how to use the onSubmit event. The checkForm() function will be called
when the user clicks the submit button in the form. If the field values are not accepted, the submit
should be cancelled. The function checkForm() returns either true or false. If it returns true the form
will be submitted, otherwise the submit will be cancelled:

<form method="post" action="xxx.htm" onsubmit="return checkForm()">

5.13.4 onMouseOver and onMouseOut


onMouseOver and onMouseOut are often used to create "animated" buttons.

55
5 - javaScript

Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event
is detected:
<a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false">
<img src="w3schools.gif" width="100" height="30"> </a>

56
6 - Html DOM

6 - HTML DOM
6.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, structure, and style of a
document.
The W3C DOM provides a standard set of objects for HTML and XML documents, and a standard
interface for accessing and manipulating them.
The W3C DOM is separated into different parts (Core, XML, and HTML) and different levels (DOM
Level 1/2/3):
Core DOM - defines a standard set of objects for any structured document
XML DOM - defines a standard set of objects for XML documents
HTML DOM - 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. However, the
DOM is required by JavaScript scripts that wish to inspect or modify a web page dynamically. In other
words, the Document Object Model is the way JavaScript sees its containing HTML page and browser
state.
Because the DOM supports navigation in any direction (e.g., parent and previous sibling) and allows
for arbitrary modifications, an implementation must at least buffer the document that has been read so
far (or some parsed form of it). Hence the DOM is likely to be best suited for applications where the
document must be accessed repeatedly or out of sequence order. If the application is strictly
sequential and one-pass, the SAX model is likely to be faster and use less memory. SAX (Simple API
for XML) is a sequential access parser API for XML. SAX provides a mechanism for reading data
from an XML document. It is a popular alternative to the Document Object Model (DOM).

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, particularly those used in Web
browsers. The existing vendor-specific interfaces were dubbed intermediate DOMs.
W3C began development of the DOM in the mid-1990s. Although the W3C never produced a
specification for DOM 0, it was nonetheless a partially documented model and was included in the
specification of HTML 4. By October 1998, the first specification of DOM (DOM 1) was released. DOM
2 was issued in November 2000, with specifics on the style sheet object model and style information
manipulation. DOM 3 was released in April 2004 and is the current release of the DOM specification.
As of January 2008, the Document Object Model activity is closed. The Document Object Model
Working Group was closed in the Spring of 2004, after the completion of the DOM Level 3
Recommendations. Several W3C Working Groups have since taken the lead in maintaining and
continuing to develop standard APIs for the Web since then; HTML, SVG, CSS, or WebAPI being
among them.
Right until now (oct. 2015), what drove the DOM Specifications was the WebApps WG. The W3C
Web Applications Working Group has taken over responsibility for the Document Object Model
specifications, including a new revision of DOM Level 3 Events, a new DOM Core specification, and
potentially any errata on older DOM specifications.
The main deadline for this work group's activity was May 2014. Among the deliverables expected
were the following:

57
6 - Html DOM

Web Storage API


Indexed Database API
DOM4
DOM Level 3 Events
DOM Parsing and Serialization
Web Messaging
Web Workers
Web Sockets API
Widgets
XMLHttpRequest (XHR)

The Web Applications Working group has ceased its activity in October 2015. Its deliverables were
transferred to the Web Platform Working Group.
The W3C Web Platform Working Group is chartered to continue the development of the HTML
language, providing specifications that enable improved client-side application development on the
Web, including application programming interfaces (APIs) for client-side development and markup
vocabularies for describing and controlling client-side application behavior.

6.3 levels

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

58
6 - Html DOM

6.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
Document Object Model (DOM) Level 3 Load and Save Specification
Document Object Model (DOM) Level 3 Validation Specification
Level 3 Working Group Notes:
Document Object Model (DOM) Level 3 XPath Specification
Document Object Model (DOM) Level 3 Views and Formatting Specification
Document Object Model (DOM) Requirements
Working Draft
Window Object 1.0

6.5 web browsers implementation

Earlier, when each Web browser exclusively supported its own intermediate DOM, interoperability
problems were numerous. In order to be cross-browser compatible, that is, support multiple browsers,
large parts of Dynamic HTML code had to be rewritten for each browser to be supported. A common
DOM promised substantial simplification of the development of complex Web applications.
W3C DOM Level 1 has been a recommendation since 1 October 1998. The standardization effort
did not bring forth an immediate change, because non-conformant browsers such as Internet Explorer
4.x and Netscape 4.x were still widely used in 2000. By 2005, large parts of W3C DOM were well-
supported by common JavaScript-enabled Web browsers, including Microsoft Internet Explorer
(version 5 (1999) and version 6 (2001)), Gecko-based browsers (like Mozilla and Firefox), Opera,
Konqueror, and Safari. Web developers are starting to rely mostly or solely on W3C DOM, since it
allows browser compatibility with a large audience.

6.6 javaScript specific objects

In addition to the built-in JavaScript objects, you can also access and manipulate all of the HTML
DOM objects with JavaScript. Besides the generic objects listed bellow, the bulk of the HTML DOM
objects are presented in the next paragraph.

Object Description
Window The top level object in the JavaScript hierarchy. The Window object
represents a browser window. A Window object is created automatically
with every instance of a <body> or <frameset> tag
Navigator Contains information about the client's browser
Screen Contains information about the client's display screen
History Contains the visited URLs in the browser window

59
6 - Html DOM

Location Contains information about the current URL

6.7 the HTML DOM

The HTML DOM defines a standard set of objects for HTML, and a standard way to access and
manipulate HTML documents.
All HTML elements, along with their containing text and attributes, can be accessed through the
DOM. The contents can be modified or deleted, and new elements can be created.
The HTML DOM is platform and language independent. It can be used by any programming
language like Java, JavaScript, and VBScript.

HTML DOM Objects

Object Description
Document Represents the entire HTML document and can be used to access all
elements in a page
Anchor Represents an <a> element
Area Represents an <area> element inside an image-map
Base Represents a <base> element (specifies a default address or a default
target for all links on a page)
Body Represents the <body> element
Button Represents a <button> element
Event Represents the state of an event
Form Represents a <form> element
Frame Represents a <frame> element
Frameset Represents a <frameset> element
Iframe Represents an <iframe> element
Image Represents an <img> element
Input button Represents a button in an HTML form
Input checkbox Represents a checkbox in an HTML form
Input file Represents a fileupload in an HTML form
Input hidden Represents a hidden field in an HTML form
Input password Represents a password field in an HTML form
Input radio Represents a radio button in an HTML form
Input reset Represents a reset button in an HTML form
Input submit Represents a submit button in an HTML form
Input text Represents a text-input field in an HTML form
Link Represents a <link> element
Meta Represents a <meta> element
Option Represents an <option> element
Select Represents a selection list in an HTML form
Style Represents an individual style statement
Table Represents a <table> element

60
6 - Html DOM

TableData Represents a <td> element


TableRow Represents a <tr> element
Textarea Represents a <textarea> element

6.8 DOM nodes

According to the DOM, everything in an HTML document is a node.


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.8.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>. All other nodes in the document are contained within
<html>.
The <html> node has two child nodes; <head> and <body>.
The <head> node holds a <title> node. The <body> node holds a <h1> and <p> node.

6.8.2 text is always stored in text nodes


A common error in DOM processing is to expect an element node to contain text.
However, the text of an element node is stored in a text node.
In this example: <title>DOM Tutorial</title>, the element node <title>, holds a text node with the
value "DOM Tutorial".
"DOM Tutorial" is not the value of the <title> element!
However, in the HTML DOM the value of the text node can be accessed by the innerHTML
property.

6.9 the HTML DOM Node Tree

61
6 - Html DOM

6.9.1 the Document Tree


The HTML DOM views a HTML document as a tree-structure. The tree structure is called a node-
tree.
All nodes can be accessed through the tree. Their contents can be modified or deleted, and new
elements can be created.
The node tree below shows the set of nodes, and the connections between them. The tree starts at
the root node and branches out to the text nodes at the lowest level of the tree:

6.9.2 node parents, children, and siblings


The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships. Parent nodes have
children. Children on the same level are called siblings (brothers or sisters).
In a node tree, the top node is called the root
Every node, except the root, 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.9.3 accessing nodes


You can access a node in three ways:
1. By using the getElementById() method
2. By using the getElementsByTagName() method
3. By navigating the node tree, using the node relationships.

The following example returns a nodeList of all <p> elements that are descendants of the element
with id="main":
document.getElementById('main').getElementsByTagName("p");

The length property defines the length of a node list (the number of nodes). You can loop through a
node list by using the length property:
x=document.getElementsByTagName("p");

62
6 - Html DOM

for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}

6.9.4 Node Properties


In the HTML Document Object Model (DOM), each node is an object.
Objects have methods (functions) and properties (information about the object), that can be
accessed and manipulated by JavaScript.
Three important HTML DOM node properties are:
nodeName
nodeValue
nodeType

the nodeName Property


The nodeName property specifies the name of a node.
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.
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. The most important node types
are:

Element type NodeType


Element 1
Attribute 2
Text 3
Comment 8
Document 9

63
6 - Html DOM

6.9.5 example - get the value of an element


The following code fragment retrieves the text node value of the first <p> element:
x=document.getElementById("intro").firstChild;
txt=x.nodeValue;

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

Category Type Attribute Description


Fires when the pointing device
button is clicked over an element.
A click is defined as a mousedown
and mouseup over the same
click onclick screen location. The sequence of
these events is:
mousedown
mouseup
click
Fires when the pointing device
dblclick ondblclick button is double clicked over an
Mouse element
Fires when the pointing device
mousedown onmousedown
button is pressed over an element
Fires when the pointing device
mouseup onmouseup
button is released over an element
Fires when the pointing device is
mouseover onmouseover
moved onto an element
Fires when the pointing device is
mousemove onmousemove
moved while it is over an element
Fires when the pointing device is
mouseout onmouseout
moved away from an element
Keyboard keypress onkeypress Fires when a key on the
keyboard is "clicked". A keypress is
defined as a keydown and keyup
on the same key. The sequence of
these events is:
keydown
keyup
keypress

64
6 - Html DOM

Fires when a key on the


keydown onkeydown
keyboard is pressed
Fires when a key on the
keyup onkeyup
keyboard is released
Fires when the user agent
finishes loading all content within a
document, including window,
load onload frames, 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
unload onunload or frame. For elements, it fires
when the target element or any of
HTML
its content has been removed
frame/object
Fires when an object/image is
abort onabort stopped from loading before
completely loaded
Fires when an
error onerror object/image/frame cannot be
loaded properly
Fires when a document view is
resize onresize
resized
Fires when a document view is
scroll onscroll
scrolled
Fires when a user selects some
select onselect text in a text field, including input
and textarea
Fires when a control loses the
change onchange input focus and its value has been
modified since gaining focus
HTML submit onsubmit Fires when a form is submitted
form reset onreset Fires when a form is reset
Fires when an element receives
focus onfocus focus either via the pointing device
or by tab navigation
Fires when an element loses
blur onblur focus either via the pointing device
or by tabbing navigation
Similar to HTML focus event, but
DOMFocusIn ondomfocusin can be applied to any focusable
element
Similar to HTML blur event, but
User DOMFocusOut ondomfocusout can be applied to any focusable
interface element
Similar to XUL command event.
Fires when an element is activated,
DOMActivate ondomactivate
for instance, through a mouse click
or a keypress.

65
6 - Html DOM

Fire when the subtree is


DOMSubtreeModified onsubtreemodified
modified
Fires when a node has been
DOMNodeInserted onnodeinserted
added as a child of another node
Fires when a node has been
DOMNodeRemoved onnoderemoved
removed from a DOM-tree
Mutation
NodeInsertedIntoDoc onnodeinsertedinto Fires when a node is being
ument document inserted into a document
Fires when an attribute has been
DOMAttrModified onattrmodified
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. Mozilla and
Opera support DOMAttrModified, DOMNodeInserted, DOMNodeRemoved and
DOMCharacterDataModified. Safari, as of version 1.3, also supports these methods.
Also, Mozilla, Safari and Opera also support readystatechange event for the XMLHttpRequest
object. Mozilla also supports the beforeunload event using traditional event registration method (DOM
Level 0). Mozilla and Safari also support contextmenu, but Internet Explorer for the Mac does not.

6.11 event flow

Consider the situation when there are 2 elements nested together. Both have event handlers
registered on the same event type, say "click". When the user clicks on the inner element, there are
two possible ways to handle it:
Trigger the elements from outer to inner (event capturing). This model is implemented in
Netscape Navigator.
Trigger the elements from inner to outer (event bubbling). This model is implemented in
Internet Explorer and other browsers.
W3C takes a middle position in this struggle. Events are first captured until it reaches the target
element, and then bubbled up. During the event flow, an event can be responded to at any element in
the path (an observer) in either phase by causing an action, and/or by stopping the event (with method
event.stopPropagation() for Mozilla and command event.cancelBubble = true for
Internet Explorer), and/or by cancelling the default action for the event.

6.12 the Event object

The Event object provides a lot of information about a particular event, including information about
target element, key pressed, mouse button pressed, mouse position, etc. Unfortunately, there are very
serious browser incompatibilities in this area. Hence only the W3C Event object is discussed here.

Event properties

Type Name Description


DOMString type The name of the event (case-insensitive).

66
6 - Html DOM

Used to indicate the EventTarget to which the event was


EventTarget target
originally dispatched.
Used to indicate the EventTarget whose EventListeners
EventTarget currentTarget
are currently being processed.
Used to indicate which phase of event flow is currently
unsigned short eventPhase
being evaluated.
Used to indicate whether or not an event is a bubbling
boolean bubbles
event.
Used to indicate whether or not an event can have its
boolean cancelable
default action prevented.
Used to specify the time (in milliseconds relative to the
DOMTimeStamp timeStamp
epoch) at which the event was created.

Event methods

Argument Argument
Name Description
type name
To prevent further propagation of an
stopPropagation
event during event flow.
To cancel the event if it is cancelable,
meaning that any default action normally
preventDefault
taken by the implementation as a result of
the event will not occur.
DOMString eventTypeArg Specifies the event type.
Specifies whether or not the event can
boolean canBubbleArg
initEvent bubble.
Specifies whether or not the event's
boolean cancelableArg
default action can be prevented.

67
7 - AJAX

7 - AJAX
7.1 what is ajax?

Ajax stands for Asynchronous JavaScript And XML. It is not a technology in itself, but rather a
collection of existing technologies bound together by JavaScript.

HTML and CSS for presenting.


JavaScript (ECMAScript) for local processing, and DOM (Document Object Model) to access
data inside the page or to access elements of the Xml file read on the server (with the
getElementByTagName method, for example)
The XMLHttpRequest class to read or send data on the server asynchronously.
optionally
The DomParser class may be used
PHP or another scripting language may be used on the server.
XML and XSLT to process the data if returned in Xml form.
SOAP may be used to dialog with the server.
XSL stands for EXtensible Stylesheet Language while XSLT stands for XSL Transformations
The "Asynchronous" word means that the response of the server will be processed when available,
without having to wait and to freeze the display of the page.

7.2 why use ajax?

Mainly to build a fast, dynamic website, but also to save resources. For improving sharing of
resources, it is better to use the power of all the client computers rather than just an unique server and
network. Ajax allows to perform processing on the client computer (in JavaScript) with data taken from
the server.
The processing of web pages was formerly done only server-side, using web services or Php
scripts, before the whole page was sent within the network.
But Ajax can selectively modify a part of a page displayed by the browser and update it without the
need to reload the whole document with all images, menus, etc.
For example, fields of forms, choices of user, may be processed and the result displayed
immediately into the same page.
Lately, the Ajax functionality is provided in a more direct approach, using calls provided by
specialized JavaScript libraries, like jQuery or AngularJS.

7.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 server does some processing retrieving data, crunching
numbers, talking to various legacy systems and then returns an HTML page to the client. Its a
model adapted from the Webs original use as a hypertext medium, but what makes the Web good for

68
7 - AJAX

hypertext doesnt necessarily make it good for software applications.

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

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

7.4 how does it work?

70
7 - AJAX

Ajax uses a programming model with display and events. These events are user actions, they call
functions associated to elements of the web page.
Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with
actions and also to extract data from Xml files provided by the server.
To get data on the server, the ajax engine uses the XMLHttpRequest object. This object provides
two methods:
- open: create a connection.
- send: send a request to the server.
Data provided by the server will be found in these attributes of the XMLHttpRequest object:
- responseXml - for a Xml file or
- responseText - for a simple text.
Take note that a new XMLHttpRequest object has to be created for each new file to load.
We have to wait for the data to be available to process it, and in this purpose, the state of availability
of data is given by the readyState attribute of XMLHttpRequest.
States of readyState follow (only the last one is really useful):

0: not initialized.
1: connection established.
2: request received.
3: answer in process.
4: finished.

7.5 the XMLHttpRequest class

Here is a closer look to the XMLHttpRequest class. It allows the interaction with the servers, thanks
to its methods and attributes.

Attributes
readyState - the code successively changes value from 0 to 4 that means "ready".
status - returned by the server - 200 is ok, 404 if the page is not found
responseText - holds loaded data as a string of characters.
responseXml - holds a Xml loaded file, DOM's method allows to extract data.
onreadystatechange - the name of the function invoked

Methods
open(mode, url, boolean) - mode: type of request, GET or POST
- url: the location of the file
- boolean: true (asynchronous) / false (synchronous)
send("string") - null for a GET command

7.6 building a request, step by step

71
7 - AJAX

First step: create an instance


This is just a classical instance of a class, but two options must be tried, for browser compatibility.

if (window.XMLHttpRequest) // Object of the current windows


{
request = new XMLHttpRequest(); // Firefox, Safari, ...
}
else if (window.ActiveXObject) // ActiveX version
{
request = new ActiveXObject("Microsoft.XMLHTTP"); // 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.

request.onreadystatechange = function()
{ // instructions to process the response };

if (request.readyState == 4)
{
// received, OK
}
else
{
// wait...
}

Third step: make the request itself


Two methods of XMLHttpRequest are used:

- open: command GET or POST, URL of the document, true for asynchronous.
- send: with POST only, the data to send to the server.

The request below reads a document on the server.

http_request.open('GET', 'http://www.xul.fr/somefile.xml', true);


http_request.send(null);

7.7 examples
7.7.1 How to get a text
<html>
<head>
<script>
function submitForm()

72
7 - AJAX

{
var req = null;
if(window.XMLHttpRequest) req = new XMLHttpRequest();
else if (window.ActiveXObject)
req = new ActiveXObject(Microsoft.XMLHTTP);

req.onreadystatechange = function()
{
if(req.readyState == 4)
if(req.status == 200)
document.ajax.dyn="Received:" + req.responseText;
else
document.ajax.dyn="Error code " + req.status;
};

req.open("GET", "data.xml", true);


req.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
req.send(null);
}
</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.7.2 how to get from xml


To get data from a xml file we have just to replace this line:
document.ajax.dyn=""Received:" + req.responseText;

by this code:

var doc = req.responseXML; // assign the Xml file to a var


var element = doc.getElementsByTagName('root').item(0); // read the
first element with a dom's method
document.ajax.dyn.value= element.firstChild.data; // assign the
content of the element to the form

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

73
7 - AJAX

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

7.10 Specifications

Ajax is based on these specifications:


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

74
8 - WEB APPLICATIONS

8 - WEB APPLICATIONS
8.1 web application types

A web application is a dynamic extension of a web or application server. Web applications are of
the following types:
Presentation-oriented: A presentation-oriented web application generates interactive web
pages containing various types of markup language (HTML, XHTML, XML, and so on) and
dynamic content in response to requests.
Service-oriented: A service-oriented web application implements the endpoint of a web
service. Presentation-oriented applications are often clients of service-oriented web
applications.
In the Java EE platform, web components provide the dynamic extension capabilities for a web
server. Web components can be Java servlets, web pages implemented with JavaServer Faces
technology, web service endpoints, or JSP pages.
Servlets are Java programming language classes that dynamically process requests and construct
responses. Java technologies, such as JavaServer Faces and Facelets, are used for building
interactive web applications. (Frameworks can also be used for this purpose.) Although servlets and
JavaServer Faces and Facelets pages can be used to accomplish similar things, each has its own
strengths. Servlets are best suited for service-oriented applications (web service endpoints can be
implemented as servlets) and the control functions of a presentation-oriented application, such as
dispatching requests and handling nontextual data. JavaServer Faces and Facelets pages are more
appropriate for generating text-based markup, such as XHTML, and are generally used for
presentation-oriented applications.
Web components are supported by the services of a runtime platform called a web container. A
web container provides such services as request dispatching, security, concurrency, and lifecycle
management. A web container also gives web components access to such APIs as naming,
transactions, and email.
Certain aspects of web application behavior can be configured when the application is installed, or
deployed, to the web container. The configuration information can be specified using Java EE
annotations or can be maintained in a text file in XML format called a web application deployment
descriptor (DD). A web application DD must conform to the schema described in the Java Servlet
specification.

8.2 web application lifecycle

A web application consists of web components; static resource files, such as images and cascading
style sheets (CSS); and helper classes and libraries. The web container provides many supporting
services that enhance the capabilities of web components and make them easier to develop.
However, because a web application must take these services into account, the process for creating
and running a web application is different from that of traditional stand-alone Java classes.
The process for creating, deploying, and executing a web application can be summarized as follows:
1. Develop the web component code.
2. Develop the web application deployment descriptor, if necessary.
3. Compile the web application components and helper classes referenced by the components.
4. Optionally, package the application into a deployable unit.
5. Deploy the application into a web container.
6. Access a URL that references the web application.

75
8 - WEB APPLICATIONS

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

Besides these mandatory parts, a web application may contain other, generic or application server
specific files. Typically, the WEB-INF directory may contain a generic application.xml file or a vendor
specific xml file. For example, on a Weblogic application server, the WEB-INF directory contains an
extra deployment descriptor, called weblogic.xml.

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
Starting with Java EE 5, the content of the deployment descriptor may be replaced by annotations
within the java source files of the application.
Annotations are a form of syntactic metadata (smart comments) that can be added to Java source
code. Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc
tags, Java annotations can be reflective in that they can be embedded in class files generated by the
compiler and may be retained by the Java VM to be made retrievable at run-time.

8.4 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 (BEA Systems, now Oracle), Enterprise Application Server
(Borland) 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 with

76
8 - WEB APPLICATIONS

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

Deployment descriptor Deployment descriptor

Java EE Web Container

8.5 web container providers

8.5.1 non-commercial web containers


Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under
the Apache Software License.
Apache Geronimo is a full Java EE implementation by Apache.
GlassFish (open source), from Oracle
JBoss Application Server (open source) is a full Java EE implementation by Red Hat inc.,
division Jboss.
Jetty is (open source) from the Eclipse Foundation. Also supports SPDY and WebSocket
protocols.
Jaminid contains a higher abstraction than servlets.
Enhydra Winstone has a focus on minimal configuration and the ability to strip the container

77
8 - WEB APPLICATIONS

down to only what you need.


Tiny Java Web Server (TJWS) 2.5 [1], small footprint, modular design
Eclipse Virgo provides modular, OSGi based web containers implemented using embedded
Tomcat and Jetty. Virgo is open source and available under theEclipse Public License.

8.5.2 commercial web containers


Borland Enterprise Server
Sun GlassFish Server, from Sun Microsystems (bought by Oracle)
Sun Java System Web Server, from Sun Microsystems (Oracle now)
Sun Java System Application Server (is an Application Server, but includes a web container)
JBoss Enterprise Application Platform (open source)
JRun, from Adobe Systems (formerly developed by Allaire Corporation)
LiteWebServer (open source)
WebLogic Application Server, from Oracle Corporation (developed by BEA Systems)
Orion Application Server, from IronFlare
Caucho's Resin Server (open source)
ServletExec, from New Atlanta Communications
WebSphere Application Server, from IBM
NetWeaver, from SAP
tc Server (SpringSource)

8.6 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.
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.
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 Java EE remote connectivity model manages low-level communications between
clients and enterprise beans. After an enterprise bean is created, a client invokes methods on
it as if it were in the same virtual machine.
Because the Java EE architecture provides configurable services, application components within the
same Java EE application can behave differently based on where they are deployed. For example, 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.

78
8 - WEB APPLICATIONS

The container also manages nonconfigurable services such as enterprise bean and servlet life
cycles, database connection resource pooling, data persistence, and access to the Java EE platform
APIs.

8.7 deployment descriptor

The deployment descriptor is an xml file (named, in general, web.xml) which allows the
customization of the web application at deployment time. Extra deployment information can be
contained in separate xml file(s) (like application.xml) or included as annotation(s) in the java source
files.
The deployment descriptor serves several purposes, like:
1. Initialization of parameters for servlets, JSPs and Java Server Faces.
2. Servlet, JSPs and Java Server Faces definitions, servlet classes, precompiled JSP entities are
declared (names, classes, descriptions).
3. Servlet, JSPs and Java Server Faces mappings.
4. MIME types used by the web application.
5. Security related entries may specify which pages require login and the roles different users
may have.
6. Others, like what pages are error, welcome pages, entries related to session configuration.
Here is a small, but typical web.xml file:

<?xml version="1.0" encoding="ISO-8859-1" ?>


<!DOCTYPE web-app (View Source for full doctype...)>
<web-app>
<!-- Define the Bank 11 ccards Servlets -->
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.bank11.ccards.servlets.LoginServlet
</servlet-class>
</servlet>
</web-app>

8.8 practical deployment issues

There are several issues with the web applications deployment. Behind a very benign URL, like
"http://localhost:8080/ccards/servlet/Enroll" there are 3 things which have to be fixed in order to make
things work properly.
Assume that we work with Tomcat and that the environment variable %TOMCAT_HOME% (or
$TOMCAT_HOME, in an UNIX environment) is set to "C:\TW\Tomcat".

1. The "/servlet" part of the URL tells the web server (Tomcat, in our case) to execute the invoker
servlet. This association is made in the file "%TOMCAT_HOME%\conf\web.xml". Unfortunately,
the lines which deal with this issue are commented out in the latest version of Tomcat (for so-
called "security issues"). To make anything work:
de-comment the following section:

79
8 - WEB APPLICATIONS

<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

in the configuration file "%TOMCAT_HOME%\conf\web.xml"

2. The "/ccards" part of the URL is, basicly, the name of the web application. In general, the base
directory of an application is a subdirectory of the "%TOMCAT_HOME%\webapps" directory.
This subdirectory has (in general) the same name as the application itself. However, for
flexibility, the location of the base directory of a web application may be any sub(sub)directory
of "%TOMCAT_HOME%\webapps". 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.xml" file. For example, if the base directory of the "/ccards"
web application is "%TOMCAT_HOME%\webapps\vdumitrascu\cc", then the corresponding
<context> element in the "%TOMCAT_HOME%\conf\server.xml" file looks like:

<context path="/ccards" docbase="vdumitrascu/cc" />

3. The "/Enroll" part of the URL identifies the servlet. Basicly, it is the alias of the real servlet class,
whose name is rather long. Let's say that this class is "EnrollServlet.class" and that it is part of
the package "com.bank11.ccards.servlets". Then the "EnrollServlet.class" file must be located
in the directory "%TOMCAT_HOME%\webapps\vdumitrascu\cc\WEB-
INF\classes\com.bank11.ccards.servlets". This association between the (short) alias of the
servlet and its real (long) name is made in the web.xml file of the web application. More
exactly the corresponding <servlet> element should look like:
<servlet>
<servlet-name>Enroll</servlet-name>
<servlet-class>com.bank11.ccards.servlets.EnrollServlet
</servlet-class>
</servlet>

80
9 - SERVLETS

9 - SERVLETS
9.1 the servlets as part of web applications

Java servlets small, platform independent programs, which extend the functionality of the web
server.
Technically speaking, a servlet is a Java class that extends the GenericServlet (or, more often, the
HttpServlet) class. Theoretically, servlets can communicate over any client-server protocol, but most
often, they communicate over the HTTP protocol.
The Java Servlet API provides a simple frame for building web applications on web servers.
The first Servlet specification (version 1.0) was finalized by Sun June 1997. It continued with
versions 2.0, 2.1 and 2.2 in the next couple of years. Starting with version 2.3, the Servlet specification
is part of the Java Community process. The current (as of Oct. 2015) Java Servlet specification is 3.1
(JSR 340) and dates back to May 2013. It is part of the Java EE 7 SDKs.
The 3.1 spec is supported in Tomcat 8.0, Glassfish 4.0 and Netbeans 7.3.1.
The servlet does not communicate directly with the client, but through a web container. The servlet
lives within this container which provides an execution environment for the servlet class. Web
containers are implemented by various vendors, in most cases as part of an application server.

9.2 servlet packages and classes

The Java servlet API consists of 2 packages, which are part of the Java Platform SDK, Enterprise
Edition. These packages are:
javax.servlet
javax.servlet.http

The classes and interfaces defined in the javax.servlet package are protocol independent, while the
second one, the javax.servlet.http contains classes and interfaces which are HTTP specific.
The classes and interfaces of the Java servlet API can be divided in several categories, namely:
servlet implementation
servlet configuration
servlet exceptions
request and responses
session tracking
servlet context
servlet collaboration
miscellaneous

9.3 the Servlet interface

The Servlet interface is part of the javax.servlet package. It declares the following methods:

public void init(ServletConfig config) throws ServletException;

81
9 - SERVLETS

public void service(ServletRequest req, ServletResponse resp) throws


ServletException, IOException;
public void destroy() throws ServletException;
public ServletConfig getServletConfig();
public String getServletInfo();

After instantiating the servlet, the web container calls its init() method. The method performs all
initialization required, before the servlet processes any HTTP request. The servlet specification
insures that the init() method is called just once for any given instance of the servlet.
The web container calls the service() method in response to any incoming request. This method
has two arguments, arguments which implement the ServletRequest and ServletResponse
interfaces, respectively.
More on the servlet life cycle, in a different section.

9.4 the GenericServlet class

public abstract class GenericServlet implements


Servlet, ServletConfig, Serializable

This class provides a basic implementation of the Servlet interface. Since this class implements
the ServletConfig interface, as well, the developer may call ServletConfig methods directly,
without having to obtain a ServletConfig object first. All classes extending the GenericServlet class
should provide an implementation for the service() method.
Methods specific to this class:

public void init()


public void log(String msg)
public void log(String msg, Throwable t)

9.5 the HttpServlet class

It is very likely that the only implementation of the Servlet interface we'll ever use is one that
processes an HTTP request. The servlet API provides such a specific class, namely the
HttpServlet class.

public abstract class HttpServlet extends GenericServlet implements Serializable

The HttpServlet provides an HTTP specific implementation of the Servlet interface. This abstract
class specifies the following methods:

public void service(ServletRequest req, ServletResponse resp)


public void service(HttpServletRequest req, HttpServletResponse resp)
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)

82
9 - SERVLETS

protected void doDelete(HttpServletRequest req,


HttpServletResponse resp)
protected void doOptions(HttpServletRequest req,
HttpServletResponse resp)
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
protected void doTrace(HttpServletRequest req,
HttpServletResponse resp)

9.6 the ServletConfig interface

This interface abstracts configuration information about the servlet, namely:


initialization parameters (as name-value pairs)
the name of the servlet
a ServletContext object, containing web container information

This interface specifies the following methods:

public String getInitParameter(String name)


public Enumeration getInitParameterNames()
public ServletContext getServletContext()
public String getServletName()

9.7 servlet exceptions

The Java servlet API specifies two servlet specific exceptions:

javax.servlet.ServletException
javax.servlet.UnavailableException

The ServletException class extends java.lang.Exception and can be thrown by the


init(), service(), doXXX() and destroy() methods of the Servlet interface
implementations.
The UnavailableException indicates to the web container that the servlet instance is
unavaialble. It also extends the java.lang.Exception class.

9.8 the servlet lifecycle

Generally, a servlet instance goes through the following stages:


instantiation
initialization
service
destroy

83
9 - SERVLETS

unavailable

The container creates a servlet instance as first response to an incoming (HTTP) request or at
container startup. Typically, the web container creates a single instance of the servlet, which will
service all incoming requests. If the servlet does not implement the
javax.servlet.SingleThreadModel, concurrent requests are serviced in more than one service
thread, which requires that the service() method be thread safe.
After instantiation, the container calls the init() method of the servlet, method which performs the
initialization of the servlet. Typically, this method contains JDBC driver loading, DB connection
opening, etc.
The web container makes sure that the init() method of the servlet will be completed before
invoking its service() method. Also, the servlet's destroy() method will be called before the
servlet itself is destroyed.

9.9 the ServletRequest interface

Here are some of the methods of this interface:

public Object getAttribute(String name)


public Object setAttribute(String name, Object attr)
public Enumeration getAttributeNames()
public int getContentLength()
public String getContentType()
public String getParameter(String name)
public Enumeration getParameterNames()
public String[] getParameterValues()
public String getServerName()
public int getServerPort()
public String getRemoteAddr()
public String getRemoteHost()

Most of the above methods are self explanatory. But what is the difference between a parameter
and an attribute? While the parameters of the request are part of the request itself, the attributes of the
request are attached by the web containers or by the servlets/JSPs/JSFs.
There are 3 different ways for attaching and retrieving attributes. The first one is to attach attributes
to the request object. The other two use the HttpSession and ServletContext objects, respectively. The
purpose of attributes is to allow the container to provide additional data to a servlet, JSP or JSF, or to
allow sending data from a servlet to another.

9.10 the HttpServletRequest interface

public interface HttpServletRequest extends ServletRequest

This interface contains HTTP specific methods. One has to take in account the structure of an
HTTP request when overviewing the most important methods of this interface. Here are some of them:

84
9 - SERVLETS

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.11 the ServletResponse interface

This interface defines methods for constructing responses to servlet 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.12 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 void addCookie(Cookie cookie)


public String encodeURL(String url)
public void sendError(int status)
public void sendError(int status, String message)
public void setHeader(String headerName, String value)
public void addHeader(String headerName, String value)
public void setStatus(int statusCode)

9.13 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. Each servlet context is rooted at a specific path in the
web server. 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. This is done in server's
(container's) server.xml file.

85
9 - SERVLETS

There is only one ServletContext for the entire web application and all the components of the web
application can share it. The ServletContext is created by the container where the web application is
deployed.
The ServletContext interface abstracts the context of a web application. A reference to an
object of this type can be obtained by invoking the getServletContext() method of the
HttpServlet object.

public String getMIMEType(String fileName)


public String getResource(String path)
public ServletContext getContext(String urlPath)
public String getInitParameter(String name)
public Enumeration getInitParameterNames()
public Object getAttribute(String name)
public Enumeration getAttributeNames()
public void setAttribute(String name, Object attr)
public String removeAttribute(String name)

9.14 a simple web application using a servlet

This application consists, essentially, of


an html file OAM.html, which is the entry point of the application
a servlet OAMServlet, which processes the data sent from the OAM.html form
the deployment descriptor web.xml

9.14.1 the OAM.html form

This file is the entry point for the web application. It can be accessed by specifying in the address
field of the browser the address of the (Tomcat, in our case) server, the port number (if not the default
value of 80) and the web application id (as specified in the context element of the sever.xml file). The
OAM.html file is displayed, because this is the welcome-file specified in the deployment descriptor
web.xml.

86
9 - SERVLETS

Once the data is introduced, the client presses the submit button, a validation script is executed, and
in case data is validated, it is transmitted for processing to the servlet OAMServlet (as specified in the
ACTION attribute of the <form> element of the OAM.html file).

9.14.2 the OAM servlet

The OAM servlet services the request sent by the web browser when we submit the OAM form (the
file OAM.html)

Here is its abbreviated form of the "OAMServlet.java" file:

package com.bank11.ccards.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OAMServlet extends HttpServlet {

87
9 - SERVLETS

/**
* Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
Connection myConn=null;
boolean isThere;

@Override
public void init(ServletConfig config) throws ServletException{
super.init(config);
String driverName = getInitParameter("jdbcDriver");
String connURL = getInitParameter("dbServer");
try {
Class.forName(driverName).newInstance();
myConn = DriverManager.getConnection
(connURL,"tw2011","tw2011");
}catch(Exception e){
e.printStackTrace();
}
}

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
isThere=true;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String outMess = "Connection established";

if(myConn == null){
outMess="Nu exista conexiune ";
}else{
String fName=request.getParameter("fname");
String lName=request.getParameter("lname");
String cnp=request.getParameter("cnp");
String street=request.getParameter("street");
String city=request.getParameter("city");
String county=request.getParameter("county");
String code=request.getParameter("code");
String phoneNumber=request.getParameter("phoneNo");
String email=request.getParameter("email");
String mName=request.getParameter("mname");
String pryAccount=request.getParameter("primaryacc");
try{

88
9 - SERVLETS

String query="select * from TW2010.customers WHERE


cnp="+cnp;
System.out.println(query);
java.sql.Statement stmtQuery = myConn.createStatement();
ResultSet resultQuery = stmtQuery.executeQuery(query);
if(!resultQuery.next()){
isThere=false;
}
if(isThere==false){
String sql="INSERT INTO TW2010.CUSTOMERS
(FIRST_NAME,LAST_NAME,CNP,STR_NUM,CITY,COUNTY,CODE,PHONE_NUM,E_MAIL,MM_NAME
,PRIMARY_ACCT) VALUES
('"+fName+"','"+lName+"',"+cnp+",'"+street+"','"+city+"','"+county+"',"+cod
e+",'"+phoneNumber+"','"+email+"','"+mName+"',"+pryAccount+")";

java.sql.Statement stmt = myConn.createStatement();


int result = stmt.executeUpdate(sql);
if(result!=-1){
System.out.println(outMess+="<br />Record added");
}else{
System.out.println(outMess+="<br />The record
couldn't be added");
}
}
}catch(Exception e){
e.printStackTrace();
}
}

try {
//TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet OAM</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet OAM at " + request.getContextPath ()
+ "</h1>");
if(isThere==false){
out.println(outMess);
}else{
out.println(outMess+="<br />The CNP already exists in the
database");
}
out.println("</body>");
out.println("</html>");

}catch(Exception e){e.printStackTrace();
}finally {

89
9 - SERVLETS

out.close();
}
}

In the init() part, the jdbc driver is loaded and the connection with the database server is is
established.
In the processing part, the parameters of the request (coming from the input fields of the OAM.html
form) are retrieved and used to generate a database query.
This query is then executed and an INSERT is performed in case an user with the same CNP does
not exist in the CUSTOMERS table of the database.
Finally, the servlet generates a response to the client in the form of an html file containing the status
of the request.

9.14.3 the deployment descriptor

The deployment descriptor (the file web.xml) is shown below.

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>OAM</servlet-name>
<servlet-class>com.bank11.ccards.servlets.OAMServlet</servlet-
class>
<init-param>
<param-name>jdbcDriver</param-name>
<param-value>org.apache.derby.jdbc.ClientDriver</param-value>
</init-param>
<init-param>
<param-name>dbServer</param-name>
<param-value>jdbc:derby://localhost:1527/ccards</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>OAM</servlet-name>
<url-pattern>/OAM</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>OAM.html</welcome-file>
</welcome-file-list>
</web-app>

90
9 - SERVLETS

The deployment descriptor contains several elements of interest.


The <servlet-name> and <servlet-class> elements which associates to the servlet identified by
the name OAM the implementation class: OAMSevlet.class
A couple of initialization parameters: jdbcDriver, which identifies the jdbc driver used, and the
URL of the database server: dbServer
the welcome-file-list, which specifies the entry point(s) of the web application, in our case, the
static file OAM.html

91
10 - JDBC

10 - JDBC
10.1 what is jdbc?

JDBC stands for Java Data Base Connectivity and is the Java version of ODBC (Open Data Base
Connectivity). It offers an API for SQL-compliant relational databases access. It abstracts the vendor-
specific details and offers support for the most common database access functions.
The first release of the JDBC specification dates back to Feb. 1997, as part of the Java
Development Kit (JDK) 1.1. After that, JDBC was part of Java Standard Edition (JSE). Starting with
version 3.0, JDBC evolution is part of the Java Community Process. JSR 54 defines JDBC 3.0 while
the current (4.0) JDBC specification is defined in JSR 221. Version 4.1 is specified by a maintenance
release of JSR 221 and is included in Java SE 7. The latest version (as of Oct 2015) is 4.2, a second
maintenance release of JSR 221 and is included in Java SE 8.
The JDBC 4.2 API consists of 2 packages:
1. the java.sql package
2. the javax.sql package, which provides several server-side capabilities
The JDBC API provides programmatic access from applications written in the Java programming
language to standard SQL. The JDBC API presents a standard API to access a wide range of
underlying data sources or legacy systems.

10.2 jdbc drivers

Each database vendor offers its own version of DB access API. A JDBC driver is a middleware layer
that translates JDBC calls into vendor specific calls. These drivers fall into four standard categories, as
recognized by the DB industry. A new category of highly functional drivers with superior performance
may be considered, as well.

Type 1. JDBC ODBC Bridge


The driver translates the JDBC calls into equivalent ODBC calls. Both the JDBC and the JDBC-
ODBC calls are invoked within the client application. This solution is inefficient, due to the multiple
layers of indirection involved and to the limitations imposed to the JDBC layer by the ODBC frame.
The standard JDK includes all classes for this bridge - sun.jdbc.odbc.JdbcOdbcDriver .

Type 2. Part Java, Part Native Driver

92
10 - JDBC

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. The DB returns the
result of the call to the API, which in turn, forwards them to the JDBC driver. It is much faster than the
Type 1 drivers, because it eliminates one level of indirection.

Type 3. Intermediate Database Access Server (Java + Middleware translation)


Type 3 drivers are all Java JDBC drivers that are used by DataBase servers which act as
intermediate tier between multiple clients and multiple Database servers. The client application sends
a JDBC call through a JDBC driver to the intermediate Database servers. 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, like WebLogic (of BEA Systems) or Inprise Application
Server (of Borland).

Type 4. Pure Java Drivers


These are the most efficient drivers. The JDBC API calls are converted to direct network calls using
vendor provided protocols. All major vendors provide type 4 JDBC drivers for their Database products.

93
10 - JDBC

Type 5. Highly-functional drivers with superior performance


Includes drivers like DataDirect Connect for JDBC drivers, offering advanced functionality and
superior performance over other driver types.

10.3 the java.sql package

This package contains the core JDBC API. An exhaustive list of the classes and interfaces of this
package can be found in the latest JDBC specification (4.0). The document containing this
specification is JSR 221 and can be viewed at http://jcp.org/en/jsr/detail?id=221.
Of the 80+ classes and interfaces defined in this specification, let's remind some of the most
important ones, defined in the JDBC 3.0 API.
java.sql.Array
java.sql.Blob
java.sql.CallableStatement
java.sql.Clob
java.sql.Connection
java.sql.Date
java.sql.Driver
java.sql.DriverManager

java.sql.ResultSet
java.sql.ResultSetMetaData
java.sql.SQLData
java.sql.SQLDataException
java.sql.SQLException
java.sql.SQLInput
java.sql.SQLOutput
java.sql.SQLPermission
java.sql.SQLXML
java.sql.SQLWarning
java.sql.Statement
java.sql.Struct
java.sql.Time
java.sql.Timestamp
java.sql.Types

94
10 - JDBC

The following list contains all of the classes and interfaces new or updated in version 4.0.

java.sql.CallableStatement
java.sql.Clob
java.sql.ClientinfoStatus
java.sql.Connection
java.sql.DatabaseMetaData
java.sql.NClob
java.sql.PreparedStatement
java.sql.ResultSet
java.sql.RowId
java.sql.RowIdLifeTime
java.sql.SQLClientInfoException
java.sql.SQLDataException
java.sql.SQLException
java.sql.SQLFeatureNotSupportedException
java.sql.SQLInput
java.sql.SQLIntegrityConstraintViolationException
java.sql.SQLInvalidAuthorizationSpecException
java.sql.SQLNonTransientConnectionException
java.sql.SQLNonTransientException
java.sql.SQLOutput
java.sql.SQLSyntaxErrorException
java.sql.SQLTimeoutException
java.sql.SQLTransactionRollbackException
java.sql.SQLTransientConnectionException
java.sql.SQLTransientException
java.sql.SQLXML
java.sql.SQLWarning
java.sql.Statement
java.sql.Types
java.sql.Wrapper
javax.sql.CommonDataSource
javax.sql.StatementEvent
javax.sql.StatementEventListener

10.4 interaction schema in the java.sql package

The figure below shows the interactions and relationships between the major classes and interfaces
of the java.sql package.
The main steps in communicating with a database are:
1. loading a database driver
2. establishing a database connection

95
10 - JDBC

3. querying the database


4. processing the result set

10.5 loading a DB driver connecting to the database

There are two main steps in connecting to an existing database. The first one is
loading a database driver.
A database driver is specified by the driver name. Here are some examples of actual database
driver names:
com.ibm.db2.jdbc.app.DB2Driver
oracle.jdbc.driver.OracleDriver
com.borland.datastore.jdbc.DataStoreDriver
com.sybase.jdbc.SybDriver

96
10 - JDBC

sun.jdbc.odbc.JdbcOdbcDriver
weblogic.jdbc.mssqlserver4.Driver
org.postgresql.Driver

The Java code to load the driver name is somewhat obscure, but let's take it for granted:

import java.sql.*;
import java.util.*;

try
{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
} catch (Exception e) {
// driver not found
e.printStackTrace();
}
(Each object in java has (belongs to) a class, and has a respective Class object, which contains
metadata about it, that is accessible at runtime.)

The actual location of the database is specified by its URL (also known as connection URL). The
URL has 3 parts separated by colons, as follows:

jdbc:<subprotocol>:subname

jdbc is the protocol name (actually, the only protocol allowed in JDBC).
the sub-protocol is used to identify the JDBC driver, as specified by the driver vendor.
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?ServiceName=<databaseName>
jdbc:derby:net://<host>:1527/<databaseName>
jdbc:db2://db2.bank11.com:50002/ccards
jdbc:oracle:thin:@loclahost:1521:ORCL
jdbc:postgresql://<host>:5432/<databaseName>

The second step in connecting to an existing database is to open the connection, by using the
connection URL.
Here is some sample code which shows how this is done:

String connURL = "jdbc:mysql://localhost:3306/ccards";


String user = "root";
String passwd = "root"
Connection conn = DriverManager.getConnection(connURL,
user, passwd);

Since we just used it, let's have a better look in the next section at the DriverManager class.

97
10 - JDBC

10.6 the DriverManager class

This class belongs to the javax.sql package and offers a common access layer on top of
different JDBC drivers. Each driver used by the application must be registered (loaded) before the
DriverManager class tries to obtain a connection.
There are 3 versions of the getConnection() method of the DriverManager class. Here they
are:

public static Connection getConnection(String connURL)


throws SQLException
public static Connection getConnection(String connURL, String user, String passwd)
throws SQLException
public static Connection getConnection(String connURL,
java.util.Properties info) throws SQLException

While the first two forms of getConnection() are pretty straightforward, let's see an example of how
to use the last of the three forms.

Properties prp = new Properties();


prp.put("autocommit", "true");
prp.put("create", "true");
Connection conn = DriverManager.getConnection(connURL, prp);

10.7 the Connection interface

The Connection interface is part of then javax.sql package. Once we get the hold of a
Connection object, we can use it for various purposes, but we will restrict ourselves to creating SQL
statements. The most important methods for creating statements:

Statement createStatement() throws SQLException


Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException
Statement createStatement(int resultSetType, int resultSetConcurrency,
int resultSetHoldability)
PreparedStatement prepareStatement(String sql)
throws SQLException
CallableStatement prepareCall(String sql)
throws SQLException

10.8 statement interfaces

The objects we encountered in the previous section, namely, Statement, PreparedStatement


and CallableStatement abstract regular SQL statements, prepared statements and stored
procedures, respectively.

98
10 - JDBC

The Statement interface has (among others) the following methods:

1. methods for executing statements:


execute()
executeQuery()
executeUpdate()

2. methods for batch updates:


addBatch()
executeBatch()
clearBatch()

3. methods for result set fetch size and direction:


setFetchSize()
getFetchSize()
setFetchDirection()
getFetchDirection()

4. method to get the current result set:


getResultSet()

5. methods for result set concurrency and type:


getResultSetConcurrency()
getResultSetType()

6. other methods:
setQueryTimeout()
getQueryTimeout()
setMaxFieldSize()
getMaxFieldSize()
cancel()
getConnection()

The Statement interfaces also support the same methods for transaction support as the
Connection objects.

Objects implementing the Connection interface are mainly used for SQL queries execution. Here is
a typical example:

Statement stmt = conn.createStatement();


String sqlString = "CREATE TABLE customer ...";
stmt.executeUpdate(sqlString);

10.9 the ResultSet interface

The result of a query by a Statement object is a java.sql.ResultSet object which is available

99
10 - JDBC

to the user and allows access to the data retrieved. The interface ResultSet is implemented by
driver vendors.

Methods to retrieve data:


getAsciiStream()
getBoolean()
getDate()
getInt()
getShort()
getTimeStamp()
getBinaryStream()
getBytes()
getFloat()
getObject()
getTime()
getString()
getByte()
getDouble()
getLong()
getBigDecimal()
getMetaData()
getClob()
getWarnings()
getBlob()

Most of these methods require the column index (which in SQL starts at 1, not at 0) or the column
name, as the argument.
The usage of these retrieval methods assumes the prior knowledge of the type and the index (or
name) of a particular column. What if we don't have this knowledge? Fortunately, all this data about
the DB schema (or metadata) can be retrieved using the ResultSetMetaData interface. The
invocation of the getMetaData() method of a ResultSet object returns an object of
ResultSetMetaData type.
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()

100
10 - JDBC

isCaseSensitive()
isSigned()
isAutoIncrement()
isReadOnly()
isDefinitelyWritable()

10.10 ResultSet characteristics

By default, all created ResultSets have a type of forward only, a concurrency of read only, and
cursors are held over commit boundaries. An exception to this is that WebSphere currently changes
the cursor holdability default so that cursors are implicitly closed when committed. These
characteristics are configurable through methods that are accessible on Statement,
PreparedStatement and CallableStatement objects.
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.

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.

101
10 - JDBC

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 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 java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class DisplayServlet extends HttpServlet {


Connection conn;

// Initializes the servlet


public void init(ServletConfig config) throws ServletException {
super.init(config);
String driverName = "com.mysql.jdbc.Driver";
try {
Class.forName(driverName).newInstance();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}

String connURL="jdbc:mysql://localhost:3306/ccards";

102
10 - JDBC

try {
conn=DriverManager.getConnection(connURL,"root","root");
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}

// Destroys the servlet.


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)

103
10 - JDBC

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 {
processRequest(req, resp);
}

// Returns a short description of the servlet.


public String getServletInfo() {
return "Short description";
}
}

10.12 example of data insert

Connection conn = null;


Statement stmt = null;
try {
Class.forName(org.postgresql.Driver).newInstance();
}
catch(ClassNotFoundException e) {
System.out.println(e.toString());
}
String connUrl = "jdbc:mysql://localhost:3306/ccards;
try {
conn = DriverManager.getConnection(connUrl, root, root);
stmt = conn.createStatement();
String query = INSERT INTO STUDENTS VALUES(1009, 'Vasile',
'Abrudan', 'IE3');
// Update the table
stmt.executeUpdate(query);
} catch(Exception e) {
System.out.println(e.toString());
} finally {
// close the connection
stmt.close();
conn.close();
}

10.13 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

104
10 - JDBC

question mark '?'.


The following lines of Java code give an example of how to use PreparedStatement objects. It is
assumed that we already have established a connection with the database.

Statement stmt = conn.createStatement();


PreparedStatement pstmt = conn.prepareStatement("INSERT INTO customer
VALUES (?, ?, ?)");
stmt.executeUpdate("CREATE TABLE customer (id int, firstName
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();

10.14 another insert example

import java.sql.*;

public class InsertRows {

public static void main(String args[]) {


String url = "jdbc:mySubprotocol:myDataSource";
Connection con;
Statement stmt;
try {
Class.forName("myDriver.ClassName");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "myLogin",
"myPassword");
stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

uprs.moveToInsertRow();
uprs.updateString("COF_NAME", "Kona");
uprs.updateInt("SUP_ID", 150);
uprs.updateFloat("PRICE", 10.99f);
uprs.updateInt("SALES", 0);
uprs.updateInt("TOTAL", 0);
uprs.insertRow();

uprs.updateString("COF_NAME", "Kona_Decaf");

105
10 - JDBC

uprs.updateInt("SUP_ID", 150);
uprs.updateFloat("PRICE", 11.99f);
uprs.updateInt("SALES", 0);
uprs.updateInt("TOTAL", 0);
uprs.insertRow();
uprs.beforeFirst();

System.out.println("Table COFFEES after insertion:");


while (uprs.next()) {
String name = uprs.getString("COF_NAME");
int id = uprs.getInt("SUP_ID");
float price = uprs.getFloat("PRICE");
int sales = uprs.getInt("SALES");
int total = uprs.getInt("TOTAL");
System.out.print(name + " " + id + " " + price);
System.out.println(" " + sales + " " + total);
}
uprs.close();
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}

10.15 jdbc and sql types and their corresponding java classes

JDBC Type Purpose SQL Type Java Type


ARRAY SQL array ARRAY java.sql.Array
BIGINT 64 bit integer BIGINT long
BINARY binary value none byte[]
BIT one bit value BIT boolean
BLOB binary large object BLOB java.sql.Blob
CHAR char string CHAR String
CLOB character large object CLOB java.sql.Clob
DATE day, month, year DATE java.sql.Date
DECIMAL decimal value DECIMAL java.math.BigDe
cimal
DISTINCT distinct DISTINCT none
DOUBLE double precision DOUBLE PRECISION double
FLOAT double precision FLOAT double
INTEGER 32 bit integer INTEGER int

106
10 - JDBC

JDBC Type Purpose SQL Type Java Type


JAVA_OBJECT stores Java objects none Object
LONGVARBINARY variable length binary val none byte[]
LONGVARCHAR variable length char string none String
NULL null values NULL null
NUMERIC decimal value NUMERIC java.math.BigDe
cimal
OTHER db specific types none Object
REAL single precision REAL float
REF
SMALLINT 16 bit integer SMALLINT short
STRUCT
TIME hrs, mins, secs TIME java.sql.Time
TIMESTAMP date, time, nanoseconds TIMESTAMP java.sql.Timesta
mp
TINYINT 8 bit integer TINYINT short
VARBINARY variable length binary none byte[]
value
VARCHAR variable length char string VARCHAR String

10.16 JDBC Data Sources

In the JDBC 2.0 optional package, the DriverManager interface is replaced by the DataSource
interface as main method of obtaining DB connections.
While the DriverManager interface was used at run time to load explicitly a JDBC driver, the new
mechanism uses a centralized JNDI service to locate a javax.sql.DataSource object.
This interface is a factory for creating DB connections. It is part of the javax.sql package.
The DataSource interface is implemented by a driver vendors. There are three types of
implementations:
1. Basic implementation -- produces a standard Connection object
2. Connection pooling implementation -- produces a Connection object that will automatically
participate in connection pooling. This implementation works with a middle-tier connection
pooling manager.
3. Distributed transaction implementation -- produces a Connection object that may be used
for distributed transactions and almost always participates in connection pooling. This
implementation works with a middle-tier transaction manager and almost always with a
connection pooling manager.

Main methods:

public Connection getConnection() throws SQLException


public Connection getConnection(String user, String pwd) throws
SQLException

107
10 - JDBC

A servlet example using the DataSource interface:

package com.bank11.ccards.servlets;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;

public class TestDataSource extends HttpServlet


{
private final static Logger log =
Logger.getLogger(TestDataSource.class.getName());
private final static String DATASOURCE_NAME = "jdbc/ccards";
private DataSource theDataSource;
public void setDataSource(DataSource dataSource)
{
theDataSource = dataSource;
}
public DataSource getDataSource()
{
return theDataSource;
}
public void init() throws ServletException
{
if (theDataSource == null) {
try {
Context env =
(Context) new InitialContext().lookup("java:comp/env");
theDataSource = (DataSource) env.lookup(DATASOURCE_NAME);
if (theDataSource == null)
throw new ServletException("`" + DATASOURCE_NAME +
"' is an unknown DataSource");
} catch (NamingException e) {
throw new ServletException(e);
}
}
}

public void doGet(HttpServletRequest request, HttpServletResponse


response) throws IOException, ServletException
{
...
}
}

108
11 - JSP

11 - JSP
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.
A JSP is loaded by a JSP container and is converted to servlet code. If the JSP is modified, the
servlet code is regenerated.
The current JSP specification is JSP 2.2 and is related to the 2.5 Java Servlet specification. JSR
245 is the official document containing the current specification of JSP as a maintenance release..
The JSP specific interfaces, classes and exceptions are part of two packages, namely
javax.servlet.jsp and javax.servlet.jsp.tagext.
The javax.servlet.jsp package contains a number of classes and interfaces that describe and
define the contracts between a JSP page implementation class and the runtime environment provided
for an instance of such a class by a conforming JSP container.
The package javax.servlet.jsp defines two interfaces JspPage and HttpJspPage. The interface
HttpJspPage is the interface that a JSP processor-generated class for the HTTP protocol must satisfy.
The JspPage interface is the interface that a JSP processor-generated class must satisfy.
The package javax.servlet.jsp.tagext contains classes and interfaces for the definition of
JavaServer Pages Tag Libraries.

11.2 the java.servlet.jsp.JspPage interface

This interface has 2 methods:

public void jspInit()


public void jspDestroy()

The javax.servlet.HttpJspPage interface has a single method:

public void jspService(HttpServletRequest req,


HttpServletResponse resp) throws ServletException, IOException

The implementation of this method is generated by the web container never by the developer.

11.3 the generated servlet an example

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

109
11 - JSP

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() {


return _jspx_dependants;
}

public void _jspService(HttpServletRequest request, HttpServletResponse


response)
throws java.io.IOException, ServletException {

PageContext pageContext = null;


HttpSession session = null;
ServletContext application = null;

110
11 - JSP

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");
} 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);
}

111
11 - JSP

}
}

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

A few words about serialization. To serialize an object means to convert its state to a byte stream so that
the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of
its superclasses implements either the java.io.Serializable interface or its
subinterface,java.io.Externalizable. Deserialization is the process of converting the serialized form of
an object back into a copy of the object.

Here is a typical example of a java bean.

/*
* NewBean.java
*/

import java.beans.*;
import java.io.Serializable;

public class NewBean extends Object implements Serializable {

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;
}

112
11 - JSP

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 behavior of the JSP

Rules for JSP tags:


attribute values are always quoted (single or double quotes)
URLs follow the servlet conventions
if the URL does not start with / , it is interpreted relative to the position of the current JSP

11.6 jsp directives

The JSP directives are messages sent by the Java Server Page to the JSP container. These
directives do not produce any client output and affect the whole JSP file. For more information, check
http://beginnersbook.com/2013/05/jsp-tutorial-directives/

The general format of a JSP directive is as follows:


<%@directive_name attr1="val1" ... attrn="valn" %>
There are three JSP directives: page, include and taglib.

The page directive format:


<%@page attr1="val1" ... %>
attributes:
language values: "java"

113
11 - JSP

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", 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, 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). It has the following format:
<%@taglib uri="tagLibUri" prefix="tagPrefix" %>

where the tagPrefix indicates a name scope.

11.7 scripting elements

11.7.1 declarations

<%! java vars and method declarations %>

Basicly, a bloc of java code used to define class-wide variables and methods in the generated
servlet.

11.7.2 scriptlets

<% valid java statements %>

Block of java code which is executed during request processing. In Tomcat, this code goes to inside
the service() method.

11.7.3 expressions

<%= java expressions to be evaluated %>

A scriptlet that sends a value of a Java expression to back to the client. It is evaluated at request
processing time and the result is converted to a string which is then displayed.

114
11 - JSP

11.8 standard actions

Tags that affect the runtime behaviour of the JSP and the response to the client. A tag can be
embedded into a JSP page. The standard actions are detailed in the next paragraphs.

11.8.1 the useBean standard action

<jsp:useBean>
Used to instantiate a Java bean or locate a bean instance. Assigns it to available name or id.

The syntax for this action is:


<jsp:useBean id="beanName" scope="sName" beandetails />

where beandetails is one of the following:


class="className"
class="className" type="typeName"
beanName="beanName" type="typeName"
type="typeName"

To clarify the distinction between class and beaName, read the remarks below.

class="package.class" type="package.class"
Instantiates a bean from the class named in class and assigns the bean the data type you specify
in type. The value of type can be the same as class, a superclass of class, or an interface
implemented by class.
The class you specify in class must not be abstract and must have a public, no-argument
constructor. The package and class names you use with both class and type are case sensitive.
beanName="{package.class | <%= expression %>}" type="package.class"
Instantiates a bean from a class, a serialized template, or an expression that evaluates to a class
or serialized template. When you use beanName, the bean is instantiated by the
java.beans.Beans.instantiate method. The Beans.instantiate method checks
whether the package and class you specify represents a class or a serialized template. If they
represent a serialized template, Beans.instantiate reads the serialized form (which has a
name like package.class.ser) using a class loader.
The value of type can be the same as beanName, a superclass of beanName, or an interface
implemented by beanName. The package and class names you use with both beanName and
type are case sensitive.

11.8.2 the setProperty standard action

115
11 - JSP

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

Attributes description:
name - the name of a bean instance, already defined in a <jsp:useBean>
property specifies the relationship between request parameters and corresponding bean
properties
property="*" - stores all of the values in the request object parameters (called request
parameters) in matching Bean properties. The property names in the Bean must match the
request parameters
property="propertyName" [ param="parameterName" ] - Sets one Bean property to the
value of one request parameter. The request parameter can have a different name than the
Bean property, and if so, you must specify param.
property="propertyName" value="{ string | <%= expression %> }" - Sets one Bean
property to a specific value. The value can be a String or an Expression

11.8.3 the getProperty standard action

<jsp:getProperty>
Used to access the properties of a bean, converts them to string and displays the output to the
client.

The syntax for this action is:


<jsp:getProperty name="beanName" property="propName" />

Attributes description:
name - the name of a bean instance whose property is to be retrieved
property - name of the property to be retrieved

11.8.4 the param standard action

<jsp:param>
Provide other tags with additional information in the form of name:value pairs. It is used in
conjunction with the <jsp:include>, <jsp:forward>, <jsp:plugin> actions.

116
11 - JSP

The syntax for this action is:


<jsp:param name="paramName" value="paramValue" />

11.8.5 the include standard action

<jsp:include>
Used for the inclusion of a static or dynamic resource into the current JSP page at request
processing time. An included page has access only to the JspWriter object and cannot set headers or
cookies. While the <%@include> directive is executed at compile time and has static content, the
<jsp:include> action is executed at request processing time and has static or dynamic content.

The syntax for this action is:


<jsp:include page="pageURL" flush="true" />

Attributes description:
page - the URL of the page, same format as the <%@include> directive.
flush - only the "true" value is supported.

11.8.6 the forward standard action

<jsp:forward>
Used to forward the the request to another JSP, servlet or to a static resource..

The syntax for this action is:


<jsp:forward page="pageURL" />

The action may include several <jsp:param> tags, as well. It is used mainly, when we want to
separate the application into different views, depending on request.

11.8.7 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), followed by the execution of the applet or JavaBeans
component specified by the tag.

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>

117
11 - JSP

</jsp:plugin>

Attributes description:
name - the name of a bean instance, already defined in a <jsp:useBean>
type="bean|applet" - the type of object the plugin will execute. You must specify either bean
or applet, as this attribute has no default value.
code="classFileName" - the name of the Java class file that the plugin will execute. You
must include the .class extension in the name following code. The filename is relative to the
directory named in the codebase attribute.
codebase="classFileDirectoryName" - the absolute or relative path to the directory that
contains the applet's code. If you do not supply a value, the path of the JSP file that calls
<jsp:plugin> is used.
name="instanceName" - a name for the Bean or applet instance, which makes it possible for
applets or Beans called by the same JSP file to communicate with each other.
archive="URIToArchive, ..." - a comma-separated list of paths that locate archive files to be
preloaded with a class loader located in the directory named in codebase.
align="bottom|top|middle|left|right" - 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.
height="displayPixels" width="displayPixels" - the initial height and width, in pixels, of the
image the applet or Bean displays, not counting any windows or dialog boxes the applet or
Bean brings up.
hspace="leftRightPixels" vspace="topBottomPixels" - the amount of space, in pixels, to
the left and right (or top and bottom) of the image the applet or Bean displays. Must be a small
nonzero number.
jreversion="JREVersionNumber|1.1" - the version of the Java Runtime Environment (JRE)
the applet or Bean requires. The default value is 1.1.
nspluginurl="URLToPlugin" - the URL where the user can download the JRE plugin for
Netscape Navigator. The value is a full URL, with a protocol name, optional port number, and
domain name.
iepluginurl="URLToPlugin"

11.9 implicit objects

JSP provides several implicit objects, based on the servlet API, objects which are automaticly
available.
1. request - represents the object that triggered the service() method invokation and has type
HttpServletRequest with scope request
2. response - represents server's response to the request, it has HttpServletResponse type
and page scope
3. pageContext - provides a single point of access to attributes and shared data within the page,
it has type PageContext with scope page
4. session - it has HttpSession type and session scope
5. application - represents the servlet context, it has type ServletContext and scope
application
6. out - it represents the buffered version of java.io.PrintWriter, writes to the output
stream to the client, it has javax.servlet.jsp.JspWriter type and scope page
7. config - it is the SevletConfig for the current JSP page, it is of type ServletConfig and has

118
11 - JSP

page scope
8. page - it is an instance of the page's implementation of the servlet class, it has
java.lang.Object type and scope page

11.10 scopes

1. request - an object with request scope is bound to the HttpServletRequest object; the
object can be accessed by invoking the getAttribute() method on the implicit request
object; the generated servlet binds the object to HttpServletRequest object using the
setAttribute(String key, Object value) method
2. session - an object with session scope is bound to the HttpSession object; the object can
be accessed by invoking the getValue() method on the implicit session object; the
generated servlet binds the object to HttpSession object using the
setAttribute(String key, Object value) method
3. application - an object with application scope is bound to the ServletContext object; the
object can be accessed by invoking the getAttribute() method on the implicit application
object; the generated servlet binds the object to the ServletContext object using the
setAttribute(String key, Object value) method
4. page - an object with page scope is bound to the PageContext object; the object can be
accessed by invoking the getAttribute() method on the implicit pageContext object; the
generated servlet binds the object to PageContext object using the
setAttribute(String key, Object value) method

11.11 a short example

The following is the Enroll.jsp file.

<%@page contentType="text/html" errorPage="error.jsp"%>

<jsp:useBean id="enrollBean" scope="session"


class="com.bank11.ccards.beans.EnrollBean" />
<jsp:setProperty name="enrollBean" property="*" />

<% enrollBean.init();

if (enrollBean.invalidAcct())
{ %>
<jsp:forward page="retry.jsp">
<jsp:param name="resolution" value="invalidAcct"/>
</jsp:forward>
<% }
else if (enrollBean.registeredAcct())
{ %>
<jsp:forward page="response.jsp">
<jsp:param name="resolution" value="registeredAcct"/>
</jsp:forward>

119
11 - JSP

<% }
else if (enrollBean.userExists())
{ %>
<jsp:forward page="retry.jsp">
<jsp:param name="resolution" value="userExists"/>
</jsp:forward>
<% }
else
{
enrollBean.register(); %>
<jsp:forward page="response.jsp">
<jsp:param name="resolution" value="userEnrolled"/>
</jsp:forward>
<% }
%>

11.12 an extended example


This example is provided by Devsphere, a software development and consulting company.

11.12.1 Data beans


SimpleBean is a Java bean that contains several standard properties (a String, a float, an int, a
boolean and another String), two indexed standard properties (a String[] and an int[]) and another data
bean (a SimpleSubBean). The SimpleBean class is declared public, has a no-arg constructor and
provides accessors (get & set methods) for its properties. The public constructor could have been
omitted, since the Java compiler generates one in the absence of any other constructors.
SimpleBean.java:
package com.devsphere.examples.mapping.simple;

// Simple bean

public class SimpleBean implements java.io.Serializable {


private String string;
private float number;
private int integer;
private boolean flag;
private String colors[];
private int list[];
private String optional;
private SimpleSubBean subBean;

// No-arg constructor
public SimpleBean() {
}

// Gets the string property


public String getString() {

120
11 - JSP

return this.string;
}

// Sets the string property


public void setString(String value) {
this.string = value;
}

// Gets the number property


public float getNumber() {
return this.number;
}

// Sets the number property


public void setNumber(float value) {
this.number = value;
}

// Gets the integer property


public int getInteger() {
return this.integer;
}

// Sets the integer property


public void setInteger(int value) {
this.integer = value;
}

// Gets the flag property


public boolean getFlag() {
return this.flag;
}

// Sets the flag property


public void setFlag(boolean value) {
this.flag = value;
}

// Gets the colors property


public String[] getColors() {
return this.colors;
}

// Sets the colors property


public void setColors(String values[]) {
this.colors = values;
}

121
11 - JSP

// Gets an element of the colors property


public String getColors(int index) {
return this.colors[index];
}

// Sets an element of the colors property


public void setColors(int index, String value) {
this.colors[index] = value;
}

// Gets the list property


public int[] getList() {
return this.list;
}

// Sets the list property


public void setList(int values[]) {
this.list = values;
}

// Gets an element of the list property


public int getList(int index) {
return this.list[index];
}

// Sets an element of the list property


public void setList(int index, int value) {
this.list[index] = value;
}

// Gets the optional property


public String getOptional() {
return this.optional;
}

// Sets the optional property


public void setOptional(String value) {
this.optional = value;
}

// Gets the subBean property


public SimpleSubBean getSubBean() {
return this.subBean;
}

// Sets the subBean property

122
11 - JSP

public void setSubBean(SimpleSubBean value) {


this.subBean = value;
}
}

SimpleSubBean contains only two standard properties (a String and a float).


SimpleSubBean.java:
package com.devsphere.examples.mapping.simple;

// Simple sub-bean
public class SimpleSubBean implements java.io.Serializable {
private String string;
private float number;

// No-arg constructor
public SimpleSubBean() {
}

// Gets the string property


public String getString() {
return this.string;
}

// Sets the string property


public void setString(String value) {
this.string = value;
}

// Gets the number property


public float getNumber() {
return this.number;
}

// Sets the number property


public void setNumber(float value) {
this.number = value;
}
}

11.12.2 the HTML Form


The properties of SimpleBean are mapped to the form elements of SimpleForm.html:

Name Property type Element type

string String text

123
11 - JSP

number float text

integer int radio[]

flag boolean checkbox

colors String[] checkbox[]

list int[] select

optional String text

subBean.string String text

subBean.number float text

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>

124
11 - JSP

<P> Optional <BR>


<INPUT TYPE="TEXT" NAME="optional" SIZE="20">

<P> String (subBean) <BR>


<INPUT TYPE="TEXT" NAME="subBean.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.12.3 bean resources


The SimpleBeanResources class is a resource bundle containing optional information that is useful
to the mapping process: default values, error messages, the list of optional properties, the processing
order, the form's name and the processor's name.
The default values are defined for a String, a float, a boolean and an int[]. The primitive values must
be wrapped by a Float and a Boolean in order to be stored as resources. The default values for the
properties of the contained bean could have been defined in another resource bundle called
SimpleSubBeanResources.
There are three error messages. Their role is to help the users to correct the input errors. The
mapping framework contains default error messages for each type of form element.
The list of optional properties has a single element. No error is signaled if the user doesn't provide a
value for this property.
The processing order isn't necessary to this example. It has been included here just for
demonstrative purposes.
The form's name and the processor's name are used by the JSP handler described in the next
section. These two resources aren't accessed by the mapping utilities.
SimpleBeanResources.java:
package com.devsphere.examples.mapping.simple;

public class SimpleBeanResources extends java.util.ListResourceBundle {


private static final Object[][] contents = {
{ "[DEFAULT_VALUE.string]", "abc" },
{ "[DEFAULT_VALUE.number]", new Float(0.123) },
{ "[DEFAULT_VALUE.flag]", new Boolean(true) },
{ "[DEFAULT_VALUE.list]", new int[] { 2, 3 } },
{ "[ERROR_MESSAGE.integer]", "An option must be selected" },
{ "[ERROR_MESSAGE.colors]", "One or more colors must be selected" },
{ "[ERROR_MESSAGE.list]", "One or more items must be selected" },
{
"[OPTIONAL_PROPERTIES]",

125
11 - JSP

new String[] {
"optional"
}
},
{
"[PROCESSING_ORDER]",
new String[] {
"string",
"number",
"integer",
"flag",
"colors",
"list",
"optional",
"subBean"
}
},
{ "[FORM_NAME]", "SimpleForm.html" },
{ "[PROC_NAME]", "SimpleProc.jsp" }
};

public Object[][] getContents() {


return contents;
}
}

11.12.4 JSP Handler


The SimpleHndl.jsp handler is based on a template that was described in a previous chapter.
The formToBean() method of com.devsphere.mapping.FormUtils sets the bean properties to the
values of the request parameters (form data). If necessary, string values are converted to numbers. A
boolean property is set to true if the request parameter is present no matter what its value is (except
"false"). The error messages that occur during the mapping process are stored in a Hashtable.
The beanToForm() method of com.devsphere.mapping.FormUtils inserts the bean data and the
error messages into the HTML form. It inserts a VALUE attribute for text elements, a CHECKED
attribute for checkboxes and radio buttons that must be selected and a SELECTED attribute for the list
items that must be highlighted.
For a better understanding of this example, a later section of this chapter lists two JSPs that perform
the mapping and build the HTML form without using the framework.
SimpleHndl.jsp:
<%@ page language="java" %>
<%@ page import="com.devsphere.mapping.*, com.devsphere.logging.*" %>
<jsp:useBean id="simpleBean" scope="request"
class="com.devsphere.examples.mapping.simple.SimpleBean"/>
<%
// Get the bean resources
java.util.ResourceBundle beanRes
= HandlerUtils.getBeanResources(simpleBean.getClass());

126
11 - JSP

// Construct the base path


String basePath = request.getServletPath();
int slashIndex = basePath.lastIndexOf('/');
basePath = slashIndex != -1 ? basePath.substring(0, slashIndex+1) : "";

// Determine the HTTP method


boolean isPostMethod = request.getMethod().equals("POST");

// Create a logger that wraps the servlet context


ServletLogger logger = new ServletLogger(application);

// Wrap the form data


FormData formData = new ServletFormData(request);

// Form-to-bean mapping: request parameters are mapped to bean properties


java.util.Hashtable errorTable
= FormUtils.formToBean(formData, simpleBean, logger);

if (isPostMethod && errorTable == null) {


// Construct the processor's path
String procPath = basePath + beanRes.getString("[PROC_NAME]").trim();

// Process the valid data bean instance


application.getRequestDispatcher(procPath).forward(request, response);
} else {
if (!isPostMethod)
// Ignore the user errors if the form is requested with GET.
errorTable = HandlerUtils.removeUserErrors(errorTable);

// Construct the form's path


String formPath = basePath + beanRes.getString("[FORM_NAME]").trim();
formPath = application.getRealPath(formPath);

// Get the form template


FormTemplate template = FormUtils.getTemplate(new java.io.File(formPath));

// Get a new document


FormDocument document = template.getDocument();

// Bean-to-form mapping: bean properties are mapped to form elements


FormUtils.beanToForm(simpleBean, errorTable, document, logger);

// Send the form document


document.send(out);
}

127
11 - JSP

%>

11.12.5 JSP Processor


The SimpleProc.jsp processor gets the beans that were validated by the JSP handler and prints the
values of their properties.
SimpleProc.jsp:
<%@ page language="java"%>
<jsp:useBean id="simpleBean" scope="request"
class="com.devsphere.examples.mapping.simple.SimpleBean"/>
<HTML>
<HEAD><TITLE>Simple bean</TITLE></HEAD>
<BODY>
<H3>Simple Example</H3>
<P><B> SimpleBean properties: </B>
<P> string = <jsp:getProperty name="simpleBean" property="string"/>
<P> number = <jsp:getProperty name="simpleBean" property="number"/>
<P> integer = <jsp:getProperty name="simpleBean" property="integer"/>
<P> flag = <jsp:getProperty name="simpleBean" property="flag"/>
<P> colors = <%= toString(simpleBean.getColors()) %>
<P> list = <%= toString(simpleBean.getList()) %>
<P> optional = <jsp:getProperty name="simpleBean" property="optional"/>
<P> subBean.string = <%= simpleBean.getSubBean().getString() %>
<P> subBean.number = <%= simpleBean.getSubBean().getNumber() %>
</BODY>
</HTML>

<%!
public static String toString(String list[]) {
if (list == null || list.length == 0)
return "";
if (list.length == 1 && list[0] != null)
return list[0];
StringBuffer strbuf = new StringBuffer();
strbuf.append("{ ");
for (int i = 0; i < list.length; i++)
if (list[i] != null) {
strbuf.append(list[i]);
strbuf.append(" ");
}
strbuf.append("}");
return strbuf.toString();
}

public static String toString(int list[]) {


if (list == null || list.length == 0)
return "";

128
11 - JSP

if (list.length == 1)
return Integer.toString(list[0]);
StringBuffer strbuf = new StringBuffer();
strbuf.append("{ ");
for (int i = 0; i < list.length; i++) {
strbuf.append(list[i]);
strbuf.append(" ");
}
strbuf.append("}");
return strbuf.toString();
}
%>

11.12.6 without using the devsphere framework


ComplexForm.jsp generates the HTML form dynamically and inserts default values and error
messages. It uses 120 lines of Java-JSP-HTML mixture to generate a 40 lines HTML form. A single
call to FormUtils.beanToForm() can do the same using a pure HTML file. In addition, beanToForm()
handles and logs many types of application errors, making the testing and the debugging easier.
ComplexHndl.jsp uses 150 lines of Java-JSP mixture to set the properties of a bean object to the
values of the request parameters. This is the equivalent of a single FormUtils.formToBean() call.
The adding/removing of a bean property requires changes in both Complex*.jsp files. Using the
framework, you only have to add/remove a form element to/from a pure HTML file.
The localization of the Complex*.jsp files to other languages requires a lot of work and could make
the maintenance very hard. Using the framework you separate the HTML code from the Java/JSP
code. In addition, default values and error messages are kept in localizable resource bundles. A later
chapter shows how to build internationalized applications using the framework.
ComplexForm.jsp:
<%@ page language="java" %>
<jsp:useBean id="simpleBean" scope="request"
class="com.devsphere.examples.mapping.simple.SimpleBean"/>
<jsp:useBean id="errorTable" scope="request"
class="java.util.Hashtable"/>
<HTML>
<HEAD><TITLE>Without using the framework</TITLE></HEAD>
<BODY>
<H3>Equivalent of Simple Example</H3>
<FORM METHOD=POST>

<P> String <BR>


<%= getErrorMessage(errorTable, "string") %>
<INPUT TYPE="TEXT" NAME="string"
VALUE="<jsp:getProperty name="simpleBean" property="string"/>">

<P> Number <BR>


<%= getErrorMessage(errorTable, "number") %>
<INPUT TYPE="TEXT" NAME="number"
VALUE="<jsp:getProperty name="simpleBean" property="number"/>">

129
11 - JSP

<P> Integer <BR>


<%= getErrorMessage(errorTable, "integer") %>
<%
String integerLabels[] = { "Option 1", "Option 2", "Option 3" };
for (int i = 0; i < integerLabels.length; i++) {
int value = i+1;
boolean checked = simpleBean.getInteger() == value;
%>
<INPUT TYPE="RADIO" NAME="integer" VALUE="<%= value %>"
<%= checked ? "CHECKED" : "" %>> <%= integerLabels[i] %>
<%
}
%>

<P> Flag <BR>


<%= getErrorMessage(errorTable, "flag") %>
<INPUT TYPE="CHECKBOX" NAME="flag"
<%= simpleBean.getFlag() ? "CHECKED" : "" %>> Flag

<P> Colors <BR>


<%= getErrorMessage(errorTable, "colors") %>
<%
String colors[] = simpleBean.getColors();
if (colors == null)
colors = new String[0];
String colorLabels[] = { "Red", "Green", "Blue" };
String colorValues[] = { "red", "green", "blue" };
for (int i = 0; i < colorValues.length; i++) {
boolean checked = false;
if (colors != null)
for (int j = 0; j < colors.length; j++)
if (colors[j].equals(colorValues[i])) {
checked = true;
break;
}
%>
<INPUT TYPE="CHECKBOX" NAME="colors" VALUE="<%= colorValues[i] %>"
<%= checked ? "CHECKED" : "" %>> <%= colorLabels[i] %>
<%
}
%>

<P> List <BR>


<%= getErrorMessage(errorTable, "list") %>
<SELECT NAME="list" SIZE="3" MULTIPLE>

130
11 - JSP

<%
int list[] = simpleBean.getList();
if (list == null)
list = new int[0];
String listItems[] = { "Item 1", "Item 2", "Item 3" };
for (int i = 0; i < listItems.length; i++) {
int value = i+1;
boolean selected = false;
if (list != null)
for (int j = 0; j < list.length; j++)
if (list[j] == value) {
selected = true;
break;
}
%>
<OPTION VALUE = "<%= value %>"
<%= selected ? "SELECTED" : "" %>> <%= listItems[i] %>
<%
}
%>
</SELECT>

<P> Optional <BR>


<%= getErrorMessage(errorTable, "optional") %>
<INPUT TYPE="TEXT" NAME="optional"
VALUE="<jsp:getProperty name="simpleBean" property="optional"/>">

<% if (simpleBean.getSubBean() == null) simpleBean.setSubBean(


new com.devsphere.examples.mapping.simple.SimpleSubBean()); %>

<P> String (subBean) <BR>


<%= getErrorMessage(errorTable, "subBean.string") %>
<INPUT TYPE="TEXT" NAME="subBean.string"
VALUE="<%= simpleBean.getSubBean().getString() %>">

<P> Number (subBean) <BR>


<%= getErrorMessage(errorTable, "subBean.number") %>
<INPUT TYPE="TEXT" NAME="subBean.number"
VALUE="<%= simpleBean.getSubBean().getNumber() %>">

<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET" VALUE="Reset">

</FORM>
</BODY>

131
11 - JSP

</HTML>

<%!
String getErrorMessage(java.util.Hashtable errorTable, String property) {
String message = (String) errorTable.get(property);
if (message == null)
message = "";
return message;
}
%>

ComplexHndl.jsp:
<%@ page language="java" %>
<jsp:useBean id="simpleBean" scope="request"
class="com.devsphere.examples.mapping.simple.SimpleBean"/>
<jsp:useBean id="simpleSubBean" scope="page"
class="com.devsphere.examples.mapping.simple.SimpleSubBean"/>
<jsp:useBean id="errorTable" scope="request"
class="java.util.Hashtable"/>
<%
simpleBean.setSubBean(simpleSubBean);

boolean isPostMethod = request.getMethod().equals("POST");


if (isPostMethod) {

//* string : text

%>
<jsp:setProperty name="simpleBean" property="string"/>
<%
if (simpleBean.getString() == null
|| simpleBean.getString().length() == 0) {
simpleBean.setString("abc");
setErrorMessage(errorTable, "string", "Must be filled");
}

//* number : text

try {
String numberValue = request.getParameter("number");
if (numberValue != null && numberValue.length() != 0)
simpleBean.setNumber(new Float(numberValue).floatValue());
else {
simpleBean.setNumber(0.123f);
setErrorMessage(errorTable, "number", "Must be filled");
}

132
11 - JSP

} catch (NumberFormatException e) {
simpleBean.setNumber(0.123f);
setErrorMessage(errorTable, "number", "Must be a number");
}

//* integer : radio group

%>
<jsp:setProperty name="simpleBean" property="integer"/>
<%
if (simpleBean.getInteger() == 0) {
setErrorMessage(errorTable, "integer", "An option must be selected");
}

//* flag : checkbox

String flagValue = request.getParameter("flag");


if (flagValue != null) {
flagValue = flagValue.trim();
if (flagValue.length() == 0 || flagValue.equals("false"))
flagValue = null;
}
simpleBean.setFlag(flagValue != null);

//* color : checkbox group

%>
<jsp:setProperty name="simpleBean" property="colors"/>
<%
if (simpleBean.getColors() == null
|| simpleBean.getColors().length == 0) {
setErrorMessage(errorTable, "colors",
"One or more colors must be selected");
}

//* list : select

%>
<jsp:setProperty name="simpleBean" property="list"/>
<%
if (simpleBean.getList() == null
|| simpleBean.getList().length == 0) {
simpleBean.setList(new int[] { 2, 3 });
setErrorMessage(errorTable, "list",
"One or more items must be selected");
}

133
11 - JSP

//* optional : text

%>
<jsp:setProperty name="simpleBean" property="optional"/>
<%
if (simpleBean.getOptional() == null)
simpleBean.setOptional("");

//* subBean.string : text

%>
<jsp:setProperty name="simpleSubBean" property="string"
param="subBean.string"/>
<%
if (simpleSubBean.getString() == null
|| simpleSubBean.getString().length() == 0) {
simpleSubBean.setString("");
setErrorMessage(errorTable, "subBean.string", "Must be filled");
}

//* subBean.number : text

try {
String numberValue = request.getParameter("subBean.number");
if (numberValue != null && numberValue.length() != 0)
simpleSubBean.setNumber(new Float(numberValue).floatValue());
else {
setErrorMessage(errorTable, "subBean.number", "Must be filled");
}
} catch (NumberFormatException e) {
setErrorMessage(errorTable, "subBean.number", "Must be a number");
}
} else {
simpleBean.setString("abc");
simpleBean.setNumber(0.123f);
simpleBean.setFlag(true);
simpleBean.setList(new int[] { 2, 3 });
simpleBean.setOptional("");
simpleSubBean.setString("");
}

if (isPostMethod && errorTable.isEmpty()) {


%>
<jsp:forward page="SimpleProc.jsp"/>
<%

134
11 - JSP

} else {
%>
<jsp:forward page="ComplexForm.jsp"/>
<%
}
%>

<%!
void setErrorMessage(java.util.Hashtable errorTable,
String property, String message) {
message = "<FONT COLOR=\"#FF0000\">" + message + "</FONT><BR>";
errorTable.put(property, message);
}
%>

11.12.7 using the framework with servlets and JSPs


The SimpleHndl.jsp handler is basically a Java scriptlet. That was a simple and compact way to
present a handler. The Java code could easily be moved to a utility class. A more elegant solution is
the replacement of the JSP handler with a general Java servlet.
The com.devsphere.helpers.mapping package contains an abstract class called GenericHandler.
This class is extended by BeanDispatcher, which is the bean-independent equivalent of
SimpleHndl.jsp. The JSP handler can be replaced by only a few lines that are added to
servlets.properties or web.xml:

SimpleHndl.code=com.devsphere.helpers.mapping.BeanDispatcher
SimpleHndl.initparams=\
BEAN_NAME=com.devsphere.examples.mapping.simple.SimpleBean,\
BEAN_ID=simpleBean,\
BASE_PATH=/simple
or
<servlet>
<servlet-name>SimpleHndl</servlet-name>
<servlet-class>com.devsphere.helpers.mapping.BeanDispatcher</servlet-class>
<init-param>
<param-name>BEAN_NAME</param-name>
<param-value>com.devsphere.examples.mapping.simple.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.

135
11 - JSP

11.12.8 why using servlets?


Using a JSP, you have to declare the bean within a <jsp:useBean> tag. If your Web application
contains many forms/beans, you have to provide a JSP handler for each bean. A servlet can be made
bean-independent.
In many cases, a servlet is identified with its class. Users invoke the servlet by requesting a URL like
this:
http://www.host.com/AppName/servlet/ServletName

The servlet engine associates a servlet to a class in the servlets.properties (or web.xml) file:
ServletName.code=com.company.ClassName
There is nothing that can stop you associating many servlets with the same class. You may use the
same class to declare one servlet for each bean component. A standard servlet engine running on a
single JVM will instantiate the servlet class once for each servlet declaration. All requests to one of the
declared servlets will be serviced by the same instance of the servlet class.
The previous section showed how to declare a BeanDispatcher servlet. If you have another bean-
form pair, you could add a few other lines to servlets.properties:
AnotherHndl.code=com.devsphere.helpers.mapping.BeanDispatcher
AnotherHndl.initparams=\
BEAN_NAME=com.devsphere.examples.mapping.another.AnotherBean,\
BEAN_ID=anotherBean,\
BASE_PATH=/another
The two servlets that share the same code could be invoked with something like this
http://www.host.com/AppName/servlet/SimpleHndl
http://www.host.com/AppName/servlet/AnotherHndl

136
12 - javaserver faces

12 - JAVASERVER FACES
12.1 what are javaServer faces?

JavaServer Faces technology is a server-side user interface component framework for Java based
web applications. This technology includes:

1. A set of APIs for:


representing UI components, like input fields, buttons, links
UI components management
events handling
input validation
error handling
page navigation specification
support for internationalization and accessibility.

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, using
XML files called view templates or Facelets views. Requests are processed by the FacesServlet,
which loads the appropriate view template, builds a component tree, processes events, and renders
the response (typically HTML) to the client.

12.2 javaServer Faces Technology 2.2

The latest official version (as of november 2015) of JavaServer Faces technology is Mojarra version
2.2.12, released through the Java Community Process under Java Specification Requests (JSR) 314
and 344.
Version 2.3 is under development and reached Milestone 3 in July 2015.
Version 2.0 is part of the Java Enterprise Edition 6 while versions 2.2.* are part of Java EE 7.
Version 2.0 supersedes version 1.2 and brings in mandatory support for Facelets as the view
technology for JSF pages, built in Ajax support and built in support for bookmarking & page-load.
Version 2.2 introduced new concepts like stateless views, page flow and the ability to create portable
resource contracts.
There are five JSF specific tag libraries defined in this specification, namely
JSF HTML Tag Library
JSF Core Tag Library
JSTL Core Tag Library
JSTL Functions Tag Library
JSF Facelets Tag Library

137
12 - javaserver faces

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. JSP pages are
compiled into servlets but its not the case with Facelets because Facelet pages are XML compliant
and its framework uses a fast SAXbased compiler to build views. Facelets can make changes to
pages immediately so developing JSF applications with Facelets is simply faster.

12.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. As of version 1.2 of the JFS
specification, there are 25 HTML JSF tags.

The HTML tags can be grouped in the following categories:


inputs
outputs
commands
selections
layouts
data table
errors and messages

12.4.1 the list of JSF HTML Tags


For reference, here is an exhaustive list of the JSF HTML tags:
column
commandButton
commandLink
dataTable
form
graphicImage
inputHidden
inputSecret
inputText
inputTextArea
message
messages
outputFormat
outputLabel

138
12 - javaserver faces

outputLink
outputText
panelGrid
pnelGroup
selectBooleanCheckbox
selectManyCheckbox
selectManyListbox
selectManyMenu
selectOneListbox
selectOneMenu
selectOneRadio

In the next paragraphs, we'll have a closer look at some of these tags.

12.4.2 h:dataTable
The dataTable tag renders an HTML 4.01 compliant table element that can be associated with a
backing bean to obtain its data as well as for event handling purposes.
The table can be customized extensively using cascading stylesheet (CSS) classes and definitions
to enhance the appearance of the table's headers, footers, columns and rows. Common formatting
techniques, such as alternating row colors, can be accomplished quite easily with this tag.
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. For more information about columns, see
the column tag documentation.
A dataTable tag can also contain header and footer facets. 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,
respectively.
Example:
<h:dataTable id="table1" value="#{shoppingCartBean.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.description}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Price" />
</f:facet>
<h:outputText value="#{item.price}" />
</h:column>

139
12 - javaserver faces

<f:facet name="footer">
<h:outputText value="Total: #{shoppingCartBean.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.00</td></tr>
<tr><td>Tasty Melon</td><td>$5.00</td></tr>
</tbody>
<tfoot>
<tr><td colspan="2">Total: $15.00</td></tr>
</tfoot>
</table>

12.4.3 h:form
The form tag renders an HTML form element. JSF forms use the "post-back" technique to submit
form data back to the page that contains the form. 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.
If your application requires the use of the GET method for form submission, your options include
using plain HTML forms, binding request parameters to backing bean properties, and using the
outputLink tag to generate dynamic hyperlinks.
Example:
<h:form id="form1"></h:form>

HTML Output
<form id="form1" name="form1" method="post" action="/demo/form.jsp" enctype="application/x-
www-form-urlencoded"></form>

12.4.4 h:commandButton
The commandButton tag renders an HTML submit button that can be associated with a backing
bean or ActionListener class for event handling purposes. The display value of the button can also be
obtained from a message bundle to support internationalization (I18N).
Example:
<h:commandButton id="button1" value="#{bundle.checkoutLabel}"
action="#{shoppingCartBean.checkout}" />

HTML Output
<input id="form:button1" name="form:button1" type="submit" value="Check Out"
onclick="someEvent();" />

140
12 - javaserver faces

12.4.5 h:inputText
The inputText tag renders an HTML input element of the type "text".
Example:
<h:inputText id="username" value="#{userBean.user.username}" />

HTML Output
<input id="form:username" name="form:username" type="text" />

12.4.6 message Tag


The message tag renders a message for a specific component. You can customize the message
generated by this component by applying different CSS styles to the message depending on its
severity (eg. red for error, green for information) as well as the detail level of the message itself. You
can also customize the standard error messages by overriding specific JSF properties in your
message bundle.
Example:
<h:inputText id="username" required="#{true}"
value="#{userBean.user.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.</span>

12.5 the core JSF tags

The core JavaServer Faces tags define custom actions that are independent of any particular
RenderKit.

12.5.1 the list of JSF Core Tags


Here is an exhaustive list of the JSF core tags:
actionListener
attribute
convertDateTime
converter
convertNumber
facet
loadBundle
param
selectItem
selectItems
subview
validateDoubleRange

141
12 - javaserver faces

validateLength
validateLongRange
validator
valueChangeListener
verbatim
view
Some of these tags will be detailed in the next paragraphs.
12.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.
The Facet tag registers a named facet on the component associated with the enclosing tag. 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>

12.5.3 f:validator
The Validator tag registers a named Validator instance on the component associated with the
enclosing tag. The JavaServer Faces framework includes three standard validators (see the
validateDoubleRange, validateLength, and validateLongRange tags) but the Validator interface can be
implemented by classes that provide custom validation for your application. This tag accepts one value
matching the validator ID you assigned to your validator class in your Faces configuration file. The
body content of this tag must be empty.
Example:
<h:inputText id="emailAddress"

142
12 - javaserver faces

value="#{customerBean.customer.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.

12.5.4 f:valueChangeListener
The ValueChangeListener tag registers a ValueChangeListener instance on the component
associated with the enclosing tag. The ValueChangeListener interface should be implemented by
classes that you want to register with components that publish value change events.
Any component that receives user input, such as one of the HTML select or text input components,
can publish value change events. A component fires a value change event when its input changes, but
only if the new input is validated successfully.
You can register several ValueChangeListeners with a component and they will be invoked in the
order that they are registered. An alternative to this tag is to use a method-binding expression pointing
at a value change listener method of a backing bean on the component tag itself.
Notice in the example below the use of the JavaScript onchange() event to trigger form submission
when the list selection changes. Without this JavaScript event, the user must manually submit the
form to invoke the ValueChangeListener.
Example:
<h:selectOneMenu id="optionMenu" value="#{optionBean.selectedOption}"
onchange="submit()">
<f:selectItems value="#{optionBean.optionList}" />
<f:valueChangeListener
type="com.mycompany.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>

12.5.5 f:view
The View tag is the container for all JavaServer Faces component tags used on a page. 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.
This tag is useful for internationalization (I18N) purposes. It provides you with several options for
presenting your user with localized views of your application. 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.
If the locale requested by the user is not supported by your application, the JSF framework will use
the default locale specified in your Faces configuration file. If you have not specified a default locale,
JSF will use the default locale for the Java Virtual Machine serving your application.
If your application supports the locale requested by the user, JSF will set that locale for the view and

143
12 - javaserver faces

will display the messages for that locale defined in the locale's message bundle.
You can also specify the locale for which the view is to be rendered by explicitly setting the locale
attribute of the view tag. This allows you to design localized versions of each page, including images
and styles, for each locale you wish to support.
Another option is to obtain the locale dynamically through user interaction. This information could
later be stored in a cookie and/or a database to identify which locale is preferred by your user. The
locale attribute accepts a value-binding expression that could resolve to the desired locale.
Example:
welcome_en.jsp (English)
<f:view locale="en">
<f:loadBundle basename="com.mycompany.MessageBundle" var="bundle" />
<h:outputText value="#{bundle.welcomeMessage}" />
</f:view>
welcome_fr.jsp (French)
<f:view locale="fr">
<f:loadBundle basename="com.mycompany.MessageBundle" var="bundle" />
<h:outputText value="#{bundle.welcomeMessage}" />
</f:view>

HTML Output
welcome_en.jsp (English)
Welcome to our site!
welcome_fr.jsp (French)
Bienvenue notre site!

12.6 the structure of a JSF application

Here is a typical directory structure for a JSP application. The directory myJSFapp is the base
directory of the application.

myJSFapp
/ant
build.xml
/JavaSource
/WebContent
/WEB-INF
/classes
/lib
jsf-impl.jar
jsf-api.jar
faces-config.xml
web.xml
/pages

Comments on this structure:

144
12 - javaserver faces

myJSFapp application base directory with application name


/ant directory containing Ant build scripts with a default build.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 - contains libraries required by the application, like third party jar files
jsf-impl.jar, jsf-api.jar files included in the /lib directory, mandatory for any JSF application
web.xml the deployment descriptor of the application, included in the /WEB-INF directory
faces-config.xml the JSF configuration file, included in the /WEB-INF directory
/pages directory containing JSP and HTML presentation pages

12.7 how does JSF work? a first example

Example taken from http://www.exadel.com/tutorial/jsf/jsftutorial-kickstart.html.


A JSF application is nothing else but a servlet/JSP application. It has a deployment descriptor, JSP
pages, custom tag libraries, static resources, and so on. What makes it different is that a JSF
application is event-driven. The way the application behaves is controlled by an event listener class.
Let's have a look at the steps needed to build a JSF application:
1. Create JSP pages
2. Define navigation rules
3. Create managed beans
4. Create properties files
5. Edit JSP pages
6. Create an index.jsp file
7. Compile the application
8. Deploy and run the application

12.7.1 creating JSP Pages


Create the inputname.jsp and greeting.jsp files in WebContent/pages/. You only need to create
the JSP files. The directory structure already exists.
These files will act as place holders for now. We will complete the content of the files a little bit later.
Now that we have the two JSP pages, we can create a navigation rule.

12.7.2 navigation
Navigation is the heart of JavaServer Faces. The navigation rule for this application is described in
the faces-config.xml file. This file already exists in the skeleton directory structure. You just need to
create its contents.
In our application, we just want to go from inputname.jsp to greeting.jsp. As a diagram, it would

145
12 - javaserver faces

look something like this:

The navigation rule shown in the picture is defined below. The rule says that from the view (page)
inputname.jsp go to the view (page) greeting.jsp, if the "outcome" of executing inputname.jsp is
greeting. And that's all there is to this.

<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/pages/greeting.jsp</to-view-id>
</navigation-case>
</navigation-rule>

This is, of course, a very simple navigation rule. You can easily create more complex ones. To read
more about navigation rules, visit the JSP Navigation Example forum item.

12.7.3 creating the Managed Bean


Next, we will create a myJFSapp folder inside the JavaSource folder. Inside this myJFSapp folder,
we will create a PersonBean.java file. This class is straight-forward. It's a simple Java bean with one
attribute and setter/getter methods. The bean simply captures the name entered by a user after the
user clicks the submit button. 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.)

12.7.3.1 PersonBean.java
Put this code in the file:
package myJFSapp;

public class PersonBean {


String personName;
/**
* @return Person Name
*/
public String getPersonName() {

146
12 - javaserver faces

return personName;
}
/**
* @param Person Name
*/
public void setPersonName(String name) {
personName = name;
}
}
Later you will see how to "connect" this bean with the JSP page.

12.7.3.2 declaring the Bean in faces-config.xml


Now, the second part of faces-config.xml describes our Java bean that we created in the previous
steps. This section defines a bean name PersonBean. The next line is the full class name,
myJFSapp.PersonBean. request sets the bean scope in the application.

<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>myJFSapp.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>

12.7.3.3 faces-config.xml
Your final faces-config.xml file should look like this:

<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/pages/greeting.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>myJFSapp.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>

12.7.4 creating a Properties File (Resource Bundle)


A properties file is just a file with param=value pairs. We use the messages stored in the properties

147
12 - javaserver faces

file in our JSP pages. Keeping the messages separate from the JSP page allows us to quickly modify
the messages without editing the JSP page.
Let's create a bundle folder in the JavaSource/myJFSapp folder and then a messages.properties
file in the bundle folder. We need to place it in the JavaSource folder so that during project
compilation, this properties file will be copied to the classes folder where the runtime can find it.

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

12.7.5 editing the JSP Pages


Two pages should already have been created in myJFSapp/WebContent/pages.

12.7.5.1 inputname.jsp
Put the following coding into this file:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="myJFSapp.bundle.messages" var="msg"/>

<html>
<head>
<title>enter your name page</title>
</head>
<body>
<f:view>
<h1>
<h:outputText value="#{msg.inputname_header}"/>
</h1>
<h:form id="helloForm">
<h:outputText value="#{msg.prompt}"/>
<h:inputText value="#{personBean.personName}" required=true>
<f:validateLength minimum="2" maximum="10"/>
</h:inputText>
<h:commandButton action="greeting" value="#{msg.button_text}" />
</h:form>
</f:view>
</body>
</html>
Now, let's explain the important sections in this file after displaying the code for each section starting

148
12 - javaserver faces

from the top.

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="myJFSapp.bundle.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. The
third line loads our properties file (resource bundle) that holds messages that we want to display in our
JSP page.

<h:inputText value="#{msg.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. 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.


Then, look up the value for inputname_header in that file and print it here.

1 <h:form id="helloForm">
2 <h:outputText value="#{msg.prompt}"/>
3 <h:inputText value="#{personBean.personName}" required=true>
4 <f:validateLength minimum="2" maximum="10"/>
5 </h:inputText>
6 <h:commandButton action="greeting" value="#{msg.button_text}" />
7 </h:form>

Line 1. Creates an HTML form using JSF tags.


Line 2. Prints a message from the properties file using the value of prompt.
Lines 3-5. Creates an HTML input text box. In the value attribute we connect (bind) this field to the
managed bean attribute that we created before.
Line 6. JSF tags for the HTML form's submit button. The button's value is being retrieved from the
properties file. While the button's action attribute is set to greeting which matches the navigation-
outcome in faces-config.xml file. That's how JSF knows where to go next.

12.7.5.2 greeting.jsp
Put this coding inside the second JSP file:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="myJFSapp.bundle.messages" var="msg"/>

<html>
<head>
<title>greeting page</title>

149
12 - javaserver faces

</head>
<body>
<f:view>
<h3>
<h:outputText value="#{msg.greeting_text}" />,
<h:outputText value="#{personBean.personName}" />
<h:outputText value="#{msg.sign}" />
</h3>
</f:view>
</body>
</html>

This page is very simple. The first three lines are identical to our first page. Theses lines import JSF
tag libraries and our properties file (resource bundle) with the messages.
The main code of interest to us is between the <h3>...</h3> tags. The first line will take a message
from the resource bundle and print it on the page. The second line will access a Java bean,
specifically the bean attribute personName, and also print its contents on the page.
Once this page is displayed in a Web browser, you will see something like this:
Welcome to JSF, name!

12.7.6 creating the index.jsp File


We will now create a third JSP file that doesn't actually function as a presentation page. It uses a
JSP tag to "forward" to the inputname.jsp page.
Create the index.jsp file inside the WebContent folder. Note that this file is not created in the
pages folder like the previous JSP files.
Having an index.jsp file will allow us to start the application like this:

http://localhost:8080/myJFSapp/

Now, put this coding into the file:

<html>
<body>
<jsp:forward page="/pages/inputname.jsf" />
</body>
</html>

If you look at the path for the forward, you'll notice the file suffix is .jsf and not .jsp. This is used
here, because in the web.xml file for the application *.jsf is the URL pattern used to signal that the
forwarded page should be handled by the JavaServer Faces servlet within Tomcat.
We are almost done with this example.

12.7.7 Compiling
An Ant build script is provided for you. To build the application run the build.xml script from the ant
folder:
ant build

150
12 - javaserver faces

12.7.8 Deploying
Before you can run this application within the servlet container, we need to deploy it. We will use null
(link) deployment to deploy the application in-place. To do this we need to register a context in
Tomcat's {TomcatHome}\conf\server.xml file.
To do this, insert this code:

<Context debug="0"
docBase="Path_to_WebContent"
path="/myJFSapp" reloadable="true"/>

near the end of the server.xml file within the Host element just before the closing </Host> tag. Of
course, Path_to_WebContent needs to be replaced with the exact path on your system to the
WebContent folder inside the myJFSapp folder (for example,
C:/examples/myJFSapp/WebContent).

12.7.9 Running
Next, start the Tomcat server (probably using the script startup.bat in Tomcat's bin directory).
When Tomcat is done loading, launch a web browser and enter: http://localhost:8080/myJFSapp.
(Port 8080 is the default port in Tomcat. Your setup, though, might possibly be different).

12.8 creating a JSF application in eclipse with the facesIDE plugin

Example taken from http://amateras.sourceforge.jp/docs/FacesIDE/SampleJSFApp.html .

12.8.1 Overview
This is a tutorial in which we create a simple JSF application to demonstrate FacesIDE's
functionality. This is a "login" application, which asks an user for an ID and password, verifies the
information, and forwards the user to a success or error page.
The application will use a few JSP pages with JSF elements, and a session-scoped managed bean
to coordinate their interactions. 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.xml Editor (see faces-config.xml Editor)
As a prerequisite for the tutorial, make sure FacesIDE and required plugins have been installed; see
Installing & Uninstalling. We don't assume that a J2EE server-specific plugin, such as the Sysdeo
Tomcat plugin has been installed.

12.8.2 Creating A Project


Here we create an Eclipse project, and set up folders for a web application. The folder structure
created is simply one that works for this author; your mileage may vary.
1. From the menu bar select File/New/Project.... The New Project wizard appears.
2. Select Java Project; click Next.
3. Enter project name, say, jsf-login; click Finish
4. Create the web root folder: in Package Explorer select the jsf-login project, and from the

151
12 - javaserver faces

menubar select File/New/Folder; name the folder webroot


5. Create the web pages folder: in Package Explorer select the webroot folder, and from its
context menu select File/New/Folder; name the folder pages. This folder will contain all
"functional" pages.
6. Use FacesIDE to add JSF support: we use a FacesIDE wizard to create J2EE-prescribed
folders and files in webroot, and to add JSF libraries to the project.
a. in Package Explorer select the jsf-login project
b. from the menubar select File/New/Other...
c. in the wizard that appears, select Amateras/JSF/Add JSF Support; click Next
d. in the Add JSF Support page, for Web Application Root enter /jsf-
login/webroot; make sure all checkboxes are checked; click Next.
7. From the menubar open Project/Properties
8. Select the Amateras node; note that Root: has automatically been set to /webroot; make
sure HTML validation and DTD/XSD validation are enabled.
9. Create the source folder: select the Java Build Path node; select the Source tab; click Add
Folder...; in the dialog that appears create a folder named src directly under the project folder
(jsf-login); click Yes through messages that appear.
10.Set the output folder: in the Default output folder textbox at the bottom, enter jsf-
login/webroot/WEB-INF/classes; click OK to dismiss the properties dialog.

Your folder structure should now be as follows:


jsf-login
|
+-- src
|
+-- webroot
|
+-- WEB-INF
| |
| +-- classes (not shown in Java perspective)
| |
| +-- lib
|
+-- pages

12.8.3 Creating & Configuring Managed Beans


Here we create a class called LoginManager which will be used as a backing bean for the login
process. We then configure it to be a managed bean.
1. In Package Explorer select the src folder; from its context menu select New/Class. The New
Java Class wizard appears.
2. In the Package field, enter login; in the Name field enter LoginManager. Click Finish. The
Java code editor opens.
3. Enter and save the following code for the LoginManager class:

// LoginManager.java

152
12 - javaserver faces

package login;

public class LoginManager {


private String _uid = "";
private String _pwd = "";

public String getUserID() { return _uid; }


public void setUserID(String uid) { _uid = uid; }
public String getPassword() { return _pwd; }
public void setPassword(String pwd) { _pwd = pwd; }

public String loginAction() {


String action = null;

if ( _uid.equalsIgnoreCase("foo") &&
_pwd.equalsIgnoreCase("bar") )
action = "loginPass";
else
action = "loginFail";

return action;
}
}

4. Use FacesIDE to configure the bean: we use a FacesIDE editor to configure


LoginManager as a session-scoped managed bean.
a. in Package Explorer select jsf-login/webroot/WEB-INF/faces-config.xml;
from its context menu select Open With/faces-config.xml Editor. The faces-
config.xml editor opens.
b. along the bottom of the editor there are 3 tabs; click Managed Bean.
c. click Add; input widgets appear
d. for name enter mgr; for class enter login.LoginManager; for scope select
session.
e. from the menubar select File/Save, then close the editor

12.8.4 Creating JSP Pages


Here we create the JSP pages that make up the application's user interface. We will have 4 pages:
a start page (index.jsp), and 3 content pages (login.jsp, success.jsp and error.jsp).
Content pages are placed in webroot/pages; index.jsp is placed directly in webroot, and its
sole function is to forward users to the login page.
All pages except login.jsp are simple pages with static content, so we create them first, using
the Workbench's standard file-creation facilities. Then we create login.jsp using a FacesIDE
wizard.
1. Create index.jsp:
a. in Package Explorer select webroot; from its context menu select New/File; the New
File wizard appears.
b. for File name enter index.jsp; make sure that the parent folder is set to /jsf-
login/webroot; click Finish; the JSP Editor opens.
c. enter the following code, save the file and close the editor.

<!-- webroot/index.jsp -->

153
12 - javaserver faces

<html>
<body>
<jsp:forward page="faces/pages/login.jsp" />
</body>
</html>

2. Create success.jsp: create this file similarly to index.jsp, but in webroot/pages. Enter
the following code:

<!-- webroot/pages/success.jsp -->


<html>
<head>
<title>jsf-login</title>
</head>
<body>
<h2>Success!</h2>
</body>
</html>

3. Create error.jsp: create this file similarly to index.jsp, but in webroot/pages. Enter
the following code:

<!-- webroot/pages/error.jsp -->


<html>
<head>
<title>jsf-login</title>
</head>
<body>
<h2>Error!</h2>
The user-id and or password were invalid. Please try again.
</body>
</html>

4. Create login.jsp:
a. in Package Explorer select webroot/pages; from its context menu select
New/Other...; the New wizard appears.
b. select Amateras/JSF/Faces JSP File; click Next
c. for File name enter login.jsp; make sure that Container is set to /jsf-
login/webroot/pages, and that Use MyFaces Tomahawk components and Use
MyFaces SandBox components are unchecked, and choose default for Template;
click Finish; the FacesIDE JSP Editor opens, with the following template code.

<%@ page contentType="text/html; charset=Cp1252" %>


<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=Cp1252"/>
<title></title>
</head>
<body>
<f:view>
<h:form>
</h:form>
</f:view>
</body>

154
12 - javaserver faces

</html>

We will now edit this page to contain our input widgets, etc.
d. place the cursor between the <title></title> elements; enter jsf-login
e. Open the JSF palette, and dock it along the right. (See Show View Dialog)
f. create a few blank lines between the <h:form> elements; place your cursor in one of
these lines, expand the JSF HTML panel in the palette, and click on the icon for
<h:inputText>; this inserts the corresponding JSF element at the cursor location.
Note: the JSP editor is aware of referenced tag libraries, and uses them for code
completion as well. Thus if you were to type <h: and hit CTRL + Spacebar, you would
get a popup window of JSF HTML elements.
g. now we want to add attributes to this element, and the JSP Editor can help with code-
completion. To see this in action, place the cursor inside the <h:inputText> element,
and hit CTRL + Spacebar; a code-completion window pops up, as shown below.

h. in the code-completion window scroll down to value, and hit Enter; this inserts
value="" at the cursor. We will now bind this to the userID property of
LoginManager; FacesIDE can provide code completion here as well.
i. place the cursor between the quotes in value="", enter #{mgr., and hit CTRL +
Spacebar; a code-completion window pops up, with bean properties available in mgr.
This is shown below:

155
12 - javaserver faces

(Recall that we configured LoginManager as a managed bean called mgr.)


j. select userID from the code-completion window; complete the expression with the
closing {
k. insert another <h:inputText> element; set its value binding expression to
value="#{mgr.password}"
l. insert a <h:commandButton> element; set its value to Login, and its action to
the value binding expression #{mgr.loginAction}
The final code, with the barest presentational formatting, is shown below:

<%@ page contentType="text/html; charset=Cp1252" %>


<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<title>jsf-title</title>
</head>
<body>
<f:view>
<h:form>
UserID: <h:inputText value="#{mgr.userID}"/>
<br/>Password: <h:inputText value="#{mgr.password}"/>
<br/><h:commandButton value="Login"
action="#{mgr.loginAction}"/>
</h:form>
</f:view>
</body>
</html>

12.8.5 Creating Navigation Rules


Here we create navigation rules among pages, using a FacesIDE editor.
1. Open faces-config.xml; it should open in the faces-config.xml Editor.
2. Select the Navigation tab
3. from the Navigation panel in the palette at left, click on Page, then click inside the editor
window; this inserts a page icon into the editor, and the page's properties appear in the
Workbech's Properties view. This is shown below.

156
12 - javaserver faces

Note that the icon has a small triangle overlay--this indicates that something is wrong,
specifically that FacesIDE could not locate a page at path /page1.jsp
4. in the Properties view, change the value of path to /index.jsp. You can also change it on
the diagram directly (select the page and click once more); notice that the warning triangle
disappears.
5. add 3 more pages, and set them to /pages/login.jsp, /pages/success.jsp and
/pages/error.jsp. Arrange them as shown below:

157
12 - javaserver faces

Now we'll add navigation rules among the pages.


6. from the palette at left, select Navigation Case, then click first on the icon for login.jsp
and then on the icon for success.jsp. This inserts a forward-action between the two pages,
and is represented by an arrow. "Decharge" the mouse pointer by clicking on the pointer icon
in the palette, then click on the newly-added forward-action icon to select it. Its properties
appear in the Properties view. This is shown below:

158
12 - javaserver faces

7. in the Properties view (or direct editing on the diagram), change the value of from-outcome
to loginPass. Recall that this is the success-value returned by LoginManager's
loginAction method. You can also change values by direct-editing (select once and re-
click) in the diagram
8. Similarly add a forward-action from login.jsp to error.jsp, and set its from-outcome to
loginFail
We're done with setting up navigation rules. We'll set some properties in web.xml, and we'll then
be ready to deploy the application.

12.8.6 Editing web.xml


Here we edit web.xml for the specifics of our application. As it turns out, since we have such a
trivial application, all we need do in web.xml is indicate the Faces Servlet mapping.
1. open web.xml; scroll to the bottom and look for the comment
<!-- Faces Servlet Mapping -->
2. by default virtual path-based mapping is commented out, and extension-based mapping is
turned on. We want virtual path-based mapping, so uncomment it. You may comment out the
entry for extension-based mapping, or leave it as-is.
The application is now complete, and you should be able to deploy it to your server of choice. Once
deployed browse to index.jsp, and you should be automatically forwarded to login.jsp. Use
UserID/Password of foo/bar, and you should be sent to the success page; any other id/password
should send you to the error page.

Deployment to some servers is described below:

159
12 - javaserver faces

12.8.7 Deploying To Tomcat 5.0


1. start Tomcat; open its Manager application in a browser; the default URL for this is
http://localhost:8080/manager/html
2. scroll down to Deploy; we'll deploy our app by providing its directory; for Context path enter
/jsf-login; for WAR or Directory URL enter the path to webroot, as file:///...;
leave XML Configuration File URL blank; click Deploy
3. the Manager application should reload, and you should see /jsf-login in the list of running
applications. Click on its link to launch the application.

12.9 packges in the JavaServer Faces API

The classes and interfaces of the JavaServer Faces API are grouped in several packages, namely:
javax.faces
javax.faces.application
javax.faces.component
javax.faces.component.html
javax.faces.context
javax.faces.convert
javax.faces.el
javax.faces.event
javax.faces.lifecycle
javax.faces.model
javax.faces.render
javax.faces.validator
javax.faces.webapp

12.10 the javax.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. For a given factory class name, a corresponding implementation class is
searched for based on the following algorithm. 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, that factory is used.
If the JavaServer Faces configuration files named by the javax.faces.CONFIG_FILES
ServletContext init parameter contain any factory entries of the given factory class
name, those factories are used, with the last one taking precedence.
If there are any JavaServer Faces configuration files bundled into the META-INF directory of

160
12 - javaserver faces

any jars on the ServletContext's resource paths, the factory entries of the given factory
class name in those files are used, with the last one taking precedence.
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), its first line is read and assumed to be the name of the factory
implementation class to use.
If none of the above steps yield a match, the JavaServer Faces implementation specific class
is used.

public class FacesException extends RuntimeException

This class encapsulates general JavaServer Faces exceptions.

12.11 the javax.faces.application package

Contains the following classes:


Application - A set of APIs for representing UI components and managing their state,
handling events and input validation, defining page navigation, and supporting
internationalization and accessibility.
ApplicationFactory - a factory object that creates (if needed) and returns Application
instances. Implementations of JavaServer Faces must provide at least a default
implementation of Application.
FacesMessage - represents a single validation (or other) message, which is typically
associated with a particular component in the view. A FacesMessage instance may be
created based on a specific messageId.
FacesMessage.Severity - used to represent message severity levels in a typesafe
enumeration.
NavigationHandler An object of this type is passed the outcome string returned by an
application action invoked for this application, and will use this (along with related state
information) to choose the view to be displayed next.
StateManager - directs the process of saving and restoring the view between requests.
StateManagerWrapper - Provides a simple implementation of StateManager that can be
subclassed by developers wishing to provide specialized behavior to an existing
StateManager instance. The default implementation of all methods is to call through to the
wrapped StateManager.
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. This allows
for implementations to support different response generation technologies, as well as
alternative strategies for saving and restoring the state of each view.
ViewHandlerWrapper - Provides a simple implementation of ViewHandler that can be
subclassed by developers wishing to provide specialized behavior to an existing
ViewHandler instance. The default implementation of all methods is to call through to the
wrapped ViewHandler.
ViewExpiredException - implementations must throw this FacesException when
attempting to restore the view
StateManager.restoreView(javax.faces.context.FacesContext, String,

161
12 - javaserver faces

String) results in failure on postback.

12.12 the javax.faces.component package

Defines both a set of interfaces and classes. The interfaces defined in this package are:
ActionSource - an interface that may be implemented by any concrete UIComponent that
wishes to be a source of ActionEvents, including the ability to invoke application actions via
the default ActionListener mechanism.
ActionSource2 - extends ActionSource and provides a JavaBeans property analogous to
the "action" property on ActionSource. The difference is the type of this property is a
MethodExpression rather than a MethodBinding. This allows the ActionSource
concept to leverage the new Unified EL API.
ContextCallBack - A simple callback interface 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.
EditableValueHolder - an extension of ValueHolder that describes additional features
supported by editable components, including ValueChangeEvents and Validators.
NamingContainer - an interface that must be implemented by any UIComponent that wants
to be a naming container.
StateHolder - interface implemented by classes that need to save their state between
requests.
ValueHolder - an interface that may be implemented by any concrete UIComponent that
wishes to support a local value, as well as access data in the model tier via a value binding
expression, and support conversion between String and the model tier data's native data type.

The classes in this package are all UI related. Here they are:
UIColumn - a UIComponent that represents a single column of data within a parent UIData
component.
UICommand - a UIComponent that represents a user interface component which, when
activated by the user, triggers an application specific "command" or "action". Such a
component is typically rendered as a push button, a menu item, or a hyperlink.
UIComponent - the base class for all user interface components in JavaServer Faces. 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.
UIComponentBase - a convenience base class that implements the default concrete
behavior of all methods defined by UIComponent.
UIData - a UIComponent that supports data binding to a collection of data objects
represented by a DataModel instance, which is the current value of this component itself
(typically established via a ValueBinding). During iterative processing over the rows of data
in the data model, the object for the current row is exposed as a request attribute under the
key specified by the var property.
UIForm - a UIComponent that represents an input form to be presented to the user, and
whose child components represent (among other things) the input fields to be included when
the form is submitted.
UIGraphic - a UIComponent that displays a graphical image to the user. The user cannot
manipulate this component; it is for display purposes only.
UIInput - a UIComponent that represents a component that both displays output to the user

162
12 - javaserver faces

(like UIOutput components do) and processes request parameters on the subsequent
request that need to be decoded.
UIMessage - This component is responsible for displaying messages for a specific
UIComponent, identified by a clientId.
UIMessages - The renderer for this component is responsible for obtaining the messages
from the FacesContext and displaying them to the user.
UINamingContainer - a convenience base class for components that wish to implement
NamingContainer functionality.
UIOutput - a UIComponent that has a value, optionally retrieved from a model tier bean via a
value binding expression, that is displayed to the user. The user cannot directly modify the
rendered value; it is for display purposes only.
UIPanel - a UIComponent that manages the layout of its child components.
UIParameter - a UIComponent that represents an optionally named configuration parameter
for a parent component.
UISelectBoolean - a UIComponent that represents a single boolean (true or false) value.
It is most commonly rendered as a checkbox.
UISelectItem - a component that may be nested inside a UISelectMany or UISelectOne
component, and causes the addition of a SelectItem instance to the list of available options
for the parent component.
UISelectMany - a UIComponent that represents the user's choice of a zero or more items
from among a discrete set of available options. The user can modify the selected values.
Optionally, the component can be preconfigured with zero or more currently selected items, by
storing them as an array in the value property of the component.This component is generally
rendered as a select box or a group of checkboxes.
UISelectOne - a UIComponent that represents the user's choice of zero or one items from
among a discrete set of available options. The user can modify the selected value. Optionally,
the component can be preconfigured with a currently selected item, by storing it as the value
property of the component.
UIViewRoot - the UIComponent that represents the root of the UIComponent tree. This
component has no rendering, it just serves as the root of the component tree.

12.13 the java.faces.component.html package

Contains HTML related classes.

HtmlColumn - represents a column that will be rendered in an HTML table element.


HtmlCommandButton - represents an HTML input element for a button of type submit or
reset. The label text is specified by the component value.
HtmlCommandLink - represents an HTML a element for a hyperlink that acts like a submit
button. This component must be placed inside a form, and requires JavaScript to be enabled
in the client.
HtmlDataTable - represents a set of repeating data (segregated into columns by child
UIColumn components) that will be rendered in an HTML table element.
HtmlForm - represents an HTML form element. Child input components will be submitted
unless they have been disabled.
HtmlGraphicImage - represents an HTML img element, used to retrieve and render a
graphical image.
HtmlInputHidden - represents an HTML input element of type hidden.

163
12 - javaserver faces

HtmlInputSecret - represents an HTML input element of type password. On a redisplay,


any previously entered value will not be rendered (for security reasons) unless the
redisplay property is set to true.
HtmlInputText - represents an HTML input element of type text.
HtmlInputTextarea - represents an HTML textarea element.
HtmlMessage - by default, the rendererType property must be set to
"javax.faces.Message". This value can be changed by calling the setRendererType()
method.
HtmlMessages - by default, the rendererType property must be set to
"javax.faces.Messages" This value can be changed by calling the setRendererType()
method.
HtmlOutputFormat - represents a component that looks up a localized message in a
resource bundle, optionally uses it as a MessageFormat pattern string and substitutes in
parameter values from nested UIParameter components, and renders the result. If the "dir" or
"lang" attributes are present, render a span element and pass them through as attributes on
the span.
HtmlOutputLabel - represents an HTML label element, used to define an accessible label
for a corresponding input element.
HtmlOutputLink - represents an HTML a (hyperlink) element that may be used to link to an
arbitrary URL defined by the value property.
HtmlOutputText - renders the component value as text, optionally wrapping in a span
element if CSS styles or style classes are specified.
HtmlPanelGrid - renders child components in a table, starting a new row after the specified
number of columns.
HtmlPanelGroup - causes all child components of this component to be rendered. This is
useful in scenarios where a parent component is expecting a single component to be present,
but the application wishes to render more than one.
HtmlSelectBooleanCheckbox - represents an HTML input element of type checkbox. The
checkbox will be rendered as checked, or not, based on the value of the value property.
HtmlSelectManyCheckbox - 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 either all available options or the specified number of
options.
HtmlSelectManyMenu - represents a multiple-selection component that is rendered as an
HTML select element, showing a single available option at a time.
HtmlSelectOneListbox - represents a single-selection component that is rendered as an
HTML select element, showing either all available options or the specified number of
options.
HtmlSelectOneMenu - represents a single-selection component that is rendered as an HTML
select element, showing a single available option at a time.
HtmlSelectOneRadio - represents a single-selection component that is rendered as a set of
HTML input elements of typeradio.

12.14 the java.faces.context package

Contains the following classes:

164
12 - javaserver faces

ExternalContext - allows the Faces API to be unaware of the nature of its containing
application environment. In particular, this class allows JavaServer Faces based applications
to run in either a Servlet or a Portlet environment.
FacesContext - contains all of the per-request state information related to the processing of a
single JavaServer Faces request, and the rendering of the corresponding response. It is
passed to, and potentially modified by, each phase of the request processing lifecycle.
FacesContextFactory - a factory object that creates (if needed) and returns new
FacesContext instances, initialized for the processing of the specified request and response
objects.
ResponseStream - an interface describing an adapter to an underlying output mechanism for
binary output.
ResponseWriter - an abstract class describing an adapter to an underlying output
mechanism for character-based output.
ResponseWriterWrapper - 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.

12.15 the java.faces.convert package

12.15.1 the interface Converter


Converter is an interface describing a Java class that can perform Object-to-String and String-to-
Object conversions between model data objects and a String representation of those objects that is
suitable for rendering.
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 - an exception thrown by the getAsObject() or getAsText()
method of a Converter, to indicate that the requested conversion cannot be performed.

165
12 - javaserver faces

12.16 the java.faces.el package

Contains classes and interfaces for evaluating and processing reference expressions.
Classes:

MethodBinding - an object that can be used to call an arbitrary public method, on an


instance that is acquired by evaluatng the leading portion of a method binding expression via a
ValueBinding.
PropertyResolver - represents a pluggable mechanism for accessing a "property" of an
underlying Java object instance.
ValueBinding - an object that can be used to access the property represented by an action or
value binding expression.
VariableResolver - represents a pluggable mechanism for resolving a top-level variable
reference at evaluation time.

Exceptions:

EvaluationException - an exception reporting an error that occurred during the evaluation of


an expression in a MethodBinding or ValueBinding.
MethodNotFoundException - an exception caused by a method name that cannot be
resolved against a base object.
PropertyNotFoundException - an exception caused by a property name that cannot be
resolved against a base object.
ReferenceSyntaxException - an exception reporting a syntax error in a method binding
expression or value binding expression.

12.17 the java.faces.event package

Contains interfaces describing events and event listeners, and event implementation classes.
Interfaces:

ActionListener - listener interface for receiving ActionEvents.


FacesListener - a generic base interface for event listeners for various types of
FacesEvents.
PhaseListener - 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.
ValueChangeListener - listener interface for receiving ValueChangeEvents.

Classes:

ActionEvent - represents the activation of a user interface component (such as a


UICommand).
FacesEvent - the base class for user interface and application events that can be fired by
UIComponents.
PhaseEvent - represents the beginning or ending of processing for a particular phase of the
request processing lifecycle, for the request encapsulated by the specified FacesContext.

166
12 - javaserver faces

PhaseId - typesafe enumeration of the legal values that may be returned by the
getPhaseId() method of the FacesEvent interface.
ValueChangeEvent - a notification that the local value of the source component has been
change as a result of user interface activity.

One exception - AbortProcessingException - thrown by event listeners to terminate the


processing of the current event.

12.18 the java.faces.lifecycle package

This package contains 2 classes.


The Lifecycle class manages the processing of the entire lifecycle of a particular JavaServer Faces
request.
The LifecycleFactory class is a factory object that creates (if needed) and returns Lifecycle
instances.

12.19 the java.faces.model package

Contains the interface DataModelListener and several classes providing standard model data beans
for JavaServer Faces. Classes:

ArrayDataModel - a convenience implementation of DataModel that wraps an array of Java


objects.
DataModel - 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).
DataModelEvent - represents an event of interest to registered listeners that occurred on the
specified DataModel.
ListDataModel - a convenience implementation of DataModel that wraps an List of Java
objects.
ResultDataModel - a convenience implementation of DataModel that wraps a JSTL Result
object, typically representing the results of executing an SQL query via JSTL tags.
ResultSetDataModel - a convenience implementation of DataModel that wraps a
ResultSet of Java objects. Note that the specified ResultSet MUST be scrollable.
ScalarDataModel - a convenience implementation of DataModel that wraps an individual
Java object.
SelectItem - represents a single item in the list of supported items associated with a
UISelectMany or UISelectOne component.
SelectItemGroup - a subclass of SelectItem that identifies a set of options that will be
made available as a subordinate "submenu" or "options list", depending upon the
requirements of the UISelectMany or UISelectOne renderer that is actually used.

12.20 the java.faces.render package

Contains classes defining the rendering model.

167
12 - javaserver faces

Renderer - converts the internal representation of UIComponents into the output stream (or
writer) associated with the response we are creating for a particular request. Each Renderer
knows how to render one or more UIComponent types (or classes), and advertises a set of
render-dependent attributes that it recognizes for each supported UIComponent.
RenderKit - represents a collection of Renderer instances that, together, know how to
render JavaServer Faces UIComponent instances for a specific client. Typically,
RenderKits are specialized for some combination of client device type, markup language,
and/or user Locale. A RenderKit also acts as a Factory for associated Renderer
instances, which perform the actual rendering process for each component.
RenderKitFactory - a factory object that registers and returns RenderKit instances.
Implementations of JavaServer Faces must provide at least a default implementation of
RenderKit.
ResponseStateManager - the helper class to StateManager that knows the specific
rendering technology being used to generate the response.

12.21 the java.faces.validator package

Interface defining the validator model, and concrete validator implementation classes.
A Validator implementation is a class that can perform validation (correctness checks) on a
EditableValueHolder.
Implementation classes:
DoubleRangeVlidator - a Validator that checks the value of the corresponding component
against specified minimum and maximum values
LengthValidator - a Validator that checks the number of characters in the String
representation of the value of the associated component.
LongRangeValidator - a Validator that checks the value of the corresponding component
against specified minimum and maximum values.
The package contains an exception, as well.
A ValidatorException is an exception thrown by the validate() method of a Validator to
indicate that validation failed.

12.22 the java.faces.webapp package

Contains classes required for integration of JavaServer Faces into web applications, including a
standard servlet, base classes for JSP custom component tags, and concrete tag implementations for
core tags.

AttributeTag - Tag implementation that adds an attribute with a specified name and String
value to the component whose tag it is nested inside, if the component does not already
contain an attribute with the same name.
ConverterTag - a base class for all JSP custom actions that create and register a
Converter instance on the ValueHolder associated with our most immediate surrounding
instance of a tag whose implementation class is a subclass of UIComponentTag.
FacesServlet - a servlet that manages the request processing lifecycle for web applications
that are utilizing JavaServer Faces to construct the user interface.
FacetTag - the JSP mechanism for denoting a UIComponent is to be added as a facet to

168
12 - javaserver faces

the component associated with its parent.


UIComponentBodyTag - a base class for all JSP custom actions, related to a UIComponent,
that need to process their tag bodies.
UIComponentTag - the base class for all JSP custom actions that correspond to user
interface components in a page that is rendered by JavaServer Faces.
ValidatorTag - 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.

12.23 the JSF lifecycle

Regardless of whether you are using JSF with JSP pages, servlets, or some other web technology,
each request/response flow that involves JSF follows a certain life cycle. Several kinds of
request/response cycles can occur in a JSF-enabled application. 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). Likewise, you can have a JSF response or a non-JSF response. 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, you can also have a non-JSF request that generates a non-JSF response. Because this
does not involve JSF in any way, the JSF life cycle does not apply.
JSP pages have a relatively simple life cycle. A JSP page source is compiled into a page
implementation class. When a web server receives a request, that request is passed to the container,
which passes the request to the page class. The page class processes the request and then writes the
response back to the client. When other pages are included or the request is forwarded, or when an
exception occurs, the process includes a few more components or pages, but basically, a small set of
classes processes a request and sends back a response.
When using JSF, the life cycle is more complicated. This is because the core of JSF is the MVC
pattern, which has several implications. User actions in JSF-generated views take place in a client that
does not have a permanent connection to the server. The delivery of user actions or page events is
delayed until a new connection is established. The JSF life cycle must handle this delay between event
and event processing. Also, the JSF life cycle must ensure that the view is correct before rendering
the view. To ensure that the business state is never invalid, the JSF system includes a phase for
validating inputs and another for updating the model only after all inputs pass validation.
In MVC, the presentation of data (the view) is separate from its representation in the system (the
model). When the model is updated, the controller sends a message to the view, telling the view to
update its presentation. When the user takes some action with the presentation, the controller sends a
message to the model, telling the model to update its data. In JSF, the model is composed of business
objects that are usually implemented as JavaBeans, the controller is the JSF implementation, and the
UI components are the view.
The JSF life cycle has six phases as defined by the JSF specification:
Restore View: In this phase, the JSF implementation restores the objects and data structures that
represent the view of the request. If this is the clients first visit to a page, the JSF implementation
must create the view. When a JSF implementation creates and renders a JSF-enabled page, it
creates UI objects for each view component. The components are stored in a component tree, and the
state of the UI view is saved for subsequent requests. If this is a subsequent request, the saved UI
view is retrieved for the processing of the current request.
Apply Request Values: Any data that was sent as part of the request is passed to the

169
12 - javaserver faces

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

In the above figure, you can see a number of optional paths through the life cycle. For example, if
errors occur during any of the phases, the flow of execution transfers immediately to the Render
Response phase, skipping any remaining phases. One way this might occur is if input data is incorrect
or invalid. 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.
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, the flow of execution can exit the life cycle without completing further phases.

170
13 - WebSocket

13 - WEBSOCKET
13.1 the WebSocket API

WebSocket is an application protocol that provides full-duplex communications between two


peers over the TCP protocol.
The WebSocket protocol was standardized by the IETF as RFC 6455.
In the traditional request-response model used in HTTP, the client requests resources and the
server provides responses. The exchange is always initiated by the client; the server cannot send any
data without the client requesting it first. This model worked well for the World Wide Web when clients
made occasional requests for documents that changed infrequently, but the limitations of this
approach are increasingly relevant as content changes quickly and users expect a more interactive
experience on the web. The WebSocket protocol addresses these limitations by providing a full-duplex
communication channel between the client and the server. Combined with other client technologies,
such as JavaScript and HTML5, WebSocket enables web applications to deliver a richer user
experience. The WebSocket API is defined in JSR-356.

13.2 introduction to WebSocket

In a WebSocket application, the server publishes a WebSocket endpoint and the client uses the
endpoints URI to connect to the server. The WebSocket protocol is symmetrical after the connection
has been established: the client and the server can send messages to each other at any time while the
connection is open, and they can close the connection at any time. Clients usually connect only to one
server, and servers accept connections from multiple clients.
The WebSocket protocol has two parts: handshake and data transfer. The client initiates the
handshake by sending a request to a WebSocket endpoint using its URI. The handshake is
compatible with existing HTTP-based infrastructure: web servers interpret it as an HTTP connection
upgrade request. An example handshake from a client looks like this:

GET /path/to/websocket/endpoint HTTP/1.1


Host: localhost
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: xqBt3ImNzJbYqRINxEFlkg==
Origin: http://localhost
Sec-WebSocket-Version: 13

An example handshake from the server in response to the client looks like this:

HTTP/1.1 101 Switching Protocols


Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: K7DJLdLooIwIG/MOpvWFB3y3FE8=

The server applies a known operation to the value of the Sec-WebSocket-Key header to generate
the value of the Sec-WebSocket-Accept header. The client applies the same operation to the value

171
13 - WebSocket

of the Sec-WebSocket-Key header, and the connection is established successfully if the result
matches the value received from the server. The client and the server can send messages to each
other after a successful handshake.
WebSocket supports text messages (encoded as UTF-8) and binary messages. The control
frames in WebSocket are close, ping, and pong (a response to a ping frame). Ping and pong frames
may also contain application data. WebSocket endpoints are represented by URIs that have the
following form:

ws://host:port/path?query
wss://host:port/path?query

The ws scheme represents an unencrypted WebSocket connection, and the wss scheme
represents an encrypted connection. The port component is optional; the default port number is 80 for
unencrypted connections and 443 for encrypted connections. The path component indicates the
location of an endpoint within a server. The query component is optional.
Modern web browsers implement the WebSocket protocol and provide a JavaScript API to connect
to endpoints, send messages, and assign callback methods for WebSocket events (such as opened
connections, received messages, and closed connections).

13.3 creating WebSocket applications in Java EE

The Java EE platform includes the Java API for WebSocket (JSR-356), which enables you to
create, configure, and deploy WebSocket endpoints in web applications. The WebSocket client API
specified in JSR-356 also enables you to access remote WebSocket endpoints from any Java
application.
The Java API for WebSocket consists of the following packages:
The javax.websocket.server package contains annotations, classes, and interfaces to
create and configure server endpoints.
The javax.websocket package contains annotations, classes, interfaces, and exceptions
that are common to client and server endpoints.
WebSocket endpoints are instances of the javax.websocket.Endpoint class. The Java API for
WebSocket enables you to create two kinds of endpoints: programmatic endpoints and annotated
endpoints. To create a programmatic endpoint, you extend the Endpoint class and override its
lifecycle methods. To create an annotated endpoint, you decorate a Java class and some of its
methods with the annotations provided by the packages above. After you have created an endpoint,
you deploy it to a specific URI in the application so remote clients can connect to it.
The process for creating and deploying a WebSocket endpoint is the following:
1. Create an endpoint class.
2. Implement the lifecycle methods of the endpoint.
3. Add your business logic to the endpoint.
4. Deploy the endpoint inside a web application.
The process is slightly different for programmatic endpoints and annotated endpoints, and it is
covered in detail in the following sections.

13.4 programmatic endpoints

The following example shows how to create an endpoint by extending the Endpoint class:

172
13 - WebSocket

public class EchoEndpoint extends Endpoint {


@Override
public void onOpen(final Session session, EndpointConfig config {
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
}
});
}
}

This endpoint echoes every message received. The Endpoint class defines three lifecycle
methods: onOpen, onClose, and onError. The EchoEndpoint class implements the onOpen
method, which is the only abstract method in the Endpoint class.
The Session parameter represents a conversation between this endpoint and the remote endpoint.
The addMessageHandler method registers message handlers, and the getBasicRemote method
returns an object that represents the remote endpoint. The Session interface is covered in detail in
the rest of this chapter.
The message handler is implemented as an anonymous inner class. The onMessage method of
the message handler is invoked when the endpoint receives a text message.
To deploy this programmatic endpoint, use the following code in your Java EE application:

ServerEndpointConfig.Builder.create(EchoEndpoint.class,
"/echo").build();

When you deploy your application, the endpoint is available at


ws://<host>:<port>/<application>/echo;

for example,
ws://localhost:8080/echoapp/echo.

13.5 annotated endpoints

The following example shows how to create the same endpoint from Programmatic Endpoints using
annotations instead:

@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText(msg);

173
13 - WebSocket

} catch (IOException e) { ... }


}
}

The annotated endpoint is simpler than the equivalent programmatic endpoint, and it is deployed
automatically with the application to the relative path defined in the ServerEndpoint annotation.
Instead of having to create an additional class for the message handler, this example uses the
OnMessage annotation to designate the method invoked to handle messages.
The table below lists the annotations available in the javax.websocket package to designate the
methods that handle lifecycle events. The examples in the table show the most common parameters
for these methods. See the API reference for details on what combinations of parameters are allowed
in each case.

WebSocket Endpoint Lifecycle Annotations

Annotation Event Example

OnOpen Connection opened @OnOpen


public void open(Session session,
EndpointConfig conf) { }
OnMessage Message received @OnMessage
public void message (Session
session, String msg) { }
OnError Connection error @OnError
public void error(Session session,
Throwable error) { }
OnClose Connection closed @OnClose
public void close(Session session,
CloseReason reason) { }

13.6 sending and receiving messages

WebSocket endpoints can send and receive text and binary messages. In addition, they can also
send ping frames and receive pong frames. This section describes how to use the Session and
RemoteEndpoint interfaces to send messages to the connected peer and how to use the
OnMessage annotation to receive messages from it.

13.6.1 Sending Messages


Follow these steps to send messages in an endpoint:
1. Obtain the Session object from the connection.
The Session object is available as a parameter in the annotated lifecycle methods of the
endpoint, like those in the table above. When your message is a response to a message from
the peer, you have the Session object available inside the method that received the message
(the method annotated with @OnMessage). If you have to send messages that are not
responses, store the Session object as an instance variable of the endpoint class in the
method annotated with @OnOpen, so you can access it from other methods.
2. Use the Session object to obtain a RemoteEndpoint object.
The Session.getBasicRemote() method and the Session.getAsyncRemote()

174
13 - WebSocket

method return RemoteEndpoint.Basic and RemoteEndpoint.Async objects


respectively. The RemoteEndpoint.Basic interface provides blocking methods to send
messages; the RemoteEndpoint.Async interface provides non-blocking methods.
3. Use the RemoteEndpoint object to send messages to the peer.
The following list shows some of the methods you can use to send messages to the peer:
void RemoteEndpoint.Basic.sendText(String text)
Send a text message to the peer. This method blocks until the whole message has been
transmitted.
void RemoteEndpoint.Basic.sendBinary(ByteBuffer data)
Send a binary message to the peer. This method blocks until the whole message has
been transmitted.
void RemoteEndpoint.sendPing(ByteBuffer appData)
Send a ping frame to the peer.
void RemoteEndpoint.sendPong(ByteBuffer appData)
Send a pong frame to the peer.
The example in Annotated Endpoints demonstrates how to use this procedure to reply to every
incoming text message.

13.6.2 sending messages to all peers connected to an endpoint


Each instance of an endpoint class is associated with one and only one connection and peer;
however, there are cases when an endpoint instance needs to send messages to all connected peers.
Examples include chat applications and online auctions. The Session interface provides the
getOpenSessions method for this purpose. The following example demonstrates how to use this
method to forward incoming text messages to all connected peers:

@ServerEndpoint("/echoall")
public class EchoAllEndpoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
for (Session sess : session.getOpenSessions()) {
if (sess.isOpen()) sess.getBasicRemote().sendText(msg);
}
} catch (IOException e) { ... }
}
}

13.6.3 receiving messages


The OnMessage annotation designates methods that handle incoming messages. You can have at
most three methods annotated with @OnMessage in an endpoint, one for each message type: text,
binary, and pong. The following example demonstrates how to designate methods to receive all three
types of messages:

@ServerEndpoint("/receive")
public class ReceiveEndpoint {
@OnMessage
public void textMessage(Session session, String msg) {
System.out.println("Text message: " + msg);

175
13 - WebSocket

}
@OnMessage
public void binaryMessage(Session session, ByteBuffer msg) {
System.out.println("Binary message: " + msg.toString());
}
@OnMessage
public void pongMessage(Session session, PongMessage msg) {
System.out.println("Pong message: " +
msg.getApplicationData().toString());
}
}

13.7 using encoders and decoders

The Java API for WebSocket provides support for converting between WebSocket messages and
custom Java types using encoders and decoders. An encoder takes a Java object and produces a
representation that can be transmitted as a WebSocket message; for example, encoders typically
produce JSON, XML, or binary representations. A decoder performs the reverse function: it reads a
WebSocket message and creates a Java object.
This mechanism simplifies WebSocket applications, because it decouples the business logic from
the serialization and deserialization of objects.

13.7.1 encoders to convert java objects into WebSocket messages


The procedure to implement and use encoders in endpoints is the following:
1. Implement one of the following interfaces:
Encoder.Text<T> for text messages
Encoder.Binary<T> for binary messages
These interfaces specify the encode method. Implement an encoder class for each custom Java
type that you want to send as a WebSocket message.
2. Add the names of your encoder implementations to the encoders optional parameter of the
ServerEndpoint annotation.
3. Use the sendObject(Object data) method of the RemoteEndpoint.Basic or
RemoteEndpoint.Async interfaces to send your objects as messages. The container looks
for an encoder that matches your type and uses it to covert the object to a WebSocket
message.
For example, if you have two Java types (MessageA and MessageB) that you want to send as text
messages, implement the Encoder.Text<MessageA> and Encoder.Text<MessageB> interfaces as
follows:

public class MessageATextEncoder implements Encoder.Text<MessageA> {


@Override
public void init(EndpointConfig ec) { }
@Override
public void destroy() { }
@Override
public String encode(MessageA msgA) throws EncodeException {
// Access msgAs properties and convert to JSON text...
return msgAJsonString;

176
13 - WebSocket

}
}

And similarly for Encoder.Text<MessageB>. Then, add the encoders parameter to the
ServerEndpoint annotation as follows:

@ServerEndpoint(
value = "/myendpoint",
encoders = { MessageATextEncoder.class, MessageBTextEncoder.class }
)
public class EncEndpoint { ... }

Now you can send MessageA and MessageB objects as WebSocket messages using the
sendObject method as follows:

MessageA msgA = new MessageA(...);


MessageB msgB = new MessageB(...);
session.getBasicRemote.sendObject(msgA);
session.getBasicRemote.sendObject(msgB);

As in this example, you can have more than one encoder for text messages and more than one
encoder for binary messages. Like endpoints, encoder instances are associated with one and only one
WebSocket connection and peer, so there is only one thread executing the code of an encoder
instance at any given time.

13.7.2 decoders to convert WebSocket messages into java objects


The procedure to implement and use decoders in endpoints is the following:
1. Implement one of the following interfaces:
Decoder.Text<T> for text messages
Decoder.Binary<T> for binary messages
These interfaces specify the willDecode and decode methods.
2. Add the names of your decoder implementations to the decoders optional parameter of the
ServerEndpoint annotation.
3. Use the OnMessage annotation in the endpoint to designate a method that takes your custom
Java type as a parameter. When the endpoint receives a message that can be decoded by
one of the decoders you specified, the container calls the method annotated with
@OnMessage that takes your custom Java type as a parameter if this method exists.
For example; if you have two Java types (MessageA and MessageB) that you want to send and
receive as text messages, define them so that they extend a common class (Message). Since you can
only define one decoder for text messages, implement a decoder for the Message class as follows:

public class MessageTextDecoder implements Decoder.Text<Message> {


@Override
public void init(EndpointConfig ec) { }
@Override
public void destroy() { }
@Override
public Message decode(String string) throws DecodeException {
// Read message...

177
13 - WebSocket

if ( /* message is an A message */ )
return new MessageA(...);
else if ( /* message is a B message */ )
return new MessageB(...);
}
@Override
public boolean willDecode(String string) {
// Determine if the message can be converted into either a
// MessageA object or a MessageB object...
return canDecode;
}
}

Then, add the decoder parameter to the ServerEndpoint annotation as follows:

@ServerEndpoint(
value = "/myendpoint",
encoders = { MessageATextEncoder.class, MessageBTextEncoder.class },
decoders = { MessageTextDecoder.class }
)
public class EncDecEndpoint { ... }

Now define a method in the endpoint class that receives MessageA and MessageB objects as
follows:

@OnMessage
public void message(Session session, Message msg) {
if (msg instanceof MessageA) {
// We received a MessageA object...
else if (msg instanceof MessageB) {
// We received a MessageB object...
}
}

Like endpoints, decoder instances are associated with one and only one WebSocket connection
and peer, so there is only one thread executing the code of a decoder instance at any given time.

13.8 The dukeetf2 Example Application

The dukeetf2 example application, located in the tut-install/examples/web/dukeetf2/


directory, demonstrates how to use a WebSocket endpoint to provide data updates to web clients. The
example resembles a service that provides periodic updates on the price and trading volume of an
electronically traded fund (ETF).

13.8.1 Architecture of the dukeetf2 Sample Application


The dukeetf2 example application consists of a WebSocket endpoint, an enterprise

178
13 - WebSocket

bean, and an HTML page:


The endpoint accepts connections from clients and sends them updates when new data for
price and trading volume becomes available.
The enterprise bean updates the price and volume information once every second.
The HTML page uses JavaScript code to connect to the WebSocket endpoint, parse incoming
messages, and update price and volume information without reloading the page.

13.8.1.1 the endpoint


The WebSocket endpoint is implemented in the ETFEndpoint class, which stores all connected
sessions in a queue and provides a method that the enterprise bean calls when there is new
information available to send:

@ServerEndpoint("/dukeetf")
public class ETFEndpoint {
private static final Logger logger = Logger.getLogger("ETFEndpoint");

/* Queue for all open WebSocket sessions */


static Queue<Session> queue = new ConcurrentLinkedQueue<>();
/* PriceVolumeBean calls this method to send updates */
public static void send(double price, int volume) {
String msg = String.format("%.2f, %d", price, volume);
try {
/* Send updates to all open WebSocket sessions */
for (Session session : queue) {
session.getBasicRemote().sendText(msg);
logger.log(Level.INFO, "Sent: {0}", msg);
}
} catch (IOException e) {
logger.log(Level.INFO, e.toString());
}
}
}

The lifecycle methods of the endpoint add and remove sessions to and from the queue:

@ServerEndpoint("/dukeetf")
public class ETFEndpoint {
...
@OnOpen
public void openConnection(Session session) {
/* Register this connection in the queue */
queue.add(session);
logger.log(Level.INFO, "Connection opened.");
}
@OnClose
public void closedConnection(Session session) {
/* Remove this connection from the queue */
queue.remove(session);

179
13 - WebSocket

}
@OnError
public void error(Session session, Throwable t) {
/* Remove this connection from the queue */
queue.remove(session);
logger.log(Level.INFO, "Connection error.");
}
}

13.8.1.2 the enterprise bean


The enterprise bean uses the timer service to generate new price and volume information every
second:

@Startup
@Singleton
public class PriceVolumeBean {
/* Use the container's timer service */
@Resource TimerService tservice;
private Random random;
private volatile double price = 100.0;
private volatile int volume = 300000;
private static final Logger logger =
Logger.getLogger("PriceVolumeBean");

@PostConstruct
public void init() {
/* Intialize the EJB and create a timer */
logger.log(Level.INFO, "Initializing EJB.");
random = new Random();
tservice.createIntervalTimer(1000, 1000, new TimerConfig());
}
@Timeout
public void timeout() {
/* Adjust price and volume and send updates */
price += 1.0*(random.nextInt(100)-50)/100.0;
volume += random.nextInt(5000) - 2500;
ETFEndpoint.send(price, volume);
}
}

The enterprise bean calls the send method of the ETFEndpoint class in the timeout method.

13.8.1.3 the HTML page


The HTML page consists of a table and some JavaScript code. The table contains two fields
referenced from JavaScript code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>...</head>

180
13 - WebSocket

<body onload="makeAjaxRequest();">
<table>
...
<td id="price">--.--</td>
...
<td id="volume">--</td>
...
</table>
</body>
</html>

The JavaScript code uses the WebSocket API to connect to the server endpoint and to designate a
callback method for incoming messages. The callback method updates the page with the new
information.

var wsocket;
function connect() {
wsocket = new WebSocket("ws://localhost:8080/dukeetf2/dukeetf");
wsocket.onmessage = onMessage;
}
function onMessage(evt) {
var arraypv = evt.data.split(",");
document.getElementById("price").innerHTML = arraypv[0];
document.getElementById("volume").innerHTML = arraypv[1];
}
window.addEventListener("load", connect, false);

The WebSocket API is supported by most modern browsers, and it is widely used in HTML5 web
client development.

13.8.2 running the dukeetf2 example application using NetBeans IDE

1. From the File menu, select Open Project.


2. In the Open Project dialog box, navigate to: tut-install/examples/web/websocket
3. Select the dukeetf2 folder.
4. Click Open Project.
5. In the Projects tab, right-click the dukeetf2 project and select Run.
This command builds and packages the application into a WAR file (dukeetf2.war) located in the
target/ directory, deploys it to the server, and launches a web browser window with the following URL:
http://localhost:8080/dukeetf2/

Open the same URL on a different web browser tab or window to see how both pages get price and
volume updates simultaneously.

181
14 - JSON processing

14 - JSON PROCESSING
14.1 JSON

JSON is a text-based data exchange format derived from JavaScript that is used in web services
and other connected applications. The following sections provide an introduction to JSON syntax, an
overview of JSON uses, and a description of the most common approaches to generate and parse
JSON.

14.1.1 JSON Syntax


JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs,
and an array is a list of values. JSON defines six data types: string, number, object, array, true, false and
null.
The following example shows JSON data for a sample object that contains name-value pairs. The
value for the name is an array whose elements are two objects.

{
"firstName": "Duke",
"lastName": "Java",
"age": 18,
"streetAddress": "100 Internet Dr",
"city": "JavaTown",
"state": "JA",
"postalCode": "12345",
"phoneNumbers": [
{ "Mobile": "111-111-1111" },
{ "Home": "222-222-2222" }
]
}

JSON has the following syntax:


Objects are enclosed in braces ({}), their name-value pairs are separated by a comma (,), and
the name and value in a pair are separated by a colon (:). Names in an object are strings,
whereas values may be of any of the six data types, including another object or an array.
Arrays are enclosed in brackets ([]), and their values are separated by a coma (,). Each value
in an array may be of a different type, including another array or an object.
When objects and arrays contain other objects or arrays, the data has a tree-like structure.

14.1.2 Uses of JSON


JSON is often used as a common format to serialize and de-serialize data in applications that
communicate with each other over the Internet. These applications are created using different
programming languages and run in very different environments. JSON is suited to this scenario
because it is an open standard, it is easy to read and write, and it is more compact than other
representations.
RESTful web services use JSON extensively as the format for the data inside requests and
responses. The HTTP header used to indicate that the content of a request or a response is JSON
data is the following:

182
14 - JSON processing

Content-Type: application/json

JSON representations are usually more compact than XML representations because JSON does
not have closing tags. Unlike XML, JSON does not have a widely accepted schema for defining and
validating the structure of JSON data.

14.1.3 Generating and Parsing JSON Data

There are two programming models for generating and parsing JSON data: the object model and
the streaming model, which are similar to those used for XML documents.
The object model creates a tree that represents the JSON data in memory. The tree can then be
navigated, analyzed, or modified. This approach is the most flexible and allows for processing that
requires access to the complete contents of the tree. However, it is often slower than the streaming
model and requires more memory. The object model generates JSON output by navigating the entire
tree at once.
The streaming model uses an event-based parser that reads JSON data one element at a time. The
parser generates events and stops for processing when an object or an array begins or ends, when it
finds a key, or when it finds a value. Each element can be processed or discarded by the application
code, then the parser proceeds to the next event. This approach is adequate for local processing,
where the processing of an element does not require information from the rest of the data. The
streaming model generates JSON output to a given stream by making a function call with one element
at a time.
There are many JSON generators and parsers available for different programming languages and
environments. JSON Processing in Java EE describes the functionality provided by the Java API for
JSON Processing (JSR-353).

14.2 JSON Processing in Java EE

Java EE includes support for JSR-353, which provides an API to parse, transform, and query JSON
data using the object model or the streaming model described in Generating and Parsing JSON Data.
The Java API for JSON Processing contains the following packages:
The javax.json package contains a reader interface, a writer interface, and a model builder
interface for the object model. This package also contains other utility classes and Java types
for JSON elements.
The javax.json.stream package contains a parser interface and a generator interface for the
streaming model.

Table 141 Main classes and interfaces in javax.json

Class or Interface Description

Contains static methods to create instances of JSON parsers,


builders, generators. This class also contains methods to create
parser, builder, and generator factory objects.

Reads JSON data from a stream and creates an object model in


memory.

Create an object model or an array model in memory by adding


elements from application code.

183
14 - JSON processing

Writes an object model from memory to a stream.

Represent data types for elements in JSON data.

, , , and
are subtypes of .

and are subtypes of


.

Indicates that a problem occurred during JSON processing.

Table 142 Main classes and interfaces in javax.json.stream

Class or Interface Description

Represents an event-based parser that can read JSON data from


a stream or from an object model.

Writes JSON data to a stream one element at a time.

14.3 Using the Object Model API

This section describes four use cases of the object model API: creating an object model from JSON
data, creating an object model from application code, navigating an object model, and writing an object
model to a stream.

14.3.1 Creating an Object Model from JSON Data


The following code demonstrates how to create an object model from JSON data in a text file:

import java.io.FileReader;
import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonStructure;
...
JsonReader reader = Json.createReader(new FileReader("jsondata.txt"));
JsonStructure jsonst = reader.read();

The object reference jsonst can either be of type JsonObject or JsonArray depending on the
contents of the file. JsonObject and JsonArray are subtypes of JsonStructure. This reference
represents the top of the tree and can be used to navigate the tree or to write it to a stream as JSON
data.

184
14 - JSON processing

14.3.2 Creating an Object Model from Application Code


The following code demonstrates how to create an object model from application code:

import javax.json.Json;
import javax.json.JsonObject;
...
JsonObject model = Json.createObjectBuilder()
.add("firstName", "Duke")
.add("lastName", "Java")
.add("age", 18)
.add("streetAddress", "100 Internet Dr")
.add("city", "JavaTown")
.add("state", "JA")
.add("postalCode", "12345")
.add("phoneNumbers", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "mobile")
.add("number", "111-111-1111"))
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "222-222-2222")))
.build();

The object reference represents the top of the tree, which is created by nesting calls to the
methods and built by calling the method. The class contains the
following methods:

JsonObjectBuilder add(String name, BigDecimal value)


JsonObjectBuilder add(String name, BigInteger value)
JsonObjectBuilder add(String name, boolean value)
JsonObjectBuilder add(String name, double value)
JsonObjectBuilder add(String name, int value)
JsonObjectBuilder add(String name, JsonArrayBuilder builder)
JsonObjectBuilder add(String name, JsonObjectBuilder builder)
JsonObjectBuilder add(String name, JsonValue value)
JsonObjectBuilder add(String name, long value)
JsonObjectBuilder add(String name, String value)
JsonObjectBuilder addNull(String name)

The class contains similar methods that do not have a name (key)
parameter. You can nest arrays and objects by passing a new object or a new
object to the corresponding method as shown in this example.
The resulting tree represents the JSON data from JSON Syntax.

14.3.3 Navigating an Object Model


The following code demonstrates a simple approach to navigating an object model:

185
14 - JSON processing

import javax.json.JsonValue;
import javax.json.JsonObject;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonString;
...
public static void navigateTree(JsonValue tree, String key) {
if (key != null)
System.out.print("Key " + key + ": ");
switch(tree.getValueType()) {
case OBJECT:
System.out.println("OBJECT");
JsonObject object = (JsonObject) tree;
for (String name : object.keySet())
navigateTree(object.get(name), name);
break;
case ARRAY:
System.out.println("ARRAY");
JsonArray array = (JsonArray) tree;
for (JsonValue val : array)
navigateTree(val, null);
break;
case STRING:
JsonString st = (JsonString) tree;
System.out.println("STRING " + st.getString());
break;
case NUMBER:
JsonNumber num = (JsonNumber) tree;
System.out.println("NUMBER " + num.toString());
break;
case TRUE:
case FALSE:
case NULL:
System.out.println(tree.getValueType().toString());
break;
}
}

The method can be used with the models built in Creating an Object Model
from JSON Data and Creating an Object Model from Application Code as follows:

navigateTree(model, null);

The navigateTree() method takes two arguments: a JSON element and a key. The key is only
used to help print the key-value pairs inside objects. Elements in a tree are represented by the
JsonValue type. If the element is an object or an array, a new call to this method is made for every
element contained in the object or array. If the element is a value, it is printed to the standard output.
The JsonValue.getValueType() method identifies the element as an object, an array, or a

186
14 - JSON processing

value. For objects, the JsonObject.keySet() method returns a set of strings that contains the keys
in the object, and the JsonObject.get(String name) method returns the value of the element
whose key is name. For arrays, JsonArray implements the List<JsonValue> interface. You can
use enhanced for loops with the Set<String> instance returned by JsonObject.keySet() and
with instances of JsonArray as shown in this example.
The output of the navigateTree method for the model built in Creating an Object Model from
Application Code is the following:

OBJECT
Key firstName: STRING Duke
Key lastName: STRING Java
Key age: NUMBER 18
Key streetAddress: STRING 100 Internet Dr
Key city: STRING JavaTown
Key state: STRING JA
Key postalCode: STRING 12345
Key phoneNumbers: ARRAY
OBJECT
Key type: STRING mobile
Key number: STRING 111-111-1111
OBJECT
Key type: STRING home
Key number: STRING 222-222-2222

14.3.4 Writing an Object Model to a Stream


The object models created in Creating an Object Model from JSON Data and Creating an Object
Model from Application Code can be written to a stream using the class as follows:

import java.io.StringWriter;
import javax.json.JsonWriter;
...
StringWriter stWriter = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(stWriter);
jsonWriter.writeObject(model);
jsonWriter.close();
String jsonData = stWriter.toString();
System.out.println(jsonData);

The method takes an output stream as a parameter. The


method writes the object to the stream. The
method closes the underlying output stream.
The following example uses to close the JSON writer automatically:

StringWriter stWriter = new StringWriter();


try (JsonWriter jsonWriter = Json.createWriter(stWriter)) {
jsonWriter.writeObject(model);
}
String jsonData = stWriter.toString();

187
14 - JSON processing

System.out.println(jsonData);

14.4 Using the Streaming API

This section describes two use cases of the streaming API: reading JSON data using a parser and
writing JSON data using a generator.

14.4.1 Reading JSON Data Using a Parser


The streaming API is the most efficient approach for parsing JSON text. The following code
demonstrates how to create a object and how to parse JSON data using events:

import javax.json.Json;
import javax.json.stream.JsonParser;
...
JsonParser parser = Json.createParser(new StringReader(jsonData));
while (parser.hasNext()) {
JsonParser.Event event = parser.next();
switch(event) {
case START_ARRAY:
case END_ARRAY:
case START_OBJECT:
case END_OBJECT:
case VALUE_FALSE:
case VALUE_NULL:
case VALUE_TRUE:
System.out.println(event.toString());
break;
case KEY_NAME:
System.out.print(event.toString() + " " +
parser.getString() + " - ");
break;
case VALUE_STRING:
case VALUE_NUMBER:
System.out.println(event.toString() + " " +
parser.getString());
break;
}
}

This example consists of three steps:


1. Obtain a parser instance by calling the static method.
2. Iterate over the parser events with the and the
methods.
3. Perform local processing for each element.
The example shows the ten possible event types from the parser. The parser's method
advances it to the next event. For the event types , , and ,

188
14 - JSON processing

you can obtain the content of the element by calling the method . For
events, you can also use the methods ,
, , and
. See the JSR-353 API reference for more information.
The output of this example is the following:

START_OBJECT
KEY_NAME firstName - VALUE_STRING Duke
KEY_NAME lastName - VALUE_STRING Java
KEY_NAME age - VALUE_NUMBER 18
KEY_NAME streetAddress - VALUE_STRING 100 Internet Dr
KEY_NAME city - VALUE_STRING JavaTown
KEY_NAME state - VALUE_STRING JA
KEY_NAME postalCode - VALUE_STRING 12345
KEY_NAME phoneNumbers - START_ARRAY
START_OBJECT
KEY_NAME type - VALUE_STRING mobile
KEY_NAME number - VALUE_STRING 111-111-1111
END_OBJECT
START_OBJECT
KEY_NAME type - VALUE_STRING home
KEY_NAME number - VALUE_STRING 222-222-2222
END_OBJECT
END_ARRAY
END_OBJECT

14.4.2 Writing JSON Data Using a Generator


The following code demonstrates how to write JSON data to a file using the streaming API:

FileWriter writer = new FileWriter("test.txt");


JsonGenerator gen = Json.createGenerator(writer);
gen.writeStartObject()
.write("firstName", "Duke")
.write("lastName", "Java")
.write("age", 18)
.write("streetAddress", "100 Internet Dr")
.write("city", "JavaTown")
.write("state", "JA")
.write("postalCode", "12345")
.writeStartArray("phoneNumbers")
.writeStartObject()
.write("type", "mobile")
.write("number", "111-111-1111")
.writeEnd()
.writeStartObject()
.write("type", "home")
.write("number", "222-222-2222")

189
14 - JSON processing

.writeEnd()
.writeEnd()
.writeEnd();
gen.close();

This example obtains a JSON generator by calling the static method,


which takes a writer or an output stream as a parameter. The example writes JSON data to the
file by nesting calls to the , , , and
methods. The method closes the underlying writer or output
stream.

14.5 JSON in Java EE RESTful Web Services

This section explains how the Java API for JSON Processing is related to other Java EE packages
that provide JSON support for RESTful web services.
Jersey, the reference implementation for JAX-RS (JSR-311) (java API for RESTful Services)
included in GlassFish Server, provides support for binding JSON data from RESTful resource
methods to Java objects using JAXB (Java Architecture for XML Binding), as described in Using JAX-
RS With JAXB, "JAX-RS: Advanced Topics and Example". However, JSON support is not part of JAX-
RS (JSR-311) or JAX-B (JSR-222), so that procedure may not work for Java EE implementations
other than GlassFish Server.
The Java API for JSON Processing (JSR-353) does not explicitly support JSON binding in Java. A
future JSR (JSON Binding) that is similar to JAXB for XML is under consideration for a future release
of Java EE.
You can still use the Java API for JSON Processing with JAX-RS resource methods. For more
information, see the sample code for JSON Processing included with the Java EE 7 SDK.

14.6 The jsonpmodel Example Application

This section describes how to build and run the example application. This example is
a web application that demonstrates how to create an object model from form data, how to parse
JSON data, and how write JSON data using the object model API.
The example application is in the tut-install
directory.

14.6.1 Components of the jsonpmodel Example Application


The example application contains the following files:
1. Three Java Server Faces pages:
The page contains a form to collect information.
The page contains a text area that displays JSON data.
The page contains a table that shows the elements of the object
model.
2. The managed bean, which is a session bean that stores the data
from the form and directs the navigation between the JSF pages. This file also contains code
that uses the JSON object model API.
The code used in to create an object model from the data in the form is
similar to the example in Creating an Object Model from Application Code. The code to write JSON

190
14 - JSON processing

output from the model is similar to the example in Writing an Object Model to a Stream. The code to
navigate the object model tree is similar to the example in Navigating an Object Model.

14.6.2 Running the jsonpmodel Example Application


This section describes how to run the example application using NetBeans IDE.
1. From the File menu, select Open Project.
2. In the Open Project dialog box, navigate to: tut-install
3. Select the folder.
4. Click Open Project.
5. In the Projects tab, right-click the project and select Run.
This command builds and packages the application into a WAR file ( ) located in
the directory, deploys it to the server, and opens a web browser window with the following
URL:

http://localhost:8080/jsonpmodel/faces/index.xhtml

14.7 the jsonpstreaming Example Application

This section describes how to build and run the example application. This
example is a web application that demonstrates how to create JSON data from form data, how to
parse JSON data, and how write JSON output using the streaming API.
The example application is in the tut-
install directory.

14.7.1 Components of the jsonpstreaming Example Application


The example application contains the following files:
1. Three Java Server Faces pages:
The page contains a form to collect information.
The page contains a text area that displays JSON data.
The page contains a table that lists the events from the parser.
2. The managed bean, which is a session bean that manages the data
from the form and the navigation between the JSF pages. This file also contains code that
uses the JSON streaming API.
The code used in to write JSON data to a file is similar to the example in
Writing JSON Data Using a Generator. The code to parse JSON data from a file is similar to the
example in Reading JSON Data Using a Parser.

14.7.2 Running the jsonpstreaming Example Application


This section describes how to run the example application using NetBeans IDE.

1. From the File menu, select Open Project.


2. In the Open Project dialog box, navigate to: tut-install
3. Select the folder.
4. Click Open Project.

191
14 - JSON processing

5. In the Projects tab, right-click the project and select Run.


This command builds and packages the application into a WAR file ( )
located in the directory, deploys it to the server, and opens a web browser window with the
following URL:

http://localhost:8080/jsonpstreaming/faces/index.xhtml

192
15 - JNDI

15 - JNDI
15.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. It is designed especially for the Java platform
using Java's object model. Using JNDI, applications based on Java technology can store and retrieve
named Java objects of any type. In addition, JNDI provides methods for performing standard directory
operations, such as associating attributes with objects and searching for objects using their attributes.
JNDI has been part of Java2EE starting with version 1.2 of Java EE.
JNDI is also defined independent of any specific naming or directory service implementation. It
enables applications to access different, possibly multiple, naming and directory services using a
common API. Different naming and directory service providers can be plugged in seamlessly behind
this common API. This enables Java technology-based applications to take advantage of information
in a variety of existing naming and directory services, such as LDAP, NDS, DNS, and NIS(YP)
(Network Information Service), as well as enabling the applications to coexist with legacy software and
systems.

15.2 naming concepts

A fundamental facility in any computing system is the naming service -the means by which names
are associated with objects and objects are found based on their names. When using almost any
computer program or system, you are always naming one object or another. For example, when you
use an electronic mail system, you must provide the name of the recipient to whom you want to send
mail. To access a file in the computer, you must supply its name. A naming service allows you to look
up an object given its name.
A naming service's primary function is to map people-friendly names to objects, such as
addresses, identifiers, or objects typically used by computer programs. For example, the Internet
Domain Name System (DNS) maps machine names (such as www.sun.com) to IP addresses (such
as 192.9.48.5). A file system maps a filename (for example, c:\bin\autoexec.bat) to a file
handle that a program can use to access the contents of the file. 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.

15.2.1 names
To look up an object in a naming system, you supply it the name of the object. The naming system
determines the syntax that the name must follow. This syntax is sometimes called the naming
system's naming convention.
For example, the UNIXTM file system's naming convention is that a file is named from its path
relative to the root of the file system, with each component in the path separated from left to right using
the forward slash character ("/"). The UNIX pathname, /usr/hello, for example, names a file
hello in the file directory usr, which is located in the root of the file system.
The DNS naming convention calls for components in the DNS name to be ordered from right to left
and delimited by the dot character ("."). Thus the DNS name sales.Wiz.COM names a DNS entry
with the name sales, relative to the DNS entry Wiz.COM. The DNS entry Wiz.COM, in turn, names an
entry with the name Wiz in the COM entry.

193
15 - JNDI

The Lightweight Directory Access Protocol (LDAP) naming convention orders components from
right to left, delimited by the comma character (","). Thus the LDAP name cn=Rosanna Lee,
o=Sun, c=US names an LDAP entry cn=Rosanna Lee, relative to the entry o=Sun, which in turn, is
relative to c=us. 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 ("=").

15.2.2 bindings
The association of a name with an object is called a binding. For example, a file name is bound to
a file.
The DNS contains bindings that map machine names to IP addresses. An LDAP name is bound to
an LDAP entry.

15.2.3 references and addresses


Depending on the naming service, some objects cannot be stored directly; that is, a copy of the
object cannot be placed inside the naming service. Instead, they must be stored by reference - a
pointer or reference to the object is placed inside the naming service. A reference is information about
how to access an object. Typically, it is a much more compact representation that can be used to
communicate with the object, while the object itself might contain more state information. Using the
reference, you can contact the object and obtain more information about the object.
For example, an airplane object might contain a list of the airplane's passengers and crew, its flight
plan, and fuel and instrument status, and its flight number and departure time. By contrast, an airplane
object reference might contain only its flight number and departure time. The reference is a much
more compact representation of information about the airplane object and can be used to obtain
additional information. A file object, for example, is accessed using a file reference, also called a file
handle. A printer object, for example, might contain the state of the printer, such as its current queue
and the amount of paper in the paper tray. A printer object reference, on the other hand, might contain
only information on how to reach the printer, such as its print server name and printing protocol.
Although in general a reference can contain any arbitrary information, it is useful to refer to its
contents as addresses (or communication end points): specific information about how to access the
object.
For simplicity, this tutorial uses "object" to refer to both objects and object references when a
distinction between the two is not required.

15.2.4 context
A context is a set of name-to-object bindings. Every context has an associated naming convention.
A context provides a lookup (resolution) operation that returns the object and may provide operations
such as those for binding names, unbinding names, and listing bound names. A name in one context
object can be bound to another context object (called a subcontext) that has the same naming
convention.
For example, a file directory, such as /usr, in the UNIX file system is a context. A file directory
named relative to another file directory is a subcontext (some UNIX users refer to this as a
subdirectory). That is, in a file directory /usr/bin, the directory bin is a subcontext of usr. In
another example, a DNS domain, such as COM, is a context. A DNS domain named relative to another
DNS domain is a subcontext. For example, in the DNS domain Sun.COM, the DNS domain Sun is a
subcontext of COM.
Finally, an LDAP entry, such as c=us, is a context. An LDAP entry named relative to another LDAP
entry is a subcontext. For example, in the an LDAP entry o=sun,c=us, the entry o=sun is a
subcontext of c=us.
If we imagine all the resources available for us as a collection of rooted trees, one context can be
viewed, in a first and raw approximation as a node in one of these trees. And it kind of makes sense,

194
15 - JNDI

because we can, to some extent, identify a web application with its root directory (a node in the file
system directory tree).

15.2.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.
For example, a system that implements the DNS is a naming system. A system that communicates
using the LDAP is a naming system.
A naming system provides a naming service to its customers for performing naming-related
operations. A naming service is accessed through its own interface. For example, the DNS offers a
naming service that maps machine names to IP addresses. The LDAP offers a naming service that
maps LDAP names to LDAP entries. A file system offers a naming service that maps filenames to files
and directories.
A namespace is the set of names in a naming system. For example, the UNIX file system has a
namespace consisting of all of the names of files and directories in that file system. The DNS
namespace contains names of DNS domains and entries. The LDAP namespace contains names of
LDAP entries.

15.3 directory services

Many naming services are extended with a directory service. A directory service associates
names with objects and also allows such objects to have attributes. Thus, 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.
An example is the telephone company's directory service. It maps a subscriber's name to his
address and phone number. A computer's directory service is very much like a telephone company's
directory service in that both can be used to store information such as telephone numbers and
addresses. The computer's directory service is much more powerful, however, because it is available
online and can be used to store a variety of information that can be utilized by users, programs, and
even the computer itself and other computers.
A directory object represents an object in a computing environment. A directory object can be
used, for example, to represent a printer, a person, a computer, or a network. A directory object
contains attributes that describe the object that it represents.

15.3.1 attributes
A directory object can have attributes. For example, a printer might be represented by a directory
object that has as attributes its speed, resolution, and color. A user might be represented by a
directory object that has as attributes the user's e-mail address, various telephone numbers, postal
mail address, and computer account information.
An attribute has an attribute identifier and a set of attribute values. An attribute identifier is a token
that identifies an attribute independent of its values. For example, two different computer accounts
might have a "mail" attribute; "mail" is the attribute identifier. An attribute value is the contents of
the attribute. The email address, for example, might have an attribute identifier of "mail" and the
attribute value of "john.smith@somewhere.com".

15.3.2 directories and directory services


A directory is a connected set of directory objects. A directory service is a service that provides
operations for creating, adding, removing, and modifying the attributes associated with objects in a
directory. The service is accessed through its own interface.

195
15 - JNDI

Many examples of directory services are possible. The Novell Directory Service (NDS) is a directory
service from Novell that provides information about many networking services, such as the file and
print services. Network Information Service (NIS) is a directory service available on the Solaris
operating system for storing system-related information, such as that relating to machines, networks,
printers, and users. The SunONE Directory Server is a general-purpose directory service based on the
Internet standard LDAP.

15.3.3 searches and search filters


You can look up a directory object by supplying its name to the directory service. Alternatively, many
directories, such as those based on the LDAP, support the notion of searches. When you search, you
can supply not a name but a query consisting of a logical expression in which you specify the attributes
that the object or objects must have. The query is called a search filter. This style of searching is
sometimes called reverse lookup or content-based searching. The directory service searches for and
returns the objects that satisfy the search filter.
For example, you can query the directory service to find all users that have the attribute "age"
greater than 40 years. Similarly, you can query it to find all machines whose IP address starts with
"192.113.50".

15.3.4 combining naming and directory services


Directories often arrange their objects in a hierarchy. For example, the LDAP arranges all directory
objects in a tree, called a directory information tree (DIT). Within the DIT, an organization object, for
example, might contain group objects that might in turn contain person objects. When directory
objects are arranged in this way, they play the role of naming contexts in addition to that of containers
of attributes.

15.4 directory-enabled java applications

Directory service is a vital component of network computing. By using a directory service, you can
simplify applications and their administration by centralizing the storage of shared information. As the
use of the Java programming language to write practical applications in a network environment
increases, the ability to access directory services will become essential.

15.4.1 traditional use of the directory


A directory-enabled application is an application that uses a naming or directory service. Directory-
enabled Java applications and applets, like any other program running on the network, can use the
directory in the traditional way, that is, to store and retrieve attributes of directory objects. A Java mail
client program, for example, can use the directory as an address book for retrieving the addresses of
mail recipients. A Java mail transfer agent program can use it to retrieve mail routing information. And
a Java calendar program can use it to retrieve user preference settings.
Applications can share the common infrastructure provided by the directory. This sharing makes
applications that are deployed across the system, and even the network, more coherent and
manageable. For example, printer configuration and mail routing information can be stored in the
directory so that it can be replicated and distributed for use by all related applications and services.

15.4.2 the directory as an object store


In addition to using the directory in the traditional way, Java applications can also use it as a
repository for Java objects, that is to store and retrieve Java objects. For example, 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.

196
15 - JNDI

15.5 the JNDI API

The Java Naming and Directory Interface (JNDI) is an application programming interface (API) that
provides naming and directory functionality to applications written using the Java programming
language. It is defined to be independent of any specific directory service implementation. Thus a
variety of directories--new, emerging, and already deployed--can be accessed in a common way.

15.5.1 architecture
The JNDI architecture consists of an API and a service provider interface (SPI). Java applications
use the JNDI API to access a variety of naming and directory services. The SPI enables a variety of
naming and directory services to be plugged in transparently, thereby allowing the Java application
using the JNDI API to access their services.

15.5.2 packaging
The JNDI is included in the Java 2 SDK, v1.3 and later releases. It extends the v1.1 and v1.2
platforms to provide naming and directory functionality.
To use the JNDI, you must have the JNDI classes and one or more service providers. The Java 2
SDK, v1.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.
When using the JNDI as a Standard Extension on the JDK 1.1 and Java 2 SDK, v1.2, you must first
download the JNDI classes and one or more service providers.
The JNDI is divided into five packages:
javax.naming
javax.naming.directory
javax.naming.event
javax.naming.ldap
javax.naming.spi

15.6 the naming package

The javax.naming package contains classes and interfaces for accessing naming services.

15.6.1 context
The javax.naming package defines a Context interface, which is the core interface for looking
up, binding/unbinding, renaming objects and creating and destroying subcontexts.
The most commonly used operation is lookup(). You supply lookup() the name of the object
you want to look up, and it returns the object bound to that name. For example, the following code
fragment looks up a printer and sends a document to the printer object to be printed.

Printer printer = (Printer)ctx.lookup("treekiller");

197
15 - JNDI

printer.print(report);

15.6.2 names
Every naming method in the Context interface has two overloads: one that accepts a Name
argument and one that accepts a java.lang.String name. Name is an interface that represents a
generic name-an ordered sequence of zero or more components. For the methods in the Context
interface, a Name argument that is an instance of CompositeName represents a composite name, so
you can name an object using a name that spans multiple namespaces. A Name argument of any
other type represents a compound name. The overloads that accept Name are useful for applications
that need to manipulate names, that is, composing them, comparing components, and so on.
A java.lang.String name argument represents a composite name. The overloads that accept
java.lang.String names are likely to be more useful for simple applications, such as those that
simply read in a name and look up the corresponding object.

15.6.3 bindings
listBindings() returns an enumeration of name-to-object bindings. Each binding is represented
by an instance of the Binding class. A binding is a tuple containing the name of the bound object, the
name of the object's class, and the object itself.
list() is similar to listBindings(), except that it returns an enumeration of NameClassPair.
NameClassPair contains an object's name and the name of the object's class. 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. Although listBindings() provides all of the
same information, it is potentially a much more expensive operation.

15.6.4 references
Objects are stored in naming and directory services in different ways. A service that supports storing
Java objects might support storing an object in its serialized form. However, some naming and
directory services do not support the storing of Java objects. Furthermore, for some objects in the
directory, Java programs are but one group of applications that access them. In this case, a serialized
Java object might not be the most appropriate representation. A reference might be a very compact
representation of an object, whereas its serialized form might contain a lot more state.
The JNDI defines the Reference class to represent a reference. A reference contains information
on how to construct a copy of the object. The JNDI will attempt to turn references looked up from the
directory into the Java objects that they represent so that JNDI clients have the illusion that what is
stored in the directory are Java objects.

15.6.5 the Initial context


In the JNDI, all naming and directory operations are performed relative to a context. There are no
absolute roots. Therefore the JNDI defines an initial context, InitialContext, which provides a
starting point for naming and directory operations. Once you have an initial context, you can use it to
look up other contexts and objects.

15.6.6 exceptions
The JNDI defines a class hierarchy for exceptions that can be thrown in the course of performing
naming and directory operations. The root of this class hierarchy is NamingException. Programs
interested in dealing with a particular exception can catch the corresponding subclass of the
exception. Otherwise, they should catch NamingException.

198
15 - JNDI

15.7 directory package

The javax.naming.directory package extends the javax.naming package to provide


functionality for accessing directory services in addition to naming services. This package allows
applications to retrieve attributes associated with objects stored in the directory and to search for
objects using specified attributes.

15.7.1 the directory context


The DirContext interface represents a directory context. It defines methods for examining and
updating attributes associated with a directory object.
You use getAttributes() to retrieve the attributes associated with a directory object (for which
you supply the name). Attributes are modified using modifyAttributes(). You can add, replace, or
remove attributes and/or attribute values using this operation.
DirContext also behaves as a naming context by extending the Context interface. This means
that any directory object can also provide a naming context. For example, a directory object for a
person might contain attributes about that person as well as provide a context for naming objects,
such as the person's printers and file system relative to that person directory object.

15.7.2 searches
DirContext contains methods for performing content-based searching of the directory. In the
simplest and most common form of usage, the application specifies a set of attributes--possibly with
specific values--to match and submits this attribute set to the search() method. Other overloaded
forms of search() support more sophisticated search filters.

15.8 the event package

The javax.naming.event package contains classes and interfaces for supporting event
notification in naming and directory services.
Events
A NamingEvent represents an event that is generated by a naming/directory service. The event
contains a type that identifies the type of event. For example, event types are categorized into those
that affect the namespace, such as "object added," and those that do not, such as "object changed." A
NamingEvent also contains other information about the change, such as information about the object
before and after the change.
Listeners
A NamingListener is an object that listens for NamingEvents. Each category of event type has a
corresponding type of NamingListener. For example, a NamespaceChangeListener represents
a listener interested in namespace change events and an ObjectChangeListener represents a
listener interested in object change events.
To receive event notifications, a listener must be registered with either an EventContext or an
EventDirContext. Once registered, the listener will receive event notifications when the
corresponding changes occur in the naming/directory service.

15.9 the LDAP package

The javax.naming.ldap package contains classes and interfaces for using features that are

199
15 - JNDI

specific to the LDAP v3 that are not already covered by the more generic
javax.naming.directory package. In fact, most JNDI applications that use the LDAP will find the
javax.naming.directory package sufficient and will not need to use the javax.naming.ldap
package at all. This package is primarily for those applications that need to use "extended" operations,
controls, or unsolicited notifications.

15.9.1 "extended" operation


In addition to specifying well-defined operations such as search and modify, the LDAP v3 (RFC
2251) specifies a way to transmit yet-to-be defined operations between the LDAP client and the
server. These operations are called "extended" operations. An "extended" operation may be defined
by a standards organization such as the Internet Engineering Task Force (IETF) or by a vendor. This
package defines classes for the Start TLS extension.

15.9.2 controls
The LDAP v3 allows any request or response to be augmented by yet-to-be defined modifiers,
called controls. A control sent with a request is a request control and a control sent with a response is
a response control. A control may be defined by a standards organization such as the IETF or by a
vendor. Request controls and response controls are not necessarily paired, that is, there need not be
a response control for each request control sent, and viceversa.

15.9.3 unsolicited notifications


In addition to the normal request/response style of interaction between the client and server, the
LDAP v3 also specifies unsolicited notifications--messages that are sent from the server to the client
asynchronously and not in response to any client request.

15.9.4 the LDAP context


The LdapContext interface represents a context for performing "extended" operations, sending
request controls, and receiving response controls.

15.10 the service provider package

The javax.naming.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.

15.10.1 plug-In architecture


The javax.naming.spi package allows different implementations to be plugged in dynamically.
These implementations include those for the initial context and for contexts that can be reached from
the initial context.

15.10.2 java object support


The javax.naming.spi package supports implementors of Context.lookup() and related
methods to return Java objects that are natural and intuitive for the Java programmer. For example, 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. This support is provided in the form of object factories.
This package also provides support for doing the reverse. That is, implementors of
Context.bind() and related methods can accept Java objects and store the objects in a format
acceptable to the underlying naming/directory service. This support is provided in the form of state
factories.

200
15 - JNDI

15.10.3 multiple naming systems (federation)


JNDI operations allow applications to supply names that span multiple naming systems. In the
process of completing an operation, one service provider might need to interact with another service
provider, for example to pass on the operation to be continued in the next naming system. This
package provides support for different providers to cooperate to complete JNDI operations.

15.11 naming example

This example shows you how to write a program that looks up an object whose name is passed in
as a command-line argument. It uses a service provider for the file system. Therefore the name that
you supply to the program must be a filename. You do not need to understand details about the
service provider at this point.

15.11.1 importing the JNDI classes


Using your favorite text editor, create a file named Lookup.java. You can import either the entire
package or only individual classes and interfaces. The following code imports each class that is used
from the javax.naming package.
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

15.11.2 creating an initial context


In the main() method of the program, create an initial context. 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, as follows.
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");

Context ctx = new InitialContext(env);

15.11.3 looking up an Object


Next, use Context.lookup() to look up an object. The following code looks up the object bound
to the name supplied in the command line.
Object obj = ctx.lookup(name);

15.11.4 catching NamingException


The creation of the initial context and the lookup() method can throw a NamingException. For
this reason, you need to enclose these calls inside a try/catch clause. Here's the code fragment
repeated with the try/catch clause.
try {
// Create the initial context
Context ctx = new InitialContext(env);

// Look up an object
Object obj = ctx.lookup(name);

// Print it
System.out.println(name + " is bound to: " + obj);

201
15 - JNDI

} catch (NamingException e) {
System.err.println("Problem looking up " + name + ":" + e);
}

15.11.5 compiling the program


Next, you compile the source file using the Java compiler. To compile to program, you must have
access to the JNDI classes. If you are using the Java 2 SDK, v1.3 or higher, then the JNDI classes are
already included. Otherwise, you can include the classes either by setting the CLASSPATH variable to
include the jndi.jar that you downloaded from the JNDI Web site or by installing jndi.jar as an
installed extension.
If the compilation succeeds, then the compiler will create a file named Lookup.class in the same
directory (folder) as the Java source file (Lookup.java). If the compilation fails, then make sure that
you typed in and named the program exactly as shown here, using the capitalization shown.

15.11.6 running the program


To run the program, you need access to the JNDI classes, the file system service provider, and your
example class (Lookup.class). See the compilation step for instructions on including access to the
JNDI classes. To include the file system service provider classes (fscontext.jar and
providerutil.jar), either include them in your CLASSPATH variable or install them as extensions.
Finally, include the directory that contains your Lookup.class file in your the CLASSPATH variable.
To run the program, supply the name of a file in your file system, as follows:
# java Lookup /tmp

Or as follows:
# java Lookup \autoexec.bat

If you supply a file directory, then you will see something like the following.
# java Lookup /tmp
/tmp is bound to: com.sun.jndi.fscontext.RefFSContext@1dae083f

If the name that you supplied is a file, then you will see something like this:
/tmp/f is bound to: //tmp/f

15.12 directory example

This example shows you how to write a program that retrieves attributes from a directory object. It
uses an LDAP service provider to access an LDAP service.

15.12.1 importing the JNDI directory classes


Using your favorite text editor, create a file named Getattr.java. You can import either the entire
package or only individual classes and interfaces. The following code imports each class that is used
from the javax.naming and javax.naming.directory packages.
import javax.naming.Context;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.DirContext;
import javax.naming.directory.Attributes;
import javax.naming.NamingException;

202
15 - JNDI

15.12.2 creating an initial directory context


In the main() method of the program, create an initial directory context. This is similar to creating
an initial context in the previous naming example, except that you use the constructor for
InitialDirContext.
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,
"ldap://localhost:389/o=JNDITutorial");

DirContext ctx = new InitialDirContext(env);

Similar to the naming example, you indicate that you're using the LDAP service provider by setting
the Hashtable parameter to the InitialDirContext constructor appropriately. For now, the only
thing to understand is that the program by default identifies an LDAP server on the local machine. If
your LDAP server is located on another machine or is using another port, then you need to edit the
LDAP URL ("ldap://localhost:389/o=JNDITutorial") accordingly.

15.12.3 getting a directory Object's attributes


Next, use getAttributes() to get an object's attributes. The following code retrieves all of the
attributes associated with the object bound to the name "cn=Ted Geisel, ou=People":
Attributes attrs = ctx.getAttributes("cn=Ted Geisel, ou=People");

15.12.4 extracting the desired attribute


From a set of attributes, Attributes, you can ask for a particular attribute by using
Attributes.get() and then from that attribute get its value. The following line first gets the
surname attribute "sn" and then invokes Attribute.get() on it to get its value:
attrs.get("sn").get();

15.12.5 catching NamingException


The method calls shown so far can throw a NamingException. For this reason, you need to wrap
these calls inside a try/catch clause. Here's the code fragment repeated with the try/catch
clause.
try {
// Create the initial directory context
DirContext ctx = new InitialDirContext(env);

// Ask for all attributes of the object


Attributes attrs = ctx.getAttributes("cn=Ted Geisel,
ou=People");

// Find the surname attribute ("sn") and print it


System.out.println("sn: " + attrs.get("sn").get());

} catch (NamingException e) {
System.err.println("Problem getting attribute:" + e);
}

15.12.6 compiling the program


Next, compile the source file using the Java compiler. As with the naming example, to do this you
need access to the JNDI classes.

203
15 - JNDI

If the compilation succeeds, then the compiler creates a file named Getattr.class in the same
directory (folder) as the Java source file (Getattr.java). If the compilation fails, then make sure that
you typed in and named the program exactly as shown here, using the capitalization shown.

15.12.7 running the program


As with the naming example, you need access to both the JNDI classes and your example class,
Getattr.class. You also need access to the LDAP service provider classes (ldap.jar and
providerutil.jar). If you are using the Java 2 SDK, v1.3 or higher, then these classes are already
included.
Here's an example of a command line for running Getattr and the output it generates.
# java Getattr
sn: Geisel

Recall that the program was configured with the following property.
env.put(Context.PROVIDER_URL,
"ldap://localhost:389/o=JNDITutorial");

With this configuration, this command queries the LDAP server on machine localhost that is
listening on port 389, serving the "o=JNDITutorial" namespace. It asks for the attributes of the
entry "cn=Ted Geisel, ou=People". Once it has the attributes, it extracts the surname attribute
("sn").

204
16 - JAVA MESSAGE SERVICE

16 - JAVA MESSAGE SERVICE


16.1 JMS elements

The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for
sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise
Edition, and is defined by a specification developed under the Java Community Process as JSR 914.
The following are JMS elements:
JMS provider - An implementation of the JMS interface for a Message Oriented Middleware
(MOM). Providers are implemented as either a Java JMS implementation or an adapter to a
non-Java MOM.
JMS client - an application or process that produces and/or consumes messages.
JMS producer - a JMS client that creates and sends messages.
JMS consumer - a JMS client that receives messages.
JMS message - an object that contains the data being transferred between JMS clients.
JMS queue - a staging area that contains messages that have been sent and are waiting to
be read. As the name queue suggests, the messages are delivered in the order sent. A
message is removed from the queue once it has been read.
JMS topic - a distribution mechanism for publishing messages that are delivered to multiple
subscribers.

16.2 JMS models

The JMS API supports two models:


point-to-point or queuing model
publish and subscribe model
In the point-to-point or queuing model, a producer posts messages to a particular queue and a
consumer reads messages from the queue. Here, the producer knows the destination of the message
and posts the message directly to the consumer's queue. 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,
nor does the consumer need to be running at the time the message is sent
Every message successfully processed is acknowledged by the consumer
The publish/subscribe model supports publishing messages to a particular message topic. Zero or
more subscribers may register interest in receiving messages on a particular message topic. In this
model, neither the publisher nor the subscriber know about each other. A good metaphor for it is
anonymous bulletin board. The following are characteristics of this model:
Multiple consumers can get the message
There is a timing dependency between publishers and subscribers. The publisher has to
create a subscription in order for clients to be able to subscribe. The subscriber has to remain
continuously active to receive messages, unless it has established a durable subscription. In
that case, messages published while the subscriber is not connected will be redistributed
whenever it reconnects.
Using Java, JMS provides a way of separating the application from the transport layer of providing
data. The same Java classes can be used to communicate with different JMS providers by using the
JNDI information for the desired provider. The classes first use a connection factory to connect to the
queue or topic, and then use populate and send or publish the messages. On the receiving side, the

205
16 - JAVA MESSAGE SERVICE

clients then receive or subscribe to the messages.

16.3 the JMS API programming model

16.4 the JMS API

The JMS API is provided in the Java package javax.jms.

16.4.1 the ConnectionFactory interface


An administered object that a client uses to create a connection to the JMS provider. JMS clients
access the connection factory through portable interfaces so the code does not need to be changed if
the underlying implementation changes. Administrators configure the connection factory in the Java
Naming and Directory Interface (JNDI) namespace so that JMS clients can look them up. Depending
on the type of message, users will use either a queue connection factory or topic connection factory.
At the beginning of a JMS client program, you usually perform a JNDI lookup of a connection
factory, then cast and assign it to a ConnectionFactory object.
For example, the following code fragment obtains an InitialContext object and uses it to look
up a ConnectionFactory by name. Then it assigns it to a ConnectionFactory object:
Context ctx = new InitialContext();
ConnectionFactory connectionFactory = (ConnectionFactory)
ctx.lookup("jms/ConnectionFactory");

In a J2EE application, JMS administered objects are normally placed in the jms naming subcontext.

206
16 - JAVA MESSAGE SERVICE

16.4.2 the Connection interface


Once a connection factory is obtained, a connection to a JMS provider can be created. A connection
represents a communication link between the application and the messaging server. Depending on
the connection type, connections allow users to create sessions for sending and receiving messages
from a queue or topic.
Connections implement the Connection interface. When you have a ConnectionFactory
object, you can use it to create a Connection:
Connection connection = connectionFactory.createConnection();

Before an application completes, you must close any connections that you have created. Failure to
close a connection can cause resources not to be released by the JMS provider. Closing a connection
also closes its sessions and their message producers and message consumers.
connection.close();

Before your application can consume messages, you must call the connection's start() method.
If you want to stop message delivery temporarily without closing the connection, you call the stop()
method.

16.4.3 the Destination interface


An administered object that encapsulates the identity of a message destination, which is where
messages are delivered and consumed. It is either a queue or a topic. The JMS administrator creates
these objects, and users discover them using JNDI. Like the connection factory, the administrator can
create two types of destinations: queues for Point-to-Point and topics for Publish/Subscribe.
For example, 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.lookup("jms/MyTopic");

The following line of code looks up a queue named jms/MyQueue and casts and assigns it to a
Queue object:
Queue myQueue = (Queue) ctx.lookup("jms/MyQueue");

16.4.4 the MessageConsumer interface


An object created by a session. It receives messages sent to a destination. The consumer can
receive messages synchronously (blocking) or asynchronously (non-blocking) for both queue and
topic-type messaging.
For example, you use a Session to create a MessageConsumer for either a queue or a topic:
MessageConsumer consumer = session.createConsumer(myQueue);
MessageConsumer consumer = session.createConsumer(myTopic);

You use the Session.createDurableSubscriber() method to create a durable topic


subscriber. This method is valid only if you are using a topic.
After you have created a message consumer, it becomes active, and you can use it to receive
messages. You can use the close() method for a MessageConsumer to make the message
consumer inactive. Message delivery does not begin until you start the connection you created by
calling its start() method. (Remember always to call the start() method; forgetting to start the
connection is one of the most common JMS programming errors.)
You use the receive method to consume a message synchronously. You can use this method at
any time after you call the start method:
connection.start();

207
16 - JAVA MESSAGE SERVICE

Message m = consumer.receive();
connection.start();
Message m = consumer.receive(1000); // time out after a second

To consume a message asynchronously, a message listener object may be used.

16.4.5 the MessageListener interface


A message listener is an object that acts as an asynchronous event handler for messages. This
object implements the MessageListener interface, which contains one method, onMessage(). In
the onMessage() method, you define the actions to be taken when a message arrives.
You register the message listener with a specific MessageConsumer by using the
setMessageListener() method. For example, if you define a class named Listener that
implements the MessageListener interface, you can register the message listener as follows:
Listener myListener = new Listener();
consumer.setMessageListener(myListener);

After you register the message listener, you call the start() method on the Connection to begin
message delivery. (If you call start() before you register the message listener, you are likely to miss
messages.)
When message delivery begins, the JMS provider automatically calls the message listener's
onMessage() method whenever a message is delivered. The onMessage() method takes one
argument of type Message, which your implementation of the method can cast to any of the other
message types.
A message listener is not specific to a particular destination type. The same listener can obtain
messages from either a queue or a topic, depending on the type of destination for which the message
consumer was created. A message listener does, however, usually expect a specific message type
and format. Moreover, 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.

16.4.6 the MessageProducer interface


An object created by a session that sends messages to a destination. The user can create a sender
to a specific destination or create a generic sender that specifies the destination at the time the
message is sent.
You use a Session to create a MessageProducer for a destination. Here, the first example
creates a producer for the destination myQueue, and the second for the destination myTopic:
MessageProducer producer = session.createProducer(myQueue);
MessageProducer producer = session.createProducer(myTopic);

You can create an unidentified producer by specifying null as the argument to createProducer.
With an unidentified producer, you do not specify a destination until you send a message.
After you have created a message producer, you can use it to send messages by using the send
method:
producer.send(message);

You must first create the messages; if you created an unidentified producer, use an overloaded
send method that specifies the destination as the first parameter. For example:
MessageProducer anon_prod = session.createProducer(null);
anon_prod.send(myQueue, message);

208
16 - JAVA MESSAGE SERVICE

16.4.7 the Message interface


An object that is sent between consumers and producers; that is, from one application to another. A
message has three main parts:
1. A message header (required): Contains operational settings to identify and route messages
2. A set of message properties (optional): Contains additional properties to support compatibility
with other providers or users. It can be used to create custom fields or filters (selectors).
3. A message body (optional): Allows users to create five types of messages (text message,
map message, bytes message, stream message, and object message).
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.
For example, to create and send a TextMessage, you might use the following statements:
TextMessage message = session.createTextMessage();
message.setText(msg_text); // msg_text is a String
producer.send(message);

At the consuming end, a message arrives as a generic Message object and must be cast to the
appropriate message type. You can use one or more getter methods to extract the message contents.
The following code fragment uses the getText method:
Message m = consumer.receive();
if (m instanceof TextMessage) {
TextMessage message = (TextMessage) m;
System.out.println("Reading message: " + message.getText());
} else {
// Handle error
}

16.4.8 the Session interface


Represents a single-threaded context for sending and receiving messages. A session is single-
threaded so that messages are serialized, meaning that messages are received one-by-one in the
order sent. The benefit of a session is that it supports transactions. If the user selects transaction
support, the session context holds a group of messages until the transaction is committed, then
delivers the messages. Before committing the transaction, the user can cancel the messages using a
rollback operation. A session allows users to create message producers to send messages, and
message consumers to receive messages.
Sessions implement the Session interface. After you create a Connection object, you use it to
create a Session:
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);

The first argument means that the session is not transacted; the second means that the session
automatically acknowledges messages when they have been received successfully.
To create a transacted session, use the following code:
Session session = connection.createSession(true, 0);

Here, the first argument means that the session is transacted; the second indicates that message
acknowledgment is not specified for transacted sessions.

209
17 - ENTERPRISE JAVA BEANS

17 - ENTERPRISE JAVA BEANS


17.1 enterprise java beans versus (ordinary) java beans

(Ordinary) Java beans provide a format for general-purpose components, while the EJB (Enterprise
Java Beans) architecture provides a format for highly specialized business logic components.
What are Enterprise Java Beans? A collection of Java classes together with an xml file, bundled into
a single unit. The Java classes must follow certain rules and must offer certain callback methods.
The EJBs will run in an EJB container which is part of an application server.
Version 1.1 of EJB specification provides two EJB types:
session beans - intended to be used by a single client (client extension on the server); bean's
life span can be no longer than client's
entity beans - object oriented representation of data in a DB; multiple clients can access it
simultaneously while its life-span is the same as the data it represents. Entity beans have been
superseded by the Java Persistence API in EJB 3.0.
The 2.0 EJB specification adds another bean type:
message-driven beans
The current EJB specification is 3.2 and is the object of JSR 345, whose final release dates back to
May 2013. Novelties in the major 3.x specification try to make the development of EJBs easier. It
provides annotations for every type of metadata previously addressed by deployment descriptors, so
no XML descriptor is needed and beans deployment can be done just through a plain .jar file into the
application server.

17.2 the ejb container and its services

The EJB container provides an execution environment for a component. The component lives inside
a container, container which offers services to the component. On the other side, the container lives
(in general) in an application server, server which provides an execution environment for containers.
The main reason for using EJBs is to take advantage of the services provided by the container.
These services are:
persistence - DB interaction
transactions - transaction management can be complex, especially if we have more databases
and more access components
data caching - no developer coding, improved performance
security - EJB access can be stated without extra coding
error handling - consistent error handling framework - logging, component recovery
scalability
portability
manageability

17.3 enterprise java beans architecture

210
17 - ENTERPRISE JAVA BEANS

An EJB consists of (at least) 3 classes and an xml file. It is bean's programmer task to create them
(at least), as follows:

1. the bean itself (the class that contains the business logic)
2. the home interface of the bean
3. the remote interface of the bean
4. the deployment descriptor, which is an xml file, called ejb-jar.xml

17.4 the home interface

The home interface of an ejb is an interface that extends the EJBHome interface. It provides
methods named create() with application specific arguments, returning the remote interface and
throwing CreateException and RemoteException. It uses only argument types allowed by the
RMI standard.
Handle abstraction for a network reference to an EJB.
The methods specified by the EJBHome interface (not implemented (in general) by the programmer)
are the following:

public void remove(Handle han) throws RemoteException, RemoveException


public void remove(Object primaryKey) throws RemoteException,
RemoveException
public EJBMetaData getEJBMetaData() throws RemoteException
public HomeHandle getHomeHandle() throws RemoteException

Code example for the a home interface, called MyBeanHome:

package myBeans;
import.javax.ejb.*;
import java.rmi.RemoteException;
public interface MyBeanHome extends EJBHome
{
MyBeanObject create() throws CreateException,
RemoteException;

211
17 - ENTERPRISE JAVA BEANS

17.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. The developer does not
implement this interface.
While the Remote interface declares no methods, 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, RemoveException

Code example for a remote interface called MyBeanObject:

package myBeans;
import.javax.ejb.*;
import java.rmi.RemoteException;
public interface MyBeanObject extends EJBObject
{
// assume that we have two business logic methods
void processEntry(String firstName, String lastName, int custId) throws
RemoteException;
void deleteEntry(int custId) throws RemoteException;
}

17.6 client programmer's viewpoint

For an EJB client application, we need to know:


1. how to create or find the bean
2. what methods to use (know its interface)
3. how to release its resources

The client is able to create an EJB through an object implementing the EJBHome interface. This
object acts like a factory for EJBs, creating them for the client application.
The client gains access to the EJB through a remote interface, implemented by an object built by the
EJB host in the deployment process.

Here are the main parts of the client code:

authentication

212
17 - ENTERPRISE JAVA BEANS

Client's authentication is done in a way which is server specific. In the case of an web application,
this can be done (for example) through SSL.

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, the InitialContext is already
available:

Context ctx = new InitialContext();

if the client executes outside the container, getting the InitialContext requires the usage
of some server-side properties. Here is an example:

try
{
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory";
prop.put(Context.PROVIDER_URL,
"localhost:1099");
Context ctx = new InitialContext(prop);
}

find the home interface of the bean

for a client executing inside the container, the code may look like:

Object homeRef = ctx.lookup("java:comp/env/ejb/MyBean");

if the client executes outside the container, the bean can be associated to any name in the
JNDI name space. It is JNDI's task to identify the resource associated to the name provided:

Object homeRef = ctx.lookup("MyBean");

cast the home interface reference

To make sure that the client works with the underlying communication protocol, the client should
use the narrow() method of javax.rmi.PortableRemoteObject:

MyBeanHome myHome = (MyBeanHome)PortableRemoteObject.narrow(homeRef,


MyBeanHome.class);

Why do we have to use the narrow() method? Usually, when we perform a lookup() on a Context
object, the method will return you an Object that needs to be casted to the home interface we've asked
for. Problem is, this cannot be done using the normal/explicit casting:

213
17 - ENTERPRISE JAVA BEANS

MyBeanHome myHome = (MyBeanHome)returnedObject

The reason has to do with CORBA. Why? For EJB, the communication between the server and the
client is based on RMI (both remote and local interfaces, in fact, do implements the java.rmi.Remote
interface).
The underlying protocol that it is used for the communication is IIOP (Internet Inter ORB Protocol),
that is part of CORBA standards. It is normally used to describe this communication system using the
Java RMI over IIOP.
IIOP has not been designed for Java, but for generic languages, and this means that there are
some limitations. Some languages, in fact, do not have the concept of casting. Java RMI-IIOP
provides a mechanism to narrow the the Object you have received from your lookup, to the
appropriate type. This is done through the javax.rmi.PortableRemoteObject class and, more
specifically, using the narrow() method.

create an instance of the bean

The instance of the bean is created on the server. The client only has a remote interface to this
instance (i.e., the client has a stub).
Here is the code:

MyBeanObject myObject = myHome.create();

call business methods on the bean

myObject.processEntry("Dumitrascu", "Vasile", 1102);

remove the bean instance

myObject.remove();

17.7 bean programmer's viewpoint

Since the home interface and the remote interface have been detailed in the previous sections, we
concentrate now on the bean class itself. Besides the implementation of the business methods (which
were declared in the remote interface, as well), the bean class must implement (although the
implementation itself may be empty) a certain set of methods, set which is specific to each major type
of beans (session, entity or message driven).
Assuming that our bean (called MyBean) is a session bean, the code implementing this class may
look like this:

package com.bank11.ccards.ejbeans;
import javax.ejb.SessionContext;
public class MyBean implements javax.ejb.SessionBean
{
public void processEntry(String firstName, String lastName, int
custId)
{
// method implementation

214
17 - ENTERPRISE JAVA BEANS

...
}
public void deleteEntry(int custId)
{
// method implementation
...
}
// mandatory methods for session beans
// method implementations may be empty
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext ctx) {}
}

17.8 the deployment descriptor

The deployment descriptor of an EJB contains information about the bean in relation to the
application it belongs to.
This information can be divided into two main categories:
structural information related to a particular EJB.
application assembly information

Although not an exhaustive one, here is a typical list of entries (elements) in a deployment
descriptor:
1. access control entries - security issues; which users can access a bean or a particular method
of a bean
2. bean home name - name under which the bean is registered under JNDI
3. control descriptors - specifies control attributes for transactions
4. EJB class name
5. environment properties
6. the home interface name
7. the remote interface name
8. session specific elements
9. entity specific elements
10. attributes - like transaction, isolation level, security

Keeping in mind that the application assembler is to follow, here is how the deployment descriptor
may look like:

<?xnm version="1.1"?>
<ejb-jar>
<entrprise-beans>

<session>

215
17 - ENTERPRISE JAVA BEANS

<ejb-name>CCEnroll</ejb-name>
<home>com.bank11.ccards.ejb.CCEnrollHome</home>
<remote>com.bank11.ccards.CCEnrollObject</remote>
<ejb-class>com.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.bank11.ccards.ejb.AccountHome</home>
<remote>com.bank11.ccards.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.bank11.ccards.ejb.AccountHome</home>
<remote>com.bank11.ccards.Accountbject</remote>
<ejb-class>com.bank11.ccards.Account</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Integer</prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>accountNumber</field-name>
</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.lang.Float</env-entry-type>
<env-entry-value>2.5</env-entry-value>
</env-entry>
</entity>

216
17 - ENTERPRISE JAVA BEANS

</enterprise-beans>
</ejb-jar>

The assembly descriptor combines EJBs into a deployable application. Here is a very lean one:

</ejb-jar>
<enterprise-beans>
...
</enterprise-beans>

<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>CCEnroll</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>

217
18 - session beans

18 - SESSION BEANS
There are two types of session beans, namely stateful and stateless beans.
A stateful session bean preserves data between client accesses. A stateless bean does not.
When an EJB server needs to conserve its resources, it can evict stateful session beans from
memory. This reduces the number of instances maintained by the server. To passivate the bean and
preserve its conversational state, the bean's state is serialized to a secondary storage. When a client
invokes a method on the EJB object, the object is activated, that is, a new stateful instance is
instantiated and populated from the passivated storage.

18.1 container callbacks for session beans

There are 5 mandatory callbacks for classes implementing the SessionBean interface.

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, because the container will
never activate a stateless session bean.

18.2 the life cycle of a stateful session bean

Figure 18.1 illustrates the stages that a session bean passes through during its lifetime. The client
initiates the life cycle by invoking the create() method. The EJB container instantiates the bean and
then invokes the setSessionContext() and ejbCreate() methods in the session bean. The
bean is now ready to have its business methods invoked.

218
18 - session beans

Figure 18.1 Life Cycle of a Stateful Session Bean

While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by
moving it from memory to secondary storage. (Typically, the EJB container uses a least-recently-used
algorithm to select a bean for passivation.) The EJB container invokes the bean's ejbPassivate
method immediately before passivating it. If a client invokes a business method on the bean while it is
in the passive stage, the EJB container activates the bean, calls the bean's ejbActivate method,
and then moves it to the ready stage.
At the end of the life cycle, the client invokes the remove method, and the EJB container calls the
bean's ejbRemove method. The bean's instance is ready for garbage collection.
Your code controls the invocation of only two life-cycle methods: the create and remove methods
in the client. All other methods in Figure 18.1 are invoked by the EJB container. The ejbCreate
method, for example, is inside the bean class, allowing you to perform certain operations right after the
bean is instantiated. For example, you might wish to connect to a database in the ejbCreate
method.

18.3 the life cycle of a stateless session bean

Because a stateless session bean is never passivated, its life cycle has only two stages: nonexistent
and ready for the invocation of business methods. Figure 18.2 illustrates the stages of a stateless
session bean.

Figure 18.2 Life Cycle of a Stateless Session Bean

219
19 - entity beans

19 - ENTITY BEANS
Entity beans represent actual data (usually, stored in a Database).

The EJB container provides the developer several persistence services:


1. container callbacks to manage caching within a transaction
2. support for concurrent access
3. maintaining a cache between transactions
4. providing all the persistence management code (no SQL code necessary)

There are 2 main types of entity beans.


CMPs (Container Managed Persistence)
BMPs (Bean Managed Persistence) for which the bean developer provides the actual
persistence (SQL) code

19.1 primary keys

Every entity bean has a primary key. This primary key must be represented by a primary key class.
The requirements that must be satisfied by the primary key are different for the two main types of
entity beans.

For BMPs:
the primary key can be any legal RMI/IIOP type
it must provide suitable implementations for hashCode(), equals()
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.bank11.ccards.CustomerID</prim-key-class>
or
<prim-key-class>java.lang.String</prim-key-class>

In the case of CMP using a simple type as primary key, the field is specified:
<prim-key-field>sportsTeamID</prim-key-field>

19.2 mandatory callbacks for entity beans

220
19 - entity beans

Besides the CRUD callbacks which are discusses later in this section, 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, Read, Update and Delete. These methods are mandatory for
entity beans.

19.3 create

When a client calls a create() method on a session bean's home interface, an instance of that
bean is created. On the other side, when a client calls create() on an entity bean's home interface,
state data is stored into data store (usually, a Database) (we actually insert a record in a database).
This is transactional data that is accessible to multiple clients. We can have more create()
methods, all throwing RemoteException, CreateException.
Each create() method from the Home interface of the bean has 2 correspondent methods in the
bean implementation class, namely ejbCreate() and ejbPostCreate(), methods which have the
same parameters, in the same order, as the parameters in the original create() method.
the return type of the ejbCreate() is the same as the primary key, but the developer returns null
for CMP.
for BMP, ejbCreate() must have insertion SQL code and returns an instance of the primary key,
not null.

So what is the difference between the ejbCreate() and ejbPostCreate() methods?


ejbCreate() is called before the state of the bean is written to the persistence storage
(database). After this method is completed, a new record (based on the persistence fields) is created
and written. If the Entity EJB is BMP, then this method must contain the code for writing the new
record to the persistence storage.
If you are developing an EJB following 2.0 specs, you can have overloading methods in the form of
ejbCreateXXX(). This will improve the development so you can have different behavior for creating
a bean, if the parameters differs. The only requirement is that for each ejbCreateXXX() you need to
have corresponding createXXX() methods in the home or local interface.
ejbPostCreate() is called after the bean has been written to the database and the bean data has
been assigned to an EJB object, so when the bean is available.In an CMP Entity EJB, this method is
normally used to manage the beans' container-managed relationship fields.

19.4 read

ejbLoad(), left empty most of the time in 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

221
19 - entity beans

19.5 update

ejbStore() in CMP; the method can be used for preprocessing data to be stored, but in
general, it is empty.
in BMP, actual SQL update code; the updated data is to be stored immediately

19.6 delete

the corresponding method in the bean implementation class is ejbRemove()


data is deleted from DB (in the CMP case), for BMPs, the programmer will create actual SQL
code.

19.7 the life cycle of an entity bean

Figure 17.1 shows the stages that an entity bean passes through during its lifetime. After the EJB
container creates the instance, it calls the setEntityContext() method of the entity bean class.
The setEntityContext() method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While in the pooled stage,
the instance is not associated with any particular EJB object identity. All instances in the pool are
identical. The EJB container assigns an identity to an instance when moving it to the ready stage.
There are two paths from the pooled stage to the ready stage. On the first path, the client invokes
the create() method, causing the EJB container to call the ejbCreate() and ejbPostCreate()
methods. On the second path, the EJB container invokes the ejbActivate() method. While an
entity bean is in the ready stage, it's business methods can be invoked.
There are also two paths from the ready stage to the pooled stage. First, a client can invoke the
remove() method, which causes the EJB container to call the ejbRemove() method. Second, the
EJB container can invoke the ejbPassivate() method.

222
19 - entity beans

Figure 17.1 Life Cycle of an Entity Bean

At the end of the life cycle, the EJB container removes the instance from the pool and invokes the
unsetEntityContext() method.
In the pooled state, an instance is not associated with any particular EJB object identity. With bean-
managed persistence, when the EJB container moves an instance from the pooled state to the ready
state, it does not automatically set the primary key. Therefore, the ejbCreate() and
ejbActivate() methods must assign a value to the primary key. If the primary key is incorrect, the
ejbLoad() and ejbStore() methods cannot synchronize the instance variables with the database.
The ejbActivate() method sets the primary key (id) as follows:

id = (String)context.getPrimaryKey();

In the pooled state, the values of the instance variables are not needed. You can make these
instance variables eligible for garbage collection by setting them to null in the ejbPassivate()
method.

223
20 - JAVA PERSISTENCE ENTITIES

20 - JAVA PERSISTENCE ENTITIES


20.1 how did they surface?

Prior to the introduction of EJB 3.0 specification, many enterprise Java developers used lightweight
persistent objects, provided by either persistence frameworks (for example Hibernate) or data access
objects instead of entity beans. This is due to the fact that entity beans, in previous EJB specifications,
called for too much complicated code and heavy resource footprint, and they could be used only in
Java EE application servers because of interconnections and dependencies in the source code
between beans and DAO objects or persistence framework.
Thus, many of the features originally presented in third-party persistence frameworks were
incorporated into the Java Persistence API, and, as of 2006, projects like Hibernate (version 3.2) and
TopLink Essentials have become themselves implementations of the Java Persistence API
specification.

20.2 java persistence areas

There are four main areas which are covered beneath the generic term of Java persistence:
1. Java persistence Entities
2. The Java Persistence API.
3. The Java Persistence Query Language
4. The Java Persistence Criteria API

20.3 java persistence entities

An entity is a lightweight Java class. Typically, an entity represents a table in a relational database,
and each entity instance corresponds to a row in that table. The primary programming artifact of an
entity is the entity class, although entities can use helper classes.
Entities typically have relationships with other entities, and these relationships are expressed
through object/relational metadata.
The persistent state of an entity is represented through either persistent fields or persistent
properties. These fields or properties use object/relational mapping annotations to map the entities
and entity relationships to the relational data in the underlying data store.

20.4 the java persistence API (JPA)

The Java Persistence API (JPA) is a Java programming language application programming
interface specification that describes the management of relational data in applications using Java
Platform, Standard Edition and Java Platform, Enterprise Edition.
The Java Persistence API originated as part of the work of the JSR 220 Expert Group of the Java
Community Process. The final release of the JPA 1.0 specification dates back to May 2006.
JPA 2.0 was the work of the JSR 317 Expert Group and was released in Dec. 2009. The current
specification is JPA 2.1 and was released in April 2013 as JSR 338.

224
20 - JAVA PERSISTENCE ENTITIES

Main features included were:


Converters - allowing custom code conversions between database and object types.
Criteria Update/Delete - allows bulk updates and deletes through the Criteria API.
Stored Procedures - allows queries to be defined for database stored procedures.
Schema Generation
Entity Graphs - allow partial or specified fetching or merging of objects.
JPQL/Criteria enhancements - arithmetic sub-queries, generic database functions, join ON
clause, TREAT option.
Vendors supporting JPA 2.1
DataNucleus
EclipseLink
Hibernate

The Java Persistence API was developed in part to unify the Java Data Objects API, and the EJB
2.0 Container Managed Persistence (CMP) API. As of 2009 most products supporting each of those
APIs support the Java Persistence API.
The Java Persistence API specifies persistence only for relational database management systems.
That is, JPA focuses onobject-relational mapping (ORM) (note that there are JPA providers who
support other database models besides relational database, but this is outside the scope of what JPA
was designed for). Refer to JPA 2 spec section 1 introduction for clarification of the role of JPA, which
states very clearly "The technical objective of this work is to provide an object/relational mapping
facility for the Java application developer using a Java domain model to manage a relational
database."
The Java Data Objects specification supports ORM, as well as persistence to other types of
database models, for example flat file databases and NoSQL databases, including document
databases, graph databases, as well as literally any other conceivable datastore.

20.5 persistence entities in detail

20.5.1 requirements for entity classes


An entity class must follow these requirements.
The class must be annotated with the javax.persistence.Entity annotation.
The class must have a public or protected, no-argument constructor. The class may have
other constructors.
The class must not be declared final. No methods or persistent instance variables must be
declared final.
If an entity instance is passed by value as a detached object, such as through a session
beans remote business interface, the class must implement the Serializable interface.
Entities may extend both entity and non-entity classes, and non-entity classes may extend
entity classes.
Persistent instance variables must be declared private, protected, or package-private and can
be accessed directly only by the entity classs methods. Clients must access the entitys state
through accessor or business methods.

20.5.2 persistent fields and properties in entity classes


The persistent state of an entity can be accessed through either the entitys instance variables or
properties. The fields or properties must be of the following Java language types:

225
20 - JAVA PERSISTENCE ENTITIES

Java primitive types


java.lang.String
Other serializable types, including:
Wrappers of Java primitive types
java.math.BigInteger
java.math.BigDecimal
java.util.Date
java.util.Calendar
java.sql.Date
java.sql.Time
java.sql.TimeStamp
User-defined serializable types
byte[]
Byte[]
char[]
Character[]
Enumerated types
Other entities and/or collections of entities
Embeddable classes
Entities may use persistent fields, persistent properties, or a combination of both. If the mapping
annotations are applied to the entitys instance variables, the entity uses persistent fields. If the
mapping annotations are applied to the entitys getter methods for JavaBeans-style properties, the
entity uses persistent properties.

20.5.3 primary keys in entities


Each entity has a unique object identifier. A customer entity, for example, might be identified by a
customer number. The unique identifier, or primary key, enables clients to locate a particular entity
instance. Every entity must have a primary key. An entity may have either a simple or a composite
primary key.
Simple primary keys use the javax.persistence.Id annotation to denote the primary key
property or field.
Composite primary keys are used when a primary key consists of more than one attribute, which
corresponds to a set of single persistent properties or fields. Composite primary keys must be defined
in a primary key class. Composite primary keys are denoted using the
javax.persistence.EmbeddedId and javax.persistence.IdClass annotations.
The primary key, or the property or field of a composite primary key, must be one of the following
Java language types:
Java primitive types
Java primitive wrapper types
java.lang.String
java.util.Date (the temporal type should be DATE)
java.sql.Date
java.math.BigDecimal
java.math.BigInteger
Floating-point types should never be used in primary keys. If you use a generated primary key, only
integral types will be portable.
A primary key class must meet these requirements.
The access control modifier of the class must be public.

226
20 - JAVA PERSISTENCE ENTITIES

The properties of the primary key class must be public or protected if property-based access
is used.
The class must have a public default constructor.
The class must implement the hashCode() and equals(Object other) methods.
The class must be serializable.
A composite primary key must be represented and mapped to multiple fields or properties of
the entity class or must be represented and mapped as an embeddable class.
If the class is mapped to multiple fields or properties of the entity class, the names and types
of the primary key fields or properties in the primary key class must match those of the entity
class.
The following primary key class is a composite key, and the orderId and itemId fields together
uniquely identify an entity:

public final class LineItemKey implements Serializable {


public Integer orderId;
public int itemId;

public LineItemKey() {}

public LineItemKey(Integer orderId, int itemId) {


this.orderId = orderId;
this.itemId = itemId;
}

public boolean equals(Object otherOb) {


if (this == otherOb) {
return true;
}
if (!(otherOb instanceof LineItemKey)) {
return false;
}
LineItemKey other = (LineItemKey) otherOb;
return (
(orderId==null?other.orderId==null:orderId.equals
(other.orderId)
)
&&
(itemId == other.itemId)
);
}

public int hashCode() {


return (
(orderId==null?0:orderId.hashCode())
^
((int) itemId)
);
}

227
20 - JAVA PERSISTENCE ENTITIES

public String toString() {


return "" + orderId + "-" + itemId;
}
}

20.5.4 multiplicity in entity relationships


Multiplicities are of the following types: one-to-one, one-to-many, many-to-one, and many-to-many:
One-to-one: Each entity instance is related to a single instance of another entity. For
example, to model a physical warehouse in which each storage bin contains a single widget,
StorageBin and Widget would have a one-to-one relationship. One-to-one relationships use
the javax.persistence.OneToOne annotation on the corresponding persistent property or
field.
One-to-many: An entity instance can be related to multiple instances of the other entities. A
sales order, for example, can have multiple line items. In the order application, Order would
have a one-to-many relationship with LineItem. One-to-many relationships use the
javax.persistence.OneToMany annotation on the corresponding persistent property or
field.
Many-to-one: Multiple instances of an entity can be related to a single instance of the other
entity. This multiplicity is the opposite of a one-to-many relationship. In the example just
mentioned, the relationship to Order from the perspective of LineItem is many-to-one. Many-
to-one relationships use the javax.persistence.ManyToOneannotation on the
corresponding persistent property or field.
Many-to-many: The entity instances can be related to multiple instances of each other. For
example, each college course has many students, and every student may take several
courses. Therefore, in an enrollment application, Course and Student would have a many-to-
many relationship. Many-to-many relationships use the javax.persistence.ManyToMany
annotation on the corresponding persistent property or field.

20.5.5 direction in entity relationships


The direction of a relationship can be either bidirectional or unidirectional. A bidirectional
relationship has both an owning side and an inverse side. A unidirectional relationship has only an
owning side. The owning side of a relationship determines how the Persistence runtime makes
updates to the relationship in the database.

20.6 managing entities

Entities are managed by the entity manager, which is represented by


javax.persistence.EntityManager instances. Each EntityManager instance is associated
with a persistence context: a set of managed entity instances that exist in a particular data store. A
persistence context defines the scope under which particular entity instances are created, persisted,
and removed. The EntityManager interface defines the methods that are used to interact with the
persistence context.

20.6.1 the EntityManager interface


The EntityManager API creates and removes persistent entity instances, finds entities by the
entitys primary key, and allows queries to be run on entities.

228
20 - JAVA PERSISTENCE ENTITIES

20.6.2 container-managed entity managers


With a container-managed entity manager, an EntityManager instances persistence context is
automatically propagated by the container to all application components that use the EntityManager
instance within a single Java Transaction API (JTA) transaction.
JTA transactions usually involve calls across application components. To complete a JTA
transaction, these components usually need access to a single persistence context. This occurs when
an EntityManager is injected into the application components by means of the
javax.persistence.PersistenceContext annotation. The persistence context is automatically
propagated with the current JTA transaction, and EntityManager references that are mapped to the
same persistence unit provide access to the persistence context within that transaction. By
automatically propagating the persistence context, application components dont need to pass
references to EntityManager instances to each other in order to make changes within a single
transaction. The Java EE container manages the lifecycle of container-managed entity managers.
To obtain an EntityManager instance, inject the entity manager into the application component:

@PersistenceContext
EntityManager em;

20.6.3 application-managed entity managers


With an application-managed entity manager, on the other hand, the persistence context is not
propagated to application components, and the lifecycle of EntityManager instances is managed by
the application.
Application-managed entity managers are used when applications need to access a persistence
context that is not propagated with the JTA transaction across EntityManager instances in a
particular persistence unit. In this case, each EntityManager creates a new, isolated persistence
context. The EntityManager and its associated persistence context are created and destroyed explicitly
by the application. They are also used when directly injecting EntityManagerinstances cant be done
because EntityManager instances are not thread-safe. EntityManagerFactory instances are
thread-safe.
Applications create EntityManager instances in this case by using the createEntityManager
method of javax.persistence.EntityManagerFactory.
To obtain an EntityManager instance, you first must obtain an EntityManagerFactory
instance by injecting it into the application component by means of the
javax.persistence.PersistenceUnit annotation:

@PersistenceUnit
EntityManagerFactory emf;

Then obtain an EntityManager from the EntityManagerFactory instance:

EntityManager em = emf.createEntityManager();

Application-managed entity managers dont automatically propagate the JTA transaction context.
Such applications need to manually gain access to the JTA transaction manager and add transaction
demarcation information when performing entity operations. The
javax.transaction.UserTransaction interface defines methods to begin, commit, and roll
back transactions. Inject an instance of UserTransaction by creating an instance variable
annotated with @Resource:

@Resource

229
20 - JAVA PERSISTENCE ENTITIES

UserTransaction utx;

To begin a transaction, call the UserTransaction.begin method. When all the entity operations are
complete, call the UserTransaction.commit method to commit the transaction. The
UserTransaction.rollback method is used to roll back the current transaction.
The following example shows how to manage transactions in an application that uses an
application-managed entity manager:

@PersistenceContext
EntityManagerFactory emf;
EntityManager em;
@Resource
UserTransaction utx;
...
em = emf.createEntityManager();
try {
utx.begin();
em.persist(SomeEntity);
em.merge(AnotherEntity);
em.remove(ThirdEntity);
utx.commit();
} catch (Exception e) {
utx.rollback();
}

20.6.4 finding entities using the EntityManager


The EntityManager.find method is used to look up entities in the data store by the entitys
primary key:

@PersistenceContext
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}

20.6.5 managing an entity instances lifecycle


You manage entity instances by invoking operations on the entity by means of an EntityManager
instance. Entity instances are in one of four states: new, managed, detached, or removed.
New entity instances have no persistent identity and are not yet associated with a persistence
context.
Managed entity instances have a persistent identity and are associated with a persistence
context.
Detached entity instances have a persistent identity and are not currently associated with a
persistence context.
Removed entity instances have a persistent identity, are associated with a persistent context,
and are scheduled for removal from the data store.

230
20 - JAVA PERSISTENCE ENTITIES

20.7 querying entities

The Java Persistence API provides the following methods for querying entities.
The Java Persistence query language (JPQL) is a simple, string-based language similar to
SQL used to query entities and their relationships.
The Criteria API is used to create typesafe queries using Java programming language APIs to
query for entities and their relationships.
Both JPQL and the Criteria API have advantages and disadvantages.
Just a few lines long, JPQL queries are typically more concise and more readable than Criteria
queries. Developers familiar with SQL will find it easy to learn the syntax of JPQL. JPQL named
queries can be defined in the entity class using a Java programming language annotation or in the
applications deployment descriptor. JPQL queries are not typesafe, however, and require a cast when
retrieving the query result from the entity manager. This means that type-casting errors may not be
caught at compile time. JPQL queries dont support open-ended parameters.
Criteria queries allow you to define the query in the business tier of the application. Although this is
also possible using JPQL dynamic queries, Criteria queries provide better performance because JPQL
dynamic queries must be parsed each time they are called. Criteria queries are typesafe and therefore
dont require casting, as JPQL queries do. The Criteria API is just another Java programming
language API and doesnt require developers to learn the syntax of another query language. Criteria
queries are typically more verbose than JPQL queries and require the developer to create several
objects and perform operations on those objects before submitting the query to the entity manager.

20.8 an example

Check the link - https://docs.oracle.com/javaee/6/tutorial/doc/giqst.html - for a simple inventory and


ordering application for maintaining a catalog of parts and placing an itemized order of those parts.
The application has entities that represent parts, vendors, orders, and line items. These entities are
accessed using a stateful session bean that holds the business logic of the application. A simple
singleton session bean creates the initial entities on application deployment. A Facelets web
application manipulates the data and displays data from the catalog.

231
21 - message-driven beans

21 - MESSAGE-DRIVEN BEANS
21.1 what are the message driven beans?

A message-driven bean is an enterprise bean that allows J2EE applications to process messages
asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it
receives messages instead of events. The messages may be sent by any J2EE component - an
application client, another enterprise bean, or a Web component - or by a JMS application or system
that does not use J2EE technology.
Message-driven beans currently process only JMS messages, but in the future they may be used to
process other kinds of messages.
Session beans and entity beans allow you to send JMS messages and to receive them
synchronously, but not asynchronously. To avoid tying up server resources, you may prefer not to use
blocking synchronous receives in a server-side component. To receive messages in an asynchronous
manner, message-driven bean can be used.

21.2 differences between message-driven beans and the other


EJBs

The most visible difference between message-driven beans and session and entity beans is that
clients do not access message-driven beans through interfaces. Unlike a session or entity bean, a
message-driven bean has only a bean class.
In several respects, a message-driven bean resembles a stateless session bean.
a message-driven bean's instances retain no data or conversational state for a specific client.
all instances of a message-driven bean are equivalent, allowing the EJB container to assign a
message to any message-driven bean instance. The container can pool these instances to
allow streams of messages to be processed concurrently.
a single message-driven bean can process messages from multiple clients.
The instance variables of the message-driven bean instance can contain some state across the
handling of client messages - for example, a JMS API connection, an open database connection, or
an object reference to an enterprise bean object.
When a message arrives, the container calls the message-driven bean's onMessage() method to
process the message. 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. The onMessage()
method may call helper methods, or it may invoke a session or entity bean to process the information
in the message or to store it in a database.
A message may be delivered to a message-driven bean within a transaction context, so that all
operations within the onMessage() method are part of a single transaction. If message processing is
rolled back, the message will be redelivered.

21.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, message-driven beans are different from stateless

232
21 - message-driven beans

session EJBs (and other types of EJBs) in several significant ways:


message-driven beans process multiple JMS messages asynchronously, rather than
processing a serialized sequence of method calls.
message-driven beans have no home or remote interface, and therefore cannot be directly
accessed by internal or external clients. Clients interact with message-driven beans only
indirectly, by sending a message to a JMS Queue or Topic.

21.4 concurrent support for message-driven beans

Message-driven Beans support concurrent processing for both topics and queues. Previously, only
concurrent processing for Queues was supported.
To ensure concurrency, change the ejb-jar.xml deployment descriptor max-beans-in-free-
pool setting to >1. If this element is set to more than one, the container will spawn as many threads
as specified. For more information on this element see, max-beans-in-free-pool.

21.5 invoking a message-driven bean

When a JMS Queue or Topic receives a message, call an associated message-driven bean as
follows:
1. Obtain a new bean instance.
Obtain a new bean instance from the connection pool if one already exists, or create a new
one. See Creating and Removing Bean Instances.
2. If the bean cannot be located in the pool and a new one must be created, call the bean's
setMessageDrivenContext() to associate the instance with a container context. The bean can
utilize elements of this context as described in Using the Message-Driven Bean Context.
3. Call the bean's onMessage() method to perform business logic. See Implementing Business
Logic with onMessage().
Note: These instances can be pooled.

21.6 developing message-driven beans

To create message-driven EJBs, you must follow certain conventions described in the JavaSoft EJB
2.0 specification, as well as observe several general practices that result in proper bean behavior.
The EJB 2.0 specification provides detailed guidelines for defining the methods in a message-driven
bean class. The following output shows the basic components of a message-driven bean class.
Classes, methods, and method declarations in bold are required as part of the EJB 2.0 specification:
public class MessageTraderBean implements javax.ejb.MessageDrivenBean {
public MessageTraderBean() {...};
// An EJB constructor is required, and it must not
// accept parameters. The constructor must not be declared as
// final or abstract.
public void onMessage(javax.jms.Message MessageName) {...}
// onMessage() is required, and must take a single parameter of
// type javax.jms.Message. The throws clause (if used) must not
// include an application exception. onMessage() must not be

233
21 - message-driven beans

// declared as final or static.


public void ejbRemove() {...}
// ejbRemove() is required and must not accept parameters.
// The throws clause (if used) must not include an application
//exception. ejbRemove() must not be declared as final or static.
finalize{};
// The EJB class cannot define a finalize() method
}

21.7 creating and removing bean instances

The EJB container calls the message-driven bean's ejbCreate() and ejbRemove() methods
when creating or removing an instance of the bean class. As with other EJB types, the ejbCreate()
method in the bean class should prepare any resources that are required for the bean's operation. The
ejbRemove() method should release those resources, so that they are freed before the EJB
container removes the instance.
Message-driven beans should also perform some form of regular clean-up routine outside of the
ejbRemove() method, because the beans cannot rely on ejbRemove() being called under all
circumstances (for example, if the EJB throws a runtime exception).

21.8 using the message-driven bean context

The EJB container calls setMessageDrivenContext() to associate the message-driven bean


instance with a container context. This is not a client context; the client context is not passed along
with the JMS message. The EJB container provides the EJB with a container context, whose
properties can be accessed from within the instance by using the following methods from the
MessageDrivenContext interface:
getCallerPrincipal()
isCallerInRole()
setRollbackOnly()- The EJB can use this method only if it utilizes container-managed
transaction demarcation.
getRollbackOnly() - The EJB can use this method only if it utilizes container-managed
transaction demarcation.
getUserTransaction()- The EJB can use this method only if it utilizes bean-managed
transaction demarcation.
Note: Although getEJBHome() is also inherited as part of the MessageDrivenContext
interface, message-driven EJBs do not have a home interface. Calling getEJBHome() from
within a message-driven EJB instance yields an IllegalStateException.

21.9 implementing business logic with onMessage()

The message-driven bean's onMessage() method performs all of the business logic for the EJB.
The EJB container calls onMessage() when the EJB's associated JMS Queue or Topic receives a
message, passing the full JMS message object as an argument. It is the message-driven EJB's
responsibility to parse the message and perform the necessary business logic in onMessage().

234
21 - message-driven beans

Make sure that the business logic accounts for asynchronous message processing. For example, it
cannot be assumed that the EJB receives messages in the order they were sent by the client. Instance
pooling within the container means that messages are not received or processed in a sequential order,
although individual onMessage() calls to a given message-driven bean instance are serialized.
See javax.jms.MessageListener.onMessage() for more information.

21.10 transaction services for message-driven beans

As with other EJB types, message-driven beans can demarcate transaction boundaries either on
their own (using bean-managed transactions), or by having the The EJB container container manage
transactions (container-managed transactions). In either case, a message-driven bean does not
receive a transaction context from the client that sends a message. The EJB container always calls a
bean's onMessage() method by using the transaction context specified in the bean's deployment
descriptor, as required by the EJB 2.0 specification.
Because no client provides a transaction context for calls to a message-driven bean, beans that use
container-managed transactions must be deployed using the Required or NotSupported attribute
in ejb-jar.xml. Transaction attributes are defined in ejb-jar.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>

21.11 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. For EJBs that use bean-managed transactions, the
message receipt is always outside the scope of the bean's transaction, as described in the EJB 2.0
specification. For EJBs that use container-managed transaction demarcation, the EJB container
includes the message receipt as part of the bean's transaction only if the bean's transaction attribute is
set to Required.

21.12 message acknowledgment

For message-driven beans that use container-managed transaction demarcation, the EJB container
automatically acknowledges a message when the EJB transaction commits. If the EJB uses bean-
managed transactions, both the receipt and the acknowledgment of a message occur outside of the
EJB transaction context. The EJB container automatically acknowledges messages for EJBs with
bean-managed transactions, but the deployer can configure acknowledgment semantics using the
jms-acknowledge-mode deployment parameter.

235
21 - message-driven beans

21.13 the deployment descriptor

To deploy a message-driven bean on the EJB container, you edit the XML file to create the
deployment descriptors that associate the EJB with a configured JMS destination.
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
The EJB 2.0 specification adds the following new XML deployment elements for deploying
message-driven beans.
message-driven-destination specifies whether the EJB should be associated with a
JMS Queue or Topic destination.
subscription-durability specifies whether or not an associated Topic should be
durable.
jms-acknowledge-mode specifies the JMS acknowledgment semantics to use for beans
that demarcate their own transaction boundaries. This element may have two values:
AUTO_ACKNOWLEDGE (the default) or DUPS_OK_ACKNOWLEDGE.
These elements are defined in the ejb-jar.xml deployment file, as described in the EJB 2.0
specification. 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.ejb20.message.MessageTraderBean</ejb-class>
<transaction-type>Container</transaction-type>
<message-driven-destination>
<jms-destination-type>
javax.jms.Topic
</jms-destination-type>
</message-driven-destination>
...
</message-driven>
...
</enterprise-beans>
In addition to the new ejb-jar.xml elements, the weblogic-ejb-jar.xml file includes a new
message-driven-descriptor stanza to associate the message-driven bean with an actual destination in
the EJB container.

21.14 the life cycle of a message-driven bean

Figure 15.4 illustrates the stages in the life cycle of a message-driven bean.
The EJB container usually creates a pool of message-driven bean instances. For each instance, the
EJB container instantiates the bean and performs these tasks:
1. It calls the setMessageDrivenContext method to pass the context object to the instance.
2. It calls the instance's ejbCreate method.

236
21 - message-driven beans

Figure 15.4 Life Cycle of a Message-Driven Bean

Like a stateless session bean, a message-driven bean is never passivated, and it has only two
states: nonexistent and ready to receive messages.
At the end of the life cycle, the container calls the ejbRemove() method. The bean's instance is
then ready for garbage collection.

237

Вам также может понравиться