You are on page 1of 215

1 - web and its technologies

1 - WEB AND ITS TECHNOLOGIES


1.1 the web and its beginnings
The internet may be defined as the worldwide system of interconnected computer and
communication networks that interchange data using the nternet Protocol Suite. This suite is also
known as TCP/P, from its two most important protocols the Transmission Control Protocol
(TCP) and the nternet Protocol (P).
Not to be confused with the internet, the World Wide Web (or www for short) is a system of
interlinked hypertext based documents accessed via the internet. These documents (or web
pages) can be viewed or accessed using a web browser. Besides their content which ranges from
plain text to videos and other multimedia items, the web pages may contain hyperlinks which
identify other documents and facilitate the navigation between different web pages. n a sense,
the internet is the infrastructure of the World Wide Web.
The internet roots can be traced to a project called ARPANET within the Advanced Research
Projects Agency of the US Department of Defense (also known as DARPA Defense Advanced
Research Projects Agency). (D)ARPA itself was established in 1958 as response to the Soviet
Union launching of the first satellite in 1957. This project grew up from the necessity of
interconnecting in a reliable manner different networking systems and was based on packet
switching . Previously, data communication was based on circuit switching where a dedicated
circuit is used for the communication needs of the entities at the end points of the communication
channel. The first operational instance of ARPANET became operational in october 1969 and
consisted of 4 packet switching nodes, located at
Earlier attempts included
1.2 the natre !" web !b#e$ts
1.% distribted a&&'i$ati!ns
We detail in this section some of the technical intricacies related to distributed applications.
A distributed application is an application whose execution units lie in different address spaces.
When two people talk to each other in the same room, their communication is direct and
unobstructed. The same paradigm applies when two processes communicate within the same
address space. When the same two people are in different locations communication is done, in
general, using a whole infrastructure, in the most common case, they use cellular phones.
So what is the equivalent of the cell phone for a . The process does not. The stub is the client
side substitute for the real guy (the server). On the other side, the server application does not get
the request from the caller (the client) but from the skeleton. The skeleton is the server side
substitute for the real guy (the client). We see this in the figure from the CORBA section of this
chapter.
1
1 - web and its technologies
1.( $!rba ) bringing !b#e$ts t!gether
CORBA stands for Common Object Request Broker Architecture and is a standard defined by a
consortium called the Object Management Group (OMG). The clout of this group can be inferred
from both its founding companies (including Hewlett-Packard, BM, Sun Microsystems, Apple
Computer, American Airlines) and its present day membership structure (over 800 influential
software producing and software consuming companies).
CORBA was supposed to address object interoperability issues, issues derived from two main
sources:
1. the variety of object implementation languages and platforms
2. the distributed character of the applications and objects
Eventually, the objects, in all their variety, will meet on the ORB and will speak the same
language DL.
ORB or Object Request Broker - is a middleware which facilitates the interaction between
applications and distributed objects.
Various ORBs communicate through an abstract protocol called GOP (General nter-ORB
Protocol). The GOP architecture provides the framework for several concrete protocols like:
1. OP the nternet nter-ORB Protocol is a GOP implementation to be used over the
internet and provides message passing over the TCP/P layer.
2. SSLOP SSL nter-ORB Protocol is actually OP over SSL, ading authentication and
encryption services.
3. HTOP HyperText nter-ORB Protocol OP over HTTP with transparent proxy
bypassing
DL stands for nterface Definition Language and describes the interfaces the objects will reveal
to the outside world. The way DL maps to an actual implementation language like C++, Java,
COBOL, Python or even C is specified by CORBA.
2
1 - web and its technologies
A document which provides a detailed view of the CORBA architecture and its components can
be viewed at http://www.cs.wustl.edu/~schmidt/PDF/vinoski.pdf
However, due to the divergent nature of the implementation process of an increasingly complex
specification have lead, in time, to the decline of CORBA as architectural choice in the design and
implementation of enterprise scale applications. The technologies that sustained and inspired
CORBA in its initial stages can now be retrieved in the latest java-centric technologies. n a sense,
the evolution of java and its related technologies have lead to the demise of CORBA
1.* #a+a
What java brought to the table was:
1. A truly portable object oriented programming language and platform
2. An unsophisticated and almost free development environment
3. A well structured and established class hierarchy
4. A tightly controlled specification.
Despite its inherent drawbacks, like poor performance, java was (is) easy to use and produced
quick results.
1., a&&'i$ati!n ser+ers
An application server (or appserver) is a software framework which is used to host services
within a multitier architectural environment. n its simplest and most wide-spread representation,
an appserver serves as a functional interface between one or more databases and user
interfaces.
The term application server is used, mostly, in conjunction with the Java Enterprise Edition
specification. Some of the most known Java EE compliant application servers are:
WebLogic Server of BEA (bought by Oracle)
WebSphere Application Server of BM
Jboss of Red Hat
Jrun of Adobe
Apache Geronimo by the Apache Software Foundation
SAP Netweaver of SAP
Sun Java System Application Server and its free offspring, the Glassfish Application
Server both by Sun Microsystems
1.- #a+a &'at"!r./ enter&rise editi!n
Formerly known as J2EE (Java 2 Platform, Enterprise Edition) java EE is an industry standard
3
1 - web and its technologies
for building distributed web applications and implementing elements of SOA (Service Oriented
Architecture). J2EE is based on a broader platform J2SE (Java Platform, Standard Edition)
which provides a fully fledged environment for java-based application development end
deployment.
1.0 d1na.i$ web &ages and the s$ri&ting ga'!re
HTML, the first widely accepted programming language for web content, was inherently static.
Moving beyond this stage was, eventually achieved
1.0.1 DHT2L
Dynamic HTML (or DHTML) is a collection of technologies which allows the creation of
interactive and dynamic web pages by combining HTML, client-side scripting languages
web $!ntainer in a 32EE a&&'i$ati!n ser+er. Commercial implementations of the J2EE
specifications, like WebLogic, nprise Application Server or BM's WebSphere include web
containers.
web $!ntainer bi't int! web ser+ers. Most known cases are the Sun's Java WebServer and
the Jakarta Tomcat web server (which will be used in our applications).
web $!ntainer as a se&arate rnti.e. Some web servers, like Apache or S require a
1.4 s$ri&ting +erss a&&'i$ati!n ser+ers
n 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. n 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.
1.15 the 'atest trends
SOA, or Service Oriented Architecture is the new trend in Enterprise Application ntegration
(EA). SOA provides methods for application development and integration centered around a set
of interoperable services. These services consist of unassociated functional units that have no
calls to each other embedded in them. The way these services communicate with each other is
described by a business process expert, who specifies the way these services link and interact
through a process called !r$hestrati!n. Orchestration is done through an executable language,
4
1 - web and its technologies
B6EL (Business Process Execution Language). n practical terms, the BPEL code is generated
through a graphical front-end, which maps B62N (Business Process Modeling Notation) diagrams
into actual BPEL code. The BPEL code is executed within a BPEL engine. mplementations of
BPEL engines have been provided by various companies, starting with ActiveBPEL of Active
Endpoints and ending with the WebSphere Process Server of BM.
A special note on human interaction. Earlier BPEL specifications had serious problems in
incorporating the human acts within the business processes. Eventually, in june 2007, Active
Endpoints, Adobe, BEA, BM, Oracle and SAP jointly published the BPEL4People and WS-
HumanTask specifications, describing how human interaction can be implemented in BPEL
processes.
1.11 an e+!'ti!n &r!gn!sis
t is our belief that the web will evolve in its three many areas infrastructure, substance and
internal mechanisms as follows.
1. nfrastructure beyond its intrinsic development, the infrastructure will adapt itself to the
2. Substance as informatic entities will
3. nternal mechanisms the web's inner workings will mirror in a higher degree
5
2 - java platform, enterprise edition
2 - 3A7A 6LAT8O92/ ENTE969ISE
EDITION
2.1 the state !" #a+a EE
The Java EE 5 is the current Java Enterprise Edition specification (as of Oct. 2009). Java EE 6
is a work in progress, mainly because some of the technologies it contains are based on evolving
JSRs (Java Specification Requests). Compared to the previous specification, it introduces a
simplified programming model. Also, with Java EE 5 technology, XML deployment descriptors are
now optional. nstead, a developer can simply enter the information as an annotation directly into
a Java source file, and the Java EE server will configure the component at deployment and run-
time. These annotations are generally used to embed in a program data that would otherwise be
furnished in a deployment descriptor. With annotations, the specification information is put directly
in your code next to the program element that it affects.
2.2 the a&&'i$ati!n .!de'
The application model starts with the Java programming language and the Java Virtual
Machine. This combination provides high portability, scalability and developing efficiency.
Java EE is designed to support applications that implement enterprise services for customers,
employees, suppliers, partners, and others who make demands on or contributions to the
enterprise. Such applications are inherently complex, potentially accessing data from a variety of
sources and distributing applications to a variety of clients.
To better control and manage these applications, the business functions to support these
various users are conducted in the middle tier. The middle tier represents an environment that is
closely controlled by an enterprise's information technology department. The middle tier is
typically run on dedicated server hardware and has access to the full services of the enterprise.
The Java EE application model defines an architecture for implementing services as multi-tier
applications that deliver the scalability, accessibility, and manageability needed by 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.
2.% distribted .'titiered a&&'i$ati!ns
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 2.1 shows generic multitiered Java EE applications divided into the tiers
described in the list below. The Java EE application parts shown in figure 2.1 are presented in the
Java EE components section.
6
2 - java platform, enterprise edition
$'ient-tier components run on the client machine.
web-tier components run on the Java EE server.
bsiness-tier components run on the Java EE server.
enter&rise in"!r.ati!n s1ste. :EIS;-tier software runs on the ES server
Figure 2.1 Distributed multitiered applications
Although a Java EE application can consist of the three or four tiers shown in figure 2.1, Java
EE multitiered applications are generally considered to be three-tiered applications because they
are distributed over three locations: client machines, the Java EE server machine, and the
database or legacy machines at the back end. Three-tiered applications that run in this way
extend the standard two-tiered client and server model by placing a multithreaded application
server between the client application and back-end storage.
2.( #a+a EE $!.&!nents
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.
7
2 - java platform, enterprise edition
Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components
are web components that run on the server.
Enterprise JavaBeansTM (EJB) components (enterprise beans) are business components
that run on the server.
Java EE components are written in the Java programming language and are compiled in the
same way as any program in the language. The difference between Java EE components and
"standard Java classes is that Java EE components are assembled into a Java EE application,
are verified to be well formed and in compliance with the Java EE specification, and are deployed
to production, where they are run and managed by the Java EE server.
2.* 3a+a EE C'ients
A Java EE client can be a web client or an application client.
2.*.1 Web C'ients
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.
2.*.2 A&&'ets
A web page received from the web tier can include an embedded applet. An applet is a small
client application written in the Java programming language that executes in the Java virtual
machine installed in the web browser. However, client systems will likely need the Java Plug-in
and possibly a security policy file in order for the applet to successfully execute in the web
browser.
Web components are the preferred AP for creating a web client program because no plug-ins
or security policy files are needed on the client systems. Also, web components enable cleaner
and more modular application design because they provide a way to separate applications
programming from web page design. Personnel involved in web page design thus do not need to
understand Java programming language syntax to do their jobs.
2.*.% A&&'i$ati!n C'ients
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. t typically has a
graphical user interface (GU) created from the Swing or the Abstract Window Toolkit (AWT) AP,
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 5 servers, enabling the Java EE 5 platform
to interoperate with legacy systems, clients, and non-Java languages.
8
2 - java platform, enterprise edition
2.*.( The 3a+aBeans C!.&!nent Ar$hite$tre
The server and client tiers might also include components based on the JavaBeans component
architecture (JavaBeans components) to manage the data flow between an application client or
applet and components running on the Java EE server, or between server components and a
database. JavaBeans components are not considered Java EE components by the Java EE
specification.
JavaBeans components have properties and have get and set methods for accessing the
properties. JavaBeans components used in this way are typically simple in design and
implementation but should conform to the naming and design conventions outlined in the
JavaBeans component architecture.
2.*.* 3a+a EE Ser+er C!..ni$ati!ns
Figure 2.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. n
deciding which one to use, you should be aware of the trade-offs between keeping functionality on
the client and close to the user (thick client) and off-loading as much functionality as possible to
the server (thin client). The more functionality you off-load to the server, the easier it is to
distribute, deploy, and manage the application; however, keeping more functionality on the client
can make for a better perceived user experience.

Figure 2.2 Server communication
2., Web C!.&!nents
Java EE web components are either servlets or pages created using JSP technology (JSP
9
2 - java platform, enterprise edition
pages) and/or JavaServer 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. JavaServer
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, like HTML pages, 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.
2.- Bsiness C!.&!nents
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 2.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 2.3 Web, Business and ES Tiers
10
2 - java platform, enterprise edition
2.0 enter&rise in"!r.ati!n s1ste. tier
The enterprise information system tier handles ES 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.
2.4 #a+a EE C!ntainers
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. n 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.
2.4.1 C!ntainer Ser+i$es
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 nterface (JND) 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.
JND 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 APs.
11
2 - java platform, enterprise edition
2.4.2 C!ntainer T1&es
The deployment process installs Java EE application components in the Java EE containers
illustrated in figure 2.4.

Figure 2.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.
2.15 s&&!rt "!r web ser+i$es
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
APs 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
12
2 - java platform, enterprise edition
platforms.
To write web services and clients with the Java EE XML APs, 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 AP 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 APs fully interoperable. This does not necessarily mean
that the 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.
2.15.1 <2L
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.
2.15.2 SOA6 Trans&!rt 6r!t!$!'
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 nternet. HTTP
is a familiar request-and response standard for sending messages over the nternet, 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
ncludes 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
2.15.% WSDL Standard 8!r.at
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 UDD
registries or published on the web (or both). The Sun Java System Application Server Platform
13
2 - java platform, enterprise edition
Edition 8 provides a tool for generating the WSDL specification of a web service that uses remote
procedure calls to communicate with clients.
2.15.( =DDI and eb<2L Standard 8!r.ats
Other XML-based standards, such as Universal Description, Discovery and ntegration (UDD)
and ebXML, make it possible for businesses to publish information on the nternet about their
products and web services, where the information can be readily and globally accessed by clients
who want to do business.
2.11 #a+a EE * $!re te$hn!'!gies and A6Is
Figure 2.4 illustrates the availability of the Java EE 5 platform APs in each Java EE container
type. The following sections give a brief summary of the technologies required by the Java EE
platform, and the APs used in Java EE applications.
Figure 2.5 Java EE Platform APs
2.11.1 Enter&rise 3a+aBeans Te$hn!'!g1
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 message listener, allowing a business component to receive messages asynchronously.
Commonly, these are Java Message Service (JMS) messages.
n Java EE 5, entity beans have been replaced by Java persistence AP entities. An entity
14
2 - java platform, enterprise edition
represents persistent data stored in one row of a database table. f the client terminates, or if the
server shuts down, the persistence manager ensures that the entity data is saved.
2.11.2 3a+a Ser+'et Te$hn!'!g1
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.
2.11.% 3a+aSer+er 6ages Te$hn!'!g1
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.
2.11.( 3a+aSer+er 6ages Standard Tag Librar1
The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to
many JSP applications. nstead 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.
2.11.* 3a+aSer+er 8a$es
JavaServer Faces technology is a user interface framework for building web applications. The
main components of JavaServer Faces technology are as follows:
A GU 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 GU components:
nput validation
Event handling
Data conversion between model objects and components
Managed model object creation
Page navigation configuration
All this functionality is available via standard Java APs and XML-based configuration files.
2.11., 3a+a 2essage Ser+i$e A6I
The Java Message Service (JMS) AP is a messaging standard that allows Java EE application
components to create, send, receive, and read messages. t enables distributed communication
that is loosely coupled, reliable, and asynchronous.
15
2 - java platform, enterprise edition
2.11.- 3a+a Transa$ti!n A6I
The Java Transaction AP (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
AP to demarcate where the entire transaction, including both operations, begins, rolls back, and
commits.
2.11.0 3a+a2ai' A6I
Java EE applications use the JavaMail AP to send email notifications. The JavaMail AP 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 nternet mail.
2.11.4 3a+aBeans A$ti+ati!n 8ra.ew!r>
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.
2.11.15 3a+a A6I "!r <2L 6r!$essing
The Java AP for XML Processing (JAXP), part of the Java SE platform, supports the
processing of XML documents using Document Object Model (DOM), Simple AP 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.
2.11.11 3a+a A6I "!r <2L Web Ser+i$es :3A<-WS;
The JAX-WS specification provides support for web services that use the JAXB AP for binding
XML data to Java objects. The JAX-WS specification defines client APs 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. t 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. n 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
JND java:comp/env namespace as their associated component. Custom serializers and
deserializers, if supported, are treated in the same way as message handlers.
2.11.12 3a+a Ar$hite$tre "!r <2L Binding :3A<B;
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
16
2 - java platform, enterprise edition
AP.
2.11.1% SOA6 with Atta$h.ents A6I "!r 3a+a
The SOAP with Attachments AP for Java (SAAJ) is a low-level AP 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
AP, instead using the higher-level JAX-WS AP.
2.11.1( 3a+a A6I "!r <2L 9egistries
The Java AP 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 UDD specifications. By using JAXR, developers can learn a single AP 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.
2.11.1* 32EE C!nne$t!r Ar$hite$tre
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 ES.
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 ESs that
can be either synchronous or asynchronous. Existing applications and ESs 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
(EA) and end-to-end business integration.
2.11.1, 3a+a Database C!nne$ti+it1 A6I
The Java Database Connectivity (JDBC) AP lets you invoke SQL commands from Java
programming language methods. You use the JDBC AP in an enterprise bean when you have a
session bean access the database. You can also use the JDBC AP from a servlet or a JSP page
to access the database directly without going through an enterprise bean.
The JDBC AP 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.
2.11.1- 3a+a 6ersisten$e A6I
The Java Persistence AP 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 AP
The query language
17
2 - java platform, enterprise edition
Object/relational mapping metadata
2.11.10 3a+a Na.ing and Dire$t!r1 Inter"a$e
The Java Naming and Directory nterface (JND) 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 NS (Network nformation services). t provides applications with
methods for performing standard directory operations, such as associating attributes with objects
and searching for objects using their attributes. Using JND, a Java EE application can store and
retrieve any type of named Java object, allowing Java EE applications to coexist with many
legacy applications and systems.
Java EE naming services provide application clients, enterprise beans, and web components
with access to a JND 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 JND naming
context.
A Java EE component can locate its environment naming context using JND 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 ser!ransaction 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 #ataSo$rce
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/ej%, and JDBC #ataSo$rce references in the subcontext
java:comp/env/jd%c.
2.11.14 3a+a Athenti$ati!n and Ath!ri?ati!n Ser+i$e
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.
2.11.25 Si.&'i"ied S1ste.s Integrati!n
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 performance, better tools, or better customer support.
The Java EE 5 APs 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
18
2 - java platform, enterprise edition
Simplified interoperability with the J2EE Connector architecture
Easy database connectivity with the JDBC AP
Enterprise application integration with message-driven beans and JMS, JTA, and JND
2.12 #a+a EE a&&'i$ati!n asse.b'1 and de&'!1.ent
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 platform's 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 de&'!1.ent des$ri&t!r
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.
Figure 2.6 EAR file structure
There are two types of deployment descriptors: Java EE and runtime. A 3a+a EE de&'!1.ent
des$ri&t!r is defined by a Java EE specification and can be used to configure deployment
19
2 - java platform, enterprise edition
settings on any Java EE-compliant implementation. A rnti.e de&'!1.ent des$ri&t!r 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 application's resources
to the server's resources, and Application Server implementation-specific parameters, such as
caching directives. The Application Server runtime deployment descriptors are named s$n&
moduleType.xml and are located in the same M'!(&I)* directory as the Java EE deployment
descriptor.
A 3a+a EE .!d'e 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-a'!ne 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, GF 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 ES. Resource adapter modules are packaged as JAR files with an .rar
(resource adapter archive) extension.
20
3 - communication
% - CO22=NICATION
%.1 $!..ni$ati!n &r!t!$!'s
A $!..ni$ati!n &r!t!$!' is a set of rules that the end points in a telecom link use when they
communicate.
A protocol is specified in an industry or international standard. All internet related protocols are
defined within the frame of ETF (Internet Engineering Tas> 8!r$e) via a mechanism called
RFC (9e@est 8!r C!..ents).
Each (potential) protocol is defined by such a document. For a comprehensive list of all the
RFCs, check the official site www.ietf.org (which present the RFCs in .txt format) or www.cis.ohio-
state.edu/cgi-bin/rfc (which presents the RFCs in .html format, with up to date links embedded in
the documents).
%.2 the OSI .!de'
OS stands for O&en S1ste. Inter$!nne$ti!n, an SO (nternational Standard Organization)
standard for worldwide communications that defines a structured framework for implementing
protocols in seven layers. Control is passed from one layer to the next, starting at the application
layer at the source node, proceeding to the lower layers, over the links to the next node and back
up the hierarchy until the destination node is reached. The structure of the message which is the
object of this exchange gets modified along the way, each step down into the layer hierarchy
adding a new wrapper around the existing message (usually, consisting of a protocol specific
header), while each step up removes the wrapper specific to the layer below.
The seven layers in the OS model are:
Nr. Layer Description Protocol examples
1 Application Supports application and end user
processes. Provides application
services for file transfers, e-mail and
other network software services.
DHCP, DNS, FTP, Gopher,
HTTP, MAP4, POP3, SMTP,
SNMP, TELNET, TSL (SSL),
SOAP
2 Presentation Translates data from application to
network format and vice-versa. May
also provide compression and
encryption services.
APF, CA, LPP, NCP,
NDR, XDR, X.25 PAD
3 Session Sets up, manages and terminates
connections between communication
partners. t handles session and
connection coordination.
ASP, NetBOS, PAP,
PPTP, RPC, SMPP, SSH,
SDP
4 Transport Provides data transfer between the
end points of the communication
partners and is responsible for error
recovery and flow control.
DCCP, SCTP, TCP, UDP,
WTLS, WTP, XTP
21
3 - communication
5 Network Responsible for source to destination
delivery of packages, including routing
through intermediate nodes. Provides
quality of service and error control.
DDP, CMP, PSec, Pv4,
Pv6, PX, RP
6 Data Link Transfers data between adjacent
network nodes and handles errors
occurred at the physical level
ARCnet, ATM, CDP,
Ethernet, Frame Relay,
HDLC, Token Ring
7 Physical Translates communication requests
from the data link layer into
transmissions and receptions of
electronic signals at hardware level.
10BASE-T, DSL, Firewire,
GSM, SDN, SONET/SDH,
V.92
For a detailed description of these layers, check the site:
http://www.geocities.com/SiliconValley/Monitor/3131/ne/osimodel.html .
%.% the i& &r!t!$!'
P (or nternet Protocol) is a network level protocol used for communicating data across a
packet switched network using the nternet Protocol Suite - also known as the TCP/P suite. t was
specified in RFC 1122 and subject to subsequent changes RFC 1349 and RFC 4379. The P
addresses come in two flavors, as defined in by the two versions of the nternet Protocol currently
in use, version 4 and version 6.
Version 4 P addresses are 32 bits long and are represented as a sequence of 4 8-bit integers,
dot separated, ranging from 0 to 255, like 193.231.200.67. This version is still the dominating one,
although the next field version of the protocol, version 6. Version 5 of the protocol was actually a
UNX based, experimental, non-P, streaming protocol, called ST2, described in RFC 1819. P
version 6 was initially specified in RFC 2460 (12.1998) and was the subject of several subsequent
RFCs (2461-2467, 2893, 3513, 4294, .). t provides a much larger address space (roughly 2^128
different addresses and new features, like stateless address configuration and prefix and router
announcements.
Although version 6 is implemented by all major operating system, no country has a penetration
level above 1% yet.
%.( the i& header
The format of the version 4 header is presented bellow.
00-03 04-07 08-11 12-15 16-19 20-23 24-27 28-31
Version HL Differentiated service Total length
dentification Flags Fragment offset
TTL Protocol Header checksum
Source P address
Destination P address
22
3 - communication
Options and padding
Data
The P version 4 datagram header
Surprisingly enough, version 6 of the protocol exhibits a simplified header.
00-03 04-07 08-11 12-15 16-19 20-23 24-27 28-31
Version Traffic class Flow level
Payload length Next header Hop limit
Source address
Destination address
Data
The P version 6 datagram header
%.* ser datagra. &r!t!$!' - d&
UDP is a transport level protocol which allows the communicating entities to send and receive
messages without requiring prior communications to set up special transmission channels or data
paths. The protocol was designed in 1980 and is the object of RFC 768.
UDP uses a simple transmission model without the typical hand-shaking dialogues for
guaranteeing reliability, ordering, or data integrity. That means that data may or not arrive at the
destination, that it may be duplicated or that it may arrive in the wrong order. And all these things
could happen without notice. However, the need for speed and a better success rate in extreme
situations and its availability in raw environments make UDP a viable alternative to the more
sophisticated TCP protocol. So expect to see UDP in the initial stages of a booting process, in
network management applications, streaming videos and gaming, or just whenever the
communicating entities are not that far apart and the reliability of the link is presumed.
%., the d& header
00-03 04-07 08-11 12-15 16-19 20-23 24-27 28-31
Source port Destination port
Length Checksum
Data
The User Datagram Protocol header
23
3 - communication
%.- trans.issi!n $!ntr!' &r!t!$!' - t$&
The beginnings of TCP date back to 1974, when Vint Cerf and Bob Kahn published an article
called "A Protocol for Pacet !etwor "nterconnection#$ in which they described an
internetworking protocol based on packet-switching among the nodes of the network. At its core, it
had a Transmission Control Program that incorporated both connection-oriented links and
datagram services between hosts. The monolithic Transmission Control Program was later split
into two components consisting of the Transmission Control Protocol at the connection-oriented
layer and the "nternet Protocol at the internetworking (datagram) layer. The model became later
known informally as TCP%"P, although formally it was henceforth called the "nternet Protocol Suite.
TCP provides a communication service at an intermediate level between an application
program and the nternet Protocol (P). That is, when an application program desires to send a
large chunk of data across the nternet using P, instead of breaking the data into P-sized pieces
and issuing a series of P requests, the software can issue a single request to TCP and let TCP
handle the P details.
P works by exchanging pieces of information called packets. A packet is a sequence of bytes
and consists of a header followed by a body. The header describes the packet's destination and,
optionally, the routers to use for forwarding until it arrives at its final destination. The body
contains the data which P is transmitting.
Due to network congestion, traffic load balancing, or other unpredictable network behavior, P
packets can be lost or delivered out of order. TCP detects these problems, requests
retransmission of lost packets, rearranges out-of-order packets, and even helps minimize network
congestion to reduce the occurrence of the other problems. Once the TCP receiver has finally
reassembled a perfect copy of the data originally transmitted, it passes that datagram to the
application program. Thus, TCP abstracts the application's communication from the underlying
networking details.
%.0 The TC6 header
00-03 04-05 06-08 10-15 16-19 20-23 24-27 28-31
Source port Destination port
Sequence number
Acknowledgment number
Data offset reserved ECN Control bits Window
Checksum Urgent pointer
Options and padding
Data
The TCP header
24
3 - communication
%.4 wh!As riding the t$&Bi& eC&ress
Almost everybody. Some notable exceptions, though. Since quality and reliability comes at a
price, UDP is actually used where speed matters and also where the infrastructure required by the
TCP stack is either missing or not worth the price. Let's mention some of these areas:
network management the favorite network management protocol (SNMP) is built on top
of UDP/P.
streaming media (audio, video or gaming).
protocols like DHCP, BOOTP or TFTP use UDP as transport protocol mainly because the
system is in a pre-P state.
%.15 s!$>ets - basi$s
Although the socket concept covers a variety of cases, like Unix sockets (end-point(s) in local
interprocess communication) or end-point of a bi-directional communication link in the Berkeley
sockets, we will limit ourselves, within the scope of this book, to the most used variety, namely
internet sockets. An (internet) s!$>et is a logical entity which describes the end point(s) of a
communication link between two P entities (entities which implement the nternet Protocol).
Sockets are identified by the P address and the port number.
P addresses come in two flavors, as defined in by the two versions of the nternet Protocol
currently in use, version 4 and version 6.
Version 4 P addresses are 32 bits long and are represented as a sequence of 4 8-bit integers,
dot separated, ranging from 0 to 255, like 193.231.200.67.
Version 6 P addresses are 128 bits long and are represented by a sequence of eight 16-bit
integers, separated by columns (:). An example - 2008:0CB8:85A4:0000:0000:8F2C:0371:7714.
Port numbers range from 0 to 65535 (2^16 1) and are split into 3 categories:
1. we'' >n!wn &!rts - ranging from 0 to 1023 these ports are under the control of ANA
(nternet Assigned Number Authority), a selective list is shown in the table below:
Port
number
UDP protocol TCP protocol Other
1 TCPMUX
5 Remote Job Entry (RJE)
7 Echo
15 NETSTAT
20 FTP - data
21 FTP control
22 Secure Shell
23 Telnet
25 Simple Mail Transfer Protocol (SMTP)
41 Graphics
25
3 - communication
42 ARPA Host Name Server Protocol WNS
43 WHOS
53 Domain Name System (DNS)
57 Mail Transfer Protocol (MTP)
67 BOOTP
68 BOOTP
69 TFTP
79 Finger
80 HTTP
107 Remote Telnet
109 Post Office Protocol 2 (POP2)
110 POP3
115 Simple FTP (SFTP)
118 SQL services
123 Network Time Protocol (NTP)
137 NetBOS Name Service
138 NetBOS Datagram Service
139 NetBOS Session Service
143 nternet Message Access Protocol (MAP)
156 SQL service
161 Simple Network Management Protocol (SNMP)
162 SNMP Trap
179 Border Gateway Protocol (BGP)
194 nternet Relay Chat (RC)
213 PX
2. registered &!rts - ranging from 1024 to 49151 registered by CANN, as a convenience
to the community, should be accessible to ordinary users. A list of some of these ports is
shown below:
Port
number
UDP protocol TCP protocol Other
1080 SOCKS proxy
1085 WebObjects
1098 RM activation
1099 RM registry
1414 BM WebSphere MQ
1521 Oracle DB default listener
26
3 - communication
2030 Oracle services for Microsoft Transaction Server
2049 Network File System
2082 CPanel default
3306 MySQL DB system
3690 Subversion version control system
3724 World of Warcraft online gaming
4664 Google Desktop Search
5050 Yahoo Messenger
5190 CQ and AOL M
5432 PostgreSQL DB system
5500 VNC remote desktop protocol
5800 VNC over HTTP
6000/6001 X11
6881-6887 BitTorrent
6891-6900 Windows Live Messenger File transfer
6901 Windows Live Messenger Voice
8080 Apache Tomcat
8086/8087 Kaspersky AV Control Center
8501 Duke Nukem 3D
9043 WebSphere Application Server
14567 Battlefield 1942
24444 NetBeans DE
27010/270
15
Half-Life, Counter-Strike
28910 Nintendo Wi-Fi Connection
33434 traceroute
3. d1na.i$ :&ri+ate; &!rts, ranging from 49152 to 65535
%.11 &!siC s!$>ets
The socket APs (Application Programming nterface) are rooted into the POSX socket AP.
POSX stands for Portable Operating System nterface a common name for a set of EEE
standards used to define APs. This family of standards dates back to 1988 and is identified as
EE 1003 or SO/EC 9945.
The socket communication is, in general, asymmetric. One of the two communicating entities
plays the role of a ser+er. The server listens for incoming requests at a certain port. This port
number is public, and together with the P address identifies the server. The actual
communication is initiated by the $'ient/ who sends a connection request to the server. f the
connection request s accepted, the server creates (in general) another socket, which is dedicated
27
3 - communication
to the communication with that particular client. The closure of this communication link can be
initiated by either the client or by the server.
To create a client socket, two calls are necessary. The first one creates a file descriptor (fd)
which is basically a number which identifies an /O channel (not different from the file descriptor
resulted from a fopen() call which opens a file).
The prototype of this call is the following:
int socket(int family, int type, int protocol);
The "a.i'1 parameter specifies the address family of the socket and may take one of the
following values, the list itself depending on the implementation platform:
AF_APPLETALK
AF_NET most used, indicates an P version 4 address
AF_NET6 - indicates an P version 6 address
AF_PX
AF_KEY
AF_LOCAL
AF_NETBOS
AF_ROUTE
AF_TELEPHONY
AF_UNSPEC
The t1&e parameter specifies the socket stream type and may take the following values:
S+CK,#-RM . the transport level protocol is UDP
S+CK,S!R'(M . the transport level protocol is TCP
S+CK,R(/ & used to generate/receive packets of a type that the kernel doesn't
explicitly support
The value of the &r!t!$!' parameter is set to 0, except for raw sockets.
The second call connects the client to the server. Here is the signature of the connect01 call.
int connect(int sock_fd, struct sockaddr * server_addr, int addr_len);
The soc2addr structure varies depending on the protocol selected. For reference purposes,
let's display it, together with another associated structure soc2addr,in3 both used in the
context of Pv4.
struct sockaddr {
ushort sa_family;
28
3 - communication
char sa_data[14];
};
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
Both structures have the same size and have compatible content, therefore casting is allowed.
To create a server socket, four calls are necessary. Here are the prototypes of these calls:
int socket(int family, int type, int protocol);
int bind(int sock_fd, struct sockaddr * my_addr, int addr_len);
int listen(int sock_fd, int backlog);
int accept(int sock_fd, struct sockaddr * client_addr, int * addr_len);
The %ind01 function merely associates the socket to a specified port, while the listen01
function sets the server in listening mode. The function accept() is invoked as result of a
connection request from a client.
A few remarks. Why not binding the client socket to a particular port, as well? Well, nobody
stops us from invoking the bind() function on a client socket, but this is not exactly relevant. While
the server port has to be known, because the client must know both the P address (or the URL, if
that is the case) and the port of the server, it is not important to know the port of the client. The
assignment of a port to a client socket is done by the operating system, and this solution is quite
satisfactory.
29
4 - HTTP
( - HTT6
(.1 what is htt&
HTTP stands for HyperText Transfer 6rotocol while h1&erteCt means text containing links to
another text. HTTP was created by by Tim Berners-Lee in 1990 at CERN as a mean to store
scientific data. t quickly evolved into the preferred communication protocol over the internet.
The first oficial version HTTP 1.0 dates from 05/95 and is the object of RFC 1945
(www.cis.ohio-state.edu/cgi-bin/rfc/rfc1945.html). t is authored by Tim Berners-Lee, Roy Fielding
and Henrik Nielsen.
The second (and last, so far) 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 .
(.2 the str$tre !" htt& transa$ti!ns
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 line4
Header1: value1
...
Headern: valuen
<optional data block>
(.% the initia' re@est 'ine
Contains 3 elements, separated by spaces:
a $!..and (method) name (like GET, POST, HEAD, ...)
a file specification (&ath) (the part of the URL after the host name)
30
4 - HTTP
the HTTP +ersi!n (usually, HTTP/1.0).
Here is an example of an initial request line:
GET /path/to/the/file/index.html HTTP/1.0
(.( htt& $!..ands :.eth!ds;
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. OPTONS
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:
LNK
UNLNK
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.
(.* the GET and 6OST .eth!ds
The GET method means retrieve whatever information (in the form of an entity) is identified by
the Request-UR. f the Request-UR 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-UR in the Request-Line.
POST is designed to allow a uniform method to cover the following functions:
- Annotation of existing resources;
- Posting a message to a bulletin board, newsgroup, mailing list,
31
4 - HTTP
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-UR. The posted entity is subordinate to that UR 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 UR. n 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.
(., di""eren$es between GET and 6OST
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&5orm&$rlencoded content type), or in the message
body, (encoded as m$ltipart/5orm&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.
(.- the initia' res&!nse :stats; 'ine
Contains 3 elements, separated by spaces (although the reason phrase may contain spaces, as
well):
the HTTP +ersi!n of the response
a response stats $!de (a number)
a response status reas!n &hrase (a human readable response status)
Here is an example of an initial response line:
6!!7/8.9 :9: )ot *o$nd
(.0 the stats $!de
A three-digit integer, where the first digit identifies the general category of response:
1CC indicates an informational message only
32
4 - HTTP
2CC indicates success of some kind
%CC redirects the client to another URL
(CC indicates an error on the client's part
*CC indicates an error on the server's part
The most common status codes are:
255 OD - the request succeeded, and the resulting resource (e.g. file or script output) is
returned in the message body.
(5( N!t 8!nd - the requested resource doesn't exist.
%51 2!+ed 6er.anent'1
%52 2!+ed Te.&!rari'1
%5% See Other (HTTP 1.1 only) - the resource has moved to another URL (given by the
L!$ati!nE response header), and should be automatically retrieved by the client. This is
often used by a CG script to redirect the browser to an existing file.
*55 Ser+er Err!r - 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).
(.4 header 'ines
A header line consists of two parts, header na.e and header +a'e, 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.
(.15 the .essage b!d1
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. n a request, this is where user-entered data
or uploaded files are sent to the server.
f an HTTP message includes a body, the header lines of the message are used to describe the
body. n particular,
the C!ntent-T1&eE header gives the MME-type of the data in the body, such as teCtBht.'
or i.ageB#&g.
the C!ntent-LengthE header gives the number of bytes in the body.
33
4 - HTTP
(.11 .i.e t1&esBsbt1&es
MME stands for Multipurpose nternet Mail Extensions. Each extension consists of a type and
a subtype. RFC 1521 (www.cis.ohio-state.edu/cgi-bin/rfc/rfc1521.html) defines 7 types and
several subtypes, 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. teCt, with subtype plain
2. .'ti&art, with subtypes mixed, alternative, digest, parallel
3. .essage, with subtypes rfc822, partial, external-body
4. a&&'i$ati!n, with subtypes octet-stream, postscript
5. i.age, with subtypes jpeg, gif
6. adi!, with subtype basic
7. +ide!, with subtype mpeg
(.12 an eCa.&'e !" an htt& transa$ti!n
To retrieve the file at the URL
http://web.info.uvt.ro/path/file.html
first open a socket to the host web.in"!.+t.r!, 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)
.
.
34
4 - HTTP
.
</body>
</html>
After sending the response, the server closes the socket.
35
5 - HTML
* - HT2L
*.1 what is ht.'F
HTML stands for HyperText 2arkup 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 (www.cis.ohio-state.edu/cgi-bin/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 newest version of HTML is 4.01. t is a revision of 4.0 and was accepted in December
1997. However, a working draft for a new version, namely HTML 5 was published in June 2008.
From 1999 on, HTML is part of a new specification XHTML. The XHTML 1.0 draft was
released in 01.99. The latest version (XHTML 2.0) dates from 08.02 and is not intended to be
backwards compatible.
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 .
*.2 'angage de"initi!n
HTML is a system for describing documents. t is a special version of SGML (Standard
Generalized Markup Language an SO standard (SO 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.
;<S-ML =IS+ >>?@:8@>A=
&&
S-ML #eclaration 5or 6Bper!ext Mar2$p Lang$age version 6!ML :.98

/ith s$pport 5or the 5irst 8? planes o5 IS+ 89A:A and increased
limits 5or tag and literal lengths etc.
&&

C6(RS'!
C(S'S'! =IS+ Registration )$m%er 8??//C6(RS'!
IS+/I'C 89A:A&8:8@@3 CS&: with
implementation level 3//'SC D/E D/8E :/A=
#'SCS'! 9 @ )S'#
@ D @
88 D )S'#
36
5 - HTML
83 8 83
8: 8> )S'#
3D @E 3D
8D? 8 )S'#
8D> 3D )S'#
8A9 EE83A 8A9
EED@A D9:> )S'# && SRR+-(!'S &&
E?3:: 89EA?A> E?3::
C(7(CI!F S-MLR'*
!+!(LC(7 8E9999
-R7C(7 8E9999
')!C(7 8E9999
SC+7' #+CM')!
SF)!(X
S6)C6(R C+)!R+LS 9 8 D 3 : E A ? > @ 89 88 8D 83 8: 8E 8A
8? 8> 8@ D9 D8 DD D3 D: DE DA D? D> D@ 39 38 8D?
C(S'S'! =IS+ A:AIRG:8@@8//C6(RS'!
International Re5erence Gersion
0IRG1//'SC D/> :/D=
#'SCS'! 9 8D> 9
*)C!I+)
R' 83
RS 89
S7(C' 3D
!(C S'7C6(R @
)(MI)- LC)MS!R! ==
C)MS!R! ==
LC)MC6(R =.&,:=
C)MC6(R =.&,:=
)(M'C(S' -')'R(L F'S
')!I!F )+
#'LIM -')'R(L S-MLR'*
S6+R!R'* S-MLR'*
)(M'S S-MLR'*
H()!I!F S-MLR'*
(!!C)! A9 && increased &&
(!!S7L') AEE3A && !hese are the largest val$es &&
LI!L') AEE3A && permitted in the declaration &&
)(M'L') AEE3A && (void 5ixed limits in act$al &&
7IL') AEE3A && implementations o5 6!ML (Is &&
!(-LGL 899
!(-L') AEE3A
-R7-!C)! 8E9
-R7C)! A:
*'(!R'S
MI)IMIJ'
#(!(!(- )+
+MI!!(- F'S
R()K )+
S6+R!!(- F'S
LI)K
SIM7L' )+
IM7LICI! )+
'X7LICI! )+
37
5 - HTML
+!6'R
C+)CR )+
SC#+C )+
*+RM(L F'S
(77I)*+ )+)'
4
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. f 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.
*.% ht.' e'e.ents
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
element. An example:
;IM- SRCKL/images/logo.gi5L (L!KLlogoL 6'I-6!K:9 /I#!6K8D94
declares an image element3 with the reM$ired 0mandatorB1
attri%$tes SRC and (L! and the optional attri%$tes 6'I-6! and
/I#!6. +ther optional attri%$tes o5 the ;IM-4 element3 li2e
(LI-)3 C+R#'R3 C+)!R+LS3 #F)SRC3 N3 GS(7C' are omitted.
A comment section in an HTML document starts with <!-- and end at the first occurrence of -->.
An example:
<!-- acesta este un comentariu. <><> -->
38
5 - HTML
*.%.1 The GAH e'e.ent
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:
;( 6R'*KLhttp://we%.in5o.$vt.ro/we%mail/src/login.phpL4Login to
we% mail;/(4
*.%.2 The GI2GH e'e.ent
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
HEGHT
WDTH
*.( the .ini.a' str$tre !" an ht.' d!$.ent
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:
;6!ML4
;6'(#4MB 7age
;/6'(#4
;C+#F4'mptB CodB
;/C+#F4
;/6!ML4
*.* tab'es
A table is a visual rectangular object consisting of several r!ws and $!'.ns. The intersection
of any row and any column is called a $e''. Usually, the cells in the first row contain are called
39
5 - HTML
headers and consist of a brief description of the content of the corresponding column. Here is a
an example of a table:
*., tab'e re'ated e'e.ents
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 GTABLEH e'e.ent
attributes:
BORDER
CELLSPACNG
CELLPADDNG
WDTH
ALGN
VALGN
TBODY
BORDERCOLOR
FRAME
RULES
COLORGROUP
BACKGROUND
the GTHEADH e'e.ent
attributes:
ALGN
BGCOLOR
CHAR
CHAROFF
VALGN
the GTHH e'e.ent
attributes:
ABBR
AXS
CHAR
CHAROFF
HEADERS
40
5 - HTML
SCOPE
the GT9H e'e.ent
attributes:
ALGN
BGCOLOR
CHAR
CHAROFF
VALGN
the GTDH e'e.ent
attributes:
ABBR
ALGN
CHAR
CHAROFF
COLSPAN
ROWSPAN
SCOPE
VALGN
WDTH
*.- "!r.s
A form is a basic component container, allowing user input and paarmeter submittal.
The <FORM> element has the following attributes:
ACTON - 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:
&P'ST&- sends the form values in 2 steps: contacts first the server then the form values are
sent in a separate transmission.
&()T& - 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://we%.in5o.$vt.ro/servlet/MBServletOaK8DP%KDE
ENCTYPE - specifies the encoding type of the of the form content. Default value:
41
5 - HTML
"application%x-www-form-urlencoded" - the default value; however, since it converts spaces
to '+' and non-alphanumerical to '%HH', where 'HH' is the hexadecimal ASC 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&
*.0 "!r. re'ated e'e.ents
*.0.1 the GIN6=TH e'e.ent
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", "checbox", "radio", "submit", "image", "reset", "button",
"hidden", "file".
NAME - required, specifies the parameter name.
*.0.2 the GSELECTH e'e.ent
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 OPTON element.
Main attributes:
NAME
MULTPLE - if specified, allows multiple selections from the choice list.
SZE - maximum number of options visible to the user.
*.0.% the GO6TIONH e'e.ent
Used inside a <SELECT> element to list the selection choices. Main attributes:
SELECTED
Example of a <SELECT> element:
;S'L'C! )(M'K=action= S!FL'K=5ont&5amilB: IQ(rial nicode
MSI 5ont&siRe: 88pt=4
;+7!I+) S'L'C!'#4Select (ction
;+7!I+)4Ma2e 7aBment
;+7!I+)4!rans5er a %alance
;+7!I+)4Change Mailing (ddress
42
5 - HTML
;+7!I+)4Change e&mail (ddress
;+7!I+)4Change ser )ame/7assword
;+7!I+)4Giew (cco$nt (ctivitB
;/S'L'C!4
43
6 - JAVA PRMER
, - 3A7A 69I2E9
,.1 hist!r1
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, nc.) 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 of Java 2 Platform
Enterprise Edition is J2EE 1.4 Update 1.
,.2 #a+a the inter&reter/ #it
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 &r!g1.#a+a. The java compiler (javac) translates it to bytecode &r!g1.$'ass. The
#a+a inter&reter (as part of the JVM) parses and executes the prog1.class file.
n 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 3ust 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 ;path4
&so$rcepath ;path4
&d ;directorB4 : specifies where to put the .class file.
&g : generate all debugging info.
One example of command line compilation:
javac -classpath *+C,-T.-mySource+C,-T.-myPacages -g login*/ava
,.% #a+a a&&'i$ati!ns
44
6 - JAVA PRMER
There exist 2 types of programs that can be written in Java. The first type are embedded in web
pages a&&'ets, the others are the standalone programs Java a&&'i$ati!ns.
A java a&&'et is a java class that extends the standard Applet class.
n 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
WDTH
HEGHT
A java a&&'i$ati!n 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:
p$%lic static void main0StringST args1
A compiled java application (class) may be executed from the command line using an
executable called java (the java interpreter), as follows:
java S&optionsT class SargsT
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 S&optionsT jar5ile SargsT
,.( !b#e$t !riented $!n$e&ts
,.(.1 en$a&s'ati!n
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.
,.(.2 inheritan$e
Inheritan$e is a partial order relation in the set of all Java classes. A Java class B inherits
another class A (or is a sb$'ass of A, or is deri+ed from A, or that it eCtends A). This binary
relation is specified in the declaration of the derived class B using the keyword extends. An
example:
45
6 - JAVA PRMER
p$%lic class CaineCom$nitar extends Caine
U
N
V
n 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
!+erride 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). n fact, all classes in Java are (by default) subclasses of a universal base class, called
'b/ect. Therefore, the forest we mentioned is actually a tree, with the root the class 'b/ect.
,.(.% 6!'1.!r&his.
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.
,.(.( 2eth!d !+er'!ading
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. n OO jargon, this is called .eth!d !+er'!ading.
,.* #a+a as &r!gra..ing 'angage
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: 0yte$ Short$
"nteger$ 1ong$ Float$ 2ouble$ 0oolean$ Character.
Other peculiarities: no pointers (only references), automatic garbage collection, no templates.
46
6 - JAVA PRMER
,., a$$ess s&e$i"iers and .!di"iers in #a+a
The access attributes of a member variable or method of a class are specified by the a$$ess
s&e$i"iers. 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
&b'i$ - access from any class anywhere
&ri+ate - no access from outside the class itself
&r!te$ted - 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
&b'i$ - the class is visible from any class, anywhere
abstra$t - the class is abstract (some of its methods (inherited or specified by some
interface) are to be implemented by some of its subclasses)
An example. The declaration:
a%stract class mB*irstClass extends javax.servlet.http.6ttpServlet
implements SerialiRa%le
{
...
}
declares an abstract class, which is visible only to the classes in the same package, which
extends the class javax.servlet.http.6ttpServlet and which implements the
SerialiRa%le interface.
The modifiers of the variables and methods of a class specify their range and stability. A stati$
variable or method is one which is implemented at class level, rather than at class instance. A
"ina' variable (method, class) is one which cannot be modified (overridden, inherited). More
precisely:
A stati$ (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 "ina':
variable - one which is constant
method - the method implementation cannot be overriden by some subclass.
class - does not have any subclasses.
47
6 - JAVA PRMER
,.- eC$e&ti!ns in #a+a
An exception signals an abnormal situation or an error in an application, due to a variety of
execution factors or due to programming errors.
n Java, an eC$e&ti!n 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
)rror and the class )xception.
,.-.1 The Err!r $'ass
Represent conditions which are not expected to be caught in our code. Therte are 3 direct
subclasses of the class Error - Thread2eath$ 1inage )rror and 3irtual4achine)rror*
,.-.2 The EC$e&ti!n $'ass
Except for the 5untime)xception exceptions, all then exceptions in this category must be
caught in our code.
,.-.% 9nti.eEC$e&ti!n EC$e&ti!ns
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 /ava*lang package are:
ArithmeticException
ndexOutOfBoundException
NegativeArraySizeException
NullPointerException
ArrayStoreException
ClassCastException
llegalArgumentException
SecurityException
llegalMonitorStateException
llegalStateException
UnsupportedOperationException
,.-.( Hand'ing EC$e&ti!ns
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.
48
6 - JAVA PRMER
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.
,.0 #a+a &a$>ages
A Java &a$>age 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.
,.0.1 6a$>age na.es
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:
pac2age com.%an288.ccards.servletsW
import javax.sql.*;
import.java.util.Properties;
...
The name of the package is directly linked to the directory structure in which it is stored. n 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 ban66).
,.4 standard 3a+a &a$>ages
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
49
6 - JAVA PRMER
javax.accessibility
javax.swing - swing GU components (minimal dependence on native code)
java.swing.event - support for event handling
,.15 inter"a$es
An interface in Java corresponds to the abstra$t $'ass 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 inter"a$e 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.
f a class is declared as implementing an interface but omits some of its methods, it must be
declared as abstract.
50
7 - javaScript
- - 3A7ASC9I6T
-.1 s! what is 3a+aS$ri&tF
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)
-.2 what $an a 3a+aS$ri&t d!F
3a+aS$ri&t gi+es HT2L designers a &r!gra..ing t!!' - 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
3a+aS$ri&t $an &t d1na.i$ teCt int! an HT2L &age - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
3a+aS$ri&t $an rea$t t! e+ents - 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
3a+aS$ri&t $an read and write HT2L e'e.ents - A JavaScript can read and change the
content of an HTML element
3a+aS$ri&t $an be sed t! +a'idate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
3a+aS$ri&t $an be sed t! dete$t the +isit!rAs br!wser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser
3a+aS$ri&t $an be sed t! $reate $!!>ies - A JavaScript can be used to store and
retrieve information on the visitor's computer
-.% h!w and whereF
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 when a user triggers an event.
-.%.1 s$ri&ts in the head se$ti!n
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>
51
7 - javaScript
<head>
<script type="text/javascript">
....
</script>
</head>
-.%.2 s$ri&ts in the b!d1 se$ti!n
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>
-.%.% sing an eCterna' 3a+aS$ri&t
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>
-.( #a+aS$ri&t +ariab'es and eC&ressi!ns
A variable is a "container" for some information whose value can change during the script.
-.(.1 7ariab'e na.es
Rules for variable names:
Variable names are case sensitive
They must begin with a letter or the underscore character
-.(.2 +ariab'e de$'arati!n
A variable can be declared or even created with the var statement:
52
7 - javaScript
var strnum = "2157 Sunrise Blvd";
or
strnum = "2157 Sunrise Blvd";
-.(.% +ariab'e assign.ent
A value can be assigned to a variable at declaration time:
var strnum = "Morii 771"
Or just use a plain assignment:
strname = "Morii 771"
-.(.( +ariab'e t1&es
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.
-.* #a+aS$ri&t "'!w $!ntr!'
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.
-.*.1 3a+aS$ri&t 8!r...In State.ent
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.
S1ntaC
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.
ECa.&'e
Using for...in to loop through an array:
<html>
<body>
53
7 - javaScript
<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>
-.*.2 Cat$hing Err!rs
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 tr1...$at$h statement (available in E5+, Mozilla 1.0, and Netscape 6)
By using the !nerr!r event. This is the old standard solution to catch errors (available
since Netscape 3)
-.*.% Tr1...Cat$h State.ent
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.
S1ntaC
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
ECa.&'e
54
7 - javaScript
<html>
<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>
-., !&erat!rs
The only new one is the comparison operator === (equal values and same type). Also, strings
can be added (concateneted) using the + operator.
-.- &!&& b!Ces
-.-.1 a'ert B!C
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")
55
7 - javaScript
-.-.2 $!n"ir. B!C
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. f the user clicks "OK",
the box returns true. f the user clicks "Cancel", the box returns false.
Syntax:
confirm("sometext")
-.-.% &r!.&t B!C
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. f the user clicks "OK" the box returns the input value. f the user clicks "Cancel",
the box returns null.
Syntax:
prompt("sometext","defaultvalue")
-.0 "n$ti!ns
-.0.1 "n$ti!n de"initi!n
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>
f 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.
More about JavaScript events in the JS Events chapter.
The syntax for creating a function is:
56
7 - javaScript
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.
Note: A function with no parameters must include the parentheses () after the function name:
function functionname() { some code }
Note: Do not forget about the importance of capitals in JavaScript! The word function must be
written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a
function with the exact same capitals as in the function name.
-.0.2 the retrn State.ent
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 it will be stored in the variable called
product.
-.4 #a+aS$ri&t !b#e$ts
-.4.1 Ob#e$t Oriented 6r!gra..ing
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.
Note that an object is just a special kind of data. An object has properties and methods.
-.4.2 6r!&erties
Properties are the values associated with an object.
n 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>
57
7 - javaScript
The output of the code above will be:
12
-.4.% 2eth!ds
Methods are the actions that can be performed on objects.
n 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>
The output of the code above will be:
HELLO WORLD!
-.15 #a+aS$ri&t bi't in !b#e$ts
-.15.1 the String Ob#e$t
The String object is used to manipulate a stored piece of text.
6r!&erties
88: Firefox, N: Netscape, IE: nternet Explorer
Property Description F
F
N I
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

2eth!ds
Method Description F
F
N I
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
58
7 - javaScript
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 value in a string
1 2 3
italics() Displays a string in italic 1 2 3
lastndexOf() Returns the position of the last occurrence of a specified
string value, searching backwards from the specified position
in a string
1 2 3
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
string
1 4 4
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
new string
1 4 4
small() Displays a string in a small font 1 2 3
split() Splits a string into an array of strings 1 4 4
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
start index
1 4 4
substring() Extracts the characters in a string between two specified
indices
1 2 3
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
-.15.2 the Date Ob#e$t
The JavaScript Date object is used to work with dates and times.
6r!&erties
88: Firefox, N: Netscape, IE: nternet Explorer
Property Description
F
F
N
I
E
constructor Returns a reference to the Date function that created
the object
1 4 4
prototype Allows you to add properties and methods to the object 1 3 4
59
7 - javaScript
2eth!ds
Method Description
F
F
N
I
E
Date() Returns today's date and time 1 2 3
getDate() Returns the day of the month from a Date object (from
1-31)
1 2 3
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
object
1 4 4
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, 1970
1 2 3
getTimezoneOffset() Returns the difference in minutes between local time
and Greenwich Mean Time (GMT)
1 2 3
getUTCDate() Returns the day of the month from a Date object
according to universal time (from 1-31)
1 4 4
getUTCDay() Returns the day of the week from a Date object
according to universal time (from 0-6)
1 4 4
getUTCMonth() Returns the month from a Date object according to
universal time (from 0-11)
1 4 4
getUTCFullYear() Returns the four-digit year from a Date object according
to universal time
1 4 4
getUTCHours() Returns the hour of a Date object according to universal
time (from 0-23)
1 4 4
getUTCMinutes() Returns the minutes of a Date object according to
universal time (from 0-59)
1 4 4
getUTCSeconds() Returns the seconds of a Date object according to
universal time (from 0-59)
1 4 4
getUTCMilliseconds() Returns the milliseconds of a Date object according to
universal time (from 0-999)
1 4 4
getYear() Returns the year, as a two-digit or a three/four-digit
number, depending on the browser. Use getFullYear()
instead !!
1 2 3
parse() Takes a date string and returns the number of
milliseconds since midnight of January 1, 1970
1 2 3
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
60
7 - javaScript
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
specified number of milliseconds to/from midnight January
1, 1970
1 2 3
setUTCDate() Sets the day of the month in a Date object according to
universal time (from 1-31)
1 4 4
setUTCMonth() Sets the month in a Date object according to universal
time (from 0-11)
1 4 4
setUTCFullYear() Sets the year in a Date object according to universal
time (four digits)
1 4 4
setUTCHours() Sets the hour in a Date object according to universal
time (from 0-23)
1 4 4
setUTCMinutes() Set the minutes in a Date object according to universal
time (from 0-59)
1 4 4
setUTCSeconds() Set the seconds in a Date object according to universal
time (from 0-59)
1 4 4
setUTCMilliseconds() Sets the milliseconds in a Date object according to
universal time (from 0-999)
1 4 4
setYear() Sets the year in the Date object (two or four digits). Use
setFullYear() instead !!
1 2 3
toDateString() Returns the date portion of a Date object in readable
form

toGMTString() Converts a Date object, according to Greenwich time, to
a string. Use toUTCString() instead !!
1 2 3
toLocaleDateString() Converts a Date object, according to local time, to a
string and returns the date portion
1 4 4
toLocaleTimeString() Converts a Date object, according to local time, to a
string and returns the time portion
1 4 4
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
string
1 4 4
UTC() Takes a date and returns the number of milliseconds
since midnight of January 1, 1970 according to universal
time
1 2 3
valueOf() Returns the primitive value of a Date object 1 2 4
-.15.% the Arra1 Ob#e$t
The JavaScript Arra1 object is used to store a set of values in a single variable name.
6r!&erties
88: Firefox, N: Netscape, IE: nternet Explorer
61
7 - javaScript
Property Description
F
F
N
I
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
2eth!ds
Method Description F
F
N I
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 separated by a specified delimiter
1 3 4
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
the new length
1 4 5
.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
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
returns the new length
1 4 6
valueOf() Returns the primitive value of an Array object 1 2 4
-.15.( the N.ber Ob#e$t
The N.ber object is an object wrapper for primitive numeric values.
Syntax for creating a new Number object.
var myNum=new Number(number);
6r!&erties
88: Firefox, IE: nternet Explorer
Property Description
F
F
I
E
62
7 - javaScript
constructor Returns a reference to the Number function that created the
object
1 4
MAX_VALUE Returns the largest possible value in JavaScript 1 4
MN_VALUE Returns the smallest possible value in JavaScript 1 4
NaN Represents "Not-a-number" value 1 4
NEGATVE_NFNT
Y
Represents a value that is less than MN_VALUE 1 4
POSTVE_NFNTY Represents a value that is greater than MAX_VALUE 1 4
prototype Allows you to add properties and methods to the object 1 4
2eth!ds
Method Description F
F
I
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 digits than specified
1 5
.5
toString() Converts the Number object into a string 1 4
valueOf() Returns the value of the Number object 1 4
-.15.* the B!!'ean Ob#e$t
The JavaScript B!!'ean object is an object wrapper for a Boolean value.
6r!&erties
88: Firefox, N: Netscape, IE: nternet Explorer
Property Description
F
F
N
I
E
constructor Returns a reference to the Boolean function that created the
object
1 2 4
prototype Allows you to add properties and methods to the object 1 2 4
2eth!ds
Method Description F
F
N I
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
63
7 - javaScript
-.15., the 2ath Ob#e$t
The JavaScript 2ath object allows you to perform common mathematical tasks. t includes
several mathematical constants and functions.
6r!&erties
88: Firefox, N: Netscape, IE: nternet Explorer
Property Description
F
F
N
I
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
P Returns P (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
2eth!ds
Method Description F
F
N I
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 -P/2
and P/2 radians
1 2 3
atan2(y,x) Returns the angle theta of an (x,y) point as a numeric value
between -P and P radians
1 2 3
ceil(x) Returns the value of a number rounded upwards to the nearest
integer
1 2 3
cos(x) Returns the cosine of a number 1 2 3
exp(x)
Returns the value of E
x
1 2 3
floor(x) Returns the value of a number rounded downwards to the
nearest integer
1 2 3
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
64
7 - javaScript
toSource() Represents the source code of an object 1 4 -
valueOf() Returns the primitive value of a Math object 1 2 4
-.11 h!w t! $reate 1!r !wn !b#e$ts
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.
-.11.1 6r!&erties
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
-.11.2 2eth!ds
An object can also contain methods.
You can call a method with the following syntax:
objName.methodName()
There are different ways to create a new object:
-.11.% $reate a dire$t instan$e !" an !b#e$t
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;
65
7 - javaScript
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;
-.11.( Create a te.&'ate !" an !b#e$t
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. nside 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;
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)
66
7 - javaScript
{
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").
-.12 3a+aS$ri&t E+ents
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 nternet Explorer for each such event.
Event The event occurs when... F
F
N I
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
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
67
7 - javaScript
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
-.12.1 !n'!ad and !n=n'!ad
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!".
-.12.2 !n8!$s/ !nB'r and !nChange
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()">;
-.12.% !nSb.it
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. f the field values are not accepted, the submit
should be cancelled. The function checkForm() returns either true or false. f it returns true the
form will be submitted, otherwise the submit will be cancelled:
<form method="post" action="xxx.htm" onsubmit="return checkForm()">
-.12.( !n2!seO+er and !n2!seOt
onMouseOver and onMouseOut are often used to create "animated" buttons.
Below is an example of an onMouseOver event. An alert box appears when an onMouseOver
68
7 - javaScript
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>
69
8 - Html DOM
0 - HT2L DO2
0.1 what is the DO2F
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. n
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. f the
application is strictly sequential and one-pass, the SAX model is likely to be faster and use less
memory.
0.2 hist!r1
The World Wide Web Consortium (W3C) developed the W%C D!$.ent Ob#e$t 2!de' in
response to the development of various proprietary models for HTML, particularly those used in
Web browsers. The existing vendor-specific interfaces were dubbed inter.ediate DO2s.
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 APs for the Web since then; HTML, SVG, CSS, or WebAP being
among them.
70
8 - Html DOM
0.% 'e+e's
The .7C 2'4 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 .7C 5ecommendations which means they have reached their final form.
Le+e' 5
The application supports an intermediate DOM, which existed before the creation of DOM Level
1. Examples include the 28T41 'b/ect 4odel 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.
Le+e' 1
Navigation of DOM (HTML and XML) document (tree structure) and content manipulation
(includes adding elements). HTML-specific elements are included as well.
Le+e' 2
XML namespace support, filtered views and events.
Le+e' %
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
0.( s&e$i"i$ati!ns
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
71
8 - Html DOM
Working Draft
Window Object 1.0
0.* web br!wsers i.&'e.entati!n
Earlier, when each Web browser exclusively supported its own intermediate DOM,
interoperability problems were numerous. n 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
nternet 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 nternet 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.
0., #a+aS$ri&t s&e$i"i$ !b#e$ts
n 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
Location Contains information about the current URL
0.- the HT2L DO2
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. t can be used by any programming
language like Java, JavaScript, and VBScript.
72
8 - Html DOM
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
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
frame Represents an <iframe> element
mage Represents an <img> element
nput button Represents a button in an HTML form
nput checkbox Represents a checkbox in an HTML form
nput file Represents a fileupload in an HTML form
nput hidden Represents a hidden field in an HTML form
nput password Represents a password field in an HTML form
nput radio Represents a radio button in an HTML form
nput reset Represents a reset button in an HTML form
nput submit Represents a submit button in an HTML form
nput 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
TableData Represents a <td> element
TableRow Represents a <tr> element
Textarea Represents a <textarea> element
0.0 DO2 n!des
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
73
8 - Html DOM
Every HTML attribute is an attribute node
Comments are comment nodes
0.0.1 DO2 ECa.&'e
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.
0.0.2 TeCt is A'wa1s St!red in TeCt N!des
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.
n this example: Gtit'eHDO2 Tt!ria'GBtit'eH, the element node <title>, holds a text node with
the value "DOM Tutorial".
"DOM Tutorial" is n!t the value of the <title> element!
However, in the HTML DOM the value of the text node can be accessed by the innerHT2L
property.
0.4 the HT2L DO2 N!de Tree
0.4.1 the D!$.ent Tree
The HTML DOM views a HTML document as a tree-structure. The tree structure is called a
n!de-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:
74
8 - Html DOM

0.4.2 n!de &arents/ $hi'dren/ and sib'ings
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).
n 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
0.4.% a$$essing n!des
You can access a node in three ways:
1. By using the getElementByd() 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.getElementByd('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");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
75
8 - Html DOM
0.4.( N!de 6r!&erties
n the HTML Document Object Model (DOM), each node is an !b#e$t.
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 n!deNa.e 6r!&ert1
The n!deNa.e 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 n!de7a'e 6r!&ert1
The n!de7a'e 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 n!deT1&e 6r!&ert1
The n!deT1&e 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
0.4.* eCa.&'e - get the +a'e !" an e'e.ent
The following code fragment retrieves the text node value of the first <p> element:
x=document.getElementByd("intro").firstChild;
txt=x.nodeValue;
76
8 - Html DOM
0.15 HT2L e+ents
Common!"C 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.
C#te$ory Type %ttribute Description
Mouse
click onclick
Fires when the pointing device
button is clicked over an element.
A click is defined as a mousedown
and mouseup over the same
screen location. The sequence of
these events is:
mousedown
mouseup
click
dblclick ondblclick
Fires when the pointing device
button is double clicked over an
element
mousedown onmousedown
Fires when the pointing device
button is pressed over an element
mouseup onmouseup
Fires when the pointing device
button is released over an element
mouseover onmouseover
Fires when the pointing device is
moved onto an element
mousemove onmousemove
Fires when the pointing device is
moved while it is over an element
mouseout onmouseout
Fires when the pointing device is
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
77
8 - Html DOM
keydown onkeydown
Fires when a key on the
keyboard is pressed
keyup onkeyup
Fires when a key on the
keyboard is released
HTML
frame/object
load onload
Fires when the user agent
finishes loading all content within a
document, including window,
frames, objects and images
For elements, it fires when the
target element and all of its content
has finished loading
unload onunload
Fires when the user agent
removes all content from a window
or frame
For elements, it fires when the
target element or any of its content
has been removed
abort onabort
Fires when an object/image is
stopped from loading before
completely loaded
error onerror
Fires when an
object/image/frame cannot be
loaded properly
resize onresize
Fires when a document view is
resized
scroll onscroll
Fires when a document view is
scrolled
HTML
form
select onselect
Fires when a user selects some
text in a text field, including input
and textarea
change onchange
Fires when a control loses the
input focus and its value has been
modified since gaining focus
submit onsubmit Fires when a form is submitted
reset onreset Fires when a form is reset
focus onfocus
Fires when an element receives
focus either via the pointing device
or by tab navigation
blur onblur
Fires when an element loses
focus either via the pointing device
or by tabbing navigation
User
interface DOMFocusn ondomfocusin
Similar to HTML focus event, but
can be applied to any focusable
element
DOMFocusOut ondomfocusout Similar to HTML blur event, but
can be applied to any focusable
element
78
8 - Html DOM
DOMActivate ondomactivate
Similar to XUL command event.
Fires when an element is
activated, for instance, through a
mouse click or a keypress.
Mutation
DOMSubtreeModifi
ed
onsubtreemodified
Fire when the subtree is
modified
DOMNodenserted onnodeinserted
Fires when a node has been
added as a child of another node
DOMNodeRemove
d
onnoderemoved
Fires when a node has been
removed from a DOM-tree
NodensertedntoDo
cument
onnodeinsertedintodo
cument
Fires when a node is being
inserted into a document
DOMAttrModified onattrmodified
Fires when an attribute has been
modified
DOMCharacterData
Modified
oncharacterdatamodifi
ed
Fires when the character data
has been modified
Note that the events whose names start with "DOM are currently not well supported. Mozilla
and Opera support DOMAttrModified, DOMNodenserted, 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 nternet Explorer for the Mac
does not.

0.11 e+ent "'!w
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
nternet 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.stop7ropagation01 for Mozilla and command
event.cancelC$%%le K tr$e for nternet Explorer), and/or by cancelling the default action for
the event.
0.12 the E+ent !b#e$t
The E+ent 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
79
8 - Html DOM
discussed here.
E+ent &r!&erties
Type N#me Description
DOMString type The name of the event (case-insensitive).
EventTarget target
Used to indicate the EventTarget to which the event was
originally dispatched.
EventTarget
currentTarg
et
Used to indicate the EventTarget whose EventListeners are
currently being processed.
unsigned short eventPhase
Used to indicate which phase of event flow is currently
being evaluated.
boolean bubbles
Used to indicate whether or not an event is a bubbling
event.
boolean cancelable
Used to indicate whether or not an event can have its
default action prevented.
DOMTimeStamp timeStamp
Used to specify the time (in milliseconds relative to the
epoch) at which the event was created.
E+ent .eth!ds
N#me
%r$ument
type
%r$ument
n#me
Description
stopPropagatio
n
To prevent further propagation of an event
during event flow.
preventDefault
To cancel the event if it is cancelable,
meaning that any default action normally
taken by the implementation as a result of the
event will not occur.
initEvent
DOMString eventTypeArg Specifies the event type.
boolean canBubbleArg
Specifies whether or not the event can
bubble.
boolean cancelableArg
Specifies whether or not the event's default
action can be prevented.
80
9 - AJAX
4 - A3A<
4.1 what is a#aCF
Ajax stands for Asynchronous JavaScript And XML. t 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 Xml file read on the server (with the
getElementByTagName method for example)...
The XMLHttpRequest class 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 to wait and to freeze the display of the page.
4.2 wh1 se a#aCF
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 client computer (in JavaScript) with data taken
from the server.
The processing of web page formerly was 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.
4.% the basi$ ar$hite$tre !" a#aC
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. t's a model adapted from the Web's original use as a hypertext medium, but what makes
the Web good for hypertext doesn't necessarily make it good for software applications.
81
9 - AJAX
The traditional model for web applications 9left: compared to the A/ax model 9right:
This approach makes a lot of technical sense, but it doesn't make for a great user experience.
While the server is doing its thing, what's the user doing? That's 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 wouldn't make users
wait around. Once an interface is loaded, why should the user interaction come to a halt every
time the application needs something from the server? n 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. t seems like
adding a layer to the application would make it less responsive, but the opposite is true.
nstead of loading a webpage, 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 user's
behalf. The Ajax engine allows the user's 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.
82
9 - AJAX
The synchronous interaction pattern of a traditional web application 9top: compared with the
asynchronous pattern of an A/ax application 9bottom:
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 doesn't 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. f the engine needs something from the server in order to
respond if it's submitting data for processing, loading additional interface code, or retrieving
new data the engine makes those requests asynchronously, usually using XML, without stalling
a user's interaction with the application.
83
9 - AJAX
4.( h!w d!es it w!r>F
Ajax uses a programming model with display and events. These events are user actions, they
call functions associated to elements of the web page.
nteractivity 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 <2LHtt&9e@est object. This object
provides two methods:
- !&en: create a connection.
- send: send a request to the server.
Data furnished by the server will be found in the attributes of the XMLHttpRequest object:
- res&!nse<.' - for a Xml file or
- res&!nseTeCt - 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 read1State attribute of XMLHttpRequest.
States of read1State follow (only the last one is really useful):
0: not initialized.
1: connection established.
2: request received.
3: answer in process.
4: finished.
4.* the <2LHtt&9e@est $'ass
Here is a closer look to the XMLHttpRequest class. t allows the interaction with the servers,
thanks to its methods and attributes.
Attribtes
ReadyState - the code successively changes value from 0 to 4 that means for "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
2eth!ds
O&en(mode, url, boolean) - mode: type of request, GET or POST
- url: the location of the file
84
9 - AJAX
- boolean: true (asynchronous) / false (synchronous)
Send("string") - null for a GET command
4., bi'ding a re@est/ ste& b1 ste&
First step& cre#te #n inst#nce
This is just a classical instance of 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"); // E
}
'econd step& w#it (or the response
The response and further processing are included in a function and the return of the function
will be assigned to the !nread1state$hange attribute of the object previously created.
request.onreadystatechange = function()
{ // instructions to process the response };
if (request.readyState == 4)
{
// received, OK
}
else
{
// wait...
}
Third step& m#)e the re*uest itsel(
Two methods of XMLHttpRequest are used:
- !&en: 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);
85
9 - AJAX
4.- eCa.&'es
4.-.1 H!w t! get a teCt
<html>
<head>
<script>
function submitForm()
{
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="">
<NPUT type="BUTTON" value="Submit" ONCLCK="submitForm()">
<NPUT type="text" name="dyn" value="">
</FORM>
</body>
</html>
4.-.2 h!w t! get "r!. C.'
To get data from a xml file we have just to replace this line:
document.ajax.dyn=""Received:" + req.responseText;
by this code:
86
9 - AJAX
var doc K reM.responseXMLW // assign the Xml 5ile to a var
var element K doc.get'lementsCB!ag)ame0IrootI1.item091W // read the
5irst element with a domIs method
doc$ment.ajax.dBn.val$eK element.5irstChild.dataW // assign the
content o5 the element to the 5orm
4.-.% h!w t! &!st a teCt
A text is sent to the server and is written into a file. The call to the "open" method changes, the
argument is POST, and the "send" method also has now a value for argument.
req.open("POST", "ajax-post.xml", true);
req.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
req.send(document.getElementByd("dyn".value));
4.-.( h!w t! write t! b!d1
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.getElementByd("zone").innerHTML = "Received:" +
xhr.responseText;
4.0 the a#aC t!!'>it "ra.ew!r>
t is an Eclipse add-on that provides tools for building DE for Ajax runtimes, and testing Ajax
applications. The AJAX Toolkit Framework (ATF) provides and extensible framework and
exemplary tools for building DEs 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.
4.4 drawba$>s !" a#aC
f 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.
87
9 - AJAX
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).
4.15 S&e$i"i$ati!ns
Ajax is based on these specifications:
XML 1, HTML 4.0, DOM 2, from W3C
ECMAScript 1.5 (standard for JavaScript) from ECMA
W3C draft specification for XMLHttpRequest.
88
10 - WEB APPLCATONS
15 - WEB A66LICATIONS
15.1 the str$tre !" a web a&&'i$ati!n
A web a&&'i$ati!n 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-NF/web.xml file the deployment descriptor.
3. a WEB-NF/classes directory.
4. a WEB-NF/lib directory.
Example:
Assume that we use a Tomcat web server and that the environment variable
%TOMCAT_HOME% is set to C:\TW\Tomcat. Then, the root directory of some web application
can be:
C:\TW\Tomcat\webapps\bank11\ccards
and the mandatory directories are:
C:\TW\Tomcat\webapps\bank11\ccards\WEB-NF\classes
C:\TW\Tomcat\webapps\bank11\ccards\WEB-NF\lib
15.2 web $!ntainers
A web $!ntainer is a Java runtime providing implementation of the Java servlet AP and some
other facilities to the JSP pages. t responsible for initializing, invoking and managing the life
cycle of servlets and JSPs.
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 $!ntainer in a 32EE a&&'i$ati!n ser+er. Commercial implementations of the J2EE
specifications, like WebLogic, nprise Application Server or BM's WebSphere include web
containers.
web $!ntainer bi't int! web ser+ers. Most known cases are the Sun's Java WebServer and
the Jakarta Tomcat web server (which will be used in our applications).
web $!ntainer as a se&arate rnti.e. Some web servers, like Apache or S require a
separate runtime to run servlets and a web server plug-in to integrate this Java runtime with
89
Java
Classes
10 - WEB APPLCATONS
the web server. Typical integration scenarios are Tomcat with Apache and JRun (of Allaire)
with most of the J2EE application servers.
15.% $!ntainer ser+i$es
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 nterface (JND) lookups, and remote connectivity.
Here are some of the highlights:
The Java EE se$rit1 .!de' lets you configure a web component or enterprise
bean so that system resources are accessed only by authorized users.
90
Web Application Web Application
JavaServer
Faces
Java Servlets Java Servlets
JSP Pages
JSP Pages
JavaServer
Faces
Deployment descriptor Deployment descriptor
J2EE Web Container
10 - WEB APPLCATONS
The Java EE transa$ti!n .!de' 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.
JND '!!>& ser+i$es provide a unified interface to multiple naming and directory
services in the enterprise so that application components can access these
services.
The Java EE re.!te $!nne$ti+it1 .!de' 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 APs (see section Java EE 5 APs).
15.( de&'!1.ent des$ri&t!r
The de&'!1.ent des$ri&t!r is an xml file (namely, web.xml) which allows the customization of
the web application at deployment time.
The deployment descriptor serves several purposes, like:
1. nitialization of parameters for servlets, JSPs and JavaServer Faces.
2. Servlet, JSPs and JavaServer Faces definitions, servlet classes, precompiled JSP
entities are declared (names, classes, descriptions).
3. Servlet, JSPs and JavaServer Faces mappings.
4. MME 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:
;Oxml versionK=8.9= encodingK=IS+&>>E@&8= O4
;<#+C!F7' we%&app (View Source for full doctype...)4
;we%&app4
;<&& #e5ine the Can2 88 ccards Servlets &&4
;servlet4
;servlet&name4Login;/servlet&name4
;servlet& class4com.bank11.ccards.servlets.LoginServlet
;/servlet&class4
;/servlet4
;/we%&app4
91
10 - WEB APPLCATONS
15.* &ra$ti$a' de&'!1.ent isses
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 UNX 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:
<servlet-mapping>
<servlet-name>invoker</servlet-name>
;$rl&pattern4/servlet/X;/$rl&pattern4
;/servlet&mapping4
in the configuration file "%TOMCAT_HOME%\conf\web.xml"
2. The "/ccards" part of the URL is, basicly, the name of the web application. n 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 ;context4
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 ;context4 element in the
"%TOMCAT_HOME%\conf\server.xml" file looks like:
;context pathK=/ccards= doc%aseK=vd$mitrasc$/cc= /4
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-
NF\classes\com.bank11.ccards.servlets". This association between the (short) alias of the
servlet and its real (long) name is made in the we%.xml file of the web application. More
exactly the corresponding ;servlet4 element should look like:
;servlet4
<servlet-name>Enroll</servlet-name>
<servlet-class>
92
10 - WEB APPLCATONS
com.bank11.ccards.servlets.EnrollServlet
</servlet-class>
;/servlet4
93
11 - JND
11 - 3NDI
11.1 the ser+'ets as &art !" web a&&'i$ati!ns
3a+a ser+'ets 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.
The Java servlet AP provides a simple frame for building web applications on web servers.
The current Java Servlet specification (as of 10.2008) is 2.5 and is in final state. Java EE 5
SDK contains an implementation of the Java Servlet 2.5 specification.
11.2 dire$t!r1 ser+i$es
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.
11.2.1 N!n$!..er$ia' ser+'et $!ntainers
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.
Jetty
Jaminid contains a higher abstraction than servlets.
Enhydra
Winstone supports specification v2.4, has a focus on minimal configuration and the ability
to strip the container down to only what you need.
tjws spec 2.4, small footprint, modular design
11.2.2 $!..er$ia' ser+'et $!ntainers
BEA WebLogic Server or Weblogic Express, from BEA Systems
Borland Enterprise Server
GlassFish (open source)
Java System Application Server , from Sun Microsystems
Java System Web Server , from Sun Microsystems
JBoss (open source)
JRun , from Adobe Systems (formerly developed by Allaire Corporation)
LiteWebServer (open source)
94
11 - JND
Oracle Application Server , from Oracle Corporation
Orion Application Server , from ronFlare
Caucho's Resin Server
ServletExec , from New Atlanta Communications
WebObjects , from Apple nc.
WebSphere , from BM
11.% $!nteCts
f 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, because we can, to some extent, identify a web application with its root directory (a node in
the file system directory tree). Going now back to the rationality of this chapter, remember that a
naming serviced associates names with real objects (resources). This association between a
name
Which leads to a list of constraints:
within a given context, a name is unique

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 AP can be divided in several categories,
namely:
servlet implementation
servlet configuration
servlet exceptions
request and responses
session tracking
servlet context
servlet collaboration
miscellaneous
11.( the Ser+'et inter"a$e
The Servlet interface is part of the javax.servlet package. t declares the following
methods:
p$%lic void init0ServletCon5ig con5ig1 throws Servlet'xceptionW
p$%lic void service0ServletReM$est reM3 ServletResponse resp1 throws
95
11 - JND
Servlet'xception3 I+'xceptionW
p$%lic void destroB01 throws Servlet'xceptionW
p$%lic ServletCon5ig getServletCon5ig01W
p$%lic String getServletIn5o01W
After instantiating the servlet, the web container calls its init01 method. The method
performs all initialization required, before the servlet processes any HTTP request. The servlet
specification insures that the init01 method is called just once for any given instance of the
servlet.
The web container calls the service01 method in response to any incoming request. This
method has two arguments, arguments which implement the ServletReM$est and
ServletResponse interfaces, respectively.
More on the servlet lifecycle, in a different section.
11.* the Generi$Ser+'et $'ass
p$%lic a%stract class -enericServlet implements
Servlet3 ServletCon5ig3 SerialiRa%le
This class provides a basic implementation of the Servlet interface. Since this class
implements the ServletCon5ig interface, as well, the developer may call ServletCon5ig
methods directly, without having to obtain a ServletCon5ig object first. All classes extending
the GenericServlet class should provide an implementation for the service01 method.
Methods specific to this class:
public void init()
public void log(String msg)
public void log(String msg, Throwable t)
11., the Htt&Ser+'et $'ass
t is very likely that the only implementation of the Servlet interface we'll ever use is one that
processes an HTTP request. The servlet AP provides such a specific class, namely the
6ttpServlet 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)
96
11 - JND
public void service(HttpServletRequest req, HttpServletResponse resp)
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
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)
11.- the Ser+'etC!n"ig inter"a$e
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 getnitParameter(String name)
public Enumeration getnitParameterNames()
public ServletContext getServletContext()
public String getServletName()
11.0 ser+'et eC$e&ti!ns
The Java servlet AP specifies two servlet specific exceptions:
javax.servlet.Servlet'xception
javax.servlet.navaila%le'xception
The Servlet'xception class extends java.lang.'xception and can be thrown by the
init01, service01, doXXX01 and destroB01 methods of the Servlet interface
implementations.
The navaila%le'xception indicates to the web container that the servlet instance is
unavaialble. t also extends the java.lang.'xception class.
97
11 - JND
11.4 the ser+'et 'i"e$1$'e
Generally, a servlet instance goes through the following stages:
instantiation
initialization
service
destroy
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. f the servlet does not implement the
javax.servlet.Single!hreadModel, concurrent requests are serviced in more than one
service thread, which requires that the service01 method be thread safe.
After instantiation, the container calls the init01 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 init01 method of the servlet will be completed before
invoking its service01 method. Also, the servlet's destroB01 method will be called before the
servlet itself is destroyed.
11.15 the Ser+'et9e@est inter"a$e
Here are some of the methods of this interface:
p$%lic +%ject get(ttri%$te0String name1
p$%lic +%ject set(ttri%$te0String name3 +%ject attr1
p$%lic 'n$meration get(ttri%$te)ames01
p$%lic int getContentLength01
p$%lic String getContent!Bpe01
p$%lic String get7arameter0String name1
p$%lic 'n$meration get7arameter)ames01
p$%lic 'n$meration get7arameterGal$es01
p$%lic String getServer)ame01
p$%lic int getServer7ort01
p$%lic String getRemote(ddr01
p$%lic String getRemote6ost01
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.
There are 3 different ways for attaching and retrieving attributes. The first one is to attach
98
11 - JND
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 or JSP or to allow sending data from a servlet to another.
11.11 the Htt&Ser+'et9e@est inter"a$e
p$%lic inter5ace 6ttpServletReM$est extends ServletReM$est
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:
p$%lic Coo2ieST getCoo2ies01
p$%lic long get#ate6eader01
p$%lic String get6eader0String name1
p$%lic 'n$meration get6eaders0String name1
p$%lic 'n$meration get6eader)ames01
p$%lic String getContext7ath01
p$%lic String get7athIn5o01
p$%lic String getH$erBString01
p$%lic String getRemoteser01
11.12 the Ser+'et9es&!nse inter"a$e
This interface defines methods for constructing responses to servlet requests.
Here are the most important ones:
p$%lic Servlet+$tp$tStream get+$tp$tStream01
p$%lic 7rint/riter get/riter01
p$%lic void setContentLength0int len1
p$%lic void setContent!Bpe0String tBpe1
p$%lic void setC$55erSiRe0int siRe1
p$%lic int getC$55erSiRe01
p$%lic void 5l$shC$55er01
11.1% the Htt&Ser+'et9es&!nse inter"a$e
99
11 - JND
This interface extends the ServletResponse interface and defines methods specific for
constructing responses to HTTP requests.
Here are the most important ones:
p$%lic void addCoo2ie0Coo2ie coo2ie1
p$%lic String encodeRL0String $rl1
p$%lic void send'rror0int stat$s1
p$%lic void send'rror0int stat$s3 String message1
p$%lic void set6eader0String header)ame3 String val$e1
p$%lic void add6eader0String header)ame3 String val$e1
p$%lic void setStat$s0int stat$sCode1
11.1( the Ser+'etC!nteCt inter"a$e
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
;context4 tag which associates the the name of the application with its root directory. This is
done in server's (container's) server.xml file.
The ServletContext interface abstracts the context of a web application. A reference to an
object of this type can be obtained by invoking the getServletContext01 method of the
6ttpServlet object.
p$%lic String getMIM'!Bpe0String 5ile)ame1
p$%lic String getReso$rce0String path1
p$%lic ServletContext getContext0String $rl7ath1
p$%lic String getInit7arameter0String name1
p$%lic 'n$meration getInit7arameter)ames01
p$%lic +%ject get(ttri%$te0String name1
p$%lic 'n$meration get(ttri%$te)ames01
p$%lic void set(ttri%$te0String name3 +%ject attr1
p$%lic String remove(ttri%$te0String name1
11.1* the Enr!'' ser+'et
The Enroll servlet services the request sent by the web browser when we submit the Enroll form
(file Enroll.html)
Here is its abbreviated form (topics which are DB related are postponed) of the
100
11 - JND
"EnrollServlet.java" file:
package com.bank11.ccards.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EnrollServlet extends HttpServlet
{
public void init(ServletConfig config)
throws ServletException
{
super.init(config);
}
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, OException
{
resp.setContent!Bpe0Ytext/htmlL1W
7rint/riter o$t K resp.get/riter01W
// o$tp$t Bo$r page here
o$t.println0=;html4=1W
o$t.println0=;head4=1W
o$t.println0=;title4Servlet;/title4=1W
o$t.println0=;/head4=1W
o$t.println0=;%odB4=1W
o$t.println0=merge=1W
o$t.println0=;%r4=1W
o$t.println0=;/%odB4=1W
o$t.println0=;/html4=1W
o$t.close01W
V
V
101
12 - SERVLETS
12 - SE97LETS
12.1 the ser+'ets as &art !" web a&&'i$ati!ns
3a+a ser+'ets 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.
The Java servlet AP provides a simple frame for building web applications on web servers.
The current Java Servlet specification (as of 10.2008) is 2.5 and is in final state. Java EE 5
SDK contains an implementation of the Java Servlet 2.5 specification.
12.2 ser+'et $!ntainers
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.
12.2.1 N!n$!..er$ia' ser+'et $!ntainers
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.
Jetty
Jaminid contains a higher abstraction than servlets.
Enhydra
Winstone supports specification v2.4, has a focus on minimal configuration and the ability
to strip the container down to only what you need.
tjws spec 2.4, small footprint, modular design
12.2.2 $!..er$ia' ser+'et $!ntainers
BEA WebLogic Server or Weblogic Express, from BEA Systems
Borland Enterprise Server
GlassFish (open source)
Java System Application Server , from Sun Microsystems
Java System Web Server , from Sun Microsystems
JBoss (open source)
JRun , from Adobe Systems (formerly developed by Allaire Corporation)
LiteWebServer (open source)
102
12 - SERVLETS
Oracle Application Server , from Oracle Corporation
Orion Application Server , from ronFlare
Caucho's Resin Server
ServletExec , from New Atlanta Communications
WebObjects , from Apple nc.
WebSphere , from BM
12.% ser+'et &a$>ages and $'asses
The Java servlet AP consists of 2 packages, which are part of the J2 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 AP can be divided in several categories,
namely:
servlet implementation
servlet configuration
servlet exceptions
request and responses
session tracking
servlet context
servlet collaboration
miscellaneous
12.( the Ser+'et inter"a$e
The Servlet interface is part of the javax.servlet package. t declares the following
methods:
p$%lic void init0ServletCon5ig con5ig1 throws Servlet'xceptionW
p$%lic void service0ServletReM$est reM3 ServletResponse resp1 throws
Servlet'xception3 I+'xceptionW
p$%lic void destroB01 throws Servlet'xceptionW
p$%lic ServletCon5ig getServletCon5ig01W
p$%lic String getServletIn5o01W
103
12 - SERVLETS
After instantiating the servlet, the web container calls its init01 method. The method
performs all initialization required, before the servlet processes any HTTP request. The servlet
specification insures that the init01 method is called just once for any given instance of the
servlet.
The web container calls the service01 method in response to any incoming request. This
method has two arguments, arguments which implement the ServletReM$est and
ServletResponse interfaces, respectively.
More on the servlet lifecycle, in a different section.
12.* the Generi$Ser+'et $'ass
p$%lic a%stract class -enericServlet implements
Servlet3 ServletCon5ig3 SerialiRa%le
This class provides a basic implementation of the Servlet interface. Since this class
implements the ServletCon5ig interface, as well, the developer may call ServletCon5ig
methods directly, without having to obtain a ServletCon5ig object first. All classes extending
the GenericServlet class should provide an implementation for the service01 method.
Methods specific to this class:
public void init()
public void log(String msg)
public void log(String msg, Throwable t)
12., the Htt&Ser+'et $'ass
t is very likely that the only implementation of the Servlet interface we'll ever use is one that
processes an HTTP request. The servlet AP provides such a specific class, namely the
6ttpServlet 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)
104
12 - 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)
12.- the Ser+'etC!n"ig inter"a$e
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 getnitParameter(String name)
public Enumeration getnitParameterNames()
public ServletContext getServletContext()
public String getServletName()
12.0 ser+'et eC$e&ti!ns
The Java servlet AP specifies two servlet specific exceptions:
javax.servlet.Servlet'xception
javax.servlet.navaila%le'xception
The Servlet'xception class extends java.lang.'xception and can be thrown by the
init01, service01, doXXX01 and destroB01 methods of the Servlet interface
implementations.
The navaila%le'xception indicates to the web container that the servlet instance is
unavaialble. t also extends the java.lang.'xception class.
12.4 the ser+'et 'i"e$1$'e
Generally, a servlet instance goes through the following stages:
105
12 - SERVLETS
instantiation
initialization
service
destroy
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. f the servlet does not implement the
javax.servlet.Single!hreadModel, concurrent requests are serviced in more than one
service thread, which requires that the service01 method be thread safe.
After instantiation, the container calls the init01 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 init01 method of the servlet will be completed before
invoking its service01 method. Also, the servlet's destroB01 method will be called before the
servlet itself is destroyed.
12.15 the Ser+'et9e@est inter"a$e
Here are some of the methods of this interface:
p$%lic +%ject get(ttri%$te0String name1
p$%lic +%ject set(ttri%$te0String name3 +%ject attr1
p$%lic 'n$meration get(ttri%$te)ames01
p$%lic int getContentLength01
p$%lic String getContent!Bpe01
p$%lic String get7arameter0String name1
p$%lic 'n$meration get7arameter)ames01
p$%lic 'n$meration get7arameterGal$es01
p$%lic String getServer)ame01
p$%lic int getServer7ort01
p$%lic String getRemote(ddr01
p$%lic String getRemote6ost01
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.
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 or JSP or to allow sending data from a servlet to another.
106
12 - SERVLETS
12.11 the Htt&Ser+'et9e@est inter"a$e
p$%lic inter5ace 6ttpServletReM$est extends ServletReM$est
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:
p$%lic Coo2ieST getCoo2ies01
p$%lic long get#ate6eader01
p$%lic String get6eader0String name1
p$%lic 'n$meration get6eaders0String name1
p$%lic 'n$meration get6eader)ames01
p$%lic String getContext7ath01
p$%lic String get7athIn5o01
p$%lic String getH$erBString01
p$%lic String getRemoteser01
12.12 the Ser+'et9es&!nse inter"a$e
This interface defines methods for constructing responses to servlet requests.
Here are the most important ones:
p$%lic Servlet+$tp$tStream get+$tp$tStream01
p$%lic 7rint/riter get/riter01
p$%lic void setContentLength0int len1
p$%lic void setContent!Bpe0String tBpe1
p$%lic void setC$55erSiRe0int siRe1
p$%lic int getC$55erSiRe01
p$%lic void 5l$shC$55er01
12.1% the Htt&Ser+'et9es&!nse inter"a$e
This interface extends the ServletResponse interface and defines methods specific for
constructing responses to HTTP requests.
Here are the most important ones:
107
12 - SERVLETS
p$%lic void addCoo2ie0Coo2ie coo2ie1
p$%lic String encodeRL0String $rl1
p$%lic void send'rror0int stat$s1
p$%lic void send'rror0int stat$s3 String message1
p$%lic void set6eader0String header)ame3 String val$e1
p$%lic void add6eader0String header)ame3 String val$e1
p$%lic void setStat$s0int stat$sCode1
12.1( the Ser+'etC!nteCt inter"a$e
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
;context4 tag which associates the the name of the application with its root directory. This is
done in server's (container's) server.xml file.
The ServletContext interface abstracts the context of a web application. A reference to an
object of this type can be obtained by invoking the getServletContext01 method of the
6ttpServlet object.
p$%lic String getMIM'!Bpe0String 5ile)ame1
p$%lic String getReso$rce0String path1
p$%lic ServletContext getContext0String $rl7ath1
p$%lic String getInit7arameter0String name1
p$%lic 'n$meration getInit7arameter)ames01
p$%lic +%ject get(ttri%$te0String name1
p$%lic 'n$meration get(ttri%$te)ames01
p$%lic void set(ttri%$te0String name3 +%ject attr1
p$%lic String remove(ttri%$te0String name1
12.1* the Enr!'' ser+'et
The Enroll servlet services the request sent by the web browser when we submit the Enroll form
(file Enroll.html)
Here is its abbreviated form (topics which are DB related are postponed) of the
"EnrollServlet.java" file:
package com.bank11.ccards.servlets;
import java.io.*;
108
12 - SERVLETS
import javax.servlet.*;
import javax.servlet.http.*;
public class EnrollServlet extends HttpServlet
{
public void init(ServletConfig config)
throws ServletException
{
super.init(config);
}
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, OException
{
resp.setContent!Bpe0Ytext/htmlL1W
7rint/riter o$t K resp.get/riter01W
// o$tp$t Bo$r page here
o$t.println0=;html4=1W
o$t.println0=;head4=1W
o$t.println0=;title4Servlet;/title4=1W
o$t.println0=;/head4=1W
o$t.println0=;%odB4=1W
o$t.println0=merge=1W
o$t.println0=;%r4=1W
o$t.println0=;/%odB4=1W
o$t.println0=;/html4=1W
o$t.close01W
V
V
109
13 - JDBC
1% - 3DBC
1%.1 what is #db$F
JDBC stands for Java Data Base Connectivity and is the Java version of ODBC (Open Data
Base Connectivity). t offers an AP for SQL-compliant relational databases access. t abstracts
the vendor-specific details and offers support for the most common database access functions.
1%.2 #db$ dri+ers
Each database vendor offers its own version of DB access AP. 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.
Type 1. 3DBC ) 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 the classes for this bridge, namely
s$n.jd%c.od%c.Zd%c+d%c#river .
Type 2. 6art 3a+a/ 6art Nati+e Dri+er
The drivers in this category use a combination of Java implementation and vendor specific
APs for DB access. The driver translates JDBC specific calls into vendor specific AP calls. The
DB returns the result of the call to the AP, which in turn, forwards them to the JDBC driver. t is
much faster than the Type 1 drivers, because it eliminates one level of indirection.
110
13 - JDBC
Type 3. Inter.ediate Database A$$ess Ser+er
Type 3 drivers are 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 nprise Application Server (of Borland).
Type 4. 6re 3a+a Dri+ers
These are the most efficient drivers. The JDBC AP calls are converted to direct network calls
using vendor provided protocols. All major vendors provide type 4 JDBC drivers for their
Database products.
111
13 - JDBC
For an extensive list of JDBC drivers, check the site:
http://industry.java.sun.com/products.j/jdbc/drivers .
1%.% $!nne$ting t! a database
There are two main steps in connecting to an existing database. The first one is
'!ading a database dri+er.
A database driver is specified by the driver name. Here are some examples of actual database
driver names:
com.borland.datastore.jdbc.DataStoreDriver
com.sybase.jdbc.SybDriver
com.ibm.db2.jdbc.net.DB2Driver
oracle.jdbc.driver.OracleDriver
sun.jdbc.odbc.JdbcOdbcDriver
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").newnstance();
} catch (Exception e) {
// driver not found
e.printStackTrace();
}
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 &r!t!$!' name (actually, the only protocol allowed in JDBC).
the sb-&r!t!$!' is used to identify the JDBC driver, as specified by the driver vendor.
sbna.e the syntax of this field is vendor specific and allows the identification
Here are some examples of JDBC driver URLs:
jdbc:sybase:localhost:2025
112
13 - JDBC
jdbc:db2://db2.bank11.com:50002/ccards
jdbc:oracle:thin:@loclahost:1521:ORCL
The second step in connecting to an existing database is to !&en the $!nne$ti!n/ by using the
connection URL.
Here is some sample code which shows how this is done:
String connRL K =jd%c:mBsMl://localhost:339A/ccards=W
String $ser K =root=W
String passwd K =root=
Connection conn K #riverManager.getConnection0connRL3
$ser3 passwd1W
Since we just used it, let's have a better look in the next section at the #riverManager class.
1%.( the Dri+er2anager $'ass
This class belongs to the javax.sMl 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
#riverManager class tries to obtain a connection.
There are 3 versions of the getConnection01 method of the #riverManager 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.
7roperties prp K new 7roperties01W
prp.p$t0=a$tocommit=3 =tr$e=1W
prp.p$t0=create=3 =tr$e=1W
Connection conn K #riverManager.getConnection0connRL3 prp1W
113
13 - JDBC
1%.* the C!nne$ti!n inter"a$e
The Connection interface is part of then javax.sMl 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 createStatement01 throws SHL'xception
Statement createStatement0int res$ltSet!Bpe3 int res$ltSetConc$rrencB1
throws SHL'xception
Statement createStatement0int res$ltSet!Bpe3 int res$ltSetConc$rrencB3
int res$ltSet6olda%ilitB1
7reparedStatement prepareStatement0String sMl1
throws SHL'xception
Calla%leStatement prepareCall0String sMl1
throws SHL'xception
1%., state.ent inter"a$es
The objects we encountered in the previous section, namely, Statement,
7reparedStatement and Calla%leStatement abstract regular SQL statements, prepared
statements and stored procedures, respectively.
The Statement interface has (among others) the following methods:
1. methods for executing statements:
exec$te01
exec$teH$erB01
exec$tepdate01
2. methods for batch updates:
addCatch01
exec$teCatch01
clearCatch01
3. methods for result set fetch size and direction:
set*etchSiRe01
get*etchSiRe01
set*etch#irection01
get*etch#irection01
114
13 - JDBC
4. method to get the current result set:
getRes$ltSet01
5. methods for result set concurrency and type:
getRes$ltSetConc$rrencB01
getRes$ltSet!Bpe01
6. other methods:
setH$erB!imeo$t01
getH$erB!imeo$t01
setMax*ieldSiRe01
getMax*ieldSiRe01
cancel01
getConnection01
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 K conn.createStatement01W
String sMlString K =CR'(!' !(CL' c$stomer ...=W
stmt.exec$tepdate0sMlString1W
1%.- the 9es'tSet inter"a$e
The result of a query by a Statement object is a java.sMl.Res$ltSet object which is
available to the user and allows access to the data retrieved. The interface Res$ltSet is
implemented by driver vendors.
Methods to retrieve data:
get(sciiStream01
getCoolean01
get#ate01
getInt01
getShort01
get!imeStamp01
115
13 - JDBC
getCinarBStream01
getCBtes01
get*loat01
get+%ject01
get!ime01
getString01
getCBte01
get#o$%le01
getLong01
getCig#ecimal01
getMeta#ata01
getClo%01
get/arnings01
getClo%01
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 Res$ltSetMeta#ata interface.
The invocation of the getMeta#ata01 method of a Res$ltSet object returns an object of
Res$ltSetMeta#ata type.
Here are the most important methods specified by the Res$ltSetMeta#ata interface:
getCatalog)ame01
get!a%le)ame01
getSchema)ame01
getCol$mnCo$nt01
getCol$mn)ame01
getCol$mnLa%el01
getCol$mn!Bpe01
getCol$mn!Bpe)ame01
getCol$mnClass)ame01
getCol$mn#isplaBSiRe01
getScale01
get7recision01
is)$lla%le01
isC$rrencB01
isSearcha%le01
isCaseSensitive01
116
13 - JDBC
isSigned01
is($toIncrement01
isRead+nlB01
is#e5initelB/rita%le01
1%.0 eCa.&'e !" data retrie+a'
// DisplayServlet.java
package com.bank11.ccards.servlets;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.math.*;
import java.util.*;
public class DisplayServlet extends HttpServlet {
Connection conn;

// nitializes the servlet
public void init(ServletConfig config) throws ServletException {
super.init(config);
String driverName = "org.gjt.mm.mysql.Driver";
try {
Class.forName("org.gjt.mm.mysql.Driver");
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}

String connURL="jdbc:mysql://localhost:3306/ccards";
try {
conn=DriverManager.getConnection(connURL,"root","root");
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}

// Destroys the servlet.
public void destroy() {
}

117
13 - JDBC
// Processes requests for both HTTP GET and POST methods.
protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.OException {
String theCode = req.getParameter("CODE);
String sql = "SELECT FRST_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("FRST_NAME);
String lastName = rs.getString("LAST_NAME);
BigDecimal accountNum = rs.getBigDecimal("ACCOUNT_NUM);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter();
// output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet</title>");
out.println("</head>");
out.println("<body>");
...
out.println("</body>");
out.println("</html>");
out.close();
}

// Handles the HTTP GET method.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.OException {
processRequest(req, resp);
}

// Handles the HTTP POST method.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.OException {
processRequest(req, resp);
}
118
13 - JDBC
// Returns a short description of the servlet.
public String getServletnfo() {
return "Short description";
}
}
1%.4 the 6re&aredState.ent inter"a$e
f 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 7reparedStatement object. Prepared
statements are parametrized and each parameter (usually, a field (column) value or name) is
represented by a question mark '?'.
The following lines of Java code give an example of how to use 7reparedStatement objects:
Statement stmt K con.createStatement01W
7reparedStatement pstmt K con.prepareStatement0=I)S'R! I)!+ c$stomer
G(L'S 0O3 O3 O1=1W
stmt.exec$tepdate0=CR'(!' !(CL' c$stomer 0id int3 5irst)ame
varchar03D1 last)ame varchar0D:11=1W
// set parameters 5or preparedStatement
pstmt.setInt083 89D81W
pstmt.setString0D3 =Gasile=1W
pstmt.setString033 =#$mitrasc$=1W
int co$nt K pstmt.exec$tepdate01W
1%.15 #db$ and s@' t1&es and their $!rres&!nding #a+a $'asses
+D,C Type Purpose '-. Type +#v# Type
ARRAY SQL array ARRAY java.sql.Array
BGNT 64 bit integer BGNT long
BNARY binary value none byte[]
BT one bit value BT 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
DECMAL decimal value DECMAL java.math.Big
Decimal
119
13 - JDBC
+D,C Type Purpose '-. Type +#v# Type
DSTNCT distinct DSTNCT none
DOUBLE double precision DOUBLE PRECSON double
FLOAT double precision FLOAT double
NTEGER 32 bit integer NTEGER int
JAVA_OBJECT stores Java objects none Object
LONGVARBNARY variable length binary
value
none byte[]
LONGVARCHAR variable length char string none String
NULL null values NULL null
NUMERC decimal value NUMERC java.math.Big
Decimal
OTHER db specific types none Object
REAL single precision REAL float
REF
SMALLNT 16 bit integer SMALLNT short
STRUCT
TME hrs, mins, secs TME java.sql.Time
TMESTAMP date, time, nanoseconds TMESTAMP java.sql.Times
tamp
TNYNT 8 bit integer TNYNT short
VARBNARY variable length binary
value
none byte[]
VARCHAR variable length char string VARCHAR String
1%.11 3DBC Data S!r$es
n the JDBC 2.0 optional package, the #riverManager interface is replaced by the
#ataSo$rce interface as main method of obtaining DB connections.
While the #riverManager interface was used at run time to load explicitly a JDBC driver, the
new mechanism uses a centralized JND service to locate a javax.sMl.#ataSo$rce object.
This interface is, basicly, a factory for creating DB connections. t is part of the javax.sMl
package.
The #ataSo$rce 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.
120
13 - JDBC
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:
p$%lic Connection getConnection01 throws SHL'xception
p$%lic Connection getConnection0String $ser3 String pwd1 throws
SHL'xception
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 nitialContext().lookup("java:comp/env");
theDataSource = (DataSource) env.lookup(DATASOURCE_NAME);
if (theDataSource == null)
121
13 - JDBC
throw new ServletException("`" + DATASOURCE_NAME +
"' is an unknown DataSource");
} catch (NamingException e) {
throw new ServletException(e);
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws OException, ServletException
{
...
}
}
122
14 - JSP
1( - 3S6
1(.1 #a+a ser+er &ages as &art !" web a&&'i$ati!ns
A 3a+a Ser+er 6age (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). f the JSP is modified,
the servlet code is regenerated.
The current JSP specification is JSP 2.1 and is related to the 2.5 Java Servlet specification.
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.
1(.2 #a+a beans
A java bean is a java class which:
implements the java.io.Serializable interface
provides a no-argument constructor
for each of its properties, provides get and set methods
implements a property change mechanism
Here is a typical example of a java bean.
/*
* NewBean.java
*/
import java.beans.*;
import java.io.Serializable;
/**
* @author sm
123
14 - JSP
*/
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;
}

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);
}
}
1(.% the #a+a.ser+'et.#s&.3s&6age inter"a$e
This interface has 2 methods:
p$%lic void jspInit01
p$%lic void jsp#estroB01
The javax.servlet.6ttpZsp7age interface has a single method:
124
14 - JSP
p$%lic void jspService06ttpServletReM$est reM3
6ttpServletResponse resp1 throws Servlet'xception3 I+'xception
The implementation of this method is generated by the web container never by the developer.
1(.( #s& tags
There are 3 categories of JSP tags (elements):
1. directives affect the structure of the whole jsp
2. scripting elements java code inserted in the JSP page
3. actions special tags affecting the run time behaviour of the JSP
Rules for JSP tags:
attribute values are always quoted (single or double quotes)
URLs follow the servlet conventions
if the URL does not start with / , it is interpreted relative to the position of the current JSP
1(.* #s& dire$ti+es
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.
The general format of a JSP directive is as follows:
;[Qdirective,name attr8K=val8= ... attrnK=valn= [4
Ther are three JSP directives: page, include and taglib.
The &age directive format:
;[Qpage attr8K=val8= ... [4
attributes:
language values: "java"
extends superclass of the generated class
import list of packages classes
session "true" or "false", the implicit session object is available
buffer buffering model for the output stream
autoflush if "true", the buffer is flushed automatically if full
125
14 - JSP
isThreadSafe "true" or "false"
isErrorPage "true" or "false"
contentType MME type of the response
info
errorPage the URL of an error page, in case of error
The in$'de directive instructs the container to include inline the content of the resource
specified by "5ile)ame". The format of this directive:
;[Qincl$de 5ileK=5ile)ame= [4
The tag'ib directive allows the usage of custom tags (tag extensions). t has the following
format:
;[Qtagli% $riK=tagLi%ri= pre5ixK=tag7re5ix= [4
where the tagPrefix indicates a name scope.
1(., s$ri&ting e'e.ents
1(.,.1 de$'arati!ns
;[< java vars and method declarations [4
Basicly, a bloc of java code used to define class-wide variables and methods in the generated
servlet.
1(.,.2 s$ri&t'ets
;[ valid java statements [4
Block of java code which is executed during request processing. n Tomcat, this code goes to
inside the service() method.
1(.,.% eC&ressi!ns
;[K java expressions to %e eval$ated [4
126
14 - JSP
A scriptlet that sends a value of a Java expression to back to the client. t is evaluated at
request processing time and the result is converted to a string which is then displayed.
1(.,.( standard a$ti!ns
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.
1(.- the seBean standard a$ti!n
<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:$seCean idK=%ean)ame= scopeK=s)ame= %eandetails /4
where %eandetails is one of the following:
class="className"
class="className" type="typeName"
beanName="beanName" type="typeName"
type="typeName"
1(.0 the set6r!&ert1 standard a$ti!n
;jsp:set7ropertB4
Used in conjunction with the <jsp:useBean> action to set the value of the bean properties.
The syntax for this action is:
;jsp:set7ropertB nameK=%ean)ame= propertBdetails /4
where propertBdetails is one of the following:
property="*"
property="propertyName"
property="propertyName" param="parameterName"
property="propertyName" value="propertyValue"
where propertyValue is a string or a scriptlet.
127
14 - JSP
Attributes description:
name - the name of a bean instance, already defined in a <jsp:useBean>
property -
1(.4 the get6r!&ert1 standard a$ti!n
;jsp:get7ropertB4
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:get7ropertB nameK=%ean)ame= propertBK=prop)ame= /4
Attributes description:
name - the name of a bean instance whose property is to be retrieved
property - name of the property to be retrieved
1(.15 the &ara. standard a$ti!n
;jsp:param4
Provide other tags with additional information in the form of name:value pairs. t is used in
conjunction with the <jsp:include>, <jsp:forward>, <jsp:plugin> actions.
The syntax for this action is:
;jsp:param nameK=param)ame= val$eK=paramGal$e= /4
1(.11 the in$'de standard a$ti!n
;jsp:incl$de4
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:
128
14 - JSP
;jsp:incl$de pageK=pageRL= 5l$shK=tr$e= /4
Attributes description:
page - the URL of the page, same format as the ;[Qincl$de4 directive.
flush - only the "true" value is supported.
1(.12 the "!rward standard a$ti!n
;jsp:5orward4
Used to forward the the request to another JSP, servlet or to a static resource..
The syntax for this action is:
;jsp:5orward pageK=pageRL= /4
The action may include several <jsp:param> tags, as well. t is used mainly, when we want to
separate the application into different views, depending on request.
1(.1% the &'gin standard a$ti!n
;jsp:pl$gin4
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:pl$gin tBpeK=%ean\applet= codeK=o%jCode= codeCaseK=o%jCodeCase=
alignK=align= archiveK=archiveList= heightK=height= hspaceK=hSpace=
jreversionK=jreGersion= nameK=component)ame= vspaceK=vSpace=
widthK=width= nspl$gin$rlK=netscapeRL= iepl$gin$rlK=I'RL=4
;jsp:params4
;jsp:param nameK=param)ame= val$eK=paramGal$e= /4
...
;/jsp:params4
;/jsp:pl$gin4
Attributes description:
name - the name of a bean instance, already defined in a ;jsp:$seCean4
129
14 - JSP
1(.1( i.&'i$it !b#e$ts
JSP provides several implicit objects, based on the servlet AP, objects which are automaticly
available.
1. re@est - represents the object that triggered the service() method invokation and has type
Htt&Ser+'et9e@est with scope re@est
2. res&!nse - represents server's response to the request, it has Htt&Ser+'et9es&!nse type and
&age scope
3. &ageC!nteCt - provides a single point of access to attributes and shared data within the page,
it has type 6ageC!nteCt with scope &age
4. sessi!n - it has Htt&Sessi!n type and sessi!n scope
5. a&&'i$ati!n - represents the servlet context, it has type Ser+'etC!nteCt and scope
a&&'i$ati!n
6. !t - it represents the buffered version of java.io.7rint/riter, writes to the output
stream to the client, it has #a+aC.ser+'et.#s&.3s&Writer type and scope &age
7. $!n"ig - it is the SevletCon5ig for the current JSP page, it is of type Ser+'etC!n"ig and has
&age scope
8. &age - it is an instance of the page's implementation of the servlet class, it has
#a+a.'ang.Ob#e$t type and scope &age
1(.1* s$!&es
1. re@est - an object with request scope is bound to the 6ttpServletReM$est object; the
object can be accessed by invoking the get(ttri%$te01 method on the implicit re@est
object; the generated servlet binds the object to 6ttpServletReM$est object using the
set(ttri%$te0String 2eB3 +%ject val$e1 method
2. sessi!n - an object with session scope is bound to the 6ttpSession object; the object can
be accessed by invoking the getGal$e01 method on the implicit sessi!n object; the
generated servlet binds the object to 6ttpSession object using the set(ttri%$te0String
2eB3 +%ject val$e1 method
3. a&&'i$ati!n - an object with application scope is bound to the ServletContext object; the
object can be accessed by invoking the get(ttri%$te01 method on the implicit a&&'i$ati!n
object; the generated servlet binds the object to the ServletContext object using the
set(ttri%$te0String 2eB3 +%ject val$e1 method
4. &age - an object with page scope is bound to the 7ageContext object; the object can be
accessed by invoking the get(ttri%$te01 method on the implicit &ageC!nteCt object; the
generated servlet binds the object to 7ageContext object using the set(ttri%$te0String
2eB3 +%ject val$e1 method
1(.1, an eCtended eCa.&'e
This example is provided by De+s&here/ a software development and consulting company.
130
14 - JSP
1(.1,.1 Data beans
Si.&'eBean 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.
Si.&'eBean.#a+aE
pac2age com.devsphere.examples.mapping.simpleW
/XX
X Simple %ean
X/
p$%lic class SimpleCean implements java.io.SerialiRa%le U
private String stringW
private 5loat n$m%erW
private int integerW
private %oolean 5lagW
private String colorsSTW
private int listSTW
private String optionalW
private SimpleS$%Cean s$%CeanW
/XX
X )o&arg constr$ctor
X/
p$%lic SimpleCean01 U
V
/XX
X -ets the string propertB
X/
p$%lic String getString01 U
ret$rn this.stringW
V
/XX
X Sets the string propertB
X/
p$%lic void setString0String val$e1 U
this.string K val$eW
V
/XX
X -ets the n$m%er propertB
X/
p$%lic 5loat get)$m%er01 U
ret$rn this.n$m%erW
V
/XX
X Sets the n$m%er propertB
X/
p$%lic void set)$m%er05loat val$e1 U
this.n$m%er K val$eW
V
/XX
131
14 - JSP
X -ets the integer propertB
X/
p$%lic int getInteger01 U
ret$rn this.integerW
V
/XX
X Sets the integer propertB
X/
p$%lic void setInteger0int val$e1 U
this.integer K val$eW
V
/XX
X -ets the 5lag propertB
X/
p$%lic %oolean get*lag01 U
ret$rn this.5lagW
V
/XX
X Sets the 5lag propertB
X/
p$%lic void set*lag0%oolean val$e1 U
this.5lag K val$eW
V
/XX
X -ets the colors propertB
X/
p$%lic StringST getColors01 U
ret$rn this.colorsW
V
/XX
X Sets the colors propertB
X/
p$%lic void setColors0String val$esST1 U
this.colors K val$esW
V
/XX
X -ets an element o5 the colors propertB
X/
p$%lic String getColors0int index1 U
ret$rn this.colorsSindexTW
V
/XX
X Sets an element o5 the colors propertB
X/
p$%lic void setColors0int index3 String val$e1 U
this.colorsSindexT K val$eW
V
/XX
X -ets the list propertB
X/
p$%lic intST getList01 U
132
14 - JSP
ret$rn this.listW
V
/XX
X Sets the list propertB
X/
p$%lic void setList0int val$esST1 U
this.list K val$esW
V
/XX
X -ets an element o5 the list propertB
X/
p$%lic int getList0int index1 U
ret$rn this.listSindexTW
V
/XX
X Sets an element o5 the list propertB
X/
p$%lic void setList0int index3 int val$e1 U
this.listSindexT K val$eW
V
/XX
X -ets the optional propertB
X/
p$%lic String get+ptional01 U
ret$rn this.optionalW
V
/XX
X Sets the optional propertB
X/
p$%lic void set+ptional0String val$e1 U
this.optional K val$eW
V
/XX
X -ets the s$%Cean propertB
X/
p$%lic SimpleS$%Cean getS$%Cean01 U
ret$rn this.s$%CeanW
V
/XX
X Sets the s$%Cean propertB
X/
p$%lic void setS$%Cean0SimpleS$%Cean val$e1 U
this.s$%Cean K val$eW
V
V
Si.&'eSbBean contains only two standard properties (a String and a float).
Si.&'eSbBean.#a+aE
pac2age com.devsphere.examples.mapping.simpleW
133
14 - JSP
/XX
X Simple s$%&%ean
X/
p$%lic class SimpleS$%Cean implements java.io.SerialiRa%le U
private String stringW
private 5loat n$m%erW
/XX
X )o&arg constr$ctor
X/
p$%lic SimpleS$%Cean01 U
V
/XX
X -ets the string propertB
X/
p$%lic String getString01 U
ret$rn this.stringW
V
/XX
X Sets the string propertB
X/
p$%lic void setString0String val$e1 U
this.string K val$eW
V
/XX
X -ets the n$m%er propertB
X/
p$%lic 5loat get)$m%er01 U
ret$rn this.n$m%erW
V
/XX
X Sets the n$m%er propertB
X/
p$%lic void set)$m%er05loat val$e1 U
this.n$m%er K val$eW
V
V
1(.1,.2 the HT2L 8!r.
The properties of SimpleBean are mapped to the form elements of SimpleForm.html:
Name Property type Element type
string String text
number float text
integer int radio[]
134
14 - JSP
flag boolean checkbox
colors String[] checkbox[]
list int[] select
optional String text
subBean.string String text
subBean.number float text
Si.&'e8!r..ht.'E
;6!ML4
;6'(#4;!I!L'4Simple 5orm;/!I!L'4;/6'(#4
;C+#F4
;634Simple 'xample;/634
;*+RM M'!6+#K=7+S!=4
;74 String ;CR4
;I)7! !F7'K=!'X!= )(M'K=string= SIJ'K=D9=4
;74 )$m%er ;CR4
;I)7! !F7'K=!'X!= )(M'K=n$m%er= SIJ'K=D9=4
;74 Integer ;CR4
;I)7! !F7'K=R(#I+= )(M'K=integer= G(L'K=8=4+ption 8
;I)7! !F7'K=R(#I+= )(M'K=integer= G(L'K=D=4+ption D
;I)7! !F7'K=R(#I+= )(M'K=integer= G(L'K=3=4+ption 3
;74 *lag ;CR4
;I)7! !F7'K=C6'CKC+X= )(M'K=5lag=4*lag
;74 Colors ;CR4
;I)7! !F7'K=C6'CKC+X= )(M'K=colors= G(L'K=red=4Red
;I)7! !F7'K=C6'CKC+X= )(M'K=colors= G(L'K=green=4-reen
;I)7! !F7'K=C6'CKC+X= )(M'K=colors= G(L'K=%l$e=4Cl$e
;74 List ;CR4
;S'L'C! )(M'K=list= SIJ'K=3= ML!I7L'4
;+7!I+) G(L'K=8=4Item 8;/+7!I+)4
;+7!I+) G(L'K=D=4Item D;/+7!I+)4
;+7!I+) G(L'K=3=4Item 3;/+7!I+)4
;/S'L'C!4
;74 +ptional ;CR4
;I)7! !F7'K=!'X!= )(M'K=optional= SIJ'K=D9=4
;74 String 0s$%Cean1 ;CR4
;I)7! !F7'K=!'X!= )(M'K=s$%Cean.string= SIJ'K=D9=4
;74 )$m%er 0s$%Cean1 ;CR4
;I)7! !F7'K=!'X!= )(M'K=s$%Cean.n$m%er= SIJ'K=D9=4
;74
135
14 - JSP
;I)7! !F7'K=SCMI!= G(L'K=S$%mit=4
;I)7! !F7'K=R'S'!= G(L'K=Reset=4
;/*+RM4
;/C+#F4
;/6!ML4
1(.1,.% bean res!r$es
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. t 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.
Si.&'eBean9es!r$es.#a+aE
pac2age com.devsphere.examples.mapping.simpleW
p$%lic class SimpleCeanReso$rces extends java.$til.ListReso$rceC$ndle U
private static 5inal +%jectSTST contents K U
U =S#'*(L!,G(L'.stringT=3 =a%c= V3
U =S#'*(L!,G(L'.n$m%erT=3 new *loat09.8D31 V3
U =S#'*(L!,G(L'.5lagT=3 new Coolean0tr$e1 V3
U =S#'*(L!,G(L'.listT=3 new intST U D3 3 V V3
U =S'RR+R,M'SS(-'.integerT=3 =(n option m$st %e selected= V3
U =S'RR+R,M'SS(-'.colorsT=3 =+ne or more colors m$st %e
selected= V3
U =S'RR+R,M'SS(-'.listT=3 =+ne or more items m$st %e
selected= V3
U
=S+7!I+)(L,7R+7'R!I'ST=3
new StringST U
=optional=
V
V3
U
=S7R+C'SSI)-,+R#'RT=3
new StringST U
=string=3
=n$m%er=3
=integer=3
=5lag=3
=colors=3
=list=3
=optional=3
=s$%Cean=
136
14 - JSP
V
V3
U =S*+RM,)(M'T=3 =Simple*orm.html= V3
U =S7R+C,)(M'T=3 =Simple7roc.jsp= V
VW
p$%lic +%jectSTST getContents01 U
ret$rn contentsW
V
V
1(.1,.( 3S6 Hand'er
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). f 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. t 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.
Si.&'eHnd'.#s&E
;[Q page lang$ageK=java= [4
;[Q page importK=com.devsphere.mapping.X3 com.devsphere.logging.X= [4
;jsp:$seCean idK=simpleCean= scopeK=reM$est=
classK=com.devsphere.examples.mapping.simple.SimpleCean=/4
;[
// -et the %ean reso$rces
java.$til.Reso$rceC$ndle %eanRes
K 6andlertils.getCeanReso$rces0simpleCean.getClass011W
// Constr$ct the %ase path
String %ase7ath K reM$est.getServlet7ath01W
int slashIndex K %ase7ath.lastIndex+50I/I1W
%ase7ath K slashIndex <K &8 O %ase7ath.s$%string093 slashIndex]81 :
==W
// #etermine the 6!!7 method
%oolean is7ostMethod K reM$est.getMethod01.eM$als0=7+S!=1W
// Create a logger that wraps the servlet context
ServletLogger logger K new ServletLogger0application1W
// /rap the 5orm data
*orm#ata 5orm#ata K new Servlet*orm#ata0reM$est1W
// *orm&to&%ean mapping: reM$est parameters are mapped to %ean
properties
java.$til.6ashta%le error!a%le
K *ormtils.5orm!oCean05orm#ata3 simpleCean3 logger1W
137
14 - JSP
i5 0is7ostMethod PP error!a%le KK n$ll1 U
// Constr$ct the processorIs path
String proc7ath K %ase7ath ]
%eanRes.getString0=S7R+C,)(M'T=1.trim01W
// 7rocess the valid data %ean instance
application.getReM$est#ispatcher0proc7ath1.5orward0reM$est3
response1W
V else U
i5 0<is7ostMethod1
// Ignore the $ser errors i5 the 5orm is reM$ested with -'!.
error!a%le K 6andlertils.removeser'rrors0error!a%le1W
// Constr$ct the 5ormIs path
String 5orm7ath K %ase7ath ]
%eanRes.getString0=S*+RM,)(M'T=1.trim01W
5orm7ath K application.getReal7ath05orm7ath1W
// -et the 5orm template
*orm!emplate template K *ormtils.get!emplate0new
java.io.*ile05orm7ath11W
// -et a new doc$ment
*orm#oc$ment doc$ment K template.get#oc$ment01W
// Cean&to&5orm mapping: %ean properties are mapped to 5orm
elements
*ormtils.%ean!o*orm0simpleCean3 error!a%le3 doc$ment3 logger1W
// Send the 5orm doc$ment
doc$ment.send0o$t1W
V
[4
1(.1,.* 3S6 6r!$ess!r
The SimpleProc.jsp processor gets the beans that were validated by the JSP handler and prints
the values of their properties.
Si.&'e6r!$.#s&E
;[Q page lang$ageK=java=[4
;jsp:$seCean idK=simpleCean= scopeK=reM$est=
classK=com.devsphere.examples.mapping.simple.SimpleCean=/4
;6!ML4
;6'(#4;!I!L'4Simple %ean;/!I!L'4;/6'(#4
;C+#F4
;634Simple 'xample;/634
;74;C4 SimpleCean properties: ;/C4
;74 string K ;jsp:get7ropertB nameK=simpleCean= propertBK=string=/4
;74 n$m%er K ;jsp:get7ropertB nameK=simpleCean= propertBK=n$m%er=/4
;74 integer K ;jsp:get7ropertB nameK=simpleCean=
propertBK=integer=/4
;74 5lag K ;jsp:get7ropertB nameK=simpleCean= propertBK=5lag=/4
;74 colors K ;[K toString0simpleCean.getColors011 [4
;74 list K ;[K toString0simpleCean.getList011 [4
;74 optional K ;jsp:get7ropertB nameK=simpleCean=
propertBK=optional=/4
;74 s$%Cean.string K ;[K simpleCean.getS$%Cean01.getString01 [4
138
14 - JSP
;74 s$%Cean.n$m%er K ;[K simpleCean.getS$%Cean01.get)$m%er01 [4
;/C+#F4
;/6!ML4
;[<
p$%lic static String toString0String listST1 U
i5 0list KK n$ll \\ list.length KK 91
ret$rn ==W
i5 0list.length KK 8 PP listS9T <K n$ll1
ret$rn listS9TW
StringC$55er str%$5 K new StringC$55er01W
str%$5.append0=U =1W
5or 0int i K 9W i ; list.lengthW i]]1
i5 0listSiT <K n$ll1 U
str%$5.append0listSiT1W
str%$5.append0= =1W
V
str%$5.append0=V=1W
ret$rn str%$5.toString01W
V
p$%lic static String toString0int listST1 U
i5 0list KK n$ll \\ list.length KK 91
ret$rn ==W
i5 0list.length KK 81
ret$rn Integer.toString0listS9T1W
StringC$55er str%$5 K new StringC$55er01W
str%$5.append0=U =1W
5or 0int i K 9W i ; list.lengthW i]]1 U
str%$5.append0listSiT1W
str%$5.append0= =1W
V
str%$5.append0=V=1W
ret$rn str%$5.toString01W
V
[4
1(.1,., with!t sing the de+s&here "ra.ew!r>
ComplexForm.jsp generates the HTML form dynamically and inserts default values and error
messages. t 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. n 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. n addition, default values and error messages are kept in localizable resource
bundles. A later chapter shows how to build internationalized applications using the framework.
C!.&'eC8!r..#s&E
;[Q page lang$ageK=java= [4
139
14 - JSP
;jsp:$seCean idK=simpleCean= scopeK=reM$est=
classK=com.devsphere.examples.mapping.simple.SimpleCean=/4
;jsp:$seCean idK=error!a%le= scopeK=reM$est=
classK=java.$til.6ashta%le=/4
;6!ML4
;6'(#4;!I!L'4/itho$t $sing the 5ramewor2;/!I!L'4;/6'(#4
;C+#F4
;634'M$ivalent o5 Simple 'xample;/634
;*+RM M'!6+#K7+S!4
;74 String ;CR4
;[K get'rrorMessage0error!a%le3 =string=1 [4
;I)7! !F7'K=!'X!= )(M'K=string=
G(L'K=;jsp:get7ropertB nameK=simpleCean= propertBK=string=/4=4
;74 )$m%er ;CR4
;[K get'rrorMessage0error!a%le3 =n$m%er=1 [4
;I)7! !F7'K=!'X!= )(M'K=n$m%er=
G(L'K=;jsp:get7ropertB nameK=simpleCean= propertBK=n$m%er=/4=4
;74 Integer ;CR4
;[K get'rrorMessage0error!a%le3 =integer=1 [4
;[
String integerLa%elsST K U =+ption 8=3 =+ption D=3 =+ption 3= VW
5or 0int i K 9W i ; integerLa%els.lengthW i]]1 U
int val$e K i]8W
%oolean chec2ed K simpleCean.getInteger01 KK val$eW
[4
;I)7! !F7'K=R(#I+= )(M'K=integer= G(L'K=;[K val$e [4=
;[K chec2ed O =C6'CK'#= : == [44 ;[K integerLa%elsSiT [4
;[
V
[4
;74 *lag ;CR4
;[K get'rrorMessage0error!a%le3 =5lag=1 [4
;I)7! !F7'K=C6'CKC+X= )(M'K=5lag=
;[K simpleCean.get*lag01 O =C6'CK'#= : == [44 *lag
;74 Colors ;CR4
;[K get'rrorMessage0error!a%le3 =colors=1 [4
;[
String colorsST K simpleCean.getColors01W
i5 0colors KK n$ll1
colors K new StringS9TW
String colorLa%elsST K U =Red=3 =-reen=3 =Cl$e= VW
String colorGal$esST K U =red=3 =green=3 =%l$e= VW
5or 0int i K 9W i ; colorGal$es.lengthW i]]1 U
%oolean chec2ed K 5alseW
i5 0colors <K n$ll1
5or 0int j K 9W j ; colors.lengthW j]]1
i5 0colorsSjT.eM$als0colorGal$esSiT11 U
chec2ed K tr$eW
%rea2W
V
[4
;I)7! !F7'K=C6'CKC+X= )(M'K=colors= G(L'K=;[K colorGal$esSiT
[4=
;[K chec2ed O =C6'CK'#= : == [44 ;[K colorLa%elsSiT [4
140
14 - JSP
;[
V
[4
;74 List ;CR4
;[K get'rrorMessage0error!a%le3 =list=1 [4
;S'L'C! )(M'K=list= SIJ'K=3= ML!I7L'4
;[
int listST K simpleCean.getList01W
i5 0list KK n$ll1
list K new intS9TW
String listItemsST K U =Item 8=3 =Item D=3 =Item 3= VW
5or 0int i K 9W i ; listItems.lengthW i]]1 U
int val$e K i]8W
%oolean selected K 5alseW
i5 0list <K n$ll1
5or 0int j K 9W j ; list.lengthW j]]1
i5 0listSjT KK val$e1 U
selected K tr$eW
%rea2W
V
[4
;+7!I+) G(L' K =;[K val$e [4=
;[K selected O =S'L'C!'#= : == [44 ;[K listItemsSiT [4
;[
V
[4
;/S'L'C!4
;74 +ptional ;CR4
;[K get'rrorMessage0error!a%le3 =optional=1 [4
;I)7! !F7'K=!'X!= )(M'K=optional=
G(L'K=;jsp:get7ropertB nameK=simpleCean= propertBK=optional=/4=4
;[ i5 0simpleCean.getS$%Cean01 KK n$ll1 simpleCean.setS$%Cean0
new com.devsphere.examples.mapping.simple.SimpleS$%Cean011W [4
;74 String 0s$%Cean1 ;CR4
;[K get'rrorMessage0error!a%le3 =s$%Cean.string=1 [4
;I)7! !F7'K=!'X!= )(M'K=s$%Cean.string=
G(L'K=;[K simpleCean.getS$%Cean01.getString01 [4=4
;74 )$m%er 0s$%Cean1 ;CR4
;[K get'rrorMessage0error!a%le3 =s$%Cean.n$m%er=1 [4
;I)7! !F7'K=!'X!= )(M'K=s$%Cean.n$m%er=
G(L'K=;[K simpleCean.getS$%Cean01.get)$m%er01 [4=4
;74
;I)7! !F7'K=SCMI!= G(L'K=S$%mit=4
;I)7! !F7'K=R'S'!= G(L'K=Reset=4
;/*+RM4
;/C+#F4
;/6!ML4
;[<
String get'rrorMessage0java.$til.6ashta%le error!a%le3 String
propertB1 U
String message K 0String1 error!a%le.get0propertB1W
141
14 - JSP
i5 0message KK n$ll1
message K ==W
ret$rn messageW
V
[4
C!.&'eCHnd'.#s&E
;[Q page lang$ageK=java= [4
;jsp:$seCean idK=simpleCean= scopeK=reM$est=
classK=com.devsphere.examples.mapping.simple.SimpleCean=/4
;jsp:$seCean idK=simpleS$%Cean= scopeK=page=
classK=com.devsphere.examples.mapping.simple.SimpleS$%Cean=/4
;jsp:$seCean idK=error!a%le= scopeK=reM$est=
classK=java.$til.6ashta%le=/4
;[
simpleCean.setS$%Cean0simpleS$%Cean1W
%oolean is7ostMethod K reM$est.getMethod01.eM$als0=7+S!=1W
i5 0is7ostMethod1 U
//X string : text
[4
;jsp:set7ropertB nameK=simpleCean= propertBK=string=/4
;[
i5 0simpleCean.getString01 KK n$ll
\\ simpleCean.getString01.length01 KK 91 U
simpleCean.setString0=a%c=1W
set'rrorMessage0error!a%le3 =string=3 =M$st %e 5illed=1W
V
//X n$m%er : text
trB U
String n$m%erGal$e K reM$est.get7arameter0=n$m%er=1W
i5 0n$m%erGal$e <K n$ll PP n$m%erGal$e.length01 <K 91
simpleCean.set)$m%er0new
*loat0n$m%erGal$e1.5loatGal$e011W
else U
simpleCean.set)$m%er09.8D351W
set'rrorMessage0error!a%le3 =n$m%er=3 =M$st %e 5illed=1W
V
V catch 0)$m%er*ormat'xception e1 U
simpleCean.set)$m%er09.8D351W
set'rrorMessage0error!a%le3 =n$m%er=3 =M$st %e a n$m%er=1W
V
//X integer : radio gro$p
[4
;jsp:set7ropertB nameK=simpleCean= propertBK=integer=/4
;[
i5 0simpleCean.getInteger01 KK 91 U
set'rrorMessage0error!a%le3 =integer=3 =(n option m$st %e
selected=1W
V
//X 5lag : chec2%ox
142
14 - JSP
String 5lagGal$e K reM$est.get7arameter0=5lag=1W
i5 05lagGal$e <K n$ll1 U
5lagGal$e K 5lagGal$e.trim01W
i5 05lagGal$e.length01 KK 9 \\ 5lagGal$e.eM$als0=5alse=11
5lagGal$e K n$llW
V
simpleCean.set*lag05lagGal$e <K n$ll1W
//X color : chec2%ox gro$p
[4
;jsp:set7ropertB nameK=simpleCean= propertBK=colors=/4
;[
i5 0simpleCean.getColors01 KK n$ll
\\ simpleCean.getColors01.length KK 91 U
set'rrorMessage0error!a%le3 =colors=3
=+ne or more colors m$st %e selected=1W
V
//X list : select
[4
;jsp:set7ropertB nameK=simpleCean= propertBK=list=/4
;[
i5 0simpleCean.getList01 KK n$ll
\\ simpleCean.getList01.length KK 91 U
simpleCean.setList0new intST U D3 3 V1W
set'rrorMessage0error!a%le3 =list=3
=+ne or more items m$st %e selected=1W
V
//X optional : text
[4
;jsp:set7ropertB nameK=simpleCean= propertBK=optional=/4
;[
i5 0simpleCean.get+ptional01 KK n$ll1
simpleCean.set+ptional0==1W
//X s$%Cean.string : text
[4
;jsp:set7ropertB nameK=simpleS$%Cean= propertBK=string=
paramK=s$%Cean.string=/4
;[
i5 0simpleS$%Cean.getString01 KK n$ll
\\ simpleS$%Cean.getString01.length01 KK 91 U
simpleS$%Cean.setString0==1W
set'rrorMessage0error!a%le3 =s$%Cean.string=3 =M$st %e
5illed=1W
V
//X s$%Cean.n$m%er : text
trB U
String n$m%erGal$e K reM$est.get7arameter0=s$%Cean.n$m%er=1W
i5 0n$m%erGal$e <K n$ll PP n$m%erGal$e.length01 <K 91
simpleS$%Cean.set)$m%er0new
143
14 - JSP
*loat0n$m%erGal$e1.5loatGal$e011W
else U
set'rrorMessage0error!a%le3 =s$%Cean.n$m%er=3 =M$st %e
5illed=1W
V
V catch 0)$m%er*ormat'xception e1 U
set'rrorMessage0error!a%le3 =s$%Cean.n$m%er=3 =M$st %e a
n$m%er=1W
V
V else U
simpleCean.setString0=a%c=1W
simpleCean.set)$m%er09.8D351W
simpleCean.set*lag0tr$e1W
simpleCean.setList0new intST U D3 3 V1W
simpleCean.set+ptional0==1W
simpleS$%Cean.setString0==1W
V
i5 0is7ostMethod PP error!a%le.is'mptB011 U
[4
;jsp:5orward pageK=Simple7roc.jsp=/4
;[
V else U
[4
;jsp:5orward pageK=Complex*orm.jsp=/4
;[
V
[4
;[<
void set'rrorMessage0java.$til.6ashta%le error!a%le3
String propertB3 String message1 U
message K =;*+)! C+L+RK^=_**9999^=4= ] message ] =;/*+)!4;CR4=W
error!a%le.p$t0propertB3 message1W
V
[4
1(.1,.- sing the "ra.ew!r> with ser+'ets and 3S6s
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:
Simple6ndl.codeKcom.devsphere.helpers.mapping.Cean#ispatcher
Simple6ndl.initparamsK^
C'(),)(M'Kcom.devsphere.examples.mapping.simple.SimpleCean3^
C'(),I#KsimpleCean3^
C(S',7(!6K/simple
or
;servlet4
;servlet&name4Simple6ndl;/servlet&name4
;servlet&
144
14 - JSP
class4com.devsphere.helpers.mapping.Cean#ispatcher;/servlet&class4
;init&param4
;param&name4C'(),)(M';/param&name4
;param&
val$e4com.devsphere.examples.mapping.simple.SimpleCean;/param&val$e4
;/init&param4
;init&param4
;param&name4C'(),I#;/param&name4
;param&val$e4simpleCean;/param&val$e4
;/init&param4
;init&param4
;param&name4C(S',7(!6;/param&name4
;param&val$e4/simple;/param&val$e4
;/init&param4
;/servlet4
GenericHandler and BeanDispatcher were presented in a previous chapter.
1(.1,.0 wh1 sing ser+'etsF
Using a JSP, you have to declare the bean within a <jsp:useBean> tag. f your Web application
contains many forms/beans, you have to provide a JSP handler for each bean. A servlet can be
made bean-independent.
n many cases, a servlet is identified with its class. Users invoke the servlet by requesting a
URL like this:
http://www.host.com/(pp)ame/servlet/Servlet)ame
The servlet engine associates a servlet to a class in the servlets.properties (or web.xml) file:
Servlet)ame.codeKcom.companB.Class)ame
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. f you have another
bean-form pair, you could add a few other lines to servlets.properties:
(nother6ndl.codeKcom.devsphere.helpers.mapping.Cean#ispatcher
(nother6ndl.initparamsK^
C'(),)(M'Kcom.devsphere.examples.mapping.another.(notherCean3^
C'(),I#KanotherCean3^
C(S',7(!6K/another
The two servlets that share the same code could be invoked with something like this
http://www.host.com/(pp)ame/servlet/Simple6ndl
http://www.host.com/(pp)ame/servlet/(nother6ndl
145
15 - javaserver faces
1* - 3A7ASE97E9 8ACES
1*.1 what are #a+aSer+er "a$esF
JavaServer Faces technology is a server-side user interface component framework for Java
based web applications. This technology includes:
1. A set of APs for:
representing U components, like input fields, buttons, links
U 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.
1*.2 #a+aSer+er 8a$es Te$hn!'!g1 1.2
The latest version of JavaServer Faces technology is version 1.2, the final version of which has
been released through the Java Community Process under Java Specification Request (JSR)
252.
The latest implementation of version 1.2 is the patch release, version 1.2_09.
There are two JSF specific tag libraries defined in this specification, namely the core JSF tags
and the html JSF tags.
1*.% the ht.' 3S8 tags
This tag library contains JavaServer Faces component tags for all UComponent + 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
146
15 - javaserver faces
commands
selections
layouts
data table
errors and messages
1*.%.1 the 'ist !" 3S8 HT2L Tags
For reference, here is an exhaustive list of the JSF HTML tags:
column
commandButton
commandLink
dataTable
form
graphicmage
inputHidden
inputSecret
inputText
inputTextArea
message
messages
outputFormat
outputLabel
outputLink
outputText
panelGrid
pnelGroup
selectBooleanCheckbox
selectManyCheckbox
selectManyListbox
selectManyMenu
selectOneListbox
selectOneMenu
selectOneRadio
n the next paragraphs, we'll have a closer look at some of these tags.
147
15 - javaserver faces
1*.%.2 hEdataTab'e
The dataTab'e 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 dataTab'e 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 dataTab'e 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.
ECa.&'eE
<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="tem 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>
<f:facet name="footer">
<h:outputText value="Total: #{shoppingCartBean.total}" />
</f:facet>
</h:dataTable>
/TM. Output
<table id="table1">
<thead>
<tr><th scope="colgroup" colspan="2">Your Shopping Cart</th></tr>
<tr><th>tem 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>
148
15 - javaserver faces
</tbody>
<tfoot>
<tr><td colspan="2">Total: $15.00</td></tr>
</tfoot>
</table>
1*.%.% hE"!r.
The "!r. 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.
f 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.
ECa.&'eE
<h:form id="form1"></h:form>
/TM. Output
<form id="form1" name="form1" method="post" action="/demo/form.jsp"
enctype="application/x-www-form-urlencoded"></form>
1*.%.( hE$!..andBtt!n
The $!..andBtt!n 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 (18N).
ECa.&'eE
<h:commandButton id="button1" value="#{bundle.checkoutLabel}"
action="#{shoppingCartBean.checkout}" />
/TM. Output
<input id="form:button1" name="form:button1" type="submit" value="Check
Out" onclick="someEvent();" />
1*.%.* hEin&tTeCt
The in&tTeCt tag renders an HTML input element of the type "text".
ECa.&'eE
<h:inputText id="username" value="#{userBean.user.username}" />
/TM. Output
<input id="form:username" name="form:username" type="text" />
1*.%., .essage Tag
The .essage tag renders a message for a specific component. You can customize the
message generated by this component by applying different CSS st1'es to the message
149
15 - javaserver faces
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 !+erriding specific JSF
properties in your message bundle.
ECa.&'eE
;h:inp$t!ext idK=$sername= reM$iredK=_Utr$eV=
val$eK=_U$serCean.$ser.$sernameV=
errorStBleK=color:red=/4
;h:message 5orK=$sername= /4
/TM. Output
;inp$t tBpeK=text= idK=5orm:$sername= nameK=5orm:$sername= val$eK==/4
;span stBleK=color:red=4=$sername=: Gal$e is reM$ired.;/span4
1*.( the $!re 3S8 tags
The core JavaServer Faces tags define custom actions that are independent of any particular
RenderKit.
1*.(.1 the 'ist !" 3S8 C!re Tags
Here is an exhaustive list of the JSF core tags:
actionListener
attribute
convertDateTime
converter
convertNumber
facet
loadBundle
param
selecttem
selecttems
subview
validateDoubleRange
validateLength
validateLongRange
validator
valueChangeListener
verbatim
view
Some of these tags will be detailed in the next paragraphs.
150
15 - javaserver faces
1*.(.2 "E"a$et
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. A
facet represents a named section within a container component. For example, you can create a
header and a footer facet for a dataTable component.
ECa.&'eE
;h:data!a%le idK=report!a%le= val$eK=_UreportCean.dailBReportV=
varK=item=4
<h:column>
<f:facet name="header">
<h:outputText value="Daily Report" />
</f:facet>
<h:outputText value="#{item}" />
</h:column>
</h:dataTable>
/TM. Output
<table id="reportTable">
<thead>
<tr><th>Daily Report</th></tr>
</thead>
<tbody>
<tr><td>tem 1</td></tr>
<tr><td>tem 2</td></tr>
<tr><td>tem 3</td></tr>
</tbody>
</table>
1*.(.% "E+a'idat!r
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 D you assigned to your validator class in your Faces
configuration file. The body content of this tag must be empty.
ECa.&'eE
<h:inputText id="emailAddress"
value="#{customerBean.customer.emailAddress}">
<f:validator validatord="emailAddressValidator" />
</h:inputText>
<h:message for="emailAddress" />
/TM. Output
<input id="form:emailAddress" name="form:emailAddress" type="text"
value="fake@email"/>
nvalid email address.
151
15 - javaserver faces
1*.(.( "E+a'eChangeListener
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.
ECa.&'eE
<h:selectOneMenu id="optionMenu" value="#{optionBean.selectedOption}"
onchange="submit()">
<f:selecttems value="#{optionBean.optionList}" />
<f:valueChangeListener
type="com.mycompany.MyValueChangeListenermpl" />
</h:selectOneMenu>
/TM. 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>
1*.(.* "E+iew
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 (18N) purposes. t 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.
f 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. f you have not specified a default
locale, JSF will use the default locale for the Java Virtual Machine serving your application.
f your application supports the locale requested by the user, JSF will set that locale for the view
and 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
152
15 - javaserver faces
user. The locale attribute accepts a value-binding expression that could resolve to the desired
locale.
ECa.&'eE
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>
/TM. Output
welcome_en.jsp (English)
Welcome to our site!
welcome_fr.jsp (French)
Bienvenue notre site!
1*.* the str$tre !" a 3S8 a&&'i$ati!n
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-NF
/classes
/lib
jsf-impl.jar
jsf-api.jar
faces-config.xml
web.xml
/pages
Comments on this structure:
.13S8a&& application base directory with application name
/ant directory containing Ant build scripts with a default bi'd.C.' file
153
15 - javaserver faces
/3a+aS!r$e application specific java source classes and properties files
/WebC!ntent contains the Web application files used by the application server or by
the web container
/WEB-IN8 contains files used as part of the runtime Web application
/$'asses compiled Java classes and properties files copied from the /JavaSource
directory
/'ib - contains libraries required by the application, like third party jar files
#s"-i.&'.#ar, #s"-a&i.#ar files included in the /lib directory, mandatory for any JSF
application
web.C.' the deployment descriptor of the application, included in the /WEB-NF
directory
"a$es-$!n"ig.C.' the JSF configuration file, included in the /WEB-NF directory
/&ages directory containing JSP and HTML presentation pages
1*., h!w d!es 3S8 w!r>F a "irst eCa.&'e
Example taken from http://www.exadel.com/tutorial/jsf/jsftutorial-kickstart.html.
A JSF application is nothing else but a servlet/JSP application. t 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
1*.,.1 $reating 3S6 6ages
Create the in&tna.e.#s& and greeting.#s& files in WebC!ntentB&agesB. 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.
1*.,.2 na+igati!n
Navigation is the heart of JavaServer Faces. The navigation rule for this application is
described in the "a$es-$!n"ig.C.' file. This file already exists in the skeleton directory structure.
154
15 - javaserver faces
You just need to create its contents.
n our application, we just want to go from in&tna.e.#s& to greeting.#s&. As a diagram, it
would look something like this:
"mage from )xadel Studio Pro
The navigation rule shown in the picture is defined below. The rule says that from the view
(page) in&tna.e.#s& go to the view (page) greeting.#s&, if the "outcome" of executing
in&tna.e.#s& 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.
1*.,.% $reating the 2anaged Bean
Next, we will create a .138Sa&& folder inside the 3a+aS!r$e folder. nside this .138Sa&&
folder, we will create a 6ers!nBean.#a+a file. This class is straight-forward. t'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.)
01.2.".0 Person,e#n.j#v#
Put this code in the file:
package myJFSapp;
public class PersonBean {
String personName;
155
15 - javaserver faces
/**
* @return Person Name
*/
public String getPersonName() {
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.
01.2.".3 decl#rin$ the ,e#n in (#ces4con(i$.5ml
Now, the second part of "a$es-$!n"ig.C.' describes our Java bean that we created in the
previous steps. This section defines a bean name 6ers!nBean. The next line is the full class
name, .138Sa&&.6ers!nBean. re@est 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>
01.2."." (#ces4con(i$.5ml
Your final "a$es-$!n"ig.C.' file should look like this:
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLC
"-//Sun Microsystems, nc.//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>
156
15 - javaserver faces
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
1*.,.( $reating a 6r!&erties 8i'e :9es!r$e Bnd'e;
A properties file is just a file with param=value pairs. We use the messages stored in the
properties 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 bnd'e folder in the 3a+aS!r$eB.138Sa&& folder and then a
.essages.&r!&erties file in the bnd'e folder. We need to place it in the 3a+aS!r$e folder so
that during project compilation, this properties file will be copied to the $'asses folder where the
runtime can find it.
01.2.6.0 mess#$es.properties
Put this text in the properties file:
inputname_header=JSF KickStart
prompt=Tell us your name:
greeting_text=Welcome to JSF
button_text=Say Hello
sign=!
We now have everything to create the JSP pages.
1*.,.* editing the 3S6 6ages
Two pages should already have been created in .138Sa&&BWebC!ntentB&ages.
01.2.1.0 inputn#me.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>
157
15 - javaserver faces
<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 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 re@ired attribute of the hEin&tTeCt 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 in&tna.eIheader 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 &r!.&t.
Lines 3-5. Creates an HTML input text box. n the +a'e 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 a$ti!n attribute is set to greeting which matches the
navigation-outcome in "a$es-$!n"ig.C.' file. That's how JSF knows where to go next.
01.2.1.3 $reetin$.jsp
Put this coding inside the second JSP file:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
158
15 - javaserver faces
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="myJFSapp.bundle.messages" var="msg"/>
<html>
<head>
<title>greeting page</title>
</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 Gh%H...GBh%H 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 &ers!nNa.e, 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!
1*.,., $reating the indeC.#s& 8i'e
We will now create a third JSP file that doesn't actually function as a presentation page. t uses
a JSP tag to "forward" to the in&tna.e.#s& page.
Create the indeC.#s& file inside the WebC!ntent folder. Note that this file is not created in the
&ages folder like the previous JSP files.
Having an indeC.#s& 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>
f you look at the path for the forward, you'll notice the file suffix is .#s" and not .#s&. This is used
here, because in the we%.xml file for the application X.js5 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.
159
15 - javaserver faces
1*.,.- C!.&i'ing
An Ant build script is provided for you. To build the application run the bi'd.C.' script from the
ant folder:
ant build
1*.,.0 De&'!1ing
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 JT!.$atH!.eKL$!n"Lser+er.C.' file.
To do this, insert this code:
<Context debug="0"
docBase="Path_to_WebContent"
path="/myJFSapp" reloadable="true"/>
near the end of the ser+er.C.' file within the H!st element just before the closing GBH!stH tag.
Of course, 6athIt!IWebC!ntent needs to be replaced with the exact path on your system to the
WebC!ntent folder inside the .138Sa&& folder (for example,
C:/examples/mBZ*Sapp//e%Content).
1*.,.4 9nning
Next, start the Tomcat server (probably using the script start&.bat in Tomcat's bin directory).
When Tomcat is done loading, launch a web browser and enter:
htt&EBB'!$a'h!stE0505B.138Sa&&. (Port 8080 is the default port in Tomcat. Your setup, though,
might possibly be different).
1*.- $reating a 3S8 a&&'i$ati!n in e$'i&se with the "a$esIDE &'gin
Example taken from http://amateras.sourceforge.jp/docs/FacesDE/SampleJSFApp.html .
1*.-.1 O+er+iew
This is a tutorial in which we create a simple JSF application to demonstrate FacesDE's
functionality. This is a "login" application, which asks an user for an D 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 FacesDE 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 FacesDE and required plugins have been installed;
see nstalling & Uninstalling. We don't assume that a J2EE server-specific plugin, such as the
Sysdeo Tomcat plugin has been installed.
1*.-.2 Creating A 6r!#e$t
Here we create an Eclipse project, and set up folders for a web application. The folder structure
160
15 - javaserver faces
created is simply one that works for this author; your mileage may vary.
1. From the menu bar select 8i'eBNewB6r!#e$t.... The New Project wizard appears.
2. Select 3a+a 6r!#e$t; click Next.
3. Enter project name, say, js5&login; click 8inish
4. Create the web root folder, in Package Explorer select the js5&login project, and from
the menubar select 8i'eBNewB8!'der; name the folder we%root
5. Create the web pages folder, in Package Explorer select the we%root folder, and from its
context menu select 8i'eBNewB8!'der; name the folder pages. This folder will contain all
"functional" pages.
6. =se 8a$esIDE t! add 3S8 s&&!rtE we use a FacesDE wizard to create J2EE-
prescribed folders and files in webroot, and to add JSF libraries to the project.
a. in Package Explorer select the js5&login project
b. from the menubar select 8i'eBNewBOther...
c. in the wizard that appears, select A.aterasB3S8BAdd 3S8 S&&!rt; click NeCt
d. in the Add 3S8 S&&!rt page, for Web A&&'i$ati!n 9!!t enter /js5&
login/we%root; make sure all checkboxes are checked; click NeCt.
7. From the menubar open 6r!#e$tB6r!&erties
8. Select the A.ateras node; note that 9!!tE has automatically been set to /we%root;
make sure HTML validation and DTD/XSD validation are enabled.
9. Create the source folder, select the 3a+a Bi'd 6ath node; select the S!r$e tab; click
Add 8!'der...; in the dialog that appears create a folder named src directly under the
project folder (js5&login); click Mes through messages that appear.
10.Set the output folder, in the De"a't !t&t "!'der textbox at the bottom, enter js5&
login/we%root//'C&I)*/classes; click OK to dismiss the properties dialog.
Your folder structure should now be as follows:
js5&login
\
]&& src
\
]&& we%root
\
]&& /'C&I)*
\ \
\ ]&& classes 0not shown in Zava perspective1
\ \
\ ]&& li%
\
]&& pages
1*.-.% Creating N C!n"igring 2anaged 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.
161
15 - javaserver faces
1. n Package Explorer select the src folder; from its context menu select NewBC'ass. The
New 3a+a C'ass wizard appears.
2. n the 6a$>age field, enter login; in the Na.e field enter LoginManager. Click 8inish.
The Java code editor opens.
3. Enter and save the following code for the LoginManager class:
// LoginManager.java
pac2age loginW
p$%lic class LoginManager U
private String ,$id K ==W
private String ,pwd K ==W

p$%lic String getserI#01 U ret$rn ,$idW V
p$%lic void setserI#0String $id1 U ,$id K $idW V
p$%lic String get7assword01 U ret$rn ,pwdW V
p$%lic void set7assword0String pwd1 U ,pwd K pwdW V

p$%lic String login(ction01 U
String action K n$llW

i5 0 ,$id.eM$alsIgnoreCase0=5oo=1 PP
,pwd.eM$alsIgnoreCase0=%ar=1 1
action K =login7ass=W
else
action K =login*ail=W

ret$rn actionW
V
V
4. =se 8a$esIDE t! $!n"igre the beanE we use a FacesDE editor to configure
LoginManager as a session-scoped managed bean.
a. in Package Explorer select js5&login/we%root//'C&I)*/5aces&
con5ig.xml; from its context menu select O&en WithB"a$es-$!n"ig.C.' Edit!r.
The faces-config.xml editor opens.
b. along the bottom of the editor there are 3 tabs; click 2anaged Bean.
c. click Add; input widgets appear
d. for na.e enter mgr; for $'ass enter login.LoginManager; for s$!&e select
session.
e. from the menubar select 8i'eBSa+e, then close the editor
1*.-.( Creating 3S6 6ages
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, s$ccess.jsp and
error.jsp). Content pages are placed in we%root/pages; index.jsp is placed directly in
we%root, 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
FacesDE wizard.
162
15 - javaserver faces
1. Create index.jsp:
a. in Package Explorer select we%root; from its context menu select NewB8i'e; the
New File wizard appears.
b. for 8i'e na.e enter index.jsp; make sure that the parent folder is set to /js5&
login/we%root; click 8inish; the JSP Editor opens.
c. enter the following code, save the file and close the editor.
;<&& we%root/index.jsp &&4
;html4
;%odB4
;jsp:5orward pageK=5aces/pages/login.jsp= /4
;/%odB4
;/html4
2. Create success.jsp: create this file similarly to index.jsp, but in we%root/pages.
Enter the following code:
;<&& we%root/pages/s$ccess.jsp &&4
;html4
;head4
;title4js5&login;/title4
;/head4
;%odB4
;hD4S$ccess<;/hD4
;/%odB4
;/html4
3. Create error.jsp: create this file similarly to index.jsp, but in we%root/pages.
Enter the following code:
;<&& we%root/pages/error.jsp &&4
;html4
;head4
;title4js5&login;/title4
;/head4
;%odB4
;hD4'rror<;/hD4
!he $ser&id and or password were invalid. 7lease trB
again.
;/%odB4
;/html4
4. Create login.jsp:
a. in Package Explorer select we%root/pages; from its context menu select
NewBOther...; the New wizard appears.
b. select A.aterasB3S8B8a$es 3S6 8i'e; click NeCt
c. for 8i'e na.e enter login.jsp; make sure that C!ntainer is set to /js5&
login/we%root/pages, and that =se 218a$es T!.ahaw> $!.&!nents and
=se 218a$es SandB!C $!.&!nents are unchecked, and choose de"a't for
Te.&'ate; click 8inish; the FacesDE JSP Editor opens, with the following
template code.
163
15 - javaserver faces
;[Q page content!BpeK=text/htmlW charsetKCp8DED= [4
;[Q tagli% $riK=http://java.s$n.com/js5/html= pre5ixK=h= [4
;[Q tagli% $riK=http://java.s$n.com/js5/core= pre5ixK=5= [4
;html4
;head4
;meta http&eM$ivK=Content&!Bpe= contentK=text/htmlW
charsetKCp8DED=/4
;title4;/title4
;/head4
;%odB4
;5:view4
;h:5orm4
;/h:5orm4
;/5:view4
;/%odB4
;/html4
We will now edit this page to contain our input widgets, etc.
d. place the cursor between the ;title4;/title4 elements; enter js5&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:5orm4 elements; place your cursor in
one of these lines, expand the 3S8 HT2L panel in the palette, and click on the
icon for ;h:inp$t!ext4; this inserts the corresponding JSF element at the
cursor location.
N!teE 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 CT9L O S&a$ebar, 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 CT9L O S&a$ebar; a code-completion window pops up, as
shown below.
164
15 - javaserver faces
h. in the code-completion window scroll down to +a'e, and hit Enter; this inserts
val$eK== at the cursor. We will now bind this to the $serI# property of
LoginManager; FacesDE can provide code completion here as well.
i. place the cursor between the quotes in val$eK==, enter _Umgr., and hit CT9L O
S&a$ebar; a code-completion window pops up, with bean properties available in
mgr. This is shown below:
(Recall that we configured LoginManager as a managed bean called mgr.)
j. select $serI# from the code-completion window; complete the expression with
the closing U
k. insert another ;h:inp$t!ext4 element; set its value binding expression to
val$eK=_Umgr.passwordV=
l. insert a ;h:commandC$tton4 element; set its val$e to Login, and its action
to the value binding expression _Umgr.login(ctionV
The final code, with the barest presentational formatting, is shown below:
;[Q page content!BpeK=text/htmlW charsetKCp8DED= [4
;[Q tagli% $riK=http://java.s$n.com/js5/html= pre5ixK=h= [4
;[Q tagli% $riK=http://java.s$n.com/js5/core= pre5ixK=5= [4
;html4
;head4
;title4js5&title;/title4
;/head4
;%odB4
;5:view4
;h:5orm4
serI#: ;h:inp$t!ext val$eK=_Umgr.$serI#V=/4
;%r/47assword: ;h:inp$t!ext
val$eK=_Umgr.passwordV=/4
;%r/4;h:commandC$tton val$eK=Login=
actionK=_Umgr.login(ctionV=/4
;/h:5orm4
;/5:view4
;/%odB4
;/html4
1*.-.* Creating Na+igati!n 9'es
Here we create navigation rules among pages, using a FacesDE editor.
1. Open 5aces&con5ig.xml; it should open in the "a$es-$!n"ig.C.' Edit!r.
2. Select the Na+igati!n tab
165
15 - javaserver faces
3. from the Na+igati!n panel in the palette at left, click on 6age, 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.
Note that the icon has a small triangle overlay--this indicates that something is wrong,
specifically that FacesDE could not locate a page at path /page8.jsp
4. in the 6r!&erties 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/s$ccess.jsp and
/pages/error.jsp. Arrange them as shown below:
166
15 - javaserver faces
Now we'll add navigation rules among the pages.
6. from the palette at left, select Na+igati!n Case, then click first on the icon for
login.jsp and then on the icon for s$ccess.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. ts properties appear in the 6r!&erties view. This is shown below:
167
15 - javaserver faces
7. in the 6r!&erties view (or direct editing on the diagram), change the value of 5rom&
o$tcome to login7ass. Recall that this is the success-value returned by
LoginManager's login(ction 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 5rom&
o$tcome to login*ail
We're done with setting up navigation rules. We'll set some properties in we%.xml, and we'll
then be ready to deploy the application.
1*.-., Editing web.C.'
Here we edit we%.xml for the specifics of our application. As it turns out, since we have such a
trivial application, all we need do in we%.xml is indicate the Faces Servlet mapping.
1. open we%.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 UserD/Password of "!!Bbar, 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:
168
15 - javaserver faces
1*.-.- De&'!1ing T! T!.$at *.5
1. start Tomcat; open its Manager application in a browser; the default URL for this is
http://localhost:>9>9/manager/html
2. scroll down to De&'!1; we'll deploy our app by providing its directory; for C!nteCt &ath
enter /js5&login; for WA9 !r Dire$t!r1 =9L enter the path to we%root, as
5ile:///...; leave <2L C!n"igrati!n 8i'e =9L blank; click De&'!1
3. the Manager application should reload, and you should see /js5&login in the list of
running applications. Click on its link to launch the application.
1*.0 &a$>ges in the 3a+aSer+er 8a$es A6I
The classes and interfaces of the JavaServer Faces AP 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

1*.4 the #a+aC."a$es &a$>age
Contains 2 classes FactoryFinder and FacesException
p$%lic 5inal class FactoryFinder extends +%ject
8a$t!r18inder implements the standard discovery algorithm for all factory objects specified in
the JavaServer Faces APs. For a given factory class name, a corresponding implementation
class is searched for based on the following algorithm. tems are listed in order of decreasing
search precedence:
f the JavaServer Faces configuration file bundled into the /'C&I)* directory of the
webapp contains a 5actorB entry of the given factory class name, that factory is used.
f the JavaServer Faces configuration files named by the javax.5aces.C+)*I-,*IL'S
169
15 - javaserver faces
ServletContext init parameter contain any 5actorB entries of the given factory class
name, those factories are used, with the last one taking precedence.
f there are any JavaServer Faces configuration files bundled into the M'!(&I)* directory
of any jars on the ServletContext's resource paths, the 5actorB entries of the given
factory class name in those files are used, with the last one taking precedence.
f a M'!(&I)*/services/U5actorB&class&nameV 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.
f none of the above steps yield a match, the JavaServer Faces implementation specific
class is used.
p$%lic class FacesException extends R$ntime'xception
This class encapsulates general JavaServer Faces exceptions.
1*.15 the #a+aC."a$es.a&&'i$ati!n &a$>age
Contains the following classes:
A&&'i$ati!n - A set of APs for representing U components and managing their state,
handling events and input validation, defining page navigation, and supporting
internationalization and accessibility.
A&&'i$ati!n8a$t!r1 - a factory object that creates (if needed) and returns (pplication
instances. mplementations of JavaServer Faces must provide at least a default
implementation of (pplication.
8a$es2essage - represents a single validation (or other) message, which is typically
associated with a particular component in the view. A *acesMessage instance may be
created based on a specific messageId.
8a$es2essage.Se+erit1 - used to represent message severity levels in a typesafe
enumeration.
Na+igati!nHand'er 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.
State2anager - directs the process of saving and restoring the view between requests.
State2anagerWra&&er - 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.
7iewHand'er - the pluggablity mechanism for allowing implementations of or applications
using the JavaServer Faces specification to provide their own handling of the activities in
the 5ender 5esponse and 5estore 3iew 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.
7iewHand'erWra&&er - Provides a simple implementation of Giew6andler that can be
170
15 - javaserver faces
subclassed by developers wishing to provide specialized behavior to an existing
Giew6andler instance. The default implementation of all methods is to call through to
the wrapped Giew6andler.
7iewEC&iredEC$e&ti!n - implementations must throw this *aces'xception when
attempting to restore the view
StateManager.restoreGiew0javax.5aces.context.*acesContext3 String3
String1 results in failure on postback.
1*.11 the #a+aC."a$es.$!.&!nent &a$>age
Defines both a set of interfaces and classes. The interfaces defined in this package are:
A$ti!nS!r$e - an interface that may be implemented by any concrete IComponent
that wishes to be a source of (ction'vents, including the ability to invoke application
actions via the default (ctionListener mechanism.
A$ti!nS!r$e2 - extends (ctionSo$rce and provides a JavaBeans property analogous
to the "action" property on (ctionSo$rce. The difference is the type of this property is
a Method'xpression rather than a MethodCinding. This allows the (ctionSo$rce
concept to leverage the new Unified EL AP.
C!nteCtCa''Ba$> - A simple callback interace that enables taking action on a specific
UComponent (either facet or child) in the view while preserving any contextual state for
that component instance in the view.
Editab'e7a'eH!'der - an extension of ValueHolder that describes additional features
supported by editable components, including Gal$eChange'vents and Galidators.
Na.ingC!ntainer - an interface that must be implemented by any IComponent that
wants to be a naming container.
StateH!'der - interface implemented by classes that need to save their state between
requests.
7a'eH!'der - an interface that may be implemented by any concrete IComponent 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 U related. Here they are:
=IC!'.n - a IComponent that represents a single column of data within a parent
I#ata component.
=IC!..and - a IComponent 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.
=IC!.&!nent - the base class for all user interface components in JavaServer Faces.
The set of IComponent instances associated with a particular request and response are
organized into a component tree under a IGiewRoot that represents the entire content
of the request or response.
=IC!.&!nentBase - a convenience base class that implements the default concrete
behavior of all methods defined by IComponent.
171
15 - javaserver faces
=IData - a IComponent that supports data binding to a collection of data objects
represented by a #ataModel instance, which is the current value of this component itself
(typically established via a Gal$eCinding). 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.
=I8!r. - a IComponent 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.
=IGra&hi$ - a IComponent that displays a graphical image to the user. The user cannot
manipulate this component; it is for display purposes only.
=IIn&t - a IComponent that represents a component that both displays output to the
user (like I+$tp$t components do) and processes request parameters on the
subsequent request that need to be decoded.
=I2essage - This component is responsible for displaying messages for a specific
IComponent, identified by a clientId.
=I2essages - The renderer for this component is responsible for obtaining the messages
from the *acesContext and displaying them to the user.
=INa.ingC!ntainer - a convenience base class for components that wish to implement
)amingContainer functionality.
=IOt&t - a IComponent 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.
=I6ane' - a IComponent that manages the layout of its child components.
=I6ara.eter - a IComponent that represents an optionally named configuration
parameter for a parent component.
=ISe'e$tB!!'ean - a IComponent that represents a single boolean (tr$e or 5alse)
value. t is most commonly rendered as a checkbox.
=ISe'e$tIte. - a component that may be nested inside a ISelectManB or
ISelect+ne component, and causes the addition of a SelectItem instance to the list
of available options for the parent component.
=ISe'e$t2an1 - a IComponent 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 val$e property of the component.This
component is generally rendered as a select box or a group of checkboxes.
=ISe'e$tOne - a IComponent 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 val$e property of the component.
=I7iew9!!t - the UComponent that represents the root of the UComponent tree. This
component has no rendering, it just serves as the root of the component tree.
1*.12 the #a+a."a$es.$!.&!nent.ht.' &a$>age
172
15 - javaserver faces
Contains HTML related classes.
Ht.'C!'.n - represents a column that will be rendered in an HTML ta%le element.
Ht.'C!..andBtt!n - represents an HTML inp$t element for a button of type
s$%mit or reset. The label text is specified by the component value.
Ht.'C!..andLin> - 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.
Ht.'DataTab'e - represents a set of repeating data (segregated into columns by child
UColumn components) that will be rendered in an HTML ta%le element.
Ht.'8!r. - represents an HTML 5orm element. Child input components will be
submitted unless they have been disabled.
Ht.'Gra&hi$I.age - represents an HTML img element, used to retrieve and render a
graphical image.
Ht.'In&tHidden - represents an HTML inp$t element of type hidden.
Ht.'In&tSe$ret - represents an HTML inp$t element of type password. On a
redisplay, any previously entered value will not be rendered (for security reasons) unless
the redisplaB property is set to tr$e.
Ht.'In&tTeCt - represents an HTML inp$t element of type text.
Ht.'In&tTeCtarea - represents an HTML textarea element.
Ht.'2essage - by default, the renderer!Bpe property must be set to
"javax.5aces.Message". This value can be changed by calling the
setRenderer!Bpe01 method.
Ht.'2essages - by default, the renderer!Bpe property must be set to
"javax.5aces.Messages" This value can be changed by calling the
setRenderer!Bpe01 method.
Ht.'Ot&t8!r.at - represents a component that looks up a localized message in a
resource bundle, optionally uses it as a Message*ormat pattern string and substitutes in
parameter values from nested ;"Parameter components, and renders the result. f the
"dir" or "lang" attributes are present, render a span element and pass them through as
attributes on the span.
Ht.'Ot&tLabe' - represents an HTML la%el element, used to define an accessible
label for a corresponding input element.
Ht.'Ot&tLin> - represents an HTML a (hyperlink) element that may be used to link to
an arbitrary URL defined by the val$e property.
Ht.'Ot&tTeCt - renders the component value as text, optionally wrapping in a span
element if CSS styles or style classes are specified.
Ht.'6ane'Grid - renders child components in a table, starting a new row after the
specified number of columns.
Ht.'6ane'Gr!& - 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.
Ht.'Se'e$tB!!'eanChe$>b!C - represents an HTML inp$t element of type chec2%ox.
The checkbox will be rendered as checked, or not, based on the value of the val$e
173
15 - javaserver faces
property.
Ht.'Se'e$t2an1Che$>b!C - represents a multiple-selection component that is rendered
as a set of HTML inp$t elements of type chec2%ox.
Ht.'Se'e$t2an1Listb!C - represents a multiple-selection component that is rendered as
an HTML select element, showing either all available options or the specified number of
options.
Ht.'Se'e$t2an12en - represents a multiple-selection component that is rendered as an
HTML select element, showing a single available option at a time.
Ht.'Se'e$tOneListb!C - represents a single-selection component that is rendered as an
HTML select element, showing either all available options or the specified number of
options.
Ht.'Se'e$tOne2en - represents a single-selection component that is rendered as an
HTML select element, showing a single available option at a time.
Ht.'Se'e$tOne9adi! - represents a single-selection component that is rendered as a set
of HTML inp$t elements of typeradio.
1*.1% the #a+a."a$es.$!nteCt &a$>age
Contains the following classes:
ECterna'C!nteCt - allows the Faces AP to be unaware of the nature of its containing
application environment. n particular, this class allows JavaServer Faces based
applications to run in either a Servlet or a Portlet environment.
8a$esC!nteCt - 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. t
is passed to, and potentially modified by, each phase of the request processing lifecycle.
8a$esC!nteCt8a$t!r1 - a factory object that creates (if needed) and returns new
*acesContext instances, initialized for the processing of the specified request and
response objects.
9es&!nseStrea. - an interface describing an adapter to an underlying output
mechanism for binary output.
9es&!nseWriter - an abstract class describing an adapter to an underlying output
mechanism for character-based output.
9es&!nseWriterWra&&er - provides a simple implementation of Response/riter that
can be subclassed by developers wishing to provide specialized behavior to an existing
Response/riter instance. The default implementation of all methods is to call through
to the wrapped Response/riter.
1*.1( the #a+a."a$es.$!n+ert &a$>age
174
15 - javaserver faces
1*.1(.1 the inter"a$e C!n+erter
C!n+erter 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:
BigDe$i.a'C!n+erter
BigIntegerC!n+erter
B!!'eanC!n+erter
B1teC!n+erter
Chara$terC!n+erter
DateTi.eC!n+erter
D!b'eC!n+erter
En.C!n+erter
8L!atC!n+erter
IntegerC!n+erter
L!ngC!n+erter
N.berC!n+erter
Sh!rtC!n+erter
The package also contains one exception:
C!n+erterEC$e&ti!n - an exception thrown by the get(s+%ject01 or get(s!ext01
method of a Converter, to indicate that the requested conversion cannot be performed.
1*.1* the #a+a."a$es.e' &a$>age
Contains classes and interfaces for evaluating and processing reference expressions.
Classes:
2eth!dBinding - 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 Gal$eCinding.
6r!&ert19es!'+er - represents a pluggable mechanism for accessing a "property" of an
underlying Java object instance.
7a'eBinding - an object that can be used to access the property represented by an
action or value binding expression.
7ariab'e9es!'+er - represents a pluggable mechanism for resolving a top-level variable
reference at evaluation time.
175
15 - javaserver faces
Exceptions:
E+a'ati!nEC$e&ti!n - an exception reporting an error that occurred during the
evaluation of an expression in a MethodCinding or Gal$eCinding.
2eth!dN!t8!ndEC$e&ti!n - an exception caused by a method name that cannot be
resolved against a base object.
6r!&ert1N!t8!ndEC$e&ti!n - an exception caused by a property name that cannot be
resolved against a base object.
9e"eren$eS1ntaCEC$e&ti!n - an exception reporting a syntax error in a method binding
expression or value binding expression.
1*.1, the #a+a."a$es.e+ent &a$>age
Contains interfaces describing events and event listeners, and event implementation classes.
nterfaces:
A$ti!nListener - listener interface for receiving (ction'vents.
8a$esListener - a generic base interface for event listeners for various types of
*aces'vents.
6haseListener - 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.
7a'eChangeListener - listener interface for receiving Gal$eChange'vents.
Classes:
A$ti!nE+ent - represents the activation of a user interface component (such as a
ICommand).
8a$esE+ent - the base class for user interface and application events that can be fired by
IComponents.
6haseE+ent - represents the beginning or ending of processing for a particular phase of
the request processing lifecycle, for the request encapsulated by the specified
*acesContext.
6haseId - typesafe enumeration of the legal values that may be returned by the
get7haseId01 method of the *aces'vent interface.
7a'eChangeE+ent - a notification that the local value of the source component has
been change as a result of user interface activity.
One exception - Ab!rt6r!$essingEC$e&ti!n - thrown by event listeners to terminate the
processing of the current event.
176
15 - javaserver faces
1*.1- the #a+a."a$es.'i"e$1$'e &a$>age
This package contains 2 classes.
The Li"e$1$'e class manages the processing of the entire lifecycle of a particular JavaServer
Faces request.
The Li"e$1$'e8a$t!r1 class is a factory object that creates (if needed) and returns Li5ecBcle
instances.
1*.10 the #a+a."a$es..!de' &a$>age
Contains the interface DataModelListener and several classes providing standard model data
beans for JavaServer Faces. Classes:
Arra1Data2!de' - a convenience implementation of #ataModel that wraps an array of
Java objects.
Data2!de' - 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 I#ata).
Data2!de'E+ent - represents an event of interest to registered listeners that occurred on
the specified #ataModel.
ListData2!de' - a convenience implementation of #ataModel that wraps an List of
Java objects.
9es'tData2!de' - a convenience implementation of #ataModel that wraps a JSTL
Res$lt object, typically representing the results of executing an SQL query via JSTL
tags.
9es'tSetData2!de' - a convenience implementation of #ataModel that wraps a
Res$ltSet of Java objects. Note that the specified Res$ltSet 2=ST be scrollable.
S$a'arData2!de' - a convenience implementation of #ataModel that wraps an
individual Java object.
Se'e$tIte. - represents a single item in the list of supported items associated with a
ISelectManB or ISelect+ne component.
Se'e$tIte.Gr!& - 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 ISelectManB or ISelect+ne renderer that is actually used.
1*.14 the #a+a."a$es.render &a$>age
Contains classes defining the rendering model.
9enderer - converts the internal representation of IComponents into the output stream
177
15 - javaserver faces
(or writer) associated with the response we are creating for a particular request. Each
Renderer knows how to render one or more IComponent types (or classes), and
advertises a set of render-dependent attributes that it recognizes for each supported
IComponent.
9enderDit - represents a collection of Renderer instances that, together, know how to
render JavaServer Faces IComponent 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.
9enderDit8a$t!r1 - a factory object that registers and returns RenderKit instances.
mplementations of JavaServer Faces must provide at least a default implementation of
RenderKit.
9es&!nseState2anager - the helper class to StateManager that knows the specific
rendering technology being used to generate the response.
1*.25 the #a+a."a$es.+a'idat!r &a$>age
nterface defining the validator model, and concrete validator implementation classes.
A 7a'idat!r implementation is a class that can perform validation (correctness checks) on a
'dita%leGal$e6older.
mplementation classes:
D!b'e9ange7'idat!r - a Galidator that checks the value of the corresponding
component against specified minimum and maximum values
Length7a'idat!r - a Galidator that checks the number of characters in the String
representation of the value of the associated component.
L!ng9ange7a'idat!r - a Galidator that checks the value of the corresponding
component against specified minimum and maximum values.
The package contains an exception, as well.
A 7a'idat!rEC$e&ti!n is an exception thrown by the validate01 method of a Galidator to
indicate that validation failed.
1*.21 the #a+a."a$es.weba&& &a$>age
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.
AttribteTag - 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.
C!n+erterTag - a base class for all JSP custom actions that create and register a
Converter instance on the Gal$e6older associated with our most immediate
178
15 - javaserver faces
surrounding instance of a tag whose implementation class is a subclass of
IComponent!ag.
8a$esSer+'et - a servlet that manages the request processing lifecycle for web
applications that are utilizing JavaServer Faces to construct the user interface.
8a$etTag - the JSP mechanism for denoting a IComponent is to be added as a 5acet
to the component associated with its parent.
=IC!.&!nentB!d1Tag - a base class for all JSP custom actions, related to a
UComponent, that need to process their tag bodies.
=IC!.&!nentTag - the base class for all JSP custom actions that correspond to user
interface components in a page that is rendered by JavaServer Faces.
7a'idat!rTag - a base class for all JSP custom actions that create and register a
Galidator instance on the 'dita%leGal$e6older associated with our most
immediate surrounding instance of a tag whose implementation class is a subclass of
IComponent!ag.
1*.22 the 3S8 'i"e$1$'e
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.
n 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. n JSF, the model is
composed of business objects that are usually implemented as JavaBeans, the controller is the
179
15 - javaserver faces
JSF implementation, and the U components are the view.
The JSF life cycle has six phases as defined by the JSF specification:
9est!re 7iewE n this phase, the JSF implementation restores the objects and data structures
that represent the view of the request. if this is the client's 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 U objects for each view component. The components are stored in a
component tree, and the state of the U view is saved for subsequent requests. f this is a
subsequent request, the saved U view is retrieved for the processing of the current request.
A&&'1 9e@est 7a'esE Any data that was sent as part of the request is passed to the
appropriate U 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. t updates only the U components with the new data.
6r!$ess 7a'idati!nsE 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.
=&date 2!de' 7a'esE After all validations are complete, the business objects that make up
the application are updated with the validated data from the request. n 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.
In+!>e A&&'i$ati!nE During this phase, the action method of any command button or link that
was activated is called. n 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.
9ender 9es&!nseE The response U components are rendered, and the response is sent to
the client. The state of the U 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.
180
15 - javaserver faces
n 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. f 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.
181
16 - java RM
1, - 3A7A 92I
1,.1 9e.!te &r!$edre $a''s
n distributed applications, the simple act of invoking a method may take us beyond and away
from our own address space, just for the simple fact that that method is located into another
process, possibly running on a different machine. We enter the domain of Remote Procedure
Calls, which is, eventually, just another form of nter Process Communication.
The idea of RPC dates back to 1976 when the rules were defined in RFC 707.
magine now the same person in a completely different location, maybe hundreds of miles
away. Talking to him (her) is no longer . The difference is that we do not talk to that person mouth
to mouth, but mouth to phone, rather. So the communication medium is no longer, but a segment
of a sophisticated infrastructure.
Technically speaking, a servlet is a Java class that extends the GenericServlet (or, more often,
the HttpServlet) class.
The Java servlet AP provides a simple frame for building web applications on web servers.
The current Java Servlet specification (as of 10.2008) is 2.5 and is in final state. Java EE 5
SDK contains an implementation of the Java Servlet 2.5 specification.
1,.2 ser+'et $!ntainers
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.
1,.2.1 N!n$!..er$ia' ser+'et $!ntainers
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.
Jetty
Jaminid contains a higher abstraction than servlets.
Enhydra
Winstone supports specification v2.4, has a focus on minimal configuration and the ability
to strip the container down to only what you need.
tjws spec 2.4, small footprint, modular design
1,.2.2 $!..er$ia' ser+'et $!ntainers
BEA WebLogic Server or Weblogic Express, from BEA Systems
Borland Enterprise Server
182
16 - java RM
GlassFish (open source)
Java System Application Server , from Sun Microsystems
Java System Web Server , from Sun Microsystems
JBoss (open source)
JRun , from Adobe Systems (formerly developed by Allaire Corporation)
LiteWebServer (open source)
Oracle Application Server , from Oracle Corporation
Orion Application Server , from ronFlare
Caucho's Resin Server
ServletExec , from New Atlanta Communications
WebObjects , from Apple nc.
WebSphere , from BM
1,.% ser+'et &a$>ages and $'asses
The Java servlet AP consists of 2 packages, which are part of the J2 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 AP can be divided in several categories,
namely:
servlet implementation
servlet configuration
servlet exceptions
request and responses
session tracking
servlet context
servlet collaboration
miscellaneous
1,.( the Ser+'et inter"a$e
The Servlet interface is part of the javax.servlet package. t declares the following
methods:
183
16 - java RM
p$%lic void init0ServletCon5ig con5ig1 throws Servlet'xceptionW
p$%lic void service0ServletReM$est reM3 ServletResponse resp1 throws
Servlet'xception3 I+'xceptionW
p$%lic void destroB01 throws Servlet'xceptionW
p$%lic ServletCon5ig getServletCon5ig01W
p$%lic String getServletIn5o01W
After instantiating the servlet, the web container calls its init01 method. The method
performs all initialization required, before the servlet processes any HTTP request. The servlet
specification insures that the init01 method is called just once for any given instance of the
servlet.
The web container calls the service01 method in response to any incoming request. This
method has two arguments, arguments which implement the ServletReM$est and
ServletResponse interfaces, respectively.
More on the servlet lifecycle, in a different section.
1,.* the Generi$Ser+'et $'ass
p$%lic a%stract class -enericServlet implements
Servlet3 ServletCon5ig3 SerialiRa%le
This class provides a basic implementation of the Servlet interface. Since this class
implements the ServletCon5ig interface, as well, the developer may call ServletCon5ig
methods directly, without having to obtain a ServletCon5ig object first. All classes extending
the GenericServlet class should provide an implementation for the service01 method.
Methods specific to this class:
public void init()
public void log(String msg)
public void log(String msg, Throwable t)
1,., the Htt&Ser+'et $'ass
t is very likely that the only implementation of the Servlet interface we'll ever use is one that
processes an HTTP request. The servlet AP provides such a specific class, namely the
6ttpServlet class.
public abstract class HttpServlet extends GenericServlet implements Serializable
184
16 - java RM
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)
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)
1,.- the Ser+'etC!n"ig inter"a$e
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 getnitParameter(String name)
public Enumeration getnitParameterNames()
public ServletContext getServletContext()
public String getServletName()
1,.0 ser+'et eC$e&ti!ns
The Java servlet AP specifies two servlet specific exceptions:
javax.servlet.Servlet'xception
javax.servlet.navaila%le'xception
The Servlet'xception class extends java.lang.'xception and can be thrown by the
init01, service01, doXXX01 and destroB01 methods of the Servlet interface
implementations.
185
16 - java RM
The navaila%le'xception indicates to the web container that the servlet instance is
unavaialble. t also extends the java.lang.'xception class.
1,.4 the ser+'et 'i"e$1$'e
Generally, a servlet instance goes through the following stages:
instantiation
initialization
service
destroy
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. f the servlet does not implement the
javax.servlet.Single!hreadModel, concurrent requests are serviced in more than one
service thread, which requires that the service01 method be thread safe.
After instantiation, the container calls the init01 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 init01 method of the servlet will be completed before
invoking its service01 method. Also, the servlet's destroB01 method will be called before the
servlet itself is destroyed.
1,.15 the Ser+'et9e@est inter"a$e
Here are some of the methods of this interface:
p$%lic +%ject get(ttri%$te0String name1
p$%lic +%ject set(ttri%$te0String name3 +%ject attr1
p$%lic 'n$meration get(ttri%$te)ames01
p$%lic int getContentLength01
p$%lic String getContent!Bpe01
p$%lic String get7arameter0String name1
p$%lic 'n$meration get7arameter)ames01
p$%lic 'n$meration get7arameterGal$es01
p$%lic String getServer)ame01
p$%lic int getServer7ort01
p$%lic String getRemote(ddr01
p$%lic String getRemote6ost01
186
16 - java RM
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.
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 or JSP or to allow sending data from a servlet to another.
1,.11 the Htt&Ser+'et9e@est inter"a$e
p$%lic inter5ace 6ttpServletReM$est extends ServletReM$est
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:
p$%lic Coo2ieST getCoo2ies01
p$%lic long get#ate6eader01
p$%lic String get6eader0String name1
p$%lic 'n$meration get6eaders0String name1
p$%lic 'n$meration get6eader)ames01
p$%lic String getContext7ath01
p$%lic String get7athIn5o01
p$%lic String getH$erBString01
p$%lic String getRemoteser01
1,.12 the Ser+'et9es&!nse inter"a$e
This interface defines methods for constructing responses to servlet requests.
Here are the most important ones:
p$%lic Servlet+$tp$tStream get+$tp$tStream01
p$%lic 7rint/riter get/riter01
p$%lic void setContentLength0int len1
p$%lic void setContent!Bpe0String tBpe1
p$%lic void setC$55erSiRe0int siRe1
p$%lic int getC$55erSiRe01
p$%lic void 5l$shC$55er01
187
16 - java RM
1,.1% the Htt&Ser+'et9es&!nse inter"a$e
This interface extends the ServletResponse interface and defines methods specific for
constructing responses to HTTP requests.
Here are the most important ones:
p$%lic void addCoo2ie0Coo2ie coo2ie1
p$%lic String encodeRL0String $rl1
p$%lic void send'rror0int stat$s1
p$%lic void send'rror0int stat$s3 String message1
p$%lic void set6eader0String header)ame3 String val$e1
p$%lic void add6eader0String header)ame3 String val$e1
p$%lic void setStat$s0int stat$sCode1
1,.1( the Ser+'etC!nteCt inter"a$e
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
;context4 tag which associates the the name of the application with its root directory. This is
done in server's (container's) server.xml file.
The ServletContext interface abstracts the context of a web application. A reference to an
object of this type can be obtained by invoking the getServletContext01 method of the
6ttpServlet object.
p$%lic String getMIM'!Bpe0String 5ile)ame1
p$%lic String getReso$rce0String path1
p$%lic ServletContext getContext0String $rl7ath1
p$%lic String getInit7arameter0String name1
p$%lic 'n$meration getInit7arameter)ames01
p$%lic +%ject get(ttri%$te0String name1
p$%lic 'n$meration get(ttri%$te)ames01
p$%lic void set(ttri%$te0String name3 +%ject attr1
p$%lic String remove(ttri%$te0String name1
1,.1* the Enr!'' ser+'et
The Enroll servlet services the request sent by the web browser when we submit the Enroll form
188
16 - java RM
(file Enroll.html)
Here is its abbreviated form (topics which are DB related are postponed) of the
"EnrollServlet.java" file:
package com.bank11.ccards.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EnrollServlet extends HttpServlet
{
public void init(ServletConfig config)
throws ServletException
{
super.init(config);
}
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, OException
{
resp.setContent!Bpe0Ytext/htmlL1W
7rint/riter o$t K resp.get/riter01W
// o$tp$t Bo$r page here
o$t.println0=;html4=1W
o$t.println0=;head4=1W
o$t.println0=;title4Servlet;/title4=1W
o$t.println0=;/head4=1W
o$t.println0=;%odB4=1W
o$t.println0=merge=1W
o$t.println0=;%r4=1W
o$t.println0=;/%odB4=1W
o$t.println0=;/html4=1W
o$t.close01W
V
V
189
17 - JAVA MESSAGE SERVCE
1- - 3A7A 2ESSAGE SE97ICE
1-.1 32S e'e.ents
The 3a+a 2essage Ser+i$e (32S) AP is a Java Message Oriented Middleware (MOM) AP 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:
32S &r!+ider - 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.
32S $'ient - an application or process that produces and/or consumes messages.
32S &r!d$er - a JMS client that creates and sends messages.
32S $!ns.er - a JMS client that receives messages.
32S .essage - an object that contains the data being transferred between JMS clients.
32S @ee - a staging area that contains messages that have been sent and are waiting
to be read. As the name <ueue suggests, the messages are delivered in the order sent. A
message is removed from the queue once it has been read.
32S t!&i$ - a distribution mechanism for publishing messages that are delivered to
multiple subscribers.
1-.2 32S .!de's
The JMS AP supports two models:
point-to-point or queuing model
publish and subscribe model
n 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. t 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. n
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
190
17 - JAVA MESSAGE SERVCE
subscription. n 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 JND 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 clients then receive or subscribe to the messages.
1-.% the 32S A6I &r!gra..ing .!de'
1-.( the 32S A6I
The JMS AP is provided in the Java package javax.jms.
1-.(.1 the C!nne$ti!n8a$t!r1 inter"a$e
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 nterface (JND) 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.
191
17 - JAVA MESSAGE SERVCE
At the beginning of a JMS client program, you usually perform a JND lookup of a connection
factory, then cast and assign it to a Connection*actorB object.
For example, the following code fragment obtains an InitialContext object and uses it to
look up a Connection*actorB by name. Then it assigns it to a Connection*actorB object:
Context ctx = new nitialContext();
ConnectionFactory connectionFactory = (ConnectionFactory)
ctx.lookup("jms/ConnectionFactory");
n a J2EE application, JMS administered objects are normally placed in the jms naming
subcontext.
1-.(.2 the C!nne$ti!n inter"a$e
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 Connection*actorB
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 start01
method. f you want to stop message delivery temporarily without closing the connection, you call
the stop method.
1-.(.% the Destinati!n inter"a$e
An administered object that encapsulates the identity of a message destination, which is where
messages are delivered and consumed. t is either a queue or a topic. The JMS administrator
creates these objects, and users discover them using JND. 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 JND lookup of the previously created topic
jms/MB!opic and casts and assigns it to a #estination object:
Destination myDest = (Destination) ctx.lookup("jms/MyTopic");
The following line of code looks up a queue named jms/MBH$e$e and casts and assigns it to a
H$e$e object:
Queue myQueue = (Queue) ctx.lookup("jms/MyQueue");
1-.(.( the 2essageC!ns.er inter"a$e
An object created by a session. t receives messages sent to a destination. The consumer can
192
17 - JAVA MESSAGE SERVCE
receive messages synchronously (blocking) or asynchronously (non-blocking) for both queue and
topic-type messaging.
For example, you use a Session to create a MessageCons$mer for either a queue or a topic:
MessageConsumer consumer = session.createConsumer(myQueue);
MessageConsumer consumer = session.createConsumer(myTopic);
You use the Session.create#$ra%leS$%scri%er01 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 close01 method for a MessageCons$mer to make the message
consumer inactive. Message delivery does not begin until you start the connection you created by
calling its start01 method. (Remember always to call the start01 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();
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.
1-.(.* the 2essageListener inter"a$e
A .essage 'istener is an object that acts as an asynchronous event handler for messages.
This object implements the MessageListener interface, which contains one method,
onMessage01. n the onMessage01 method, you define the actions to be taken when a message
arrives.
You register the message listener with a specific MessageCons$mer by using the
setMessageListener01 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 start01 method on the Connection to
begin message delivery. (f you call start01 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
onMessage01 method whenever a message is delivered. The onMessage01 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.
193
17 - JAVA MESSAGE SERVCE
1-.(., the 2essage6r!d$er inter"a$e
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 Message7rod$cer for a destination. Here, the first example
creates a producer for the destination mBH$e$e, and the second for the destination mB!opic:
MessageProducer producer = session.createProducer(myQueue);
MessageProducer producer = session.createProducer(myTopic);
You can create an unidentified producer by specifying n$ll as the argument to
create7rod$cer. 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);
1-.(.- the 2essage inter"a$e
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. t 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 AP provides methods for creating messages of each type and for filling in their
contents. For example, to create and send a !extMessage, 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 get!ext method:
Message m = consumer.receive();
if (m instanceof TextMessage) {
TextMessage message = (TextMessage) m;
194
17 - JAVA MESSAGE SERVCE
System.out.println("Reading message: " + message.getText());
} else {
// Handle error
}
1-.(.0 the Sessi!n inter"a$e
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. f 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.
195
18 - ENTERPRSE JAVA BEANS
10 - ENTE969ISE 3A7A BEANS
10.1 enter&rise #a+a beans +erss :!rdinar1; #a+a 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
The 2.0 EJB specification adds another bean type:
message-driven beans
The current EJB specification is 3.0. Novelties in this specification try to make the development
of EJBs easier. t 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.
10.2 enter&rise #a+a beans ar$hite$tre
196
18 - ENTERPRSE JAVA BEANS
10.% the e#b $!ntainer and its ser+i$es
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
10.( the h!.e inter"a$e
The home interface of an ejb is an interface that extends the EJBHome interface. t provides
methods named create() with application specific arguments, returning the remote interface and
throwing Create'xception and Remote'xception. t uses only argument types allowed by
the RM 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:
p$%lic void remove06andle han1 throws Remote'xception3 Remove'xception
p$%lic void remove0+%ject primarBKeB1 throws Remote'xception3
Remove'xception
p$%lic 'ZCMeta#ata get'ZCMeta#ata01 throws Remote'xception
p$%lic 6ome6andle get6ome6andle01 throws Remote'xception
Code example for the a home interface, called MyBeanHome:
pac2age mBCeansW
import.javax.ejb.*;
import java.rmi.RemoteException;
public interface MyBeanHome extends EJBHome
197
18 - ENTERPRSE JAVA BEANS
{
MyBeanObject create() throws CreateException,
RemoteException;
}
10.* the re.!te inter"a$e
The remote interface of a bean is a standard Java interface that extends the 'ZC+%ject and
Remote inter5aces and declares the business logic methods of the bean. The developer does
not implement this interface.
While the Remote interface declares no methods, the 'ZC+%ject declares the following ones:
p$%lic 'ZC6ome get'ZC6ome01 throws Remote'xception
p$%lic +%ject get7rimarBKeB01 throws Remote'xception
p$%lic 6andle get6andle01 throws Remote'xception
p$%lic %oolean isIdentical0'ZC+%ject o%j1 throws
Remote'xception
p$%lic void remove01 throws Remote'xception3 Remove'xception
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 custd)
throws RemoteException;
void deleteEntry(int custd) throws RemoteException;
}
10., $'ient &r!gra..erAs +iew&!int
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 its resources
198
18 - ENTERPRSE JAVA BEANS
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:
athenti$ati!n
Client's authentication is done in a way which is server specific. n the case of an web
application, this can be done (for example) through SSL.
getting an initia' $!nteCt
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 nitialContext is already available:
Context ctx K new InitialContext01W
if the client executes outside the container, getting the nitialContext requires the usage of
some server-side properties. Here is an example:
trB
{
Properties prop = new Properties();
prop.put(Context.NTAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory";
prop.put(Context.PROVDER_URL,
"localhost:1099");
Context ctx = new nitialContext(prop);
}
"ind the h!.e inter"a$e !" the bean
for a client executing inside the container, the code may look like:
+%ject homeRe5 K ctx.loo2$p0=java:comp/env/ej%/MBCean=1W
if the client executes outside the container, the bean can be associated to any name in the
JND name space. t is JND's task to identify the resource associated to the name provided:
199
18 - ENTERPRSE JAVA BEANS
+%ject homeRe5 K ctx.loo2$p0=MBCean=1W
$ast the h!.e inter"a$e re"eren$e
To make sure that the client works with the underlying communication protocol, the client
should use the narrow() method of javax.rmi.PortableRemoteObject:
MBCean6ome home K 0MBCean6ome17orta%leRemote+%ject.narrow0homeRe53
MBCean6ome.class1W
$reate an instan$e !" 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:
MBCean+%ject mBCean+%ject K home.create01W
$a'' bsiness .eth!ds !n the bean
mBCean+%ject.process'ntrB0=#$mitrasc$=3 =Gasile=3 889D1W
re.!+e the bean instan$e
mBCean+%ject.remove01W
10.- bean &r!gra..erAs +iew&!int
An EJB consists of (at least) 3 classes and an xml file. t 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 ej%&jar.xml
Since the home interface and the remote interface have been detailed in the previous sections,
200
18 - ENTERPRSE JAVA BEANS
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 or entity).
Assuming that our bean (called MyBean) is a session bean, the code implementing this class
may look like this:
package myBeans;
import.javax.ejb.SessionContext;
public class MyBean implements javax.ejb.SessionBean
{
public void processEntry(String firstName, String lastName, int custd)
{
// method implementation
...
}
public void deleteEntry(int custd)
{
// 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) {}
}
The deployment descriptor of the bean will be detailed in another section.
10.0 sessi!n beans
There are two types of session beans, namely state"' and state'ess 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 &assi+ate 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 a$ti+ated, that is, a new stateful
instance is instantiated and populated from the passivated storage.
201
18 - ENTERPRSE JAVA BEANS
10.4 $!ntainer $a''ba$>s "!r sessi!n beans
There are 5 mandatory callbacks for classes implementing the SessionBean interface.
p$%lic void ej%(ctivate01
p$%lic void ej%7assivate01
p$%lic void ej%Create01
p$%lic void ej%Remove01
p$%lic void setSessionContext0SessionContext ctx1
The first two methods will never be called for stateless session beans, because the container
will never activate a stateless session bean.
10.15 the 'i"e $1$'e !" a state"' sessi!n bean
Figure 14.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 ej%Create methods in the session bean.
The bean is now ready to have its business methods invoked.

Figure 14.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
ej%7assivate method immediately before passivating it. f 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
ej%(ctivate 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 ej%Remove 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
202
18 - ENTERPRSE JAVA BEANS
methods in the client. All other methods in Figure 13.1 are invoked by the EJB container. The
ej%Create 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 ej%Create method.
10.11 the 'i"e $1$'e !" a state'ess sessi!n 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 14.2 illustrates the stages of
a stateless session bean.

Figure 14.2 Life Cycle of a Stateless Session Bean
10.12 entit1 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.
C26s (Container Managed Persistence)
B26s (Bean Managed Persistence) for which the bean developer provides the actual
203
18 - ENTERPRSE JAVA BEANS
persistence (SQL) code
10.1% &ri.ar1 >e1s
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 RM/OP 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&2eB&class4com.%an288.ccards.C$stomerI#;/prim&2eB&class4
or
;prim&2eB&class4java.lang.String;/prim&2eB&class4
n the case of CMP using a simple type as primary key, the field is specified:
;prim&2eB&5ield4sports!eamI#;/prim&2eB&5ield4
10.1( .andat!r1 $a''ba$>s "!r entit1 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:
p$%lic void ej%(ctivate01
p$%lic void ej%7assivate01
p$%lic void set'ntitBContext0'ntitBContext ctx1
p$%lic void $nset'ntitBContext01
204
18 - ENTERPRSE JAVA BEANS
CRUD translates through Create, Read, Update and Delete. These methods are mandatory for
entity beans.
10.1(.1 $reate
When a client calls a create01 method on a session bean's home interface, an instance of
that bean is created. On the other side, when a client calls create01 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
create01 methods, all throwing Remote'xception, Create'xception.
Each create01 method from the Home interface of the bean has 2 correspondent methods in
the bean implementation class, namely ej%Create01 and ej%7ostCreate01, methods which
have the same parameters, in the same order, as the parameters in the original create01
method.
the return type of the ej%Create01 is the same as the primary key, but the developer returns
null for CMP.
for BMP, ej%Create01 must have insertion SQL code and returns an instance of the primary
key, not null.
10.1(.2 read
ej%Load01, 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
ej%Load01 may contain processing code
10.1(.% &date
ej%Store01 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
10.1(.( de'ete
the corresponding method in the bean implementation class is ej%Remove01
data is deleted from DB (in the CMP case), for BMPs, the programmer will create actual SQL
code.
10.1* the 'i"e $1$'e !" an entit1 bean
Figure 14.3 shows the stages that an entity bean passes through during its lifetime. After the
EJB container creates the instance, it calls the set'ntitBContext method of the entity bean
class. The set'ntitBContext 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
205
18 - ENTERPRSE JAVA BEANS
invokes the create method, causing the EJB container to call the ej%Create and
ej%7ostCreate methods. On the second path, the EJB container invokes the ej%(ctivate
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 ej%Remove method. Second, the
EJB container can invoke the ej%7assivate method.

Figure 14.3 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 $nset'ntitBContext method.
n 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 ej%Create and
ej%(ctivate methods must assign a value to the primary key. f the primary key is incorrect,
the ej%Load and ej%Store methods cannot synchronize the instance variables with the
database. The ej%(ctivate method sets the primary key (id) as follows:
id K 0String1context.get7rimarBKeB01W
n 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 n$ll in the ej%7assivate
method.
10.1, .essage-dri+en beans
A message-driven bean is an enterprise bean that allows J2EE applications to process
206
18 - ENTERPRSE JAVA BEANS
messages asynchronously. t 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.
10.1,.1 when t! se .essage-dri+en beans
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.
10.1,.2 di""eren$es between .essage-dri+en beans and the !ther e#bAs
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.
n 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 AP 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. f message processing
is rolled back, the message will be redelivered.
10.1,.% di""eren$es between .essage-dri+en beans and state'ess sessi!n
E3Bs
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
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.
207
18 - ENTERPRSE JAVA BEANS
10.1,.( $!n$rrent s&&!rt "!r .essage-dri+en 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 we%logic&ej%&jar.xml deployment descriptor max&
%eans&in&5ree&pool setting to >1. f 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.
10.1,.* in+!>ing a .essage-dri+en bean
When a JMS Queue or Topic receives a message, use WebLogic Server to 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 nstances.
2. f 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 mplementing
Business Logic with onMessage().
N!teE These instances can be pooled.
10.1,., de+e'!&ing .essage-dri+en 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.
10.1,.- bean $'ass re@ire.ents
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
// declared as final or static.
public void ejb"emove! {...}
// ejbRemove() is required and must not accept parameters.
// The throws clause (if used) must not include an application
208
18 - ENTERPRSE JAVA BEANS
//exception. ejbRemove() must not be declared as final or static.
#inali$e%&'
// The EJB class cannot define a finalize() method
}
Creating and Removing Bean nstances
The WebLogic Server container calls the message-driven bean's ej%Create01 and
ej%Remove01 methods when creating or removing an instance of the bean class. As with other
EJB types, the ej%Create01 method in the bean class should prepare any resources that are
required for the bean's operation. The ej%Remove01 method should release those resources, so
that they are freed before WebLogic Server removes the instance.
Message-driven beans should also perform some form of regular clean-up routine outside of the
ej%Remove01 method, because the beans cannot rely on ej%Remove01 being called under all
circumstances (for example, if the EJB throws a runtime exception).
10.1,.0 sing the .essage-dri+en bean $!nteCt
WebLogic Server calls setMessage#rivenContext01 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. WebLogic Server provides the EJB with a container context, whose
properties can be accessed from within the instance by using the following methods from the
Message#rivenContext interface:
getCaller7rincipal01
isCallerInRole01
setRoll%ac2+nlB01& The EJB can use this method only if it utilizes container-
managed transaction demarcation.
getRoll%ac2+nlB01 & The EJB can use this method only if it utilizes container-
managed transaction demarcation.
getser!ransaction01& The EJB can use this method only if it utilizes bean-
managed transaction demarcation.
N!teE Although get'ZC6ome01 is also inherited as part of the Message#rivenContext
interface, message-driven EJBs do not have a home interface. Calling get'ZC6ome01
from within a message-driven EJB instance yields an IllegalState'xception.
10.1,.4 i.&'e.enting bsiness '!gi$ with !n2essage:;
The message-driven bean's onMessage01 method performs all of the business logic for the
EJB. WebLogic Server calls onMessage01 when the EJB's associated JMS Queue or Topic
receives a message, passing the full JMS message object as an argument. t is the message-
driven EJB's responsibility to parse the message and perform the necessary business logic in
onMessage01.
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. nstance pooling within the container means that messages are not received or
processed in a sequential order, although individual onMessage01 calls to a given message-
driven bean instance are serialized.
See javax.jms.MessageListener.onMessage() for more information.
209
18 - ENTERPRSE JAVA BEANS
10.1,.15 hand'ing eC$e&ti!ns
Message-driven bean methods should not throw an application exception or a
Remote'xception, even in onMessage01. f any method throws such an exception, WebLogic
Server immediately removes the EJB instance without calling ej%Remove01. However, from the
client perspective the EJB still exists, because future messages are forwarded to a new instance
that WebLogic Server creates.
10.1,.11 transa$ti!n ser+i$es "!r .essage-dri+en 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 WebLogic Server container
manage transactions (container-managed transactions). n either case, a message-driven bean
does not receive a transaction context from the client that sends a message. WebLogic Server
always calls a bean's onMessage01 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 ReM$ired or )otS$pported
transaction attribute in ej%&jar.xml. Transaction attributes are defined in ej%&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>
10.1,.12 .essage re$ei&ts
The receipt of a JMS message that triggers a call to an EJB's onMessage01 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, WebLogic Server includes the
message receipt as part of the bean's transaction only if the bean's transaction attribute is set to
ReM$ired.
10.1,.1% .essage a$>n!w'edg.ent
For message-driven beans that use container-managed transaction demarcation, WebLogic
Server automatically acknowledges a message when the EJB transaction commits. f the EJB
uses bean-managed transactions, both the receipt and the acknowledgment of a message occur
outside of the EJB transaction context. WebLogic Server automatically acknowledges messages
for EJBs with bean-managed transactions, but the deployer can configure acknowledgment
semantics using the jms-acknowledge-mode deployment parameter.
Deploying Message-Driven Beans in WebLogic Server
To deploy a message-driven bean on WebLogic Server, you edit the XML file to create the
deployment descriptors that associate the EJB with a configured JMS destination.
210
18 - ENTERPRSE JAVA BEANS
Deployment Descriptors
The deployment descriptor for a message-driven bean also specifies:
Whether the EJB is associated with a JMS Topic or Queue
Whether an associated Topic is durable or non-durable
Transaction attributes for the EJB
JMS acknowledgment semantics to use for beans that demarcate their own transactions
10.1,.1( de&'!1.ent e'e.ents
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.
s$%scription&d$ra%ilitB specifies whether or not an associated Topic
should be durable.
jms&ac2nowledge&mode specifies the JMS acknowledgment semantics to use
for beans that demarcate their own transaction boundaries. This element has
two possible values: (!+,(CK)+/L'#-' (the default ) or
#7S,+K,(CK)+/L'#-'.
These elements are defined in the ej%&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>
n addition to the new ej%&jar.xml elements, the we%logic&ej%&jar.xml file includes a
new message-driven-descriptor stanza to associate the message-driven bean with an actual
destination in WebLogic Server.
10.1- the 'i"e $1$'e !" a .essage-dri+en bean
Figure 13.4 illustrates the stages in the life cycle of a message-driven bean.
211
18 - ENTERPRSE JAVA BEANS
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. t calls the setMessage#rivenContext method to pass the context object to the
instance.
2. t calls the instance's ej%Create method.

Figure 13.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 ej%Remove method. The bean's instance is
then ready for garbage collection.
10.10 the de&'!1.ent des$ri&t!r
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 JND
3. control descriptors - specifies control attributes for transactions
4. EJB class name
5. environment properties
212
18 - ENTERPRSE JAVA BEANS
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:
;Oxnm versionK=8.8=O4
;ej%&jar4
;entrprise&%eans4
;session4
;ej%&name4CC'nroll;/ej%&name4
;home4com.%an288.ccards.ej%.CC'nroll6ome;/home4
;remote4com.%an288.ccards.CC'nroll+%ject;/remote4
;ej%&class4com.%an288.ccards.CC'nroll;/ej%&class4
;session&tBpe4Stateless;/session&tBpe4
;transaction&tBpe4Container;transaction&tBpe4
;ej%&re54
;ej%&re5&name4ej%/CC(cco$nt;/ej%&re5&name4
;ej%&re5&tBpe4'ntitB;/ej%&re5&tBpe4
;home4com.%an288.ccards.ej%.(cco$nt6ome;/home4
;remote4com.%an288.ccards.ej%.(cco$nt+%j;/remote4
;/ej%&re54
;sec$ritB&role&re54
;description4
!his role relates to cash advances 5rom (!Ms
;/description4
;role&name4Cash(dv(!M;/role&name4
;sec$ritB&role&re54
;/session4
;entitB4
;ej%&name4(cco$nt;/ej%&name4
;home4com.%an288.ccards.ej%.(cco$nt6ome;/home4
;remote4com.%an288.ccards.(cco$nt%ject;/remote4
213
18 - ENTERPRSE JAVA BEANS
;ej%&class4com.%an288.ccards.(cco$nt;/ej%&class4
;persistence&tBpe4Container;/persistence&tBpe4
;prim&2eB&class4java.lang.Integer;/prim&2eB&class4
;reentrant4*alse;/reentrant4
;cmp&5ield4
;5ield&name4acco$nt)$m%er;/5ield&name4
;/cmp&5ield4
;cmp&5ield4
;5ield&name4$ser)ame;/5ield&name4
;/cmp&5ield4
;cmp&5ield4
;5ield&name4c$stomerI#;/5ield&name4
;/cmp&5ield4
;cmp&5ield4
;prim&2eB&5ield4acco$nt)$m%er;/prim&2eB&5ield4
;/cmp&5ield4
;env&entrB4
;env&entrB&name4env/min7aBment7erc;/env&entrB&name4
;env&entrB&tBpe4java.lang.*loat;/env&entrB&tBpe4
;env&entrB&val$e4D.E;/env&entrB&val$e4
;/env&entrB4
;/entitB4
;/enterprise&%eans4
;/ej%&jar4
The assembly descriptor combines EJBs into a deployable application. Here is a very lean one:
;/ej%&jar4
;enterprise&%eans4
...
;/enterprise&%eans4

<assembly-descriptor>
;container&transaction4
;method4
;ej%&name4CC'nroll;/ej%&name4
;method&name4X;/method&name4
214
18 - ENTERPRSE JAVA BEANS
;/method4
;trans&attri%$te4ReM$ired;/trans&attri%$te4
;/container&transaction4
;/assem%lB&descriptor4
;/ej%&jar4
215

You might also like