Basic Java EE Book
Basic Java EE Book
The Java EE 6 is the current Java Enterprise Edition specification (as of Oct. 2010). Compared
to the previous specification, it introduces several new features:
• Profiles, configurations of the Java EE platform targeted at specific classes of
applications. Specifically, the Java EE 6 platform introduces a Web Profile targeted at
web applications, as well as a Full Profile that contains all Java EE technologies.
• New technologies, including the following:
• Java API for RESTful Web Services (JAX-RS)
• Contexts and Dependency Injection for the Java EE Platform (JSR-299),
informally known as Web Beans
• Java Authentication Service Provider Interface for Containers (JASPIC)
• New features for Enterprise JavaBeansTM (EJBTM) components
• New features for servlets
• New features for JavaServer TM Faces components
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.
1
1 - java platform, enterprise edition
The Java EE platform uses a distributed multitiered application model for enterprise
applications. Application logic is divided into components according to function, and the various
application components that make up a Java EE application are installed on different machines
depending on the tier in the multitiered Java EE environment to which the application component
belongs. Figure 1.1 shows generic multitiered Java EE applications divided into the tiers
described in the list below. The Java EE application parts shown in figure 1.1 are presented in the
Java EE components section.
• client-tier components run on the client machine.
• web-tier components run on the Java EE server.
• business-tier components run on the Java EE server.
• enterprise information system (EIS)-tier software runs on the EIS server
Although a Java EE application can consist of the three or four tiers shown in figure 1.1, Java
EE multitiered applications are generally considered to be three-tiered applications because they
are distributed over three locations: client machines, the Java EE server machine, and the
database or legacy machines at the back end. Three-tiered applications that run in this way
extend the standard two-tiered client and server model by placing a multithreaded application
server between the client application and back-end storage.
2
1 - java platform, enterprise edition
1.5.2 Applets
A web page received from the web tier can include an embedded applet. An applet is a small
client application written in the Java programming language that executes in the Java virtual
machine installed in the web browser. However, client systems will likely need the Java Plug-in
and possibly a security policy file in order for the applet to successfully execute in the web
browser.
Web components are the preferred API for creating a web client program because no plug-ins
or security policy files are needed on the client systems. Also, web components enable cleaner
and more modular application design because they provide a way to separate applications
programming from web page design. Personnel involved in web page design thus do not need to
understand Java programming language syntax to do their jobs.
3
1 - java platform, enterprise edition
4
1 - java platform, enterprise edition
Java EE web components are either servlets or pages created using JSP technology (JSP
pages) and/or Java Server Faces technology. Servlets are Java programming language classes
that dynamically process requests and construct responses. JSP pages are text-based documents
that execute as servlets but allow a more natural approach to creating static content. Java Server
Faces technology builds on servlets and JSP technology and provides a user interface component
framework for web applications.
Static HTML pages and applets are bundled with web components during application assembly
but are not considered web components by the Java EE specification. Server-side utility classes
can also be bundled with web components and, 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.
Business code, which is logic that solves or meets the needs of a particular business domain
such as banking, retail, or finance, is handled by enterprise beans running in the business tier.
Figure 1.3 shows how an enterprise bean receives data from client programs, processes it (if
necessary), and sends it to the enterprise information system tier for storage. An enterprise bean
also retrieves data from storage, processes it (if necessary), and sends it back to the client
program.
5
1 - java platform, enterprise edition
The enterprise information system tier handles EIS software and includes enterprise
infrastructure systems such as enterprise resource planning (ERP), mainframe transaction
processing, database systems, and other legacy information systems. For example, Java EE
application components might need access to enterprise information systems for database
connectivity.
Normally, thin-client multitiered applications are hard to write because they involve many lines
of intricate code to handle transaction and state management, multithreading, resource pooling,
and other complex low-level details. The component-based and platform-independent Java EE
architecture makes Java EE applications easy to write because business logic is organized into
reusable components. In addition, the Java EE server provides underlying services in the form of
a container for every component type. Because you do not have to develop these services
yourself, you are free to concentrate on solving the business problem at hand.
6
1 - java platform, enterprise edition
The assembly process involves specifying container settings for each component in the Java
EE application and for the Java EE application itself. Container settings customize the underlying
support provided by the Java EE server, including services such as security, transaction
management, Java Naming and Directory Interface (JNDI) lookups, and remote connectivity.
Here are some of the highlights:
• The Java EE security model lets you configure a web component or enterprise bean so
that system resources are accessed only by authorized users.
• The Java EE transaction model lets you specify relationships among methods that make
up a single transaction so that all methods in one transaction are treated as a single unit.
• JNDI lookup services provide a unified interface to multiple naming and directory services
in the enterprise so that application components can access these services.
• The Java EE remote connectivity model manages low-level communications between
clients and enterprise beans. After an enterprise bean is created, a client invokes methods
on it as if it were in the same virtual machine.
Because the Java EE architecture provides configurable services, application components
within the same Java EE application can behave differently based on where they are deployed.
For example, an enterprise bean can have security settings that allow it a certain level of access
to database data in one production environment and another level of database access in another
production environment.
The container also manages nonconfigurable services such as enterprise bean and servlet life
cycles, database connection resource pooling, data persistence, and access to the Java EE
platform APIs.
7
1 - java platform, enterprise edition
• 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.
Web services are web-based enterprise applications that use open, XML-based standards and
transport protocols to exchange data with calling clients. The Java EE platform provides the XML
APIs and tools you need to quickly design, develop, test, and deploy web services and clients that
fully interoperate with other web services and clients running on Java-based or non-Java-based
platforms.
To write web services and clients with the Java EE XML APIs, all you do is pass parameter data
to the method calls and process the data returned; or for document-oriented web services, you
send documents containing the service data back and forth. No low-level programming is needed
because the XML API implementations do the work of translating the application data to and from
an XML-based data stream that is sent over the standardized XML-based transport protocols.
These XML-based standards and protocols are introduced in the following sections.
The translation of data to a standardized XML-based data stream is what makes web services
and clients written with the Java EE XML APIs fully interoperable. This does not necessarily mean
that the data being transported includes XML tags because the transported data can itself be plain
text, XML data, or any kind of binary data such as audio, video, maps, program files, computer-
aided design (CAD) documents and the like. The next section introduces XML and explains how
parties doing business can use XML tags and schemas to exchange data in a meaningful way.
1.10.1 XML
XML is a cross-platform, extensible, text-based standard for representing data. When XML data
is exchanged between parties, the parties are free to create their own tags to describe the data,
set up schemas to specify which tags can be used in a particular kind of XML document, and use
XML stylesheets to manage the display and handling of the data.
For example, a web service can use XML and a schema to produce price lists, and companies
that receive the price lists and schema can have their own stylesheets to handle the data in a way
that best suits their needs. Here are examples:
• One company might put XML pricing information through a program to translate the XML
to HTML so that it can post the price lists to its intranet.
• A partner company might put the XML pricing information through a tool to create a
marketing presentation.
• Another company might read the XML pricing information into an application for
processing.
8
1 - java platform, enterprise edition
Figure 1.5 illustrates the availability of the Java EE 6 platform APIs in each Java EE container
type. The following sections give a brief summary of the technologies required by the Java EE
platform, and the APIs used in Java EE applications.
9
1 - java platform, enterprise edition
10
1 - java platform, enterprise edition
11
1 - java platform, enterprise edition
12
1 - java platform, enterprise edition
emerging UDDI specifications. By using JAXR, developers can learn a single API and gain access
to both of these important registry technologies.
Additionally, businesses can submit material to be shared and search for material that others
have submitted. Standards groups have developed schemas for particular kinds of XML
documents; two businesses might, for example, agree to use the schema for their industry's
standard purchase order form. Because the schema is stored in a standard business registry, both
parties can use JAXR to access it.
13
1 - java platform, enterprise edition
Java EE naming services provide application clients, enterprise beans, and web components
with access to a JNDI naming environment. A naming environment allows a component to be
customized without the need to access or change the component's source code. A container
implements the component's environment and provides it to the component as a JNDI naming
context.
A Java EE component can locate its environment naming context using JNDI interfaces. A
component can create a javax.naming.InitialContext object and looks up the
environment naming context in InitialContext under the name java:comp/env. A
component's naming environment is stored directly in the environment naming context or in any
of its direct or indirect subcontexts.
A Java EE component can access named system-provided and user-defined objects. The
names of system-provided objects, such as JTA UserTransaction objects, are stored in the
environment naming context, java:comp/env. The Java EE platform allows a component to
name user-defined objects, such as enterprise beans, environment entries, JDBC DataSource
objects, and message connections. An object should be named within a subcontext of the naming
environment according to the type of the object. For example, enterprise beans are named within
the subcontext java:comp/env/ejb, and JDBC DataSource references in the subcontext
java:comp/env/jdbc.
14
1 - java platform, enterprise edition
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 6 APIs enable systems and applications integration through the following:
• Unified application model across tiers with enterprise beans
• Simplified request-and-response mechanism with JSP pages and servlets
• Reliable security model with JAAS
• XML-based data interchange integration with JAXP, SAAJ, and JAX-WS
• Simplified interoperability with the J2EE Connector architecture
• Easy database connectivity with the JDBC API
• Enterprise application integration with message-driven beans and JMS, JTA, and JNDI
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 deployment descriptor
is an XML document with an .xml extension that describes the deployment settings of an
application, a module, or a component. Because deployment descriptor information is declarative,
it can be changed without the need to modify the source code. At runtime, the Java EE server
reads the deployment descriptor and acts upon the application, module, or component
accordingly.
15
1 - java platform, enterprise edition
There are two types of deployment descriptors: Java EE and runtime. A Java EE deployment
descriptor is defined by a Java EE specification and can be used to configure deployment
settings on any Java EE-compliant implementation. A runtime deployment descriptor is used to
configure Java EE implementation-specific parameters. For example, the Sun Java System
Application Server Platform Edition 9 runtime deployment descriptor contains information such as
the context root of a web application, the mapping of portable names of an 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 sun-
moduleType.xml and are located in the same META-INF directory as the Java EE deployment
descriptor.
A Java EE module consists of one or more Java EE components for the same container type
and one component deployment descriptor of that type. An enterprise bean module deployment
descriptor, for example, declares transaction attributes and security authorizations for an
enterprise bean. A Java EE module without an application deployment descriptor can be deployed
as a stand-alone module.
The four types of Java EE modules are as follows:
• EJB modules, which contain class files for enterprise beans and an EJB deployment
descriptor. EJB modules are packaged as JAR files with a .jar extension.
• Web modules, which contain servlet class files, JSP files, supporting class files, GIF and
HTML files, and a web application deployment descriptor. Web modules are packaged as
JAR files with a .war (Web ARchive) extension.
• Application client modules, which contain class files and an application client deployment
descriptor. Application client modules are packaged as JAR files with a .jar extension.
• Resource adapter modules, which contain all Java interfaces, classes, native libraries,
and other documentation, along with the resource adapter deployment descriptor.
Together, these implement the Connector architecture (see J2EE Connector Architecture)
for a particular EIS. Resource adapter modules are packaged as JAR files with an .rar
(resource adapter archive) extension.
16
2 - HTTP
2 - HTTP
2.1 what is http
HTTP stands for HyperText Transfer Protocol while hypertext means text contatining links to
another text. HTTP was created by by Tim Berners-Lee in 1990 at CERN as a mean to store
scientific data. It quickly evolved into the preferred communication protocol over the internet.
The first oficial version – HTTP 1.0 – dates from 05/95 and is the object of RFC 1945
(www.apps.ietf.org/rfc/rfc1945.html). It is authored by Tim Berners-Lee, Roy Fielding and Henrik
Nielsen.
The second (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.
HTTP follows the client – server model. The client sends a request message to the server. The
server answers with a response message. These messages may have different contents, but they
also have some common structural elements, as follows:
1. an initial line
2. zero or more header lines
3. a blank line (CR/LF)
4. an optional message body
<initial line>
Header1: value1
...
Headern: valuen
17
2 - HTTP
As of HTTP 1.1, there are 8 HTTP commands (methods) that are widely supported. Here is
their list:
1. GET
2. HEAD
3. POST
4. CONNECT
5. DELETE
6. OPTIONS
7. PUT
8. TRACE
Three other commands are listed, as well, in the HTTP 1.1 specification, but lack of support
makes them obsolete. These commands are:
• LINK
• UNLINK
• PATCH
The HEAD command is identical to the GET command in all respects but one. The only
difference is that the response must not have a body. All the information requested is returned in
the header section of the response.
The GET method means retrieve whatever information (in the form of an entity) is identified by
the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data
which shall be returned as the entity in the response and not the source text of the process, unless
that text happens to be the output of the process.
The POST method is used to request that the origin server accept the entity enclosed in the
request as a new subordinate of the resource identified by the Request-URI in the Request-Line.
POST is designed to allow a uniform method to cover the following functions:
18
2 - HTTP
The actual function performed by the POST method is determined by the server and is usually
dependent on the Request-URI. The posted entity is subordinate to that URI in the same way that
a file is subordinate to a directory containing it, a news article is subordinate to a newsgroup to
which it is posted, or a record is subordinate to a database.
The action performed by the POST method might not result in a resource that can be identified
by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status,
depending on whether or not the response includes an entity that describes the result.
1. The method GET is intended for getting (retrieving) data, while POST may involve anything,
like storing or updating data, or ordering a product, or sending E-mail
2. When used for form data submission, GET attaches this data to the URL of the request, after
the “?” character, as a sequence of “name=value” pairs, separated by the character “&” or “;”
On the other side, form data submitted by POST may be encoded either as above (using
application/x-www-form-urlencoded content type), or in the message
body, (encoded as multipart/form-data).
3. A POST request requires an extra transmission to retrieve the message body, while a GET
request allows data sent via the URL to be processed immediately.
Contains 3 elements, separated by spaces (although the reason phrase may contain spaces, as
well):
• the HTTP version of the response
• a response status code (a number)
• a response status reason phrase (a human readable response status)
Here is an example of an initial response line:
HTTP/1.0 404 Not Found
A three-digit integer, where the first digit identifies the general category of response:
• 1xx indicates an informational message only
19
2 - HTTP
A header line consists of two parts, header name and header value, separated a semicolon.
The HTTP 1.0 version specifies 16 headers, none of them mandatory, while the HTTP 1.1 version
specifies 46 of them, out of which, one (Host) is mandatory. Although the header names are not
case sensitive, header values are.
A couple of examples of header lines:
User-agent: Mozilla/3.0Gold
Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT
Header lines which begin with spaces or tabs are parts of the previous header line.
An HTTP message may have a body of data sent after the header lines. The most common use
of the message body is in a response, that is, where the requested resource is returned to the
client, or perhaps explanatory text if there's an error. In a request, this is where user-entered data
or uploaded files are sent to the server.
If an HTTP message includes a body, the header lines of the message are used to describe the
body. In particular,
• the Content-Type: header gives the MIME-type of the data in the body, such as text/html
or image/jpg.
• the Content-Length: header gives the number of bytes in the body.
20
2 - HTTP
MIME stands for Multipurpose Internet Mail Extensions. Each extension consists of a type and
a subtype. RFC 1521 (www.apps.ietf.org/rfc/rfc1521.html) defines 7 types and several subtypes,
although the list of admissible subtypes is much longer.
Here is the list of the seven types, together with the subtypes defined in this particular RFC.
1. text, with subtype plain
2. multipart, with subtypes mixed, alternative, digest, parallel
3. message, with subtypes rfc822, partial, external-body
4. application, with subtypes octet-stream, postscript
5. image, with subtypes jpeg, gif
6. audio, with subtype basic
7. video, with subtype mpeg
<html>
<body>
<h1>Happy birthday!</h1>
(more file contents)
.
.
21
2 - HTTP
.
</body>
</html>
22
3 - HTML
3 - HTML
3.1 what is html?
HTML stands for HyperText Markup Language. HTML describes how text, images and other
components are to be displayed in a browser, using a variety of tags and their related attributes.
The first version of HTML, namely HTML 1.0, appeared in summer 1991 and was supported by
the first popular web browser, Mosaic. The first official version – HTML 2.0 - was approved as a
standard in September 1995 (as RFC 1866 (http://www.apps.ietf.org/rfc/rfc1866.html) and was
widely supported. A newer standard, HTML 3.2 (3.0 was not widely accepted) appeared a W3C
recommendation in January 1997.
Version 4.0 introduces the Cascading Style Sheets.
The newest version of HTML is 4.01. It is a revision of 4.0 and was accepted in December
1997. However, a working draft for the next major revision, namely HTML 5 was published in
January 2008. Originally named Web Applications 1.0, the specification includes several ideas of
the WHAT (Web Hypertext Application Technology) working group. It might take several years
before the specification reaches final Recommendation status.
From 1999 on, HTML is part of a new specification – XHTML. The XHTML 1.0 draft was
released in 01.99. 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 .
With support for the first 17 planes of ISO 10646 and increased
limits for tag and literal lengths etc.
--
CHARSET
BASESET "ISO Registration Number 177//CHARSET
ISO/IEC 10646-1:1993 UCS-4 with
implementation level 3//ESC 2/5 2/15 4/6"
23
3 - HTML
DESCSET 0 9 UNUSED
9 2 9
11 2 UNUSED
13 1 13
14 18 UNUSED
32 95 32
127 1 UNUSED
128 32 UNUSED
160 55136 160
55296 2048 UNUSED -- SURROGATES --
57344 1056768 57344
CAPACITY SGMLREF
TOTALCAP 150000
GRPCAP 150000
ENTCAP 150000
SCOPE DOCUMENT
SYNTAX
SHUNCHAR CONTROLS 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 127
BASESET "ISO 646IRV:1991//CHARSET
International Reference Version
(IRV)//ESC 2/8 4/2"
DESCSET 0 128 0
FUNCTION
RE 13
RS 10
SPACE 32
TAB SEPCHAR 9
NAMING LCNMSTRT
""
UCNMSTRT
""
LCNMCHAR
".-_:"
UCNMCHAR
".-_:"
NAMECASE
GENERAL YES
ENTITY NO
DELIM GENERAL SGMLREF
SHORTREF SGMLREF
NAMES SGMLREF
QUANTITY SGMLREF
ATTCNT 60 -- increased --
ATTSPLEN 65536 -- These are the largest values --
LITLEN 65536 -- permitted in the declaration --
NAMELEN 65536 -- Avoid fixed limits in actual --
PILEN 65536 -- implementations of HTML UA's --
TAGLVL 100
TAGLEN 65536
GRPGTCNT 150
GRPCNT 64
FEATURES
MINIMIZE
DATATAG NO
OMITTAG YES
RANK NO
SHORTTAG YES
LINK
24
3 - HTML
SIMPLE NO
IMPLICIT NO
EXPLICIT NO
OTHER
CONCUR NO
SUBDOC NO
FORMAL YES
APPINFO NONE
>
2. A Document Type Definition (DTD) – defines the syntax of markup constructs. Check the
address http://www.w3.org/TR/REC-html40/sgml/dtd.html for the latest version of the
HTML DTD.
3. A specification that describes the semantics to be ascribed to the markup and character
entity references. This specification adds new syntactic restrictions which cannot be
defined within the frame of the DTD.
4. Document instances containing data (content) and markup. Each instance contains a
reference to the DTD to be used to interpret it.
Overall, the specification of HTML 4.0 contains an SGML declaration, three DTDs (HTML 4.0
Strict DTD, HTML 4.0 Transitional DTD, HTML 4.0 Frameset DTD) and a list of character
references. If you wonder what a character reference is, look at these examples: “<”, “"”,
"水" (in hexadecimal) - the chinese character for water. You get the point.
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:
declares an image element, with the required (mandatory) attributes SRC and ALT and the
optional attributes HEIGHT and WIDTH. Other optional attributes of the <IMG> element, like
ALIGN, BORDER, CONTROLS, DYNSRC, …, VSAPCE are omitted.
A comment section in an HTML document starts with <!-- and end at the first occurrence of -->.
An example:
25
3 - HTML
Example:
<A HREF=”http://web.info.uvt.ro/webmail/src/login.php”>Login to
web mail</A>
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
3.5 tables
26
3 - HTML
A table is a visual rectangular object consisting of several rows and columns. The intersection
of any row and any column is called a cell. Usually, the cells in the first row contain are called
headers and consist of a brief description of the content of the corresponding column. Here is a
an example of a table:
The specific elements defining a table, its rows, columns, headers and cells are <TABLE>,
<THEAD>, <TR>, <TH> and <TD>. Here is their description and attributes.
the <TABLE> element
attributes:
• BORDER
• CELLSPACING
• CELLPADDING
• WIDTH
• ALIGN
• VALIGN
• TBODY
• BORDERCOLOR
• FRAME
• RULES
• COLORGROUP
• BACKGROUND
27
3 - HTML
• VALIGN
3.7 forms
A form is a basic component container, allowing user input and parameter submittal.
The <FORM> element has the following attributes:
• ACTION - required, specifies the URL of the server side process that will receive the data
28
3 - HTML
• METHOD - required, may have the values GET or POST, specifies how data will be sent to
the server. Possible values for this attribute:
• "POST"- sends the form values in 2 steps: contacts first the server then the form values are
sent in a separate transmission.
• "GET" - sends the form values in a single transmission, the browser appends the values to
the URL, after a quotation mark - ?. The pairs name=value are separated by ampersand - &
or (sometimes) by semicolon - :.
Example:
http://web.info.uvt.ro/servlet/MyServlet?a=12&b=25
• ENCTYPE - specifies the encoding type of the of the form content. Default value:
• "application/x-www-form-urlencoded" - the default value; however, since it converts spaces
to '+' and non-alphanumerical to '%HH', where 'HH' is the hexadecimal ASCII code of the
character.
Other possible values for this attribute:
• "multipart/form-data" - used with forms that contain a file-selection field, data is sent as a
single document with multiple sections.
• "text/plain"
29
3 - HTML
• SELECTED
30
4 - JAVA PRIMER
4 - JAVA PRIMER
4.1 history
The initial name of this language was OAK and was developed as part of the GREEN project at
Sun, project started in 12.90. Early versions of Java were released in 12.94 and was officially
announced at Sun World in 05.95. The first commercial version was delivered to the first
customer (Netscape, Inc.) in 08.95. The current version (as of 10.2004) of Java 2 Platform
Standard Edition is J2SE 5.0, following the 1.4.2 version. The current version (as of 10.2010) of
Java Platform Enterprise Edition is Java EE 6 Update 21.
From source to execution, A java program goes thru the following phases:
1. Java source – a file with extension .java
2. Java bytecode – a file with extension .class
3. The Java interpreter (which is part of the Java Virtual Machine) parses and executes the
Java bytecode.
Example:
Edit the file prog1.java. The java compiler (javac) translates it to bytecode – prog1.class. The
java interpreter (as part of the JVM) parses and executes the prog1.class file.
In terms of execution time, a Java interpreted program is about 10 times slower than a
compiled and linked one. To overcome this significant shortage, a tool named Just In Time
compiler, allows the compilation of the Java source into machine-dependent binary executable.
The first time a class is loaded, the compilation process occurs, which accounts for a pretty slow
execution, but next time execution is much faster, pretty much comparable to that of a binary
executable.
The java compiler is (in general) a command line tool, with the following main options:
• -classpath <path>
• -sourcepath <path>
• -d <directory> : specifies where to put the .class file.
• -g : generate all debugging info.
One example of command line compilation:
javac -classpath .;C:\TW\mySource;C:\TW\myPackages -g login.java
31
4 - JAVA PRIMER
There exist 2 types of programs that can be written in Java. The first type are embedded in web
pages – applets, the others are the standalone programs – Java applications.
A java applet is a java class that extends the standard Applet class.
In general, an applet is inserted in a HTML page by an <APPLET> tag or by an <OBJECT> tag.
The <APPLET> element has 3 mandatory attributes, namely:
• CODE – identifies the (compiled) class file of the applet
• WIDTH
• HEIGHT
A java application is a collection of java classes. Generally, each class is implemented in a
source file having the same name as the class itself and whose extension is .java. Exactly one of
these classes must implement a method called main(). This method is the entry point in the
application and must have the following signature:
A compiled java application (class) may be executed from the command line using an
executable called java (the java interpreter), as follows:
4.4.1 encapsulation
This is a fancy word for the tendency of hiding the implementation of the methods of some
class and exposing only the interface of its public (and to some degree – its protected) methods.
4.4.2 inheritance
Inheritance is a partial order relation in the set of all Java classes. A Java class B inherits
another class A (or is a subclass of A, or is derived from A, or that it extends A). This binary
relation is specified in the declaration of the derived class B using the keyword extends. An
example:
32
4 - JAVA PRIMER
In this case, all variables and methods of the base class A are automatically variables and
methods of the derived class B.
The derived class B can use (for free) all the methods of the base class, but it also can
override the implementation of any method in the base class, providing its own implementation.
While C++ allows multiple inheritance, a Java class can extend a single base class. That
means that the graph of the direct inheritance relation is a forest (its connected components are
trees). In fact, all classes in Java are (by default) subclasses of a universal base class, called
Object. Therefore, the forest we mentioned is actually a tree, with the root the class Object.
4.4.3 Polymorphism
Polymorphism means the ability of a variable of a given (base) type (class) to be used to
reference objects of different (derived) types (classes), and automatically call the method specific
to the type (derived class) of the object that the variable references.
All basic types have associated classes which extend their functionality, namely: Byte, Short,
Integer, Long, Float, Double, Boolean, Character.
33
4 - JAVA PRIMER
The access attributes of a member variable or method of a class are specified by the access
specifiers. Except for the "package" concept, they have the same basic meaning as in C++.
• no specifier - the default value allows access from any class in the same package
• public - access from any class anywhere
• private - no access from outside the class itself
• protected - accessible from any class in the same package an any subclass anywhere
While the above specifiers apply to the variables and the methods of a class, the specifiers for
the class itself can be taken from the following list:
• no specifier - the default value makes the class visible only to the classes in the same
package
• public - the class is visible from any class, anywhere
• abstract - the class is abstract (some of its methods (inherited or specified by some
interface) are to be implemented by some of its subclasses)
An example. The declaration:
abstract class myFirstClass extends javax.servlet.http.HttpServlet
implements Serializable
{
...
}
declares an abstract class, which is visible only to the classes in the same package, which
extends the class javax.servlet.http.HttpServlet and which implements the
Serializable interface.
The modifiers of the variables and methods of a class specify their range and stability. A static
variable or method is one which is implemented at class level, rather than at class instance. A
final variable (method, class) is one which cannot be modified (overridden, inherited). More
precisely:
A static (or class):
• variable - one which is defined at class level, has the same value for all class instances.
• method - all variables referenced in the function body are static variables.
Static variables and methods can be referenced (invoked) using either the name of the class or
the name of a class instance.
A final:
• variable - one which is constant
• method - the method implementation cannot be overriden by some subclass.
• class - does not have any subclasses.
34
4 - JAVA PRIMER
35
4 - JAVA PRIMER
• supply then code to deal with the exception inside the method - this can be done by
providing a try, catch, finally construct.
• ignore it (pass it to the code that called the method) - by adding the key word throws,
followed by a comma separated list of exceptions after the parameter list of the method.
A Java package is a named collection of classes. Each class belongs to a package (even if a
package name is not specified, the default package is used). The names in a package are
qualified by the package name, therefore, they have to be unique inside a package.
package com.bank11.ccards.servlets;
import javax.sql.*;
import.java.util.Properties;
...
The name of the package is directly linked to the directory structure in which it is stored. In the
example above, the class (the .class file, rather) defined in the java source must be stored in a
directory called servlets, which is a subdirectory of ccards (which itself, is a subdirectory of a
directory called bank11).
36
4 - JAVA PRIMER
• java.text
• javax.accessibility
• javax.swing - swing GUI components (minimal dependence on native code)
• java.swing.event - support for event handling
4.10 interfaces
An interface in Java corresponds to the abstract class concept in C++. While multiple
inheritance is forbidden in Java (a class can be the subclass of a single base class), Java classes
can implement zero or more interfaces.
An interface is a collection of constants and "abstract" functions.
All variables (actually, constants) of an interface are automatically (by default) public, static and
final. All methods declared in an interface are (by default) public and abstract.
If a class is declared as implementing an interface but omits some of its methods, it must be
declared as abstract.
37
5 - javaScript
5 - JAVASCRIPT
5.1 so what is JavaScript?
The initial official name of this language was ECMAscript. ECMA stands for European
Computer Manufacturers Association and is an organization founded in 1961 to standardize
computer systems in Europe. The origins of this language date back to 1995, and was originally
developed by Brendan Eich of Netscape under the names Mocha, then LiveScript and finally, as
JavaScript. Subsequently, JavaScript was standardized by ECMA in June 1997 under the name
ECMAScript. However, the general public knows it only by the name given by its creator –
JavaScript. Adaptations of the ECMA standard for other applications, like KDE or Adobe Flash
bear different names, like QtScript or ActionScript.
• JavaScript gives HTML designers a programming tool - HTML authors are normally
not programmers, but JavaScript is a scripting language with a very simple syntax!
Almost anyone can put small "snippets" of code into their HTML pages
• JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
• JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
• JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
• JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
• JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser
• JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer
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
38
5 - javaScript
<html>
<head>
<script type="text/javascript">
....
</script>
</head>
<html>
<head>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>
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 variable is a "container" for some information whose value can change during the script.
39
5 - javaScript
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.
40
5 - javaScript
The variable argument can be a named variable, an array element, or a property of an object.
Example
Using for...in to loop through an array:
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
try
{
// run some code here
}
catch(err)
{
41
5 - javaScript
Example
<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>
5.6 operators
The only new one is the comparison operator === (equal values and same type). Also, strings
can be added (concateneted) using the + operator.
Syntax:
42
5 - javaScript
alert("sometext")
Syntax:
confirm("sometext")
Syntax:
prompt("sometext","defaultvalue")
5.8 functions
<html>
<head>
<script type="text/javascript">
function displaymessage() { alert("Hello World!") }
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>
If the line: alert("Hello world!!"), in the example above had not been written within a function, it
would have been executed as soon as the line was loaded. Now, the script is not executed before
the user hits the button. We have added an onClick event to the button that will execute the
function displaymessage() when the button is clicked..
43
5 - javaScript
var1, var2, etc are variables or values passed into the function. The { and the } defines the start
and end of the function.
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.
When you call the function above, you must pass along two parameters:
product=prod(2,3)
The returned value from the prod() function is 6, and will be stored in the variable called product.
5.9.2 properties
Properties are the values associated with an object.
In the following example we are using the length property of the String object to return the
number of characters in a string:
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
44
5 - javaScript
5.9.3 methods
Methods are the actions that can be performed on objects.
In the following example we are using the toUpperCase() method of the String object to display
a text in uppercase letters:
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
There are two major classes of built-in javascript objects. The first class consists of browser
specific objects. The other class are the language specific objects, which will be specified in the
next section.
45
5 - javaScript
We can think of each Web page as a collection of several individual elements, which are called
Objects. For example, every Image on the page is an Object, every Link on the page is an Object.
Even this Document itself is an Object. At its most basic level, JavaScript allows you to control
the appearance of many of the Objects that make up a Web page as we previously saw.
Objects are storage containers that have Properties (data values associated with Objects) and
Methods (functions associated with Objects) that operate on that data. Objects may also have
certain Events that are associated with them. Events are special signals or messages which occur
when certain pre-defined actions take place within a Web browser, or when the user interacts with
a Web page. When an event message has been triggered, you need a way to intercept the
message and react to it. This is achieved through the use of Event Handlers.
For an exhaustive list of properties and methods of the above objects (and for the built in
objects, as well), check the site http://www.w3schools.com/jsref/default.asp
Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
Property Description F N I
F E
constructor A reference to the function that created the object 1 4 4
length Returns the number of characters in a string 1 2 3
prototype Allows you to add properties and methods to the object 1 2 4
Methods
Method Description F N I
F E
anchor() Creates an HTML anchor 1 2 3
big() Displays a string in a big font 1 2 3
blink() Displays a blinking string 1 2
bold() Displays a string in bold 1 2 3
charAt() Returns the character at a specified position 1 2 3
charCodeAt() Returns the Unicode of the character at a specified position 1 4 4
concat() Joins two or more strings 1 4 4
fixed() Displays a string as teletype text 1 2 3
fontcolor() Displays a string in a specified color 1 2 3
fontsize() Displays a string in a specified size 1 2 3
fromCharCode() Takes the specified Unicode values and returns a string 1 4 4
46
5 - javaScript
Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
F I
Property Description N
F E
constructor Returns a reference to the Date function that created 1 4 4
the object
prototype Allows you to add properties and methods to the object 1 3 4
Methods
F I
Method Description N
F E
Date() Returns today's date and time 1 2 3
47
5 - javaScript
getDate() Returns the day of the month from a Date object (from 1 2 3
1-31)
getDay() Returns the day of the week from a Date object (from 0- 1 2 3
6)
getFullYear() Returns the year, as a four-digit number, from a Date 1 4 4
object
getHours() Returns the hour of a Date object (from 0-23) 1 2 3
getMilliseconds() Returns the milliseconds of a Date object (from 0-999) 1 4 4
getMinutes() Returns the minutes of a Date object (from 0-59) 1 2 3
getMonth() Returns the month from a Date object (from 0-11) 1 2 3
getSeconds() Returns the seconds of a Date object (from 0-59) 1 2 3
getTime() Returns the number of milliseconds since midnight Jan 1 2 3
1, 1970
getTimezoneOffset() Returns the difference in minutes between local time 1 2 3
and Greenwich Mean Time (GMT)
getUTCDate() Returns the day of the month from a Date object 1 4 4
according to universal time (from 1-31)
getUTCDay() Returns the day of the week from a Date object 1 4 4
according to universal time (from 0-6)
getUTCMonth() Returns the month from a Date object according to 1 4 4
universal time (from 0-11)
getUTCFullYear() Returns the four-digit year from a Date object according 1 4 4
to universal time
getUTCHours() Returns the hour of a Date object according to universal 1 4 4
time (from 0-23)
getUTCMinutes() Returns the minutes of a Date object according to 1 4 4
universal time (from 0-59)
getUTCSeconds() Returns the seconds of a Date object according to 1 4 4
universal time (from 0-59)
getUTCMilliseconds() Returns the milliseconds of a Date object according to 1 4 4
universal time (from 0-999)
getYear() Returns the year, as a two-digit or a three/four-digit 1 2 3
number, depending on the browser. Use getFullYear()
instead !!
parse() Takes a date string and returns the number of 1 2 3
milliseconds since midnight of January 1, 1970
setDate() Sets the day of the month in a Date object (from 1-31) 1 2 3
setFullYear() Sets the year in a Date object (four digits) 1 4 4
setHours() Sets the hour in a Date object (from 0-23) 1 2 3
setMilliseconds() Sets the milliseconds in a Date object (from 0-999) 1 4 4
setMinutes() Set the minutes in a Date object (from 0-59) 1 2 3
setMonth() Sets the month in a Date object (from 0-11) 1 2 3
setSeconds() Sets the seconds in a Date object (from 0-59) 1 2 3
setTime() Calculates a date and time by adding or subtracting a 1 2 3
specified number of milliseconds to/from midnight January
1, 1970
48
5 - javaScript
Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
F I
Property Description N
F E
49
5 - javaScript
Methods
Method Description F N I
F E
concat() Joins two or more arrays and returns the result 1 4 4
join() Puts all the elements of an array into a string. The elements 1 3 4
are separated by a specified delimiter
pop() Removes and returns the last element of an array 1 4 5
.5
push() Adds one or more elements to the end of an array and returns 1 4 5
the new length .5
reverse() Reverses the order of the elements in an array 1 3 4
shift() Removes and returns the first element of an array 1 4 5
.5
slice() Returns selected elements from an existing array 1 4 4
sort() Sorts the elements of an array 1 3 4
splice() Removes and adds new elements to an array 1 4 5
.5
toSource() Represents the source code of an object 1 4 -
toString() Converts an array to a string and returns the result 1 3 4
unshift() Adds one or more elements to the beginning of an array and 1 4 6
returns the new length
valueOf() Returns the primitive value of an Array object 1 2 4
Properties
FF: Firefox, IE: Internet Explorer
F I
Property Description
F E
constructor Returns a reference to the Number function that created the 1 4
object
50
5 - javaScript
Methods
Method Description F I
F E
toExponential() Converts the value of the object into an exponential notation 1 5
.5
toFixed() Formats a number to the specified number of decimals 1 5
.5
toLocaleString()
toPrecision() Converts a number into an exponential notation if it has 1 5
more digits than specified .5
toString() Converts the Number object into a string 1 4
valueOf() Returns the value of the Number object 1 4
Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
F I
Property Description N
F E
constructor Returns a reference to the Boolean function that created the 1 2 4
object
prototype Allows you to add properties and methods to the object 1 2 4
Methods
Method Description F N I
F E
toSource() Returns the source code of the object 1 4 -
toString() Converts a Boolean value to a string and returns the result 1 4 4
valueOf() Returns the primitive value of a Boolean object 1 4 4
51
5 - javaScript
Properties
FF: Firefox, N: Netscape, IE: Internet Explorer
F I
Property Description N
F E
E Returns Euler's constant (approx. 2.718) 1 2 3
LN2 Returns the natural logarithm of 2 (approx. 0.693) 1 2 3
LN10 Returns the natural logarithm of 10 (approx. 2.302) 1 2 3
LOG2E Returns the base-2 logarithm of E (approx. 1.442) 1 2 3
LOG10E Returns the base-10 logarithm of E (approx. 0.434) 1 2 3
PI Returns PI (approx. 3.14159) 1 2 3
SQRT1_2 Returns the square root of 1/2 (approx. 0.707) 1 2 3
SQRT2 Returns the square root of 2 (approx. 1.414) 1 2 3
Methods
Method Description F N I
F E
abs(x) Returns the absolute value of a number 1 2 3
acos(x) Returns the arccosine of a number 1 2 3
asin(x) Returns the arcsine of a number 1 2 3
atan(x) Returns the arctangent of x as a numeric value between -PI/2 1 2 3
and PI/2 radians
atan2(y,x) Returns the angle theta of an (x,y) point as a numeric value 1 2 3
between -PI and PI radians
ceil(x) Returns the value of a number rounded upwards to the nearest 1 2 3
integer
cos(x) Returns the cosine of a number 1 2 3
exp(x) Returns the value of Ex 1 2 3
floor(x) Returns the value of a number rounded downwards to the 1 2 3
nearest integer
log(x) Returns the natural logarithm (base E) of a number 1 2 3
max(x,y) Returns the number with the highest value of x and y 1 2 3
min(x,y) Returns the number with the lowest value of x and y 1 2 3
pow(x,y) Returns the value of x to the power of y 1 2 3
random() Returns a random number between 0 and 1 1 2 3
round(x) Rounds a number to the nearest integer 1 2 3
sin(x) Returns the sine of a number 1 2 3
sqrt(x) Returns the square root of a number 1 2 3
tan(x) Returns the tangent of an angle 1 2 3
52
5 - javaScript
An object is just a special kind of data, with a collection of properties and methods.
Let's illustrate with an example: A person is an object. Properties are the values associated with
the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All
persons have these properties, but the values of those properties will differ from person to person.
Objects also have methods. Methods are the actions that can be performed on objects. The
persons' methods could be eat(), sleep(), work(), play(), etc.
5.12.1 Properties
The syntax for accessing a property of an object is:
objName.propName
You can add properties to an object by simply giving it a value. Assume that the personObj
already exists - you can give it properties named firstname, lastname, age, and eyecolor as
follows:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";
document.write(personObj.firstname);
5.12.2 Methods
An object can also contain methods.
You can call a method with the following syntax:
objName.methodName()
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
53
5 - javaScript
Adding a method to the personObj is also simple. The following code adds a method called
eat() to the personObj:
personObj.eat=eat;
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
Notice that the template is just a function. Inside the function you need to assign things to
this.propertyName. The reason for all the "this" stuff is that you're going to have more than one
person at a time (which person you're dealing with must be clear). That's what "this" is: the
instance of the object at hand.
Once you have the template, you can create new instances of the object, like this:
myFather=new person("John","Doe",50,"blue");
myMother=new person("Sally","Rally",48,"green");
You can also add some methods to the person object. This is also done inside the template:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.newlastname=newlastname;
}
Note that methods are just functions attached to objects. Then we will have to write the
newlastname() function:
function newlastname(new_lastname)
{
this.lastname=new_lastname;
54
5 - javaScript
The newlastname() function defines the person's new last name and assigns that to the person.
JavaScript knows which person you're talking about by using "this.". So, now you can write:
myMother.newlastname("Doe").
New to HTML 4.0 was the ability to let HTML events trigger actions in the browser, like starting
a JavaScript when a user clicks on an HTML element.
Every element on a web page has certain events which can trigger JavaScript functions. For
example, we can use the onClick event of a button element to indicate that a function will run
when a user clicks on the button. We define the events in the HTML tags.
Examples of events:
● A mouse click
● A web page or an image loading
● Mousing over a hot spot on the web page
● Selecting an input box in an HTML form
● Submitting an HTML form
● A keystroke
Note: Events are normally used in combination with functions, and the function will not be
executed before the event occurs!
Tne following table contains an exhaustive list of events together with the support version of
FireFox, Netscape an Internet Explorer for each such event.
55
5 - javaScript
The onload event is often used to check the visitor's browser type and browser version, and load
the proper version of the web page based on the information.
Both the onload and onUnload events are also often used to deal with cookies that should be
set when a user enters or leaves a page. For example, you could have a popup asking for the
user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the
visitor arrives at your page, you could have another popup saying something like: "Welcome John
Doe!".
5.13.3 onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.
Below is an example of how to use the onSubmit event. The checkForm() function will be called
when the user clicks the submit button in the form. If the field values are not accepted, the submit
should be cancelled. The function checkForm() returns either true or false. If it returns true the
form will be submitted, otherwise the submit will be cancelled:
56
5 - javaScript
event');return false">
<img src="w3schools.gif" width="100" height="30"> </a>
57
6 - Html DOM
6 - HTML DOM
6.1 what is the DOM?
The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style of
a document.
The W3C DOM provides a standard set of objects for HTML and XML documents, and a
standard interface for accessing and manipulating them.
The W3C DOM is separated into different parts (Core, XML, and HTML) and different levels
(DOM Level 1/2/3):
• Core DOM - defines a standard set of objects for any structured document
• XML DOM - defines a standard set of objects for XML documents
• HTML DOM - defines a standard set of objects for HTML documents
A web browser is not obliged to use DOM in order to render an HTML document. However, the
DOM is required by JavaScript scripts that wish to inspect or modify a web page dynamically. In
other words, the Document Object Model is the way JavaScript sees its containing HTML page
and browser state.
Because the DOM supports navigation in any direction (e.g., parent and previous sibling) and
allows for arbitrary modifications, an implementation must at least buffer the document that has
been read so far (or some parsed form of it). Hence the DOM is likely to be best suited for
applications where the document must be accessed repeatedly or out of sequence order. If the
application is strictly sequential and one-pass, the SAX model is likely to be faster and use less
memory. SAX (Simple API for XML) is a sequential access parser API for XML. SAX provides a
mechanism for reading data from an XML document. It is a popular alternative to the Document
Object Model (DOM).
6.2 history
The World Wide Web Consortium (W3C) developed the W3C Document Object Model in
response to the development of various proprietary models for HTML, particularly those used in
Web browsers. The existing vendor-specific interfaces were dubbed intermediate DOMs.
W3C began development of the DOM in the mid-1990s. Although the W3C never produced a
specification for DOM 0, it was nonetheless a partially documented model and was included in the
specification of HTML 4. By October 1998, the first specification of DOM (DOM 1) was released.
DOM 2 was issued in November 2000, with specifics on the style sheet object model and style
information manipulation. DOM 3 was released in April 2004 and is the current release of the
DOM specification.
As of January 2008, the Document Object Model activity is closed. The Document Object
Model Working Group was closed in the Spring of 2004, after the completion of the DOM Level 3
Recommendations. Several W3C Working Groups have since taken the lead in maintaining and
continuing to develop standard APIs for the Web since then; HTML, SVG, CSS, or WebAPI being
among them.
Right now (oct. 2010), what drives the DOM Specifications is the WebApps WG. The W3C
58
6 - Html DOM
Web Applications Working Group has taken over responsibility for the Document Object Model
specifications, including a new revision of DOM Level 3 Events, a new DOM Core specification,
and potentially any errata on older DOM specifications.
6.3 levels
The W3C DOM specifications are divided into levels, each of which contains required and
optional modules. To claim to support a level, an application must implement all the requirements
of the claimed level and the levels below it. An application may also support vendor-specific
extensions which don't conflict with the W3C standards. As of 2005, Level 1, Level 2, and some
modules of Level 3 are W3C Recommendations which means they have reached their final form.
Level 0
The application supports an intermediate DOM, which existed before the creation of DOM Level
1. Examples include the DHTML Object Model or the Netscape intermediate DOM. Level 0 is not
a formal specification published by the W3C but rather a shorthand that refers to what existed
before the standardization process.
Level 1
Navigation of DOM (HTML and XML) document (tree structure) and content manipulation
(includes adding elements). HTML-specific elements are included as well.
Level 2
XML namespace support, filtered views and events.
Level 3
Consists of 6 different specifications:
1. DOM Level 3 Core;
2. DOM Level 3 Load and Save;
3. DOM Level 3 XPath;
4. DOM Level 3 Views and Formatting;
5. DOM Level 3 Requirements; and
6. DOM Level 3 Validation, which further enhances the DOM
6.4 specifications
59
6 - Html DOM
Earlier, when each Web browser exclusively supported its own intermediate DOM,
interoperability problems were numerous. In order to be cross-browser compatible, that is, support
multiple browsers, large parts of Dynamic HTML code had to be rewritten for each browser to be
supported. A common DOM promised substantial simplification of the development of complex
Web applications.
W3C DOM Level 1 has been a recommendation since 1 October 1998. The standardization
effort did not bring forth an immediate change, because non-conformant browsers such as
Internet Explorer 4.x and Netscape 4.x were still widely used in 2000. By 2005, large parts of
W3C DOM were well-supported by common JavaScript-enabled Web browsers, including
Microsoft Internet Explorer (version 5 (1999) and version 6 (2001)), Gecko-based browsers (like
Mozilla and Firefox), Opera, Konqueror, and Safari. Web developers are starting to rely mostly or
solely on W3C DOM, since it allows browser compatibility with a large audience.
In addition to the built-in JavaScript objects, you can also access and manipulate all of the
HTML DOM objects with JavaScript. Besides the generic objects listed bellow, the bulk of the
HTML DOM objects are presented in the next paragraph.
Object Description
Window The top level object in the JavaScript hierarchy. The Window object
represents a browser window. A Window object is created automatically
with every instance of a <body> or <frameset> tag
Navigator Contains information about the client's browser
Screen Contains information about the client's display screen
History Contains the visited URLs in the browser window
Location Contains information about the current URL
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
60
6 - Html DOM
DOM. The contents can be modified or deleted, and new elements can be created.
The HTML DOM is platform and language independent. It can be used by any programming
language like Java, JavaScript, and VBScript.
Object Description
Document Represents the entire HTML document and can be used to access all
elements in a page
Anchor Represents an <a> element
Area Represents an <area> element inside an image-map
Base Represents a <base> element (specifies a default address or a default
target for all links on a page)
Body Represents the <body> element
Button Represents a <button> element
Event Represents the state of an event
Form Represents a <form> element
Frame Represents a <frame> element
Frameset Represents a <frameset> element
Iframe Represents an <iframe> element
Image Represents an <img> element
Input button Represents a button in an HTML form
Input checkbox Represents a checkbox in an HTML form
Input file Represents a fileupload in an HTML form
Input hidden Represents a hidden field in an HTML form
Input password Represents a password field in an HTML form
Input radio Represents a radio button in an HTML form
Input reset Represents a reset button in an HTML form
Input submit Represents a submit button in an HTML form
Input text Represents a text-input field in an HTML form
Link Represents a <link> element
Meta Represents a <meta> element
Option Represents an <option> element
Select Represents a selection list in an HTML form
Style Represents an individual style statement
Table Represents a <table> element
TableData Represents a <td> element
TableRow Represents a <tr> element
Textarea Represents a <textarea> element
61
6 - Html DOM
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.
62
6 - Html DOM
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:
The following example returns a nodeList of all <p> elements that are descendants of the
element with id="main":
document.getElementById('main').getElementsByTagName("p");
The length property defines the length of a node list (the number of nodes). You can loop
through a node list by using the length property:
x=document.getElementsByTagName("p");
63
6 - Html DOM
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
64
6 - Html DOM
Common/W3C events
There is a huge collection of events that can be generated by most element nodes:
• Mouse events
• Keyboard events
• HTML frame/object events
• HTML form events
• User interface events
• Mutation events (notification of any changes to the structure of a document)
Note that the event classification above is not exactly the same as W3C's classification.
65
6 - Html DOM
66
6 - Html DOM
Note that the events whose names start with “DOM” are currently not well supported. Mozilla
and Opera support DOMAttrModified, DOMNodeInserted, DOMNodeRemoved and
DOMCharacterDataModified. Safari, as of version 1.3, also supports these methods.
Also, Mozilla, Safari and Opera also support readystatechange event for the XMLHttpRequest
object. Mozilla also supports the beforeunload event using traditional event registration method
(DOM Level 0). Mozilla and Safari also support contextmenu, but Internet Explorer for the Mac
does not.
Consider the situation when there are 2 elements nested together. Both have event handlers
registered on the same event type, say "click". When the user clicks on the inner element, there
are two possible ways to handle it:
• Trigger the elements from outer to inner (event capturing). This model is implemented in
Netscape Navigator.
• Trigger the elements from inner to outer (event bubbling). This model is implemented in
Internet Explorer and other browsers.
W3C takes a middle position in this struggle. Events are first captured until it reaches the target
element, and then bubbled up. During the event flow, an event can be responded to at any
element in the path (an observer) in either phase by causing an action, and/or by stopping the
event (with method event.stopPropagation() for Mozilla and command
event.cancelBubble = true for Internet Explorer), and/or by cancelling the default action for
the event.
67
6 - Html DOM
The Event object provides a lot of information about a particular event, including information
about target element, key pressed, mouse button pressed, mouse position, etc. Unfortunately,
there are very serious browser incompatibilities in this area. Hence only the W3C Event object is
discussed here.
Event properties
Event methods
Argument Argument
Name Description
type name
To prevent further propagation of an
stopPropagation
event during event flow.
To cancel the event if it is cancelable,
meaning that any default action normally
preventDefault
taken by the implementation as a result of
the event will not occur.
DOMString eventTypeArg Specifies the event type.
Specifies whether or not the event can
boolean canBubbleArg
initEvent bubble.
Specifies whether or not the event's
boolean cancelableArg
default action can be prevented.
68
7 - AJAX
7 - AJAX
7.1 what is ajax?
Ajax stands for Asynchronous JavaScript And XML. It is not a technology in itself, but rather a
collection of existing technologies bound together by JavaScript.
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.
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. It’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.
69
7 - AJAX
The traditional model for web applications (left) compared to the Ajax model (right)
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? In fact, why should the user see the
application go to the server at all?
An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by
introducing an intermediary — an Ajax engine — between the user and the server. It seems like
adding a layer to the application would make it less responsive, but the opposite is true.
Instead of loading a web page, at the start of the session, the browser loads an Ajax engine —
written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for
both rendering the interface the user sees and communicating with the server on the 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.
70
7 - AJAX
The synchronous interaction pattern of a traditional web application (top) compared with the
asynchronous pattern of an Ajax application (bottom)
Every user action that normally would generate an HTTP request takes the form of a JavaScript
call to the Ajax engine instead. Any response to a user action that 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. If 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.
71
7 - AJAX
Ajax uses a programming model with display and events. These events are user actions, they
call functions associated to elements of the web page.
Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with
actions and also to extract data from Xml files provided by the server.
To get data on the server, the ajax engine uses the XMLHttpRequest object. This object
provides two methods:
- open: create a connection.
- send: send a request to the server.
Data furnished by the server will be found in these attributes of the XMLHttpRequest object:
- responseXml - for a Xml file or
- responseText - for a simple text.
Take note that a new XMLHttpRequest object has to be created for each new file to load.
We have to wait for the data to be available to process it, and in this purpose, the state of
availability of data is given by the readyState attribute of XMLHttpRequest.
States of readyState follow (only the last one is really useful):
0: not initialized.
1: connection established.
2: request received.
3: answer in process.
4: finished.
Here is a closer look to the XMLHttpRequest class. It allows the interaction with the servers,
thanks to its methods and attributes.
Attributes
readyState - the code successively changes value from 0 to 4 that means "ready".
status - returned by the server - 200 is ok, 404 if the page is not found
responseText - holds loaded data as a string of characters.
responseXml - holds a Xml loaded file, DOM's method allows to extract data.
onreadystatechange - the name of the function invoked
Methods
open(mode, url, boolean) - mode: type of request, GET or POST
- url: the location of the file
72
7 - AJAX
request.onreadystatechange = function()
{ // instructions to process the response };
if (request.readyState == 4)
{
// received, OK
}
else
{
// wait...
}
- open: command GET or POST, URL of the document, true for asynchronous.
- send: with POST only, the data to send to the server.
73
7 - AJAX
7.7 examples
7.7.1 How to get a text
<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;
};
<body>
<FORM method="POST" name="ajax" action="">
<INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
<INPUT type="text" name="dyn" value="">
</FORM>
</body>
</html>
by this code:
74
7 - AJAX
<div id="zone">
... some text to replace ...
</div>
document.getElementById("zone").innerHTML = "Received:" +
xhr.responseText;
It is an Eclipse add-on that provides tools for building IDE for Ajax runtimes, and testing Ajax
applications. The AJAX Toolkit Framework (ATF) provides and extensible framework and
exemplary tools for building IDEs for the many different AJAX runtime offerings (Dojo, Zimbra,
Rico, etc) in the market. Tools built upon these frameworks will initially include: enhanced
JavaScript editing features such as edit-time syntax checking; an embedded Mozilla web browser;
an embedded DOM browser; and an embedded JavaScript debugger.
● If JavaScript is not activated, Ajax can't work. The user must be asked to set JavaScript
from within options of the browser, with the "noscript" tag.
● Since data to display are loaded dynamically, they are not part of the page, and the
keywords inside are not used by search engines.
● The asynchronous mode may change the page with delays (when the processing on the
server take some times), this may be disturbing.
● The back button may be deactivated (this is not the case in examples provided here).
75
7 - AJAX
7.10 Specifications
76
8 - WEB APPLICATIONS
8 - WEB APPLICATIONS
8.1 the structure of a web application
A web application is a collection of Java servlets, JSP pages, Java Server Faces, other helper
classes and class libraries, other static resources (HTML, images, etc.) and an xml file, the
deployment descriptor.
A web application consists of 4 parts:
1. a public directory – containing html, jsp files and other public resources. This is the root
directory of the application.
2. a WEB-INF/web.xml file – the deployment descriptor.
3. a WEB-INF/classes directory.
4. a WEB-INF/lib directory.
Example:
Assume that we use a Tomcat web server and that the environment variable
%TOMCAT_HOME% is set to C:\TW\Tomcat. Then, the root directory of some web application
can be:
C:\TW\Tomcat\webapps\bank11\ccards
and the mandatory directories are:
C:\TW\Tomcat\webapps\bank11\ccards\WEB-INF\classes
C:\TW\Tomcat\webapps\bank11\ccards\WEB-INF\lib
A web container is a Java runtime providing implementation of the Java servlet API and some
other facilities to the JSP and JSF pages. It responsible for initializing, invoking and managing the
life cycle of servlets, JSPs and JSFs.
A web container may either implement the basic HTTP services or delegates these services to
an external web server.
Web containers can be part of an application or web server or a separate runtime. Here is a
description of these situations.
77
8 - WEB APPLICATIONS
with the web server. Typical integration scenarios are Tomcat with Apache and JRun (of
Allaire) with most of the J2EE application servers.
JavaServer JavaServer
Faces Faces
Java
Classes
Containers are the interface between a component and the low-level platform-specific
functionality that supports the component. Before a web, enterprise bean, or application client
component can be executed, it must be assembled into a Java EE module and deployed into its
container.
The assembly process involves specifying container settings for each component in the Java
EE application and for the Java EE application itself. Container settings customize the underlying
support provided by the Java EE server, including services such as security, transaction
management, Java Naming and Directory Interface (JNDI) lookups, and remote connectivity.
Here are some of the highlights:
• The Java EE security model lets you configure a web component or enterprise bean so
that system resources are accessed only by authorized users.
78
8 - WEB APPLICATIONS
• The Java EE transaction model lets you specify relationships among methods that make
up a single transaction so that all methods in one transaction are treated as a single unit.
• JNDI lookup services provide a unified interface to multiple naming and directory
services in the enterprise so that application components can access these services.
• The Java EE remote connectivity model manages low-level communications between
clients and enterprise beans. After an enterprise bean is created, a client invokes
methods on it as if it were in the same virtual machine.
Because the Java EE architecture provides configurable services, application components
within the same Java EE application can behave differently based on where they are deployed.
For example, an enterprise bean can have security settings that allow it a certain level of access
to database data in one production environment and another level of database access in another
production environment.
The container also manages nonconfigurable services such as enterprise bean and servlet life
cycles, database connection resource pooling, data persistence, and access to the Java EE
platform APIs.
The deployment descriptor 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. Initialization of parameters for servlets, JSPs and Java Server Faces.
2. Servlet, JSPs and Java Server Faces definitions, servlet classes, precompiled JSP
entities are declared (names, classes, descriptions).
3. Servlet, JSPs and Java Server Faces mappings.
4. MIME types used by the web application.
5. Security related entries – may specify which pages require login and the roles different
users may have.
6. Others, like what pages are error, welcome pages, entries related to session
configuration.
Here is a small, but typical web.xml file:
79
8 - WEB APPLICATIONS
There are several issues with the web applications deployment. Behind a very benign URL, like
"http://localhost:8080/ccards/servlet/Enroll" there are 3 things which have to be fixed in order to
make things work properly.
Assume that we work with Tomcat and that the environment variable %TOMCAT_HOME% (or
$TOMCAT_HOME, in an UNIX environment) is set to "C:\TW\Tomcat".
1. The "/servlet" part of the URL tells the web server (Tomcat, in our case) to execute the
invoker servlet. This association is made in the file "%TOMCAT_HOME%\conf\web.xml".
Unfortunately, the lines which deal with this issue are commented out in the latest version
of Tomcat (for so-called "security issues"). To make anything work:
• de-comment the following section:
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
2. The "/ccards" part of the URL is, basicly, the name of the web application. In general, the
base directory of an application is a subdirectory of the "%TOMCAT_HOME%\webapps"
directory. This subdirectory has (in general) the same name as the application itself.
However, for flexibility, the location of the base directory of a web application may be any
sub(sub)directory of "%TOMCAT_HOME%\webapps". The association between the name
of the web application and the location of its base directory is made by a <context>
element in the "%TOMCAT_HOME%\conf\server.xml" file. For example, if the base
directory of the "/ccards" web application is "%TOMCAT_HOME
%\webapps\vdumitrascu\cc", then the corresponding <context> element in the
"%TOMCAT_HOME%\conf\server.xml" file looks like:
3. The "/Enroll" part of the URL identifies the servlet. Basicly, it is the alias of the real servlet
class, whose name is rather long. Let's say that this class is "EnrollServlet.class" and that it
is part of the package "com.bank11.ccards.servlets". Then the "EnrollServlet.class" file
must be located in the directory "%TOMCAT_HOME%\webapps\vdumitrascu\cc\WEB-
INF\classes\com.bank11.ccards.servlets". This association between the (short) alias of the
servlet and its real (long) name is made in the web.xml file of the web application. More
exactly the corresponding <servlet> element should look like:
<servlet>
<servlet-name>Enroll</servlet-name>
<servlet-class>com.bank11.ccards.servlets.EnrollServlet
</servlet-class>
</servlet>
80
9 - SERVLETS
9 - SERVLETS
9.1 the servlets as part of web applications
Java servlets – small, platform independent programs, which extend the functionality of the
web server.
Technically speaking, a servlet is a Java class that extends the GenericServlet (or, more often,
the HttpServlet) class.
The Java Servlet API provides a simple frame for building web applications on web servers.
The current Java Servlet specification is 2.5 and is in final state. Java EE 6 SDK is intended to
contain an implementation of the Java Servlet 3.0 specification, but at this point, this is just a
work in progress. As of oct. 2010, the Java Servlet 3.0 specification is available for public review.
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.
81
9 - SERVLETS
The Java servlet API consists of 2 packages, which are part of the Java Platform SDK,
Enterprise Edition. These packages are:
• javax.servlet
• javax.servlet.http
The classes and interfaces defined in the javax.servlet package are protocol independent, while
the second one, the javax.servlet.http contains classes and interfaces which are HTTP specific.
The classes and interfaces of the Java servlet API can be divided in several categories,
namely:
• servlet implementation
• servlet configuration
• servlet exceptions
• request and responses
• session tracking
• servlet context
• servlet collaboration
• miscellaneous
The Servlet interface is part of the javax.servlet package. It declares the following
methods:
82
9 - SERVLETS
After instantiating the servlet, the web container calls its init() method. The method
performs all initialization required, before the servlet processes any HTTP request. The servlet
specification insures that the init() method is called just once for any given instance of the
servlet.
The web container calls the service() method in response to any incoming request. This
method has two arguments, arguments which implement the ServletRequest and
ServletResponse interfaces, respectively.
More on the servlet life cycle, in a different section.
This class provides a basic implementation of the Servlet interface. Since this class
implements the ServletConfig interface, as well, the developer may call ServletConfig
methods directly, without having to obtain a ServletConfig object first. All classes extending
the GenericServlet class should provide an implementation for the service() method.
Methods specific to this class:
It is very likely that the only implementation of the Servlet interface we'll ever use is one that
processes an HTTP request. The servlet API provides such a specific class, namely the
HttpServlet class.
The HttpServlet provides an HTTP specific implementation of the Servlet interface. This
abstract class specifies the following methods:
83
9 - SERVLETS
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)
javax.servlet.ServletException
javax.servlet.UnavailableException
84
9 - 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. If the servlet does not implement the
javax.servlet.SingleThreadModel, concurrent requests are serviced in more than one
service thread, which requires that the service() method be thread safe.
After instantiation, the container calls the init() method of the servlet, method which
performs the initialization of the servlet. Typically, this method contains JDBC driver loading, DB
connection opening, etc.
The web container makes sure that the init() method of the servlet will be completed before
invoking its service() method. Also, the servlet's destroy() method will be called before the
servlet itself is destroyed.
Most of the above methods are self explanatory. But what is the difference between a
parameter and an attribute? While the parameters of the request are part of the request itself, the
attributes of the request are attached by the web containers or by the servlets/JSPs/JSFs.
There are 3 different ways for attaching and retrieving attributes. The first one is to attach
attributes to the request object. The other two use the HttpSession and ServletContext objects,
respectively. The purpose of attributes is to allow the container to provide additional data to a
servlet, JSP or JSF, or to allow sending data from a servlet to another.
85
9 - SERVLETS
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:
This interface extends the ServletResponse interface and defines methods specific for
constructing responses to HTTP requests.
Here are the most important ones:
86
9 - SERVLETS
A servlet context defines servlet's view of the web application and provides access to resources
common to all servlets of the web application. Each servlet context is rooted at a specific path in
the web server. The deployment of a web application involves adding an application specific
<context> tag which associates the the name of the application with its root directory. This is
done in server's (container's) server.xml file.
The ServletContext interface abstracts the context of a web application. A reference to an
object of this type can be obtained by invoking the getServletContext() method of the
HttpServlet object.
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.*;
87
9 - SERVLETS
import javax.servlet.*;
import javax.servlet.http.*;
88
10 - JDBC
10 - JDBC
10.1 what is jdbc?
JDBC stands for Java Data Base Connectivity and is the Java version of ODBC (Open Data
Base Connectivity). It offers an API for SQL-compliant relational databases access. It abstracts
the vendor-specific details and offers support for the most common database access functions.
The first release of the JDBC specification dates back to Feb. 1997, as part of the Java
Development Kit (JDK) 1.1. After that, JDBC was part of Java Standard Edition (JSE). Starting
with version 3.0, JDBC evolution is part of the Java Community Process. JSR (Java Specification
Request) 54 defines JDBC 3.0 while the current (4.0) JDBC specification is defined in JSR 221.
The JDBC 4.0 API consists of 2 packages:
1. the java.sql package
2. the javax.sql package, which provides several server-side capabilities
The JDBC API provides programmatic access from applications written in the
Java programming language to standard SQL. The JDBC API presents a standard API to access
a wide range of underlying data sources or legacy systems.
Each database vendor offers its own version of DB access API. A JDBC driver is a middleware
layer that translates JDBC calls into vendor specific calls. These drivers fall into four standard
categories, as recognized by the DB industry.
89
10 - JDBC
90
10 - JDBC
This package contains the core JDBC API. An exhaustive list of the classes and interfaces of
this package can be found in the latest JDBC specification (4.0). The document containing this
specification is JSR 221 and can be viewed at http://jcp.org/en/jsr/detail?id=221.
Of the 80+ classes and interfaces defined in this specification, let's remind some of the most
important ones, defined in the JDBC 3.0 API.
java.sql.Array
java.sql.Blob
java.sql.CallableStatement
java.sql.Clob
java.sql.Connection
java.sql.Date
java.sql.Driver
java.sql.DriverManager
java.sql.PreparedStatement
java.sql.ResultSet
java.sql.ResultSetMetaData
java.sql.SQLData
java.sql.SQLDataException
java.sql.SQLException
java.sql.SQLInput
java.sql.SQLOutput
java.sql.SQLPermission
java.sql.SQLXML
java.sql.SQLWarning
java.sql.Statement
java.sql.Struct
java.sql.Time
java.sql.Timestamp
java.sql.Types
java.sql.Wrapper
91
10 - JDBC
The following list contains all of the classes and interfaces new or updated in version 4.0.
java.sql.Blob
java.sql.CallableStatement
java.sql.Clob
java.sql.ClientinfoStatus
java.sql.Connection
java.sql.DatabaseMetaData
java.sql.NClob
java.sql.PreparedStatement
java.sql.ResultSet
java.sql.RowId
java.sql.RowIdLifeTime
java.sql.SQLClientInfoException
java.sql.SQLDataException
java.sql.SQLException
java.sql.SQLFeatureNotSupportedException
java.sql.SQLInput
java.sql.SQLIntegrityConstraintViolationException
java.sql.SQLInvalidAuthorizationSpecException
java.sql.SQLNonTransientConnectionException
java.sql.SQLNonTransientException
java.sql.SQLOutput
java.sql.SQLSyntaxErrorException
java.sql.SQLTimeoutException
java.sql.SQLTransactionRollbackException
java.sql.SQLTransientConnectionException
java.sql.SQLTransientException
java.sql.SQLXML
java.sql.SQLWarning
java.sql.Statement
java.sql.Types
java.sql.Wrapper
javax.sql.CommonDataSource
javax.sql.StatementEvent
javax.sql.StatementEventListener
The figure below shows the interactions and relationships between the major classes and
interfaces of the java.sql package.
The main steps in communicating with a database are:
1. loading a database driver
2. establishing a database connection
3. querying the database
4. processing the result set
92
10 - JDBC
There are two main steps in connecting to an existing database. The first one is
loading a database driver.
A database driver is specified by the driver name. Here are some examples of actual database
driver names:
• com.borland.datastore.jdbc.DataStoreDriver
• com.sybase.jdbc.SybDriver
• com.ibm.db2.jdbc.net.DB2Driver
• oracle.jdbc.driver.OracleDriver
• sun.jdbc.odbc.JdbcOdbcDriver
93
10 - JDBC
The Java code to load the driver name is somewhat obscure, but let's take it for granted:
import java.sql.*;
import java.util.*;
try
{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
} catch (Exception e) {
// driver not found
e.printStackTrace();
}
The actual location of the database is specified by its URL (also known as connection URL).
The URL has 3 parts separated by colons, as follows:
jdbc:<subprotocol>:subname
• jdbc is the protocol name (actually, the only protocol allowed in JDBC).
• the sub-protocol is used to identify the JDBC driver, as specified by the driver vendor.
• subname – the syntax of this field is vendor specific and allows the identification
• jdbc:sybase:localhost:2025
• jdbc:db2://db2.bank11.com:50002/ccards
• jdbc:oracle:thin:@loclahost:1521:ORCL
The second step in connecting to an existing database is to open the connection, by using the
connection URL.
Here is some sample code which shows how this is done:
Since we just used it, let's have a better look in the next section at the DriverManager class.
94
10 - JDBC
This class belongs to the javax.sql package and offers a common access layer on top of
different JDBC drivers. Each driver used by the application must be registered (loaded) before the
DriverManager class tries to obtain a connection.
There are 3 versions of the getConnection() method of the DriverManager class. Here
they are:
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.
The Connection interface is part of then javax.sql package. Once we get the hold of a
Connection object, we can use it for various purposes, but we will restrict ourselves to creating
SQL statements. The most important methods for creating statements:
95
10 - JDBC
6. other methods:
• setQueryTimeout()
• getQueryTimeout()
• setMaxFieldSize()
• getMaxFieldSize()
• cancel()
• getConnection()
96
10 - JDBC
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:
97
10 - JDBC
Most of these methods require the column index (which in SQL starts at 1, not at 0) or the
column name, as the argument.
The usage of these retrieval methods assumes the prior knowledge of the type and the index
(or name) of a particular column. What if we don't have this knowledge? Fortunately, all this data
about the DB schema (or metadata) can be retrieved using the ResultSetMetaData interface.
The invocation of the getMetaData() method of a ResultSet object returns an object of
ResultSetMetaData type.
Here are the most important methods specified by the ResultSetMetaData interface:
• getCatalogName()
• getTableName()
• getSchemaName()
• getColumnCount()
• getColumnName()
• getColumnLabel()
• getColumnType()
• getColumnTypeName()
• getColumnClassName()
• getColumnDisplaySize()
• getScale()
• getPrecision()
• isNullable()
• isCurrency()
• isSearchable()
• isCaseSensitive()
• isSigned()
• isAutoIncrement()
• isReadOnly()
• isDefinitelyWritable()
By default, all created ResultSets have a type of forward only, a concurrency of read only, and
cursors are held over commit boundaries. An exception to this is that WebSphere currently
changes the cursor holdability default so that cursors are implicitly closed when committed. These
characteristics are configurable through methods that are accessible on Statement,
PreparedStatement, and CallableStatement objects.
A cursor comprises a control structure for the successive traversal (and potential processing)
of records in a result set. One can think of a database cursor as an iterator over the collection of
rows in the result set.
98
10 - JDBC
10.10.2 Concurrency
Concurrency determines whether the ResultSet can be updated. The types are again defined by
constants in the ResultSet interface. The available concurrency settings are as follows:
CONCUR_READ_ONLY
A ResultSet that can only be used for reading data out of the database. This is the default
setting.
CONCUR_UPDATEABLE
A ResultSet that allows you to make changes to it. These changes can be placed into the
underlying database.
JDBC 1.0 ResultSets are always forward only. Updateable ResultSets were added in JDBC 2.0.
Note: According to the JDBC specification, the JDBC driver is allowed to change the ResultSet
type of the ResultSet concurrency setting if the values cannot be used together. In such cases,
the JDBC driver places a warning on the Connection object.
There is one situation where the application specifies a TYPE_SCROLL_INSENSITIVE,
CONCUR_UPDATEABLE ResultSet. Insensitivity is implemented in the database engine by
making a copy of the data. You are then not allowed to make updates through that copy to the
underlying database. If you specify this combination, the driver changes the sensitivity to
TYPE_SCROLL_SENSITIVE and create the warning indicating that your request has been
changed.
10.10.3 Holdability
The holdability characteristic determines whether calling commit on the Connection object
closes the ResultSet. The JDBC API for working with the holdability characteristic is new in
version 3.0. However, the native JDBC driver has provided a connection property for several
99
10 - JDBC
releases that allows you to specify that default for all ResultSets created under the connection.
The API support overrides any setting for the connection property. Values for the holdability
characteristic are defined by ResultSet constants and are as follows:
HOLD_CURSOR_OVER_COMMIT
All open cursors remain open when the commit clause is called. This is the native JDBC default
value.
CLOSE_CURSORS_ON_COMMIT
All open cursors are closed when commit clause is called.
// DisplayServlet.java
package com.bank11.ccards.servlets;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.math.*;
import java.util.*;
String connURL="jdbc:mysql://localhost:3306/ccards";
try {
conn=DriverManager.getConnection(connURL,"root","root");
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
100
10 - JDBC
while(rs.next()) {
String firstName = rs.getString(“FIRST_NAME”);
String lastName = rs.getString(“LAST_NAME”);
BigDecimal accountNum = rs.getBigDecimal(“ACCOUNT_NUM”);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter();
// output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet</title>");
out.println("</head>");
out.println("<body>");
...
out.println("</body>");
out.println("</html>");
out.close();
}
101
10 - JDBC
processRequest(req, resp);
}
If an SQL statement is used several times and its different forms differ only with respect to the
data they specify, a better choice is the usage of a PreparedStatement object. Prepared
statements are parametrized and each parameter (usually, a field (column) value or name) is
represented by a question mark '?'.
The following lines of Java code give an example of how to use PreparedStatement objects:
10.13 jdbc and sql types and their corresponding java classes
102
10 - JDBC
In the JDBC 2.0 optional package, the DriverManager interface is replaced by the
DataSource interface as main method of obtaining DB connections.
While the DriverManager interface was used at run time to load explicitly a JDBC driver, the
new mechanism uses a centralized JNDI service to locate a javax.sql.DataSource object.
This interface is, basicly, a factory for creating DB connections. It is part of the javax.sql
package.
The DataSource interface is implemented by a driver vendors. There are three types of
implementations:
1. Basic implementation -- produces a standard Connection object
2. Connection pooling implementation -- produces a Connection object that will
103
10 - JDBC
Main methods:
package com.bank11.ccards.servlets;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;
104
10 - JDBC
if (theDataSource == null)
throw new ServletException("`" + DATASOURCE_NAME +
"' is an unknown DataSource");
} catch (NamingException e) {
throw new ServletException(e);
}
}
}
105
11 - JSP
11 - JSP
11.1 java server pages as part of web applications
A Java Server Page (JSP) is a standard HTML or XML file which contains new scripting tags.
A JSP is loaded by a JSP container and is converted (to servlet code). If the JSP is modified,
the servlet code is regenerated.
The current JSP specification is JSP 2.1 and is related to the 2.5 Java Servlet specification.
JSR 245 is the official document containing the current specification of JSP.
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.
The implementation of this method is generated by the web container – never by the developer.
106
11 - JSP
Even if we start with a very benign java server page, like the listed “hello world” example below,
the generated servlet is still pretty complex.
First, the original index.jsp file.
<%--
Document : index
Created on : 08.11.2010, 08:17:39
Author : sm
--%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
private org.glassfish.jsp.api.ResourceInjector
_jspx_resourceInjector;
107
11 - JSP
return _jspx_dependants;
}
try {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("X-Powered-By", "JSP/2.1");
pageContext = _jspxFactory.getPageContext(this, request,
response, null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector =
(org.glassfish.jsp.api.ResourceInjector)
application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01
Transitional//EN\"\n");
out.write(" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\"
content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <h1>Hello World!</h1>\n");
out.write(" </body>\n");
out.write("</html>\n");
108
11 - JSP
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null)
_jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
/*
* NewBean.java
*/
import java.beans.*;
import java.io.Serializable;
/**
* @author sm
*/
public class NewBean extends Object implements Serializable {
109
11 - JSP
public NewBean() {
propertySupport = new PropertyChangeSupport(this);
}
110
11 - JSP
• if the URL does not start with / , it is interpreted relative to the position of the current JSP
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 include directive instructs the container to include inline the content of the resource
specified by "fileName". The format of this directive:
<%@include file="fileName" %>
The taglib directive allows the usage of custom tags (tag extensions). It has the following
format:
<%@taglib uri="tagLibUri" prefix="tagPrefix" %>
111
11 - JSP
11.7.1 declarations
Basicly, a bloc of java code used to define class-wide variables and methods in the generated
servlet.
11.7.2 scriptlets
Block of java code which is executed during request processing. In Tomcat, this code goes to
inside the service() method.
11.7.3 expressions
A scriptlet that sends a value of a Java expression to back to the client. It is evaluated at
request processing time and the result is converted to a string which is then displayed.
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.
<jsp:useBean>
Used to instantiate a Java bean or locate a bean instance. Assigns it to available name or id.
112
11 - JSP
<jsp:setProperty>
Used in conjunction with the <jsp:useBean> action to set the value of the bean properties.
Attributes description:
• name - the name of a bean instance, already defined in a <jsp:useBean>
• property – specifies the relationship between request parameters and corresponding
bean properties
• property="*" - stores all of the values in the request object parameters (called request
parameters) in matching Bean properties. The property names in the Bean must match
the request parameters
• property="propertyName" [ param="parameterName" ] - Sets one Bean property to
the value of one request parameter. The request parameter can have a different name
than the Bean property, and if so, you must specify param.
• property="propertyName" value="{ string | <%= expression %> }" - Sets one Bean
property to a specific value. The value can be a String or an Expression
<jsp:getProperty>
113
11 - JSP
Used to access the properties of a bean, converts them to string and displays the output to the
client.
Attributes description:
• name - the name of a bean instance whose property is to be retrieved
• property - name of the property to be retrieved
<jsp:param>
Provide other tags with additional information in the form of name:value pairs. It is used in
conjunction with the <jsp:include>, <jsp:forward>, <jsp:plugin> actions.
<jsp:include>
Used for the inclusion of a static or dynamic resource into the current JSP page at request
processing time. An included page has access only to the JspWriter object and cannot set
headers or cookies. While the <%@include> directive is executed at compile time and has static
content, the <jsp:include> action is executed at request processing time and has static or dynamic
content.
Attributes description:
• page - the URL of the page, same format as the <%@include> directive.
• flush - only the "true" value is supported.
114
11 - JSP
<jsp:forward>
Used to forward the the request to another JSP, servlet or to a static resource..
The action may include several <jsp:param> tags, as well. It is used mainly, when we want to
separate the application into different views, depending on request.
<jsp:plugin>
Used in pages to generate client browser specific HTML tags (<OBJECT> or <EMBED>) that
result in download of Java plugins(if required), followed by the execution of the applet or
JavaBeans component specified by the tag.
...
</jsp:params>
</jsp:plugin>
Attributes description:
• name - the name of a bean instance, already defined in a <jsp:useBean>
• type="bean|applet" - the type of object the plugin will execute. You must specify either
bean or applet, as this attribute has no default value.
• code="classFileName" - the name of the Java class file that the plugin will execute. You
must include the .class extension in the name following code. The filename is relative to
the directory named in the codebase attribute.
• codebase="classFileDirectoryName" - the absolute or relative path to the directory that
contains the applet's code. If you do not supply a value, the path of the JSP file that calls
<jsp:plugin> is used.
• name="instanceName" - a name for the Bean or applet instance, which makes it
possible for applets or Beans called by the same JSP file to communicate with each
other.
• archive="URIToArchive, ..." - a comma-separated list of paths that locate archive files
115
11 - JSP
JSP provides several implicit objects, based on the servlet API, objects which are automaticly
available.
1. request - represents the object that triggered the service() method invokation and has
type HttpServletRequest with scope request
2. response - represents server's response to the request, it has HttpServletResponse
type and page scope
3. pageContext - provides a single point of access to attributes and shared data within the
page, it has type PageContext with scope page
4. session - it has HttpSession type and session scope
5. application - represents the servlet context, it has type ServletContext and scope
application
6. out - it represents the buffered version of java.io.PrintWriter, writes to the output
stream to the client, it has javax.servlet.jsp.JspWriter type and scope page
7. config - it is the SevletConfig for the current JSP page, it is of type ServletConfig and
has page scope
8. page - it is an instance of the page's implementation of the servlet class, it has
java.lang.Object type and scope page
11.16 scopes
1. request - an object with request scope is bound to the HttpServletRequest object; the
object can be accessed by invoking the getAttribute() method on the implicit
116
11 - JSP
request object; the generated servlet binds the object to HttpServletRequest object
using the setAttribute(String key, Object value) method
2. session - an object with session scope is bound to the HttpSession object; the object
can be accessed by invoking the getValue() method on the implicit session object; the
generated servlet binds the object to HttpSession object using the
setAttribute(String key, Object value) method
3. application - an object with application scope is bound to the ServletContext object;
the object can be accessed by invoking the getAttribute() method on the implicit
application object; the generated servlet binds the object to the ServletContext
object using the setAttribute(String key, Object value) method
4. page - an object with page scope is bound to the PageContext object; the object can be
accessed by invoking the getAttribute() method on the implicit pageContext object;
the generated servlet binds the object to PageContext object using the
setAttribute(String key, Object value) method
<% enrollBean.init();
if (enrollBean.invalidAcct())
{ %>
<jsp:forward page="retry.jsp">
<jsp:param name="resolution" value="invalidAcct"/>
</jsp:forward>
<% }
else if (enrollBean.registeredAcct())
{ %>
<jsp:forward page="response.jsp">
<jsp:param name="resolution" value="registeredAcct"/>
</jsp:forward>
<% }
else if (enrollBean.userExists())
{ %>
<jsp:forward page="retry.jsp">
<jsp:param name="resolution" value="userExists"/>
</jsp:forward>
117
11 - JSP
<% }
else
{
enrollBean.register(); %>
<jsp:forward page="response.jsp">
<jsp:param name="resolution" value="userEnrolled"/>
</jsp:forward>
<% }
%>
// Simple bean
// No-arg constructor
public SimpleBean() {
}
118
11 - JSP
this.string = value;
}
119
11 - JSP
120
11 - JSP
// Simple sub-bean
public class SimpleSubBean implements java.io.Serializable {
private String string;
private float number;
// No-arg constructor
public SimpleSubBean() {
}
121
11 - JSP
SimpleForm.html:
<HTML>
<HEAD><TITLE>Simple form</TITLE></HEAD>
<BODY>
<H3>Simple Example</H3>
<FORM METHOD="POST">
<P> String <BR>
<INPUT TYPE="TEXT" NAME="string" SIZE="20">
122
11 - JSP
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>
123
11 - JSP
"optional"
}
},
{
"[PROCESSING_ORDER]",
new String[] {
"string",
"number",
"integer",
"flag",
"colors",
"list",
"optional",
"subBean"
}
},
{ "[FORM_NAME]", "SimpleForm.html" },
{ "[PROC_NAME]", "SimpleProc.jsp" }
};
124
11 - JSP
= HandlerUtils.getBeanResources(simpleBean.getClass());
125
11 - JSP
<%!
public static String toString(String list[]) {
if (list == null || list.length == 0)
return "";
if (list.length == 1 && list[0] != null)
return list[0];
StringBuffer strbuf = new StringBuffer();
strbuf.append("{ ");
for (int i = 0; i < list.length; i++)
126
11 - JSP
if (list[i] != null) {
strbuf.append(list[i]);
strbuf.append(" ");
}
strbuf.append("}");
return strbuf.toString();
}
127
11 - JSP
<BODY>
<H3>Equivalent of Simple Example</H3>
<FORM METHOD=POST>
128
11 - JSP
break;
}
%>
<INPUT TYPE="CHECKBOX" NAME="colors" VALUE="<%= colorValues[i]
%>"
<%= checked ? "CHECKED" : "" %>> <%= colorLabels[i] %>
<%
}
%>
129
11 - JSP
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>
<%!
String getErrorMessage(java.util.Hashtable errorTable, String
property) {
String message = (String) errorTable.get(property);
if (message == null)
message = "";
return message;
}
%>
ComplexHndl.jsp:
<%@ page language="java" %>
<jsp:useBean id="simpleBean" scope="request"
class="com.devsphere.examples.mapping.simple.SimpleBean"/>
<jsp:useBean id="simpleSubBean" scope="page"
class="com.devsphere.examples.mapping.simple.SimpleSubBean"/>
<jsp:useBean id="errorTable" scope="request"
class="java.util.Hashtable"/>
<%
simpleBean.setSubBean(simpleSubBean);
%>
<jsp:setProperty name="simpleBean" property="string"/>
<%
if (simpleBean.getString() == null
|| simpleBean.getString().length() == 0) {
simpleBean.setString("abc");
130
11 - JSP
try {
String numberValue = request.getParameter("number");
if (numberValue != null && numberValue.length() != 0)
simpleBean.setNumber(new
Float(numberValue).floatValue());
else {
simpleBean.setNumber(0.123f);
setErrorMessage(errorTable, "number", "Must be
filled");
}
} catch (NumberFormatException e) {
simpleBean.setNumber(0.123f);
setErrorMessage(errorTable, "number", "Must be a number");
}
%>
<jsp:setProperty name="simpleBean" property="integer"/>
<%
if (simpleBean.getInteger() == 0) {
setErrorMessage(errorTable, "integer", "An option must be
selected");
}
%>
<jsp:setProperty name="simpleBean" property="colors"/>
<%
if (simpleBean.getColors() == null
|| simpleBean.getColors().length == 0) {
131
11 - JSP
setErrorMessage(errorTable, "colors",
"One or more colors must be selected");
}
%>
<jsp:setProperty name="simpleBean" property="list"/>
<%
if (simpleBean.getList() == null
|| simpleBean.getList().length == 0) {
simpleBean.setList(new int[] { 2, 3 });
setErrorMessage(errorTable, "list",
"One or more items must be selected");
}
%>
<jsp:setProperty name="simpleBean" property="optional"/>
<%
if (simpleBean.getOptional() == null)
simpleBean.setOptional("");
%>
<jsp:setProperty name="simpleSubBean" property="string"
param="subBean.string"/>
<%
if (simpleSubBean.getString() == null
|| simpleSubBean.getString().length() == 0) {
simpleSubBean.setString("");
setErrorMessage(errorTable, "subBean.string", "Must be
filled");
}
try {
String numberValue =
request.getParameter("subBean.number");
if (numberValue != null && numberValue.length() != 0)
simpleSubBean.setNumber(new
Float(numberValue).floatValue());
else {
setErrorMessage(errorTable, "subBean.number", "Must be
132
11 - JSP
filled");
}
} catch (NumberFormatException e) {
setErrorMessage(errorTable, "subBean.number", "Must be a
number");
}
} else {
simpleBean.setString("abc");
simpleBean.setNumber(0.123f);
simpleBean.setFlag(true);
simpleBean.setList(new int[] { 2, 3 });
simpleBean.setOptional("");
simpleSubBean.setString("");
}
<%!
void setErrorMessage(java.util.Hashtable errorTable,
String property, String message) {
message = "<FONT COLOR=\"#FF0000\">" + message +
"</FONT><BR>";
errorTable.put(property, message);
}
%>
SimpleHndl.code=com.devsphere.helpers.mapping.BeanDispatcher
SimpleHndl.initparams=\
BEAN_NAME=com.devsphere.examples.mapping.simple.SimpleBean,\
133
11 - JSP
BEAN_ID=simpleBean,\
BASE_PATH=/simple
or
<servlet>
<servlet-name>SimpleHndl</servlet-name>
<servlet-
class>com.devsphere.helpers.mapping.BeanDispatcher</servlet-class>
<init-param>
<param-name>BEAN_NAME</param-name>
<param-
value>com.devsphere.examples.mapping.simple.SimpleBean</param-value>
</init-param>
<init-param>
<param-name>BEAN_ID</param-name>
<param-value>simpleBean</param-value>
</init-param>
<init-param>
<param-name>BASE_PATH</param-name>
<param-value>/simple</param-value>
</init-param>
</servlet>
GenericHandler and BeanDispatcher were presented in a previous chapter.
The servlet engine associates a servlet to a class in the servlets.properties (or web.xml) file:
ServletName.code=com.company.ClassName
There is nothing that can stop you associating many servlets with the same class. You may use
the same class to declare one servlet for each bean component. A standard servlet engine
running on a single JVM will instantiate the servlet class once for each servlet declaration. All
requests to one of the declared servlets will be serviced by the same instance of the servlet class.
The previous section showed how to declare a BeanDispatcher servlet. If you have another
bean-form pair, you could add a few other lines to servlets.properties:
AnotherHndl.code=com.devsphere.helpers.mapping.BeanDispatcher
AnotherHndl.initparams=\
BEAN_NAME=com.devsphere.examples.mapping.another.AnotherBean,\
BEAN_ID=anotherBean,\
BASE_PATH=/another
The two servlets that share the same code could be invoked with something like this
http://www.host.com/AppName/servlet/SimpleHndl
http://www.host.com/AppName/servlet/AnotherHndl
134
11 - JSP
135
12 - javaserver faces
12 - JAVASERVER FACES
12.1 what are javaServer faces?
JavaServer Faces technology is a server-side user interface component framework for Java
based web applications. This technology includes:
2. A JavaServer Pages (JSP) custom tag library for expressing a JavaServer Faces
interface within a JSP page.
JSF is a request-driven MVC web framework based on component driven UI design model,
using XML files called view templates or Facelets views. Requests are processed by the
FacesServlet, which loads the appropriate view template, builds a component tree, processes
events, and renders the response (typically HTML) to the client.
The latest version (as of november 2010) of JavaServer Faces technology is version 2.0,
released through the Java Community Process under Java Specification Request (JSR) 314.
Version 2.0 is part of the Java Enterprise Edition 6 platform.
Version 2.0 supersedes version 1.2 and brings in mandatory support for Facelets as the view
technology for JSF pages, built in Ajax support and built in support for bookmarking & page-load
actions.
There are five JSF specific tag libraries defined in this specification, namely
• JSF HTML Tag Library
• JSF Core Tag Library
• JSTL Core Tag Library
• JSTL Functions Tag Library
• JSF Facelets Tag Library
136
12 - javaserver faces
12.3 facelets
Facelet is a view technology for Java Server Faces (JSF) that allows building composite views
more quickly and easily than with JSP which is the default view technology for JSF. JSP pages
are compiled into servlets but it’s not the case with Facelets because Facelet pages are XML
compliant and its framework uses a fast SAXbased compiler to build views. Facelets can make
changes to pages immediately so developing JSF applications with Facelets is simply faster.
This tag library contains JavaServer Faces component tags for all UIComponent + HTML
RenderKit Renderer combinations defined in the JavaServer Faces specification. As of version
1.2 of the JFS specification, there are 25 HTML JSF tags.
137
12 - javaserver faces
• outputLabel
• outputLink
• outputText
• panelGrid
• pnelGroup
• selectBooleanCheckbox
• selectManyCheckbox
• selectManyListbox
• selectManyMenu
• selectOneListbox
• selectOneMenu
• selectOneRadio
In the next paragraphs, we'll have a closer look at some of these tags.
12.4.2 h:dataTable
The dataTable tag renders an HTML 4.01 compliant table element that can be associated with
a backing bean to obtain its data as well as for event handling purposes.
The table can be customized extensively using cascading stylesheet (CSS) classes and
definitions to enhance the appearance of the table's headers, footers, columns and rows.
Common formatting techniques, such as alternating row colors, can be accomplished quite easily
with this tag.
The dataTable tag typically contains one or more column tags that define the columns of the
table. A column component is rendered as a single "td" element. For more information about
columns, see the column tag documentation.
A dataTable tag can also contain header and footer facets. These are rendered as a single "th"
element in a row at the top of the table and as a single "td" element in a row at the bottom of the
table, respectively.
Example:
<h:dataTable id="table1" value="#{shoppingCartBean.items}" var="item">
<f:facet name="header">
<h:outputText value="Your Shopping Cart" />
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Item Description" />
</f:facet>
<h:outputText value="#{item.description}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Price" />
138
12 - javaserver faces
</f:facet>
<h:outputText value="#{item.price}" />
</h:column>
<f:facet name="footer">
<h:outputText value="Total: #{shoppingCartBean.total}" />
</f:facet>
</h:dataTable>
HTML Output
<table id="table1">
<thead>
<tr><th scope="colgroup" colspan="2">Your Shopping Cart</th></tr>
<tr><th>Item Description</th><th>Price</th></tr>
</thead>
<tbody>
<tr><td>Delicious Apple</td><td>$5.00</td></tr>
<tr><td>Juicy Orange</td><td>$5.00</td></tr>
<tr><td>Tasty Melon</td><td>$5.00</td></tr>
</tbody>
<tfoot>
<tr><td colspan="2">Total: $15.00</td></tr>
</tfoot>
</table>
12.4.3 h:form
The form tag renders an HTML form element. JSF forms use the "post-back" technique to
submit form data back to the page that contains the form. The use of the POST method is also
required and it is not possible to use the GET method for forms generated by this tag.
If your application requires the use of the GET method for form submission, your options
include using plain HTML forms, binding request parameters to backing bean properties, and
using the outputLink tag to generate dynamic hyperlinks.
Example:
<h:form id="form1"></h:form>
HTML Output
<form id="form1" name="form1" method="post" action="/demo/form.jsp"
enctype="application/x-www-form-urlencoded"></form>
12.4.4 h:commandButton
The commandButton tag renders an HTML submit button that can be associated with a
backing bean or ActionListener class for event handling purposes. The display value of the button
can also be obtained from a message bundle to support internationalization (I18N).
Example:
<h:commandButton id="button1" value="#{bundle.checkoutLabel}"
action="#{shoppingCartBean.checkout}" />
139
12 - javaserver faces
HTML Output
<input id="form:button1" name="form:button1" type="submit"
value="Check Out" onclick="someEvent();" />
12.4.5 h:inputText
The inputText tag renders an HTML input element of the type "text".
Example:
<h:inputText id="username" value="#{userBean.user.username}" />
HTML Output
<input id="form:username" name="form:username" type="text" />
HTML Output
<input type="text" id="form:username" name="form:username" value=""/>
<span style="color:red">"username": Value is required.</span>
The core JavaServer Faces tags define custom actions that are independent of any particular
RenderKit.
140
12 - javaserver faces
• loadBundle
• param
• selectItem
• selectItems
• subview
• validateDoubleRange
• validateLength
• validateLongRange
• validator
• valueChangeListener
• verbatim
• view
Some of these tags will be detailed in the next paragraphs.
12.5.2 f:facet
A facet represents a named section within a container component
The JSF facets specify the requirements and constraints that apply to a JSF project.
The Facet tag registers a named facet on the component associated with the enclosing tag. For
example, you can create a header and a footer facet for a dataTable component.
Example:
<h:dataTable id="reportTable" value="#{reportBean.dailyReport}"
var="item">
<h:column>
<f:facet name="header">
<h:outputText value="Daily Report" />
</f:facet>
<h:outputText value="#{item}" />
</h:column>
</h:dataTable>
HTML Output
<table id="reportTable">
<thead>
<tr><th>Daily Report</th></tr>
</thead>
<tbody>
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
</tbody>
</table>
141
12 - javaserver faces
12.5.3 f:validator
The Validator tag registers a named Validator instance on the component associated with the
enclosing tag. The JavaServer Faces framework includes three standard validators (see the
validateDoubleRange, validateLength, and validateLongRange tags) but the Validator interface
can be implemented by classes that provide custom validation for your application. This tag
accepts one value matching the validator ID you assigned to your validator class in your Faces
configuration file. The body content of this tag must be empty.
Example:
<h:inputText id="emailAddress"
value="#{customerBean.customer.emailAddress}">
<f:validator validatorId="emailAddressValidator" />
</h:inputText>
<h:message for="emailAddress" />
HTML Output
<input id="form:emailAddress" name="form:emailAddress" type="text"
value="fake@email"/>
Invalid email address.
12.5.4 f:valueChangeListener
The ValueChangeListener tag registers a ValueChangeListener instance on the component
associated with the enclosing tag. The ValueChangeListener interface should be implemented by
classes that you want to register with components that publish value change events.
Any component that receives user input, such as one of the HTML select or text input
components, can publish value change events. A component fires a value change event when its
input changes, but only if the new input is validated successfully.
You can register several ValueChangeListeners with a component and they will be invoked in
the order that they are registered. An alternative to this tag is to use a method-binding expression
pointing at a value change listener method of a backing bean on the component tag itself.
Notice in the example below the use of the JavaScript onchange() event to trigger form
submission when the list selection changes. Without this JavaScript event, the user must
manually submit the form to invoke the ValueChangeListener.
Example:
<h:selectOneMenu id="optionMenu" value="#{optionBean.selectedOption}"
onchange="submit()">
<f:selectItems value="#{optionBean.optionList}" />
<f:valueChangeListener
type="com.mycompany.MyValueChangeListenerImpl" />
</h:selectOneMenu>
HTML Output
<select name="form:optionMenu" size="1" onchange="submit()">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
142
12 - javaserver faces
12.5.5 f:view
The View tag is the container for all JavaServer Faces component tags used on a page. You
can wrap the root element of the structured markup language used in your document with this tag
to ensure that all child tags are part of the same view.
This tag is useful for internationalization (I18N) purposes. It provides you with several options
for presenting your user with localized views of your application. By default the JSF framework
will attempt to select the best view for your user based on the Accept-Language header sent to
the server from the user's browser as part of the HTTP request for your page.
If the locale requested by the user is not supported by your application, the JSF framework will
use the default locale specified in your Faces configuration file. If you have not specified a default
locale, JSF will use the default locale for the Java Virtual Machine serving your application.
If your application supports the locale requested by the user, JSF will set that locale for the view
and will display the messages for that locale defined in the locale's message bundle.
You can also specify the locale for which the view is to be rendered by explicitly setting the
locale attribute of the view tag. This allows you to design localized versions of each page,
including images and styles, for each locale you wish to support.
Another option is to obtain the locale dynamically through user interaction. This information
could later be stored in a cookie and/or a database to identify which locale is preferred by your
user. The locale attribute accepts a value-binding expression that could resolve to the desired
locale.
Example:
welcome_en.jsp (English)
<f:view locale="en">
<f:loadBundle basename="com.mycompany.MessageBundle" var="bundle" />
<h:outputText value="#{bundle.welcomeMessage}" />
</f:view>
welcome_fr.jsp (French)
<f:view locale="fr">
<f:loadBundle basename="com.mycompany.MessageBundle" var="bundle" />
<h:outputText value="#{bundle.welcomeMessage}" />
</f:view>
HTML Output
welcome_en.jsp (English)
Welcome to our site!
welcome_fr.jsp (French)
Bienvenue à notre site!
Here is a typical directory structure for a JSP application. The directory myJSFapp is the base
directory of the application.
myJSFapp
143
12 - javaserver faces
/ant
build.xml
/JavaSource
/WebContent
/WEB-INF
/classes
/lib
jsf-impl.jar
jsf-api.jar
faces-config.xml
web.xml
/pages
144
12 - javaserver faces
12.7.2 navigation
Navigation is the heart of JavaServer Faces. The navigation rule for this application is
described in the faces-config.xml file. This file already exists in the skeleton directory structure.
You just need to create its contents.
In our application, we just want to go from inputname.jsp to greeting.jsp. As a diagram, it
would look something like 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>
145
12 - javaserver faces
This is, of course, a very simple navigation rule. You can easily create more complex ones. To
read more about navigation rules, visit the JSP Navigation Example forum item.
12.7.3.1 PersonBean.java
Put this code in the file:
package myJFSapp;
<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>myJFSapp.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
12.7.3.3 faces-config.xml
Your final faces-config.xml file should look like this:
146
12 - javaserver faces
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/pages/greeting.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>myJFSapp.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
12.7.4.1 messages.properties
Put this text in the properties file:
inputname_header=JSF KickStart
prompt=Tell us your name:
greeting_text=Welcome to JSF
button_text=Say Hello
sign=!
We now have everything to create the JSP pages.
12.7.5.1 inputname.jsp
Put the following coding into this file:
147
12 - javaserver faces
<html>
<head>
<title>enter your name page</title>
</head>
<body>
<f:view>
<h1>
<h:outputText value="#{msg.inputname_header}"/>
</h1>
<h:form id="helloForm">
<h:outputText value="#{msg.prompt}"/>
<h:inputText value="#{personBean.personName}" required=”true”>
<f:validateLength minimum="2" maximum="10"/>
</h:inputText>
<h:commandButton action="greeting" value="#{msg.button_text}" />
</h:form>
</f:view>
</body>
</html>
Now, let's explain the important sections in this file after displaying the code for each section
starting from the top.
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>
148
12 - javaserver faces
12.7.5.2 greeting.jsp
Put this coding inside the second JSP file:
<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 <h3>...</h3> tags. The first line will take a
message from the resource bundle and print it on the page. The second line will access a Java
bean, specifically the bean attribute personName, and also print its contents on the page.
Once this page is displayed in a Web browser, you will see something like this:
Welcome to JSF, name!
149
12 - javaserver faces
<html>
<body>
<jsp:forward page="/pages/inputname.jsf" />
</body>
</html>
If you look at the path for the forward, you'll notice the file suffix is .jsf and not .jsp. This is used
here, because in the web.xml file for the application *.jsf is the URL pattern used to signal that
the forwarded page should be handled by the JavaServer Faces servlet within Tomcat.
We are almost done with this example.
12.7.7 Compiling
An Ant build script is provided for you. To build the application run the build.xml script from the
ant folder:
ant build
12.7.8 Deploying
Before you can run this application within the servlet container, we need to deploy it. We will
use null (link) deployment to deploy the application in-place. To do this we need to register a
context in Tomcat's {TomcatHome}\conf\server.xml file.
To do this, insert this code:
<Context debug="0"
docBase="Path_to_WebContent"
path="/myJFSapp" reloadable="true"/>
near the end of the server.xml file within the Host element just before the closing </Host> tag.
Of course, Path_to_WebContent needs to be replaced with the exact path on your system to the
WebContent folder inside the myJFSapp folder (for example,
C:/examples/myJFSapp/WebContent).
12.7.9 Running
Next, start the Tomcat server (probably using the script startup.bat in Tomcat's bin directory).
When Tomcat is done loading, launch a web browser and enter:
http://localhost:8080/myJFSapp. (Port 8080 is the default port in Tomcat. Your setup, though,
might possibly be different).
12.8.1 Overview
This is a tutorial in which we create a simple JSF application to demonstrate FacesIDE's
functionality. This is a "login" application, which asks an user for an ID and password, verifies the
information, and forwards the user to a success or error page.
150
12 - javaserver faces
The application will use a few JSP pages with JSF elements, and a session-scoped managed
bean to coordinate their interactions. Along the way we'll use the following FacesIDE functionality:
• add JSF support to a project
• use the New JSF/JSP file wizard
• use the JSP Editor (see HTML/JSP/XML Editor)
• use the faces-config.xml Editor (see faces-config.xml Editor)
As a prerequisite for the tutorial, make sure FacesIDE and required plugins have been installed;
see Installing & Uninstalling. We don't assume that a J2EE server-specific plugin, such as the
Sysdeo Tomcat plugin has been installed.
151
12 - javaserver faces
| |
| +-- classes (not shown in Java perspective)
| |
| +-- lib
|
+-- pages
// LoginManager.java
package login;
if ( _uid.equalsIgnoreCase("foo") &&
_pwd.equalsIgnoreCase("bar") )
action = "loginPass";
else
action = "loginFail";
return action;
}
}
152
12 - javaserver faces
session.
e. from the menubar select File/Save, then close the editor
153
12 - javaserver faces
</html>
4. Create login.jsp:
a. in Package Explorer select webroot/pages; from its context menu select
New/Other...; the New wizard appears.
b. select Amateras/JSF/Faces JSP File; click Next
c. for File name enter login.jsp; make sure that Container is set to /jsf-
login/webroot/pages, and that Use MyFaces Tomahawk components and
Use MyFaces SandBox components are unchecked, and choose default for
Template; click Finish; the FacesIDE JSP Editor opens, with the following
template code.
We will now edit this page to contain our input widgets, etc.
d. place the cursor between the <title></title> elements; enter jsf-login
e. Open the JSF palette, and dock it along the right. (See Show View Dialog)
f. create a few blank lines between the <h:form> elements; place your cursor in
one of these lines, expand the JSF HTML panel in the palette, and click on the
icon for <h:inputText>; this inserts the corresponding JSF element at the
cursor location.
Note: the JSP editor is aware of referenced tag libraries, and uses them for code
completion as well. Thus if you were to type <h: and hit CTRL + Spacebar, you
would get a popup window of JSF HTML elements.
g. now we want to add attributes to this element, and the JSP Editor can help with
code- completion. To see this in action, place the cursor inside the <h:inputText>
element, and hit CTRL + Spacebar; a code-completion window pops up, as
shown below.
154
12 - javaserver faces
h. in the code-completion window scroll down to value, and hit Enter; this inserts
value="" at the cursor. We will now bind this to the userID property of
LoginManager; FacesIDE can provide code completion here as well.
i. place the cursor between the quotes in value="", enter #{mgr., and hit CTRL +
Spacebar; a code-completion window pops up, with bean properties available in
mgr. This is shown below:
155
12 - javaserver faces
<head>
<title>jsf-title</title>
</head>
<body>
<f:view>
<h:form>
UserID: <h:inputText value="#{mgr.userID}"/>
<br/>Password: <h:inputText
value="#{mgr.password}"/>
<br/><h:commandButton value="Login"
action="#{mgr.loginAction}"/>
</h:form>
</f:view>
</body>
</html>
Note that the icon has a small triangle overlay--this indicates that something is wrong,
156
12 - javaserver faces
157
12 - javaserver faces
7. in the Properties view (or direct editing on the diagram), change the value of from-
outcome to loginPass. Recall that this is the success-value returned by
LoginManager's loginAction method. You can also change values by direct-editing
(select once and re-click) in the diagram
8. Similarly add a forward-action from login.jsp to error.jsp, and set its from-
outcome to loginFail
We're done with setting up navigation rules. We'll set some properties in web.xml, and we'll
then be ready to deploy the application.
158
12 - javaserver faces
The classes and interfaces of the JavaServer Faces API are grouped in several packages,
namely:
• javax.faces
• javax.faces.application
• javax.faces.component
• javax.faces.component.html
• javax.faces.context
• javax.faces.convert
• javax.faces.el
• javax.faces.event
• javax.faces.lifecycle
• javax.faces.model
• javax.faces.render
• javax.faces.validator
• javax.faces.webapp
FactoryFinder implements the standard discovery algorithm for all factory objects specified in
the JavaServer Faces APIs. For a given factory class name, a corresponding implementation
class is searched for based on the following algorithm. Items are listed in order of decreasing
search precedence:
• If the JavaServer Faces configuration file bundled into the WEB-INF directory of the
webapp contains a factory entry of the given factory class name, that factory is used.
• If the JavaServer Faces configuration files named by the javax.faces.CONFIG_FILES
159
12 - javaserver faces
ServletContext init parameter contain any factory entries of the given factory class
name, those factories are used, with the last one taking precedence.
• If there are any JavaServer Faces configuration files bundled into the META-INF directory
of any jars on the ServletContext's resource paths, the factory entries of the given
factory class name in those files are used, with the last one taking precedence.
• If a META-INF/services/{factory-class-name} resource is visible to the web
application class loader for the calling application (typically as a result of being present in
the manifest of a JAR file), its first line is read and assumed to be the name of the factory
implementation class to use.
• If none of the above steps yield a match, the JavaServer Faces implementation specific
class is used.
160
12 - javaserver faces
Defines both a set of interfaces and classes. The interfaces defined in this package are:
• ActionSource - an interface that may be implemented by any concrete UIComponent
that wishes to be a source of ActionEvents, including the ability to invoke application
actions via the default ActionListener mechanism.
• ActionSource2 - extends ActionSource and provides a JavaBeans property analogous
to the "action" property on ActionSource. The difference is the type of this property is
a MethodExpression rather than a MethodBinding. This allows the ActionSource
concept to leverage the new Unified EL API.
• ContextCallBack - A simple callback interace that enables taking action on a specific
UIComponent (either facet or child) in the view while preserving any contextual state for
that component instance in the view.
• EditableValueHolder - an extension of ValueHolder that describes additional features
supported by editable components, including ValueChangeEvents and Validators.
• NamingContainer - an interface that must be implemented by any UIComponent that
wants to be a naming container.
• StateHolder - interface implemented by classes that need to save their state between
requests.
• ValueHolder - an interface that may be implemented by any concrete UIComponent that
wishes to support a local value, as well as access data in the model tier via a value
binding expression, and support conversion between String and the model tier data's
native data type.
The classes in this package are all UI related. Here they are:
• UIColumn - a UIComponent that represents a single column of data within a parent
UIData component.
• UICommand - a UIComponent that represents a user interface component which, when
activated by the user, triggers an application specific "command" or "action". Such a
component is typically rendered as a push button, a menu item, or a hyperlink.
• UIComponent - the base class for all user interface components in JavaServer Faces.
The set of UIComponent instances associated with a particular request and response are
organized into a component tree under a UIViewRoot that represents the entire content
of the request or response.
• UIComponentBase - a convenience base class that implements the default concrete
behavior of all methods defined by UIComponent.
161
12 - javaserver faces
162
12 - javaserver faces
163
12 - javaserver faces
property.
• HtmlSelectManyCheckbox - represents a multiple-selection component that is rendered
as a set of HTML input elements of type checkbox.
• HtmlSelectManyListbox - represents a multiple-selection component that is rendered as
an HTML select element, showing either all available options or the specified number of
options.
• HtmlSelectManyMenu - represents a multiple-selection component that is rendered as an
HTML select element, showing a single available option at a time.
• HtmlSelectOneListbox - represents a single-selection component that is rendered as an
HTML select element, showing either all available options or the specified number of
options.
• HtmlSelectOneMenu - represents a single-selection component that is rendered as an
HTML select element, showing a single available option at a time.
• HtmlSelectOneRadio - represents a single-selection component that is rendered as a set
of HTML input elements of typeradio.
• ExternalContext - allows the Faces API to be unaware of the nature of its containing
application environment. In particular, this class allows JavaServer Faces based
applications to run in either a Servlet or a Portlet environment.
• FacesContext - contains all of the per-request state information related to the processing
of a single JavaServer Faces request, and the rendering of the corresponding response. It
is passed to, and potentially modified by, each phase of the request processing lifecycle.
• FacesContextFactory - a factory object that creates (if needed) and returns new
FacesContext instances, initialized for the processing of the specified request and
response objects.
• ResponseStream - an interface describing an adapter to an underlying output
mechanism for binary output.
• ResponseWriter - an abstract class describing an adapter to an underlying output
mechanism for character-based output.
• ResponseWriterWrapper - provides a simple implementation of ResponseWriter that
can be subclassed by developers wishing to provide specialized behavior to an existing
ResponseWriter instance. The default implementation of all methods is to call through
to the wrapped ResponseWriter.
164
12 - javaserver faces
Contains classes and interfaces for evaluating and processing reference expressions.
Classes:
165
12 - javaserver faces
Exceptions:
Contains interfaces describing events and event listeners, and event implementation classes.
Interfaces:
Classes:
166
12 - javaserver faces
Contains the interface DataModelListener and several classes providing standard model data
beans for JavaServer Faces. Classes:
• Renderer - converts the internal representation of UIComponents into the output stream
167
12 - javaserver faces
(or writer) associated with the response we are creating for a particular request. Each
Renderer knows how to render one or more UIComponent types (or classes), and
advertises a set of render-dependent attributes that it recognizes for each supported
UIComponent.
• RenderKit - represents a collection of Renderer instances that, together, know how to
render JavaServer Faces UIComponent instances for a specific client. Typically,
RenderKits are specialized for some combination of client device type, markup
language, and/or user Locale. A RenderKit also acts as a Factory for associated
Renderer instances, which perform the actual rendering process for each component.
• RenderKitFactory - a factory object that registers and returns RenderKit instances.
Implementations of JavaServer Faces must provide at least a default implementation of
RenderKit.
• ResponseStateManager - the helper class to StateManager that knows the specific
rendering technology being used to generate the response.
Interface defining the validator model, and concrete validator implementation classes.
A Validator implementation is a class that can perform validation (correctness checks) on a
EditableValueHolder.
Implementation classes:
• DoubleRangeVlidator - a Validator that checks the value of the corresponding
component against specified minimum and maximum values
• LengthValidator - a Validator that checks the number of characters in the String
representation of the value of the associated component.
• LongRangeValidator - a Validator that checks the value of the corresponding
component against specified minimum and maximum values.
The package contains an exception, as well.
A ValidatorException is an exception thrown by the validate() method of a Validator to
indicate that validation failed.
Contains classes required for integration of JavaServer Faces into web applications, including a
standard servlet, base classes for JSP custom component tags, and concrete tag implementations
for core tags.
• AttributeTag - Tag implementation that adds an attribute with a specified name and
String value to the component whose tag it is nested inside, if the component does not
already contain an attribute with the same name.
• ConverterTag - a base class for all JSP custom actions that create and register a
Converter instance on the ValueHolder associated with our most immediate
168
12 - javaserver faces
Regardless of whether you are using JSF with JSP pages, servlets, or some other web
technology, each request/response flow that involves JSF follows a certain life cycle. Several
kinds of request/response cycles can occur in a JSF-enabled application. You can have a request
that comes from a previously rendered JSF page (a JSF request) and a request that comes from
a non-JSF page (a non-JSF request). Likewise, you can have a JSF response or a non-JSF
response. We are concerned with these three request/response pairs:
• Non-JSF request generates JSF response
• JSF request generates JSF response
• JSF request generates non-JSF response
Of course, you can also have a non-JSF request that generates a non-JSF response. Because
this does not involve JSF in any way, the JSF life cycle does not apply.
JSP pages have a relatively simple life cycle. A JSP page source is compiled into a page
implementation class. When a web server receives a request, that request is passed to the
container, which passes the request to the page class. The page class processes the request and
then writes the response back to the client. When other pages are included or the request is
forwarded, or when an exception occurs, the process includes a few more components or pages,
but basically, a small set of classes processes a request and sends back a response.
When using JSF, the life cycle is more complicated. This is because the core of JSF is the
MVC pattern, which has several implications. User actions in JSF-generated views take place in a
client that does not have a permanent connection to the server. The delivery of user actions or
page events is delayed until a new connection is established. The JSF life cycle must handle this
delay between event and event processing. Also, the JSF life cycle must ensure that the view is
correct before rendering the view. To ensure that the business state is never invalid, the JSF
system includes a phase for validating inputs and another for updating the model only after all
inputs pass validation.
In MVC, the presentation of data (the view) is separate from its representation in the system
(the model). When the model is updated, the controller sends a message to the view, telling the
view to update its presentation. When the user takes some action with the presentation, the
controller sends a message to the model, telling the model to update its data. In JSF, the model is
composed of business objects that are usually implemented as JavaBeans, the controller is the
169
12 - javaserver faces
170
12 - javaserver faces
In the above figure, you can see a number of optional paths through the life cycle. For example,
if errors occur during any of the phases, the flow of execution transfers immediately to the Render
Response phase, skipping any remaining phases. One way this might occur is if input data is
incorrect or invalid. If data fails validation in either the Apply Request Values or Process
Validations phase, information about the error is saved and processing proceeds directly to the
Render Response phase. Also, if at any point in the life cycle the request processing is complete
and a non-JSF response is to be sent to the client, the flow of execution can exit the life cycle
without completing further phases.
171
13 - JNDI
13 - JNDI
13.1 what is JNDI?
JNDI is an API specified in Java technology that provides naming and directory functionality to
applications written in the Java programming language. It is designed especially for the Java
platform using Java's object model. Using JNDI, applications based on Java technology can store
and retrieve named Java objects of any type. In addition, JNDI provides methods for performing
standard directory operations, such as associating attributes with objects and searching for objects
using their attributes.
JNDI is also defined independent of any specific naming or directory service implementation. It
enables applications to access different, possibly multiple, naming and directory services using a
common API. Different naming and directory service providers can be plugged in seamlessly
behind this common API. This enables Java technology-based applications to take advantage of
information in a variety of existing naming and directory services, such as LDAP, NDS, DNS, and
NIS(YP), as well as enabling the applications to coexist with legacy software and systems.
A fundamental facility in any computing system is the naming service--the means by which
names are associated with objects and and objects are found based on their names. When using
almost any computer program or system, you are always naming one object or another. For
example, when you use an electronic mail system, you must provide the name of the recipient to
whom you want to send mail. To access a file in the computer, you must supply its name. A
naming service allows you to look up an object given its name.
A naming service's primary function is to map people-friendly names to objects, such as
addresses, identifiers, or objects typically used by computer programs. For example, the Internet
Domain Name System (DNS) maps machine names (such as www.sun.com) to IP addresses
(such as 192.9.48.5). A file system maps a filename (for example, c:\bin\autoexec.bat)
to a file handle that a program can use to access the contents of the file. These two examples
also illustrate the wide range of scale at which naming services exist--from naming an object on
the Internet to naming a file on the local file system.
13.2.1 names
To look up an object in a naming system, you supply it the name of the object. The naming
system determines the syntax that the name must follow. This syntax is sometimes called the
naming system's naming convention.
For example, the UNIXTM file system's naming convention is that a file is named from its path
relative to the root of the file system, with each component in the path separated from left to right
using the forward slash character ("/"). The UNIX pathname, /usr/hello, for example, names a
file hello in the file directory usr, which is located in the root of the file system.
The DNS naming convention calls for components in the DNS name to be ordered from right to
left and delimited by the dot character ("."). Thus the DNS name sales.Wiz.COM names a DNS
entry with the name sales, relative to the DNS entry Wiz.COM. The DNS entry Wiz.COM, in turn,
names an entry with the name Wiz in the COM entry.
172
13 - JNDI
The Lightweight Directory Access Protocol (LDAP) naming convention orders components from
right to left, delimited by the comma character (","). Thus the LDAP name cn=Rosanna Lee,
o=Sun, c=US names an LDAP entry cn=Rosanna Lee, relative to the entry o=Sun, which in
turn, is relative to c=us. The LDAP has the further rule that each component of the name must be
a name/value pair with the name and value separated by an equals character ("=").
13.2.2 bindings
The association of a name with an object is called a binding. For example, a file name is bound
to a file.
The DNS contains bindings that map machine names to IP addresses. An LDAP name is bound
to an LDAP entry.
13.2.4 context
A context is a set of name-to-object bindings. Every context has an associated naming
convention. A context provides a lookup (resolution) operation that returns the object and may
provide operations such as those for binding names, unbinding names, and listing bound names.
A name in one context object can be bound to another context object (called a subcontext) that
has the same naming convention.
For example, a file directory, such as /usr, in the UNIX file system is a context. A file directory
named relative to another file directory is a subcontext (some UNIX users refer to this as a
subdirectory). That is, in a file directory /usr/bin, the directory bin is a subcontext of usr. In
another example, a DNS domain, such as COM, is a context. A DNS domain named relative to
another DNS domain is a subcontext. For example, in the DNS domain Sun.COM, the DNS
domain Sun is a subcontext of COM.
Finally, an LDAP entry, such as c=us, is a context. An LDAP entry named relative to another
LDAP entry is a subcontext. For example, in the an LDAP entry o=sun,c=us, the entry o=sun is
a subcontext of c=us.
173
13 - JNDI
If we imagine all the resources available for us as a collection of rooted trees, one context can
be viewed, in a first and raw approximation as a node in one of these trees. And it kind of makes
sense, 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
Many naming services are extended with a directory service. A directory service associates
names with objects and also allows such objects to have attributes. Thus, you not only can look
up an object by its name but also get the object's attributes or search for the object based on its
attributes.
An example is the telephone company's directory service. It maps a subscriber's name to his
address and phone number. A computer's directory service is very much like a telephone
company's directory service in that both can be used to store information such as telephone
numbers and addresses. The computer's directory service is much more powerful, however,
because it is available online and can be used to store a variety of information that can be utilized
by users, programs, and even the computer itself and other computers.
A directory object represents an object in a computing environment. A directory object can be
used, for example, to represent a printer, a person, a computer, or a network. A directory object
contains attributes that describe the object that it represents.
13.3.1 attributes
A directory object can have attributes. For example, a printer might be represented by a
directory object that has as attributes its speed, resolution, and color. A user might be represented
by a directory object that has as attributes the user's e-mail address, various telephone numbers,
postal mail address, and computer account information.
An attribute has an attribute identifier and a set of attribute values. An attribute identifier is a
token that identifies an attribute independent of its values. For example, two different computer
174
13 - JNDI
accounts might have a "mail" attribute; "mail" is the attribute identifier. An attribute value is
the contents of the attribute. The email address, for example, might have an attribute identifier of
"mail" and the attribute value of "[email protected]".
Directory service is a vital component of network computing. By using a directory service, you
can simplify applications and their administration by centralizing the storage of shared
information. As the use of the Java programming language to write practical applications in a
network environment increases, the ability to access directory services will become essential.
175
13 - JNDI
Applications can share the common infrastructure provided by the directory. This sharing
makes applications that are deployed across the system, and even the network, more coherent
and manageable. For example, printer configuration and mail routing information can be stored in
the directory so that it can be replicated and distributed for use by all printer-related and mail-
related applications and services.
The Java Naming and Directory Interface TM (JNDI) is an application programming interface
(API) that provides naming and directory functionality to applications written using the Java TM
programming language. It is defined to be independent of any specific directory service
implementation. Thus a variety of directories--new, emerging, and already deployed--can be
accessed in a common way.
13.5.1 architecture
The JNDI architecture consists of an API and a service provider interface (SPI). Java
applications use the JNDI API to access a variety of naming and directory services. The SPI
enables a variety of naming and directory services to be plugged in transparently, thereby
allowing the Java application using the JNDI API to access their services.
13.5.2 packaging
The JNDI is included in the Java 2 SDK, v1.3 and later releases. It is also available as a Java
Standard Extension for use with the JDK 1.1 and the Java 2 SDK, v1.2. It extends the v1.1 and
v1.2 platforms to provide naming and directory functionality.
To use the JNDI, you must have the JNDI classes and one or more service providers. The Java
2 SDK, v1.3 includes three service providers for the following naming/directory services:
• Lightweight Directory Access Protocol (LDAP)
• Common Object Request Broker Architecture (CORBA) Common Object Services (COS)
name service
• Java Remote Method Invocation (RMI) Registry
Other service providers can be downloaded from the JNDI Web site or obtained from other
vendors. When using the JNDI as a Standard Extension on the JDK 1.1 and Java 2 SDK, v1.2,
you must first download the JNDI classes and one or more service providers.
The JNDI is divided into five packages:
• javax.naming
• javax.naming.directory
• javax.naming.event
• javax.naming.ldap
176
13 - JNDI
• javax.naming.spi
The javax.naming package contains classes and interfaces for accessing naming services.
13.6.1 context
The javax.naming package defines a Context interface, which is the core interface for
looking up, binding/unbinding, renaming objects and creating and destroying subcontexts.
The most commonly used operation is lookup() . You supply lookup() the name of the
object you want to look up, and it returns the object bound to that name. For example, the
following code fragment looks up a printer and sends a document to the printer object to be
printed.
13.6.2 names
Every naming method in the Context interface has two overloads: one that accepts a Name
argument and one that accepts a java.lang.String name. Name is an interface that
represents a generic name--an ordered sequence of zero or more components. For the methods
in the Context interface, a Name argument that is an instance of CompositeName represents a
composite name , so you can name an object using a name that spans multiple namespaces. A
Name argument of any other type represents a compound name. (Names are covered in the
Beyond the Basics trail.) The overloads that accept Name are useful for applications that need to
manipulate names, that is, composing them, comparing components, and so on.
A java.lang.String name argument represents a composite name. The overloads that
accept java.lang.String names are likely to be more useful for simple applications, such as
those that simply read in a name and look up the corresponding object.
13.6.3 bindings
listBindings() returns an enumeration of name-to-object bindings. Each binding is
represented by an instance of the Binding class. A binding is a tuple containing the name of the
bound object, the name of the object's class, and the object itself.
list() is similar to listBindings(), except that it returns an enumeration of
NameClassPair. NameClassPair contains an object's name and the name of the object's
class. list() is useful for applications such as browsers that want to discover information about
the objects bound within a context but that don't need all of the actual objects. Although
listBindings() provides all of the same information, it is potentially a much more expensive
operation.
13.6.4 references
Objects are stored in naming and directory services in different ways. A service that supports
storing Java objects might support storing an object in its serialized form. However, some naming
and directory services do not support the storing of Java objects. Furthermore, for some objects in
the directory, Java programs are but one group of applications that access them. In this case, a
177
13 - JNDI
serialized Java object might not be the most appropriate representation. A reference might be a
very compact representation of an object, whereas its serialized form might contain a lot more
state (see the Naming Concepts lesson).
The JNDI defines the Reference class to represent a reference. A reference contains
information on how to construct a copy of the object. The JNDI will attempt to turn references
looked up from the directory into the Java objects that they represent so that JNDI clients have
the illusion that what is stored in the directory are Java objects.
13.6.6 exceptions
The JNDI defines a class hierarchy for exceptions that can be thrown in the course of
performing naming and directory operations. The root of this class hierarchy is
NamingException. Programs interested in dealing with a particular exception can catch the
corresponding subclass of the exception. Otherwise, they should catch NamingException.
13.7.2 searches
DirContext contains methods for performing content-based searching of the directory. In the
simplest and most common form of usage, the application specifies a set of attributes--possibly
with specific values--to match and submits this attribute set to the search() method. Other
overloaded forms of search() support more sophisticated search filters.
178
13 - JNDI
The javax.naming.event package contains classes and interfaces for supporting event
notification in naming and directory services. Event notification is described in detail in the
Beyond the Basics trail.
Events
A NamingEvent represents an event that is generated by a naming/directory service. The
event contains a type that identifies the type of event. For example, event types are categorized
into those that affect the namespace, such as "object added," and those that do not, such as
"object changed." A NamingEvent also contains other information about the change, such as
information about the object before and after the change.
Listeners
A NamingListener is an object that listens for NamingEvents. Each category of event type
has a corresponding type of NamingListener. For example, a NamespaceChangeListener
represents a listener interested in namespace change events and an ObjectChangeListener
represents a listener interested in object change events.
To receive event notifications, a listener must be registered with either an EventContext or
an EventDirContext. Once registered, the listener will receive event notifications when the
corresponding changes occur in the naming/directory service.
The javax.naming.ldap package contains classes and interfaces for using features that are
specific to the LDAP v3 that are not already covered by the more generic
javax.naming.directory package. In fact, most JNDI applications that use the LDAP will find
the javax.naming.directory package sufficient and will not need to use the
javax.naming.ldap package at all. This package is primarily for those applications that need
to use "extended" operations, controls, or unsolicited notifications.
13.9.2 controls
The LDAP v3 allows any request or response to be augmented by yet-to-be defined modifiers,
called controls . A control sent with a request is a request control and a control sent with a
response is a response control . A control may be defined by a standards organization such as the
IETF or by a vendor. Request controls and response controls are not necessarily paired, that is,
there need not be a response control for each request control sent, and vice versa.
179
13 - JNDI
180
13 - JNDI
import javax.naming.InitialContext;
import javax.naming.NamingException;
How to set up the parameters for this constructor is explained in more detail in The Basics trail.
// Look up an object
Object obj = ctx.lookup(name);
// Print it
System.out.println(name + " is bound to: " + obj);
} catch (NamingException e) {
System.err.println("Problem looking up " + name + ":" + e);
}
181
13 - JNDI
Or as follows:
# java Lookup \autoexec.bat
If you supply a file directory, then you will see something like the following.
# java Lookup /tmp
/tmp is bound to: com.sun.jndi.fscontext.RefFSContext@1dae083f
If the name that you supplied is a file, then you will see something like this:
/tmp/f is bound to: //tmp/f
This example shows you how to write a program that retrieves attributes from a directory object.
It uses an LDAP service provider to access an LDAP service.
182
13 - JNDI
Similar to the naming example, you indicate that you're using the LDAP service provider by
setting the Hashtable parameter to the InitialDirContext constructor appropriately. Details
on how to set up the parameters for this constructor are given in The Basics trail. For now, the
only thing to understand is that the program by default identifies an LDAP server on the local
machine. If your LDAP server is located on another machine or is using another port, then you
need to edit the LDAP URL ("ldap://localhost:389/o=JNDITutorial") accordingly.
Instructions for setting up a sample LDAP server for this tutorial are given in the Preparations
lesson.
} catch (NamingException e) {
System.err.println("Problem getting attribute:" + e);
}
183
13 - JNDI
Recall that the program was configured with the following property.
env.put(Context.PROVIDER_URL,
"ldap://localhost:389/o=JNDITutorial");
With this configuration, this command queries the LDAP server on machine localhost that is
listening on port 389, serving the "o=JNDITutorial" namespace. (See the Preparations lesson
for details on this configuration step.) It asks for the attributes of the entry "cn=Ted Geisel,
ou=People". Once it has the attributes, it extracts the surname attribute ("sn"). If you have any
trouble running this example, then see the Common Problems lesson.
184
14 - JAVA MESSAGE SERVICE
The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for
sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise
Edition, and is defined by a specification developed under the Java Community Process as JSR
914.
The following are JMS elements:
• JMS provider - An implementation of the JMS interface for a Message Oriented
Middleware (MOM). Providers are implemented as either a Java JMS implementation or
an adapter to a non-Java MOM.
• JMS client - an application or process that produces and/or consumes messages.
• JMS producer - a JMS client that creates and sends messages.
• JMS consumer - a JMS client that receives messages.
• JMS message - an object that contains the data being transferred between JMS clients.
• JMS queue - a staging area that contains messages that have been sent and are waiting
to be read. As the name queue suggests, the messages are delivered in the order sent. A
message is removed from the queue once it has been read.
• JMS topic - a distribution mechanism for publishing messages that are delivered to
multiple subscribers.
185
14 - JAVA MESSAGE SERVICE
subscription. In that case, messages published while the subscriber is not connected will
be redistributed whenever it reconnects.
Using Java, JMS provides a way of separating the application from the transport layer of
providing data. The same Java classes can be used to communicate with different JMS providers
by using the JNDI information for the desired provider. The classes first use a connection factory
to connect to the queue or topic, and then use populate and send or publish the messages. On the
receiving side, the clients then receive or subscribe to the messages.
186
14 - JAVA MESSAGE SERVICE
At the beginning of a JMS client program, you usually perform a JNDI lookup of a connection
factory, then cast and assign it to a ConnectionFactory object.
For example, the following code fragment obtains an InitialContext object and uses it to
look up a ConnectionFactory by name. Then it assigns it to a ConnectionFactory object:
Context ctx = new InitialContext();
ConnectionFactory connectionFactory = (ConnectionFactory)
ctx.lookup("jms/ConnectionFactory");
In a J2EE application, JMS administered objects are normally placed in the jms naming
subcontext.
Before an application completes, you must close any connections that you have created.
Failure to close a connection can cause resources not to be released by the JMS provider.
Closing a connection also closes its sessions and their message producers and message
consumers.
connection.close();
Before your application can consume messages, you must call the connection's start()
method. If you want to stop message delivery temporarily without closing the connection, you call
the stop() method.
The following line of code looks up a queue named jms/MyQueue and casts and assigns it to a
Queue object:
Queue myQueue = (Queue) ctx.lookup("jms/MyQueue");
187
14 - JAVA MESSAGE SERVICE
topic-type messaging.
For example, you use a Session to create a MessageConsumer for either a queue or a topic:
MessageConsumer consumer = session.createConsumer(myQueue);
MessageConsumer consumer = session.createConsumer(myTopic);
After you register the message listener, you call the start() method on the Connection to
begin message delivery. (If you call start() before you register the message listener, you are
likely to miss messages.)
When message delivery begins, the JMS provider automatically calls the message listener's
onMessage() method whenever a message is delivered. The onMessage() method takes one
argument of type Message, which your implementation of the method can cast to any of the other
message types.
A message listener is not specific to a particular destination type. The same listener can obtain
messages from either a queue or a topic, depending on the type of destination for which the
message consumer was created. A message listener does, however, usually expect a specific
message type and format. Moreover, if it needs to reply to messages, a message listener must
either assume a particular destination type or obtain the destination type of the message and
create a producer for that destination type.
188
14 - JAVA MESSAGE SERVICE
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);
At the consuming end, a message arrives as a generic Message object and must be cast to the
appropriate message type. You can use one or more getter methods to extract the message
contents. The following code fragment uses the getText method:
Message m = consumer.receive();
if (m instanceof TextMessage) {
TextMessage message = (TextMessage) m;
189
14 - JAVA MESSAGE SERVICE
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.
190
15 - ENTERPRISE JAVA BEANS
(Ordinary) Java beans provide a format for general-purpose components, while the EJB
(Enterprise Java Beans) architecture provides a format for highly specialized business logic
components.
What are Enterprise Java Beans? A collection of Java classes together with an xml file,
bundled into a single unit. The Java classes must follow certain rules and must offer certain
callback methods.
The EJBs will run in an EJB container which is part of an application server.
Version 1.1 of EJB specification provides two EJB types:
• session beans - intended to be used by a single client (client extension on the server);
bean's life span can be no longer than client's
• entity beans - object oriented representation of data in a DB; multiple clients can access it
simultaneously while its life-span is the same as the data it represents. Entity beans have
been superseded by the Java Persistence API in EJB 3.0.
The 2.0 EJB specification adds another bean type:
• message-driven beans
The current EJB specification is 3.0. Novelties in this specification try to make the development
of EJBs easier. It provides annotations for every type of metadata previously addressed by
deployment descriptors, so no XML descriptor is needed and beans deployment can be done just
through a plain .jar file into the application server.
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
191
15 - ENTERPRISE JAVA BEANS
• manageability
An EJB consists of (at least) 3 classes and an xml file. It is bean's programmer task to create
them (at least), as follows:
1. the bean itself (the class that contains the business logic )
2. the home interface of the bean
3. the remote interface of the bean
4. the deployment descriptor, which is an xml file, called ejb-jar.xml
The home interface of an ejb is an interface that extends the EJBHome interface. It provides
methods named create() with application specific arguments, returning the remote interface
and throwing CreateException and RemoteException. It uses only argument types allowed
by the RMI standard.
Handle – abstraction for a network reference to an EJB.
The methods specified by the EJBHome interface (not implemented (in general) by the
programmer) are the following:
192
15 - ENTERPRISE JAVA BEANS
package myBeans;
import.javax.ejb.*;
import java.rmi.RemoteException;
public interface MyBeanHome extends EJBHome
{
MyBeanObject create() throws CreateException,
RemoteException;
}
The remote interface of a bean is a standard Java interface that extends the EJBObject and
Remote interfaces and declares the business logic methods of the bean. The developer does not
implement this interface.
While the Remote interface declares no methods, the EJBObject declares the following ones:
package myBeans;
import.javax.ejb.*;
import java.rmi.RemoteException;
public interface MyBeanObject extends EJBObject
{
// assume that we have two business logic methods
void processEntry(String firstName, String lastName, int custId)
throws RemoteException;
void deleteEntry(int custId) throws RemoteException;
}
193
15 - ENTERPRISE 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.
authentication
Client's authentication is done in a way which is server specific. In the case of an web
application, this can be done (for example) through SSL.
• if the client is another EJB executing in the same container and the bean to be used is
declared as a resource in the deployment descriptor, the InitialContext is already
available:
• if the client executes outside the container, getting the InitialContext requires the
usage of some server-side properties. Here is an example:
try
{
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory";
prop.put(Context.PROVIDER_URL,
"localhost:1099");
Context ctx = new InitialContext(prop);
}
194
15 - ENTERPRISE JAVA BEANS
• for a client executing inside the container, the code may look like:
• if the client executes outside the container, the bean can be associated to any name in
the JNDI name space. It is JNDI's task to identify the resource associated to the name
provided:
To make sure that the client works with the underlying communication protocol, the client
should use the narrow() method of javax.rmi.PortableRemoteObject:
Why do we have to use the narrow() method? Usually, when we perform a lookup() on a
Context object, the method will return you an Object that needs to be casted to the home interface
we've asked for. Problem is, this cannot be done using the normal/explicit casting:
The reason has to do with CORBA. Why? For EJB, the communication between the server and
the client is based on RMI (both remote and local interfaces, in fact, do implements the
java.rmi.Remote interface).
The underlying protocol that it is used for the communication is IIOP (Internet Inter ORB
Protocol), that is part of CORBA standards. It is normally used to describe this communication
system using the Java RMI over IIOP.
IIOP has not been designed for Java, but for generic languages, and this means that there are
some limitations. Some languages, in fact, do not have the concept of casting. Java RMI-IIOP
provides a mechanism to narrow the the Object you have received from your lookup, to the
appropriate type. This is done through the javax.rmi.PortableRemoteObject class and, more
specifically, using the narrow() method.
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).
195
15 - ENTERPRISE JAVA BEANS
myObject.remove();
Since the home interface and the remote interface have been detailed in the previous sections,
we concentrate now on the bean class itself. Besides the implementation of the business methods
(which were declared in the remote interface, as well), the bean class must implement (although
the implementation itself may be empty) a certain set of methods, set which is specific to each
major type of beans (session or entity).
Assuming that our bean (called MyBean) is a session bean, the code implementing this class
may look like this:
package com.bank11.ccards.ejbeans;
import javax.ejb.SessionContext;
public class MyBean implements javax.ejb.SessionBean
{
public void processEntry(String firstName, String lastName, int
custId)
{
// method implementation
...
}
public void deleteEntry(int custId)
{
// method implementation
...
}
// mandatory methods for session beans
// method implementations may be empty
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
196
15 - ENTERPRISE JAVA BEANS
There are two types of session beans, namely stateful and stateless beans.
A stateful session bean preserves data between client accesses. A stateless bean does not.
When an EJB server needs to conserve its resources, it can evict stateful session beans from
memory. This reduces the number of instances maintained by the server. To passivate the bean
and preserve its conversational state, the bean's state is serialized to a secondary storage. When
a client invokes a method on the EJB object, the object is activated, that is, a new stateful
instance is instantiated and populated from the passivated storage.
There are 5 mandatory callbacks for classes implementing the SessionBean interface.
public void ejbActivate()
public void ejbPassivate()
public void ejbCreate()
public void ejbRemove()
public void setSessionContext(SessionContext ctx)
The first two methods will never be called for stateless session beans, because the container
will never activate a stateless session bean.
Figure 15.1 illustrates the stages that a session bean passes through during its lifetime. The
client initiates the life cycle by invoking the create method. The EJB container instantiates the
bean and then invokes the setSessionContext and ejbCreate methods in the session bean.
The bean is now ready to have its business methods invoked.
197
15 - ENTERPRISE JAVA BEANS
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 15.2 illustrates the stages of
a stateless session bean.
198
15 - ENTERPRISE JAVA BEANS
Every entity bean has a primary key. This primary key must be represented by a primary key
class. The requirements that must be satisfied by the primary key are different for the two main
types of entity beans.
For BMPs:
• the primary key can be any legal RMI/IIOP type
• it must provide suitable implementations for hashCode(), equals()
199
15 - ENTERPRISE JAVA BEANS
For CMPs:
• the container must be able to create a primary key
• the key class must have a no argument constructor
The fully qualified name of the primary key is always specified in the deployment descriptor
(except when it is not known until deployment)
An example:
<prim-key-class>com.bank11.ccards.CustomerID</prim-key-class>
or
<prim-key-class>java.lang.String</prim-key-class>
In the case of CMP using a simple type as primary key, the field is specified:
<prim-key-field>sportsTeamID</prim-key-field>
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:
CRUD translates through Create, Read, Update and Delete. These methods are mandatory for
entity beans.
15.14.1 create
When a client calls a create() method on a session bean's home interface, an instance of
that bean is created. On the other side, when a client calls create() on an entity bean's home
interface, state data is stored into data store (usually, a Database) (we actually insert a record in a
database). This is transactional data that is accessible to multiple clients. We can have more
create() methods, all throwing RemoteException, CreateException.
Each create() method from the Home interface of the bean has 2 correspondent methods in
the bean implementation class, namely ejbCreate() and ejbPostCreate(), methods which
have the same parameters, in the same order, as the parameters in the original create()
method.
200
15 - ENTERPRISE JAVA BEANS
• the return type of the ejbCreate() is the same as the primary key, but the developer returns
null for CMP.
• for BMP, ejbCreate() must have insertion SQL code and returns an instance of the primary
key, not null.
15.14.2 read
• ejbLoad(), left empty most of the time in CMP, but needs actual SQL code in BMP
• the bean's persistence implementation may choose to defer loading until it is used
• ejbLoad() may contain processing code
15.14.3 update
• ejbStore() in CMP; the method can be used for preprocessing data to be stored, but in
general, it is empty.
• in BMP, actual SQL update code; the updated data is to be stored immediately
15.14.4 delete
• the corresponding method in the bean implementation class is ejbRemove()
• data is deleted from DB (in the CMP case), for BMPs, the programmer will create actual SQL
code.
Figure 15.3 shows the stages that an entity bean passes through during its lifetime. After the
EJB container creates the instance, it calls the setEntityContext method of the entity bean
class. The setEntityContext method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While in the pooled
stage, the instance is not associated with any particular EJB object identity. All instances in the
pool are identical. The EJB container assigns an identity to an instance when moving it to the
ready stage.
There are two paths from the pooled stage to the ready stage. On the first path, the client
invokes the create method, causing the EJB container to call the ejbCreate and
ejbPostCreate methods. On the second path, the EJB container invokes the ejbActivate
method. While an entity bean is in the ready stage, it's business methods can be invoked.
There are also two paths from the ready stage to the pooled stage. First, a client can invoke the
remove method, which causes the EJB container to call the ejbRemove method. Second, the
EJB container can invoke the ejbPassivate method.
201
15 - ENTERPRISE JAVA BEANS
At the end of the life cycle, the EJB container removes the instance from the pool and invokes
the unsetEntityContext method.
In the pooled state, an instance is not associated with any particular EJB object identity. With
bean-managed persistence, when the EJB container moves an instance from the pooled state to
the ready state, it does not automatically set the primary key. Therefore, the ejbCreate and
ejbActivate methods must assign a value to the primary key. If the primary key is incorrect,
the ejbLoad and ejbStore methods cannot synchronize the instance variables with the
database. The ejbActivate method sets the primary key (id) as follows:
id = (String)context.getPrimaryKey();
In the pooled state, the values of the instance variables are not needed. You can make these
instance variables eligible for garbage collection by setting them to null in the ejbPassivate
method.
202
15 - ENTERPRISE JAVA BEANS
203
15 - ENTERPRISE JAVA BEANS
204
15 - ENTERPRISE JAVA BEANS
required for the bean's operation. The ejbRemove() 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
ejbRemove() method, because the beans cannot rely on ejbRemove() being called under all
circumstances (for example, if the EJB throws a runtime exception).
205
15 - ENTERPRISE JAVA BEANS
206
15 - ENTERPRISE JAVA BEANS
message-driven beans.
• message-driven-destination specifies whether the EJB should be associated
with a JMS Queue or Topic destination.
• subscription-durability specifies whether or not an associated Topic
should be durable.
• jms-acknowledge-mode specifies the JMS acknowledgment semantics to use
for beans that demarcate their own transaction boundaries. This element has
two possible values: AUTO_ACKNOWLEDGE (the default) or
DUPS_OK_ACKNOWLEDGE.
These elements are defined in the ejb-jar.xml deployment file, as described in the EJB 2.0
specification. The following excerpt shows a sample XML stanza for defining a message-driven
bean:
<enterprise-beans>
<message-driven>
<ejb-name>exampleMessageDriven1</ejb-name>
<ejb-class>examples.ejb20.message.MessageTraderBean</ejb-class>
<transaction-type>Container</transaction-type>
<message-driven-destination>
<jms-destination-type>
javax.jms.Topic
</jms-destination-type>
</message-driven-destination>
...
</message-driven>
...
</enterprise-beans>
In addition to the new ejb-jar.xml elements, the weblogic-ejb-jar.xml file includes a
new message-driven-descriptor stanza to associate the message-driven bean with an actual
destination in WebLogic Server.
Figure 15.4 illustrates the stages in the life cycle of a message-driven bean.
The EJB container usually creates a pool of message-driven bean instances. For each instance,
the EJB container instantiates the bean and performs these tasks:
1. It calls the setMessageDrivenContext method to pass the context object to the
instance.
2. It calls the instance's ejbCreate method.
207
15 - ENTERPRISE JAVA BEANS
Like a stateless session bean, a message-driven bean is never passivated, and it has only two
states: nonexistent and ready to receive messages.
At the end of the life cycle, the container calls the ejbRemove method. The bean's instance is
then ready for garbage collection.
The deployment descriptor of an EJB contains information about the bean in relation to the
application it belongs to.
This information can be divided into two main categories:
• structural information related to a particular EJB.
• application assembly information
Although not an exhaustive one, here is a typical list of entries (elements) in a deployment
descriptor:
1. access control entries - security issues; which users can access a bean or a particular
method of a bean
2. bean home name - name under which the bean is registered under JNDI
3. control descriptors - specifies control attributes for transactions
4. EJB class name
5. environment properties
6. the home interface name
7. the remote interface name
8. session specific elements
9. entity specific elements
10. attributes - like transaction, isolation level, security
208
15 - ENTERPRISE JAVA BEANS
Keeping in mind that the application assembler is to follow, here is how the deployment
descriptor may look like:
<?xnm version="1.1"?>
<ejb-jar>
<entrprise-beans>
<session>
<ejb-name>CCEnroll</ejb-name>
<home>com.bank11.ccards.ejb.CCEnrollHome</home>
<remote>com.bank11.ccards.CCEnrollObject</remote>
<ejb-class>com.bank11.ccards.CCEnroll</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container<transaction-type>
<ejb-ref>
<ejb-ref-name>ejb/CCAccount</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<home>com.bank11.ccards.ejb.AccountHome</home>
<remote>com.bank11.ccards.ejb.AccountObj</remote>
</ejb-ref>
<security-role-ref>
<description>
This role relates to cash advances from ATMs
</description>
<role-name>CashAdvATM</role-name>
<security-role-ref>
</session>
<entity>
<ejb-name>Account</ejb-name>
<home>com.bank11.ccards.ejb.AccountHome</home>
<remote>com.bank11.ccards.Accountbject</remote>
<ejb-class>com.bank11.ccards.Account</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Integer</prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>accountNumber</field-name>
209
15 - ENTERPRISE JAVA BEANS
</cmp-field>
<cmp-field>
<field-name>userName</field-name>
</cmp-field>
<cmp-field>
<field-name>customerID</field-name>
</cmp-field>
<cmp-field>
<prim-key-field>accountNumber</prim-key-field>
</cmp-field>
<env-entry>
<env-entry-name>env/minPaymentPerc</env-entry-name>
<env-entry-type>java.lang.Float</env-entry-type>
<env-entry-value>2.5</env-entry-value>
</env-entry>
</entity>
</enterprise-beans>
</ejb-jar>
The assembly descriptor combines EJBs into a deployable application. Here is a very lean one:
</ejb-jar>
<enterprise-beans>
...
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>CCEnroll</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
210
15 - ENTERPRISE JAVA BEANS
211