Documente Academic
Documente Profesional
Documente Cultură
New features for Enterprise JavaBeans ( EJB) components (see Enterprise JavaBeans
Technology for details)
New features for servlets (see Java Servlet Technology for details)
New features for JavaServer Faces components (see JavaServer Faces Technology for
details)
New features for the Java Message Service (JMS) (see Java Message Service API for
details)
The next release is Java EE 8 and is scheduled for Q3 2016. The state of the Java EE 8 release
can be found in a draft of the release attached to the link - https://java.net/projects/javaeespec/lists/users/archive/2014-05/message/0
Novelties expected in the forthcoming release:
Application clients and applets are components that run on the client.
Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components are
web components that run on the server.
Java EE components are written in the Java programming language and are compiled in the
same way as any program in the language. The difference between Java EE components and
standard Java classes is that Java EE components are assembled into a Java EE application, are
verified to be well formed and in compliance with the Java EE specification, and are deployed to
production, where they are run and managed by the Java EE server.
1.5.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.
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.
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.
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.
Applet container - manages the execution of applets. Consists of a web browser and Java
Plug-in running on the client together.
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.
Defines an XML-based envelope to describe what is in the message and how to process
the message
Defines an XML-based convention for representing the request to the remote service and
the resulting response
WebSocket
Concurrency utilities
Batch
JSON-P
Concurrency utilities
Batch
JSON-P
Non-blocking I/O
10
A flexible model for rendering components in different kinds of HTML or different markup
languages and technologies. A Renderer object generates the markup to render the
component and converts the data stored in a model object to types that can be represented
in a view.
Input validation
Event handling
All this functionality is available via standard Java APIs and XML-based configuration files.
New features in Java EE 7:
Faces Flows
11
12
13
14
Enterprise application integration with message-driven beans and JMS, JTA, and JNDI
Once a Java EE unit has been produced, it is ready to be deployed. Deployment typically
involves using a platforms deployment tool to specify location-specific information, such as a list of
local users that can access it and the name of the local database. Once deployed on a local
platform, the application is ready to run.
A Java EE application is delivered in an Enterprise Archive (EAR) file, a standard Java Archive
(JAR) file with an .ear extension. Using EAR files and modules makes it possible to assemble a
number of different Java EE applications using some of the same components. No extra coding is
needed; it is only a matter of assembling (or packaging) various Java EE modules into Java EE
EAR files.
An EAR file contains Java EE modules and deployment descriptors. A deployment descriptor
is an XML document with an .xml extension that describes the deployment settings of an
application, a module, or a component. Because deployment descriptor information is declarative, it
can be changed without the need to modify the source code. At runtime, the Java EE server reads
the deployment descriptor and acts upon the application, module, or component accordingly.
15
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
17
2 - HTTP
2 - HTTP
2.1 what is http?
HTTP stands for HyperText Transfer Protocol while hypertext means text contatining links to
another text. HTTP was created by by Tim Berners-Lee in 1990 at CERN as a mean to store
scientific data. It quickly evolved into the preferred communication protocol over the internet.
The first 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.
The next version of the HTTP specification is HTTP 2.0 (or HTTP/2) and is scheduled to be
released as an RFC at the beginning of 2015 (february).
The working group for HTTP/2 hopes to address the following issues and goals:
Negotiation mechanism that allows clients and servers to elect to use HTTP 1.1, 2.0, or
potentially other non-HTTP protocols.
Maintain high-level similarity with HTTP 1.1 (for example with methods, status codes,
header fields, and URIs, and most header fields)
Support common existing use cases of HTTP, such as desktop web browsers, mobile web
browsers, web APIs, web servers at various scales, proxy servers, reverse proxy servers,
firewalls, and content delivery networks
18
2 - HTTP
<initial line>
Header1: value1
...
Headern: valuen
<optional data block>
a file specification (path) (the part of the URL after the host name)
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.
19
2 - HTTP
20
2 - HTTP
well):
200 OK - the request succeeded, and the resulting resource (e.g. file or script output) is
returned in the message body.
303 See Other (HTTP 1.1 only) - the resource has moved to another URL (given by the
Location: response header), and should be automatically retrieved by the client. This is
often used by a CGI script to redirect the browser to an existing file.
500 Server Error - an unexpected server error. The most common cause is a server-side
script that has bad syntax, fails, or otherwise can't run correctly.
A complete list of status codes is in the HTTP specification (the URL was mentioned in the firs
section of this chapter) (section 9 for HTTP 1.0, and section 10 for HTTP 1.1).
21
2 - HTTP
the Content-Type: header gives the MIME-type of the data in the body, such as text/html or
image/jpg.
22
2 - HTTP
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/html
Content-Length: 1354
<html>
<body>
<h1>Happy birthday!</h1>
(more file contents)
.
.
</body>
</html>
After sending the response, the server closes the socket.
23
3 - HTML
3 - HTML
3.1 what is html?
HTML stands for HyperText Markup Language. HTML describes how text, images and other
components are to be displayed in a browser, using a variety of tags and their related attributes.
The first version of HTML, namely HTML 1.0, appeared in summer 1991 and was supported by
the first popular web browser, Mosaic. The first official version HTML 2.0 - was approved as a
standard in September 1995 (as RFC 1866 (http://www.apps.ietf.org/rfc/rfc1866.html) and was
widely supported. A newer standard, HTML 3.2 (3.0 was not widely accepted) appeared a W3C
recommendation in January 1997.
Version 4.0 introduces the Cascading Style Sheets.
The latest version of HTML as SGML application is 4.01. It is a revision of 4.0 and was accepted
in December 1997. However, a working draft for the next major revision, namely HTML 5 was
published in January 2008. Originally named Web Applications 1.0, the specification includes
several ideas of the WHAT (Web Hypertext Application Technology) working group. It might take
several years (a formal target has been set for 2014) before the specification reaches final
Recommendation status.
From 1999 on, HTML is part of a new specification XHTML. The XHTML 1.0 draft was
released in 01.99 and mirrors the HTML 4.01 specification. The latest version (XHTML 2.0) was a
working draft but was abandoned in 2009 in favor of work on XHTML5, which is being defined
alongside HTML5.
For a complete specification of the different HTML versions, check the official HTML site
www.w3c.org/Markup . As a practical reference site use www.blooberry.com/indexdot/html .
Other helpful sites - www.htmlgoodies.com/tutors, www.jmarshall.com/easy/html .
24
3 - HTML
ISO/IEC 10646-1:1993 UCS-4 with
implementation level 3//ESC 2/5 2/15 4/6"
DESCSET 0
9
UNUSED
9
2
9
11
2
UNUSED
13
1
13
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
GRPCAP
ENTCAP
150000
150000
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
NAMING
RE
RS
SPACE
TAB SEPCHAR
13
10
32
9
""
""
".-_:"
".-_:"
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
OMITTAG
RANK
SHORTTAG
LCNMSTRT
UCNMSTRT
LCNMCHAR
UCNMCHAR
NAMECASE
-----
NO
YES
NO
YES
25
3 - HTML
>
LINK
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.
3.3 html5
As of December 2012, HTML5 is a candidate recommendation of the World Wide Web
Consortium (W3C). Its core aims have been to improve the language with support for the latest
multimedia while keeping it easily readable by humans and consistently understood by computers
and devices (web browsers, parsers, etc.). HTML5 is intended to subsume not only HTML 4, but
also XHTML 1 and DOM Level 2 HTML.
It includes detailed processing models to encourage more interoperable implementations; it
extends, improves and rationalises the markup available for documents, and introduces markup
and application programming interfaces (APIs) for complex web applications.
HTML5 adds many new syntactic features. These include the new <video>, <audio> and
<canvas>elements, as well as the integration of scalable vector graphics (SVG) content (that
replaces the uses of generic<object> tags) and MathML for mathematical formulas. These features
are designed to make it easy to include and handle multimedia and graphical content on the web
without having to resort to proprietary plugins and APIs. Other new elements, such as <section>,
<article>, <header> and <nav>, are designed to enrich the semantic content of documents. New
attributes have been introduced for the same purpose, while some elements and attributes have
been removed.
a start tag
26
3 - HTML
a content
an end tag
One exception, though; the element <BR> has no content and no end tag.
There are 91 elements defined in the HTML 4.01 specification. This section deals with some of
the most common elements.
The start tag of the element contains the values of the (required or optional) attributes of the
element. An example:
NAME assigns a symbolic name to the enclosed object (text, image, etc.) in order to use
it as a destination in a hyperlink or another URL call.
Example:
<A HREF=http://web.info.uvt.ro/webmail/src/login.php>Login to
web mail</A>
ALT required; specifies the text to be displayed in case source is not found
HEIGHT
WIDTH
27
3 - HTML
All HTML documents start with the <HTML> tag and end with the corresponding end tag
</HTML>. An HTML document consists of the parts:
<HTML>
<HEAD>My Page
</HEAD>
<BODY>Empty Body
</BODY>
</HTML>
3.6 tables
A table is a visual rectangular object consisting of several rows and columns. The intersection
of any row and any column is called a cell. Usually, the cells in the first row contain are called
headers and consist of a brief description of the content of the corresponding column. Here is a an
example of a table:
BORDER
CELLSPACING
CELLPADDING
WIDTH
28
3 - HTML
ALIGN
VALIGN
TBODY
BORDERCOLOR
FRAME
RULES
COLORGROUP
BACKGROUND
ALIGN
BGCOLOR
CHAR
CHAROFF
VALIGN
ABBR
AXIS
CHAR
CHAROFF
HEADERS
SCOPE
ALIGN
BGCOLOR
CHAR
CHAROFF
VALIGN
ABBR
29
3 - HTML
ALIGN
CHAR
CHAROFF
COLSPAN
ROWSPAN
SCOPE
VALIGN
WIDTH
3.8 forms
A form is a basic component container, allowing user input and parameter submittal.
The <FORM> element has the following attributes:
ACTION - required, specifies the URL of the server side process that will receive the data
METHOD - required, may have the values GET or POST, specifies how data will be sent to the
server. Possible values for this attribute:
"POST"- sends the form values in 2 steps: contacts first the server then the form values are
sent in a separate transmission.
"GET" - sends the form values in a single transmission, the browser appends the values to
the URL, after a quotation mark - ?. The pairs name=value are separated by ampersand - &
or (sometimes) by semicolon - :.
Example:
http://web.info.uvt.ro/servlet/MyServlet?a=12&b=25
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.
"multipart/form-data" - used with forms that contain a file-selection field, data is sent as a
single document with multiple sections.
"text/plain"
TYPE - required, specifies the type of the input which can have one of the following values:
"text", "password", "checkbox", "radio", "submit", "image", "reset", "button", "hidden", "file".
30
3 - HTML
NAME
SELECTED
31
4 - JAVA PRIMER
4 - JAVA PRIMER
4.1 history
The initial name of this language was OAK and was developed as part of the GREEN project at
Sun, project started in 12.90. Early versions of Java were released in 12.94 and was officially
announced at Sun World in 05.95. The first commercial version was delivered to the first customer
(Netscape, Inc.) in 08.95. The current version (as of 10.2004) of Java 2 Platform Standard Edition
is J2SE 5.0, following the 1.4.2 version. The current version (as of 10.2014) of Java Platform
Enterprise Edition is Java EE 7.
-classpath <path>
-sourcepath <path>
32
4 - JAVA PRIMER
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:
WIDTH
HEIGHT
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:
33
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.
byte
short
int
long
float
double
other types:
boolean - 1 bit
All basic types have associated classes which extend their functionality, namely: Byte, Short,
Integer, Long, Float, Double, Boolean, Character.
Other peculiarities: no pointers (only references), automatic garbage collection, no templates.
34
4 - JAVA PRIMER
no specifier - the default value allows access from any class in the same package
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
abstract - the class is abstract (some of its methods (inherited or specified by some
interface) are to be implemented by some of its subclasses)
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:
35
4 - JAVA PRIMER
An exception signals an abnormal situation or an error in an application, due to a variety of
execution factors or due to programming errors.
In Java, an exception is an object which is created when the abnormal situation occurs.
Exception categories:
1. code or data errors - like invalid cast, array index out of bounds, division by 0.
2. standard method exceptions
3. programmer defined exceptions
4. java errors - JVM execution errors (mostly caused by programming errors).
All exceptions (even programmer defined) must inherit from the standard class Throwable.
All the standard exceptions are derived from 2 direct subclasses of Throwable, namely class
Error and the class Exception.
ArithmeticException
IndexOutOfBoundException
NegativeArraySizeException
NullPointerException
ArrayStoreException
ClassCastException
IllegalArgumentException
SecurityException
IllegalMonitorStateException
IllegalStateException
UnsupportedOperationException
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.
36
4 - JAVA PRIMER
java.io
java.net
java.nio
java.rmi
java.util - support for data collections, string analyzers, date and time info
java.sql
java.security
java.text
javax.accessibility
37
4 - JAVA PRIMER
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.
38
5 - javaScript
5 - JAVASCRIPT
5.1 so what is JavaScript?
JavaScript is a scripting language designed to add interactivity to HTML pages.
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
39
5 - javaScript
5.3.1 scripts in the head section
Scripts to be executed when they are called, or when an event is triggered, go in the head
section. When you place a script in the head section, you will ensure that the script is loaded before
anyone uses it. Here is an example:
<html>
<head>
<script type="text/javascript">
....
</script>
</head>
40
5 - javaScript
41
5 - javaScript
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
By using the try...catch statement (available in IE5+, Mozilla 1.0, and Netscape 6)
By using the onerror event. This is the old standard solution to catch errors (available
since Netscape 3)
42
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.
43
5 - javaScript
5.7.2 confirm Box
A confirm box is often used if you want the user to verify or accept something. When a confirm
box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK",
the box returns true. If the user clicks "Cancel", the box returns false.
Syntax:
confirm("sometext")
5.8 functions
5.8.1 function definition
A function contains some code that will be executed only by an event or by a call to that function.
A function can be called from anywhere within the page (or even from other pages if the function is
embedded in an external .js file). Functions are defined at the beginning of a page, in the <head>
section. Example:
<html>
<head>
<script type="text/javascript">
function displaymessage() { alert("Hello World!") }
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>
If the line: alert("Hello world!!"), in the example above had not been written within a function, it
would have been executed as soon as the line was loaded. Now, the script is not executed before
the user hits the button. We have added an onClick event to the button that will execute the
function displaymessage() when the button is clicked..
The syntax for creating a function is:
function functionname(var1,var2,...,varX) { some code }
var1, var2, etc are variables or values passed into the function. The { and the } defines the start
44
5 - javaScript
and end of the function.
function functionname() { some code }
Note: Do not forget about the importance of capitals in JavaScript! The word function must be
written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a
function with the exact same capitals as in the function name.
5.9.2 properties
Properties are the values associated with an object.
In the following example we are using the length property of the String object to return the
number of characters in a string:
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
The output of the code above will be:
12
5.9.3 methods
Methods are the actions that can be performed on objects.
45
5 - javaScript
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.
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
46
5 - javaScript
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
Description
F
constructor
length
prototype
I
E
1
1
1
4
2
2
4
3
4
Methods
Method
Description
F
anchor()
big()
blink()
bold()
charAt()
charCodeAt()
concat()
fixed()
fontcolor()
fontsize()
fromCharCode()
indexOf()
italics()
I
E
1
1
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
4
4
2
2
2
4
2
3
3
3
3
4
4
3
3
3
4
3
47
5 - javaScript
lastIndexOf()
link()
match()
replace()
search()
slice()
small()
split()
strike()
sub()
substr()
substring()
sup()
toLowerCase()
toUpperCase()
toSource()
valueOf()
1
1
1
2
4
4
3
4
4
1
1
4
4
4
4
1
1
1
1
1
2
4
2
2
4
3
4
3
3
4
1
1
1
1
1
2
2
2
4
2
3
3
3
4
Description
F
F
I
E
Methods
Method
Date()
getDate()
getDay()
Description
Returns today's date and time
Returns the day of the month from a Date object (from 131)
Returns the day of the week from a Date object (from 06)
F
F
I
E
1
1
2
2
3
3
48
5 - javaScript
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCMonth()
getUTCFullYear()
getUTCHours()
getUTCMinutes()
getUTCSeconds()
getUTCMilliseconds()
getYear()
parse()
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCMonth()
setUTCFullYear()
1
1
1
1
1
1
2
4
2
2
2
2
3
4
3
3
3
3
1
1
1
1
1
1
1
1
2
4
2
4
2
2
2
2
3
4
3
4
3
3
3
3
49
5 - javaScript
setUTCHours()
setUTCMinutes()
setUTCSeconds()
setUTCMilliseconds()
setYear()
toDateString()
toGMTString()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toSource()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()
1
1
4
2
Description
constructor
index
input
length
prototype
F
F
1
1
1
1
1
N
2
3
3
2
2
I
E
4
4
4
4
4
Methods
50
5 - javaScript
Method
Description
F
concat()
join()
pop()
push()
reverse()
shift()
slice()
sort()
splice()
toSource()
toString()
unshift()
valueOf()
I
E
1
1
4
3
1
1
3
4
1
1
1
4
3
4
1
1
1
4
3
4
4
6
4
4
.5
.5
.5
.5
5
5
4
5
4
4
5
Description
constructor
F
F
I
E
1
1
1
1
4
4
4
4
POSITIVE_INFINITY
prototype
1
1
4
4
Methods
51
5 - javaScript
Method
Description
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()
.5
.5
.5
1
1
5
5
5
4
4
Description
I
E
Methods
Method
Description
F
toSource()
toString()
valueOf()
I
E
1
1
1
4
4
4
4
4
Description
E
LN2
LN10
F
F
1
1
1
I
N
E
2 3
2 3
2 3
52
5 - javaScript
LOG2E
LOG10E
PI
SQRT1_2
SQRT2
1
1
1
1
1
2
2
2
2
2
3
3
3
3
3
1
1
1
1
N
E
2
2
2
2
2 3
2 3
1
1
2 3
2 3
2 3
1
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
4
2
Methods
Method
Description
F
abs(x)
acos(x)
asin(x)
atan(x)
atan2(y,x)
ceil(x)
cos(x)
exp(x)
floor(x)
log(x)
max(x,y)
min(x,y)
pow(x,y)
random()
round(x)
sin(x)
sqrt(x)
tan(x)
toSource()
valueOf()
53
3
3
3
3
3
3
3
3
3
3
3
3
3
4
5 - javaScript
5.12.1 Properties
The syntax for accessing a property of an object is:
objName.propName
You can add properties to an object by simply giving it a value. Assume that the personObj
already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";
document.write(personObj.firstname);
The code above will generate the following output:
John
5.12.2 Methods
An object can also contain methods.
You can call a method with the following syntax:
objName.methodName()
There are different ways to create a new object:
54
5 - javaScript
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;
}
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").
55
5 - javaScript
a user clicks on the button. We define the events in the HTML tags.
Examples of events:
A mouse click
A keystroke
Note: Events are normally used in combination with functions, and the function will not be
executed before the event occurs!
Tne following table contains an exhaustive list of events together with the support version of
FireFox, Netscape an Internet Explorer for each such event.
Event
F
onabort
onblur
onchange
onclick
ondblclick
onerror
onfocus
onkeydown
onkeypress
onkeyup
onload
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onreset
onresize
onselect
onsubmit
onunload
I
E
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
3
2
2
2
4
3
2
4
4
4
2
4
6
4
2
4
3
4
2
2
2
4
3
3
3
4
4
3
3
3
3
3
4
3
4
3
4
4
4
3
3
3
56
5 - javaScript
5.13.1 onload and onUnload
The onload and onUnload events are triggered when the user enters or leaves the page.
The onload event is often used to check the visitor's browser type and browser version, and load
the proper version of the web page based on the information.
Both the onload and onUnload events are also often used to deal with cookies that should be set
when a user enters or leaves a page. For example, you could have a popup asking for the user's
name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor
arrives at your page, you could have another popup saying something like: "Welcome John Doe!".
5.13.3 onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.
Below is an example of how to use the onSubmit event. The checkForm() function will be called
when the user clicks the submit button in the form. If the field values are not accepted, the submit
should be cancelled. The function checkForm() returns either true or false. If it returns true the form
will be submitted, otherwise the submit will be cancelled:
<form method="post" action="xxx.htm" onsubmit="return checkForm()">
event');return
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. 2013), what drives the DOM Specifications is the WebApps WG. The W3C Web
Applications Working Group has taken over responsibility for the Document Object Model
58
6 - Html DOM
specifications, including a new revision of DOM Level 3 Events, a new DOM Core specification,
and potentially any errata on older DOM specifications.
The main deadline for this work group's activity is May 2014. Among the deliverables expected
are the following:
DOM4
Web Messaging
Web Workers
Widgets
XMLHttpRequest (XHR)
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
59
6 - Html DOM
6.4 specifications
Description
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
60
6 - Html DOM
Navigator
Screen
History
Location
Object
Document
Anchor
Area
Base
Body
Button
Event
Form
Frame
Frameset
Iframe
Image
Input button
Input checkbox
Input file
Input hidden
Input password
Input radio
Input reset
Input submit
Input text
Link
Description
Represents the entire HTML document and can be used to access all
elements in a page
Represents an <a> element
Represents an <area> element inside an image-map
Represents a <base> element (specifies a default address or a default
target for all links on a page)
Represents the <body> element
Represents a <button> element
Represents the state of an event
Represents a <form> element
Represents a <frame> element
Represents a <frameset> element
Represents an <iframe> element
Represents an <img> element
Represents a button in an HTML form
Represents a checkbox in an HTML form
Represents a fileupload in an HTML form
Represents a hidden field in an HTML form
Represents a password field in an HTML form
Represents a radio button in an HTML form
Represents a reset button in an HTML form
Represents a submit button in an HTML form
Represents a text-input field in an HTML form
Represents a <link> element
61
6 - Html DOM
Meta
Option
Select
Style
Table
TableData
TableRow
Textarea
62
6 - Html DOM
"DOM Tutorial" is not the value of the <title> element!
However, in the HTML DOM the value of the text node can be accessed by the innerHTML
property.
63
6 - Html DOM
2. By using the getElementsByTagName() method
3. By navigating the node tree, using the node relationships.
The following example returns a nodeList of all <p> elements that are descendants of the
element with id="main":
document.getElementById('main').getElementsByTagName("p");
The length property defines the length of a node list (the number of nodes). You can loop
through a node list by using the length property:
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
nodeName
nodeValue
nodeType
nodeName is read-only
64
6 - Html DOM
The nodeType property returns the type of node and is read only. The most important node
types are:
Element type
Element
Attribute
Text
Comment
Document
NodeType
1
2
3
8
9
Mouse events
Keyboard events
HTML frame/object events
HTML form events
User interface events
Mutation events (notification of any changes to the structure of a document)
Note that the event classification above is not exactly the same as W3C's classification.
Category
Mouse
Type
Attribute
click
onclick
dblclick
ondblclick
mousedown
onmousedown
Description
Fires when the pointing device
button is clicked over an element.
A click is defined as a mousedown
and mouseup over the same
screen location. The sequence of
these events is:
mousedown
mouseup
click
Fires when the pointing device
button is double clicked over an
element
Fires when the pointing device
button is pressed over an element
65
6 - Html DOM
mouseup
onmouseup
mouseover
onmouseover
mousemove
onmousemove
mouseout
onmouseout
keypress
onkeypress
keydown
onkeydown
keyup
onkeyup
load
onload
unload
onunload
abort
onabort
error
onerror
resize
onresize
scroll
onscroll
select
onselect
change
onchange
submit
reset
onsubmit
onreset
Keyboard
HTML
frame/object
HTML
form
66
6 - Html DOM
Fires when an element receives
focus either via the pointing device
or by tab navigation
Fires when an element loses
blur
onblur
focus either via the pointing device
or by tabbing navigation
Similar to HTML focus event, but
DOMFocusIn
ondomfocusin
can be applied to any focusable
element
Similar to HTML blur event, but
DOMFocusOut
ondomfocusout
can be applied to any focusable
element
Similar to XUL command event.
Fires when an element is activated,
DOMActivate
ondomactivate
for instance, through a mouse click
or a keypress.
Fire when the subtree is
DOMSubtreeModified
onsubtreemodified
modified
Fires when a node has been
DOMNodeInserted
onnodeinserted
added as a child of another node
Fires when a node has been
DOMNodeRemoved
onnoderemoved
removed from a DOM-tree
NodeInsertedIntoDoc
onnodeinsertedinto
Fires when a node is being
ument
document
inserted into a document
Fires when an attribute has been
DOMAttrModified
onattrmodified
modified
DOMCharacterDataM
oncharacterdatamo
Fires when the character data
odified
dified
has been modified
focus
User
interface
Mutation
onfocus
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.
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
67
6 - Html DOM
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.
Name
type
Description
The name of the event (case-insensitive).
Used to indicate the EventTarget to which the event was
target
originally dispatched.
Used to indicate the EventTarget whose EventListeners
currentTarget
are currently being processed.
Used to indicate which phase of event flow is currently
eventPhase
being evaluated.
Used to indicate whether or not an event is a bubbling
bubbles
event.
Used to indicate whether or not an event can have its
cancelable
default action prevented.
Used to specify the time (in milliseconds relative to the
timeStamp
epoch) at which the event was created.
Event methods
Name
Argument
type
stopPropagation
preventDefault
DOMString
initEvent
boolean
boolean
Argument
name
Description
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.
optionally
XSL stands for EXtensible Stylesheet Language while XSLT stands for XSL Transformations
The "Asynchronous" word, means that the response of the server will be processed when
available, without to wait and to freeze the display of the page.
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 doesnt make for a great user experience.
While the server is doing its thing, whats the user doing? Thats right, waiting. And at every step in
a task, the user waits some more.
Obviously, if we were designing the Web from scratch for applications, we wouldnt make users
wait around. Once an interface is loaded, why should the user interaction come to a halt every time
the application needs something from the server? In fact, why should the user see the application
go to the server at all?
An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by
introducing an intermediary an Ajax engine between the user and the server. It seems like
adding a layer to the application would make it less responsive, but the opposite is true.
Instead of loading a web page, at the start of the session, the browser loads an Ajax engine
written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both
rendering the interface the user sees and communicating with the server on the users behalf. The
Ajax engine allows the users interaction with the application to happen asynchronously
independent of communication with the server. So the user is never staring at a blank browser
window and an hourglass icon, waiting around for the server to do something.
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 doesnt require a trip back to the
server such as simple data validation, editing data in memory, and even some navigation the
engine handles on its own. If the engine needs something from the server in order to respond if
its submitting data for processing, loading additional interface code, or retrieving new data the
engine makes those requests asynchronously, usually using XML, without stalling a users
interaction with the application.
71
7 - AJAX
Attributes
readyState
status
- returned by the server - 200 is ok, 404 if the page is not found
responseText
responseXml
Methods
open(mode, url, boolean)
72
7 - AJAX
send("string")
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;
};
req.open("GET", "data.xml", true);
req.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
req.send(null);
}
</script>
</head>
<body>
<FORM method="POST" name="ajax" action="">
<INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
<INPUT type="text" name="dyn" value="">
</FORM>
</body>
</html>
74
7 - AJAX
document.ajax.dyn.value= element.firstChild.data;
content of the element to the form
// assign the
If JavaScript is not activated, Ajax can't work. The user must be asked to set JavaScript
from within options of the browser, with the "noscript" tag.
Since data to display are loaded dynamically, they are not part of the page, and the
keywords inside are not used by search engines.
The asynchronous mode may change the page with delays (when the processing on the
server take some times), this may be disturbing.
The back button may be deactivated (this is not the case in examples provided here).
75
7 - AJAX
7.10 Specifications
Ajax is based on these specifications:
76
8 - WEB APPLICATIONS
8 - WEB APPLICATIONS
8.1 web application types
A web application is a dynamic extension of a web or application server. Web applications are
of the following types:
In the Java EE platform, web components provide the dynamic extension capabilities for a web
server. Web components can be Java servlets, web pages implemented with JavaServer Faces
technology, web service endpoints, or JSP pages.
Servlets are Java programming language classes that dynamically process requests and
construct responses. Java technologies, such as JavaServer Faces and Facelets, are used for
building interactive web applications. (Frameworks can also be used for this purpose.) Although
servlets and JavaServer Faces and Facelets pages can be used to accomplish similar things, each
has its own strengths. Servlets are best suited for service-oriented applications (web service
endpoints can be implemented as servlets) and the control functions of a presentation-oriented
application, such as dispatching requests and handling nontextual data. JavaServer Faces and
Facelets pages are more appropriate for generating text-based markup, such as XHTML, and are
generally used for presentation-oriented applications.
Web components are supported by the services of a runtime platform called a web container. A
web container provides such services as request dispatching, security, concurrency, and lifecycle
management. A web container also gives web components access to such APIs as naming,
transactions, and email.
Certain aspects of web application behavior can be configured when the application is installed,
or deployed, to the web container. The configuration information can be specified using Java EE
annotations or can be maintained in a text file in XML format called a web application deployment
descriptor (DD). A web application DD must conform to the schema described in the Java Servlet
specification.
77
8 - WEB APPLICATIONS
4. Optionally, package the application into a deployable unit.
5. Deploy the application into a web container.
6. Access a URL that references the web application.
web container built into web servers. Most known cases are the Sun's (Oracle's) Java
WebServer and the Jakarta Tomcat web server.
web container as a separate runtime. Some web servers, like Apache or IIS require a
separate runtime to run servlets and a web server plug-in to integrate this Java runtime
with the web server. Typical integration scenarios are Tomcat with Apache and JRun (of
Allaire) with most of the J2EE application servers.
78
8 - WEB APPLICATIONS
Web Application
Web Application
Java Servlets
Java Servlets
JSP Pages
JSP Pages
JavaServer
Faces
JavaServer
Faces
Deployment descriptor
Deployment descriptor
JBoss Application Server (open source) is a full Java EE implementation by Red Hat inc.,
division Jboss.
Jetty is (open source) from the Eclipse Foundation. Also supports SPDY and WebSocket
protocols.
79
8 - WEB APPLICATIONS
Tiny Java Web Server (TJWS) 2.5 [1], small footprint, modular design
Eclipse Virgo provides modular, OSGi based web containers implemented using embedded
Tomcat and Jetty. Virgo is open source and available under theEclipse Public License.
Sun Java System Web Server, from Sun Microsystems (Oracle now)
Sun Java System Application Server (is an Application Server, but includes a web container)
tc Server (SpringSource)
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.
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
80
8 - WEB APPLICATIONS
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.
81
8 - WEB APPLICATIONS
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:
2. The "/ccards" part of the URL is, basicly, the name of the web application. In general, the
base directory of an application is a subdirectory of the "%TOMCAT_HOME%\webapps"
directory. This subdirectory has (in general) the same name as the application itself.
However, for flexibility, the location of the base directory of a web application may be any
sub(sub)directory of "%TOMCAT_HOME%\webapps". The association between the name of
the web application and the location of its base directory is made by a <context> element
in the "%TOMCAT_HOME%\conf\server.xml" file. For example, if the base directory of the
"/ccards" web application is "%TOMCAT_HOME%\webapps\vdumitrascu\cc", then the
corresponding <context> element in the "%TOMCAT_HOME%\conf\server.xml" file looks
like:
<context path="/ccards" docbase="vdumitrascu/cc" />
3. The "/Enroll" part of the URL identifies the servlet. Basicly, it is the alias of the real servlet
class, whose name is rather long. Let's say that this class is "EnrollServlet.class" and that it
is part of the package "com.bank11.ccards.servlets". Then the "EnrollServlet.class" file must
be located in the directory "%TOMCAT_HOME%\webapps\vdumitrascu\cc\WEBINF\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>
82
9 - SERVLETS
9 - SERVLETS
9.1 the servlets as part of web applications
Java servlets small, platform independent programs, which extend the functionality of the web
server.
Technically speaking, a servlet is a Java class that extends the GenericServlet (or, more often,
the HttpServlet) class. Theoretically, servlets can communicate over any client-server protocol, but
most often, they communicate over the HTTP protocol.
The Java Servlet API provides a simple frame for building web applications on web servers.
The first Servlet specification (version 1.0) was finalized by Sun June 1997. It continued with
versions 2.0, 2.1 and 2.2 in the next couple of years. Starting with version 2.3, the Servlet
specification is part of the Java Community process. The current (as of Oct. 2013) Java Servlet
specification is 3.0 (JSR 315) and is in final state. It is part of the Java EE 6 and 7 SDKs.
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.
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
session tracking
servlet context
servlet collaboration
miscellaneous
83
9 - SERVLETS
throws ServletException;
84
9 - SERVLETS
public abstract class HttpServlet extends GenericServlet implements
Serializable
The HttpServlet provides an HTTP specific implementation of the Servlet interface. This abstract
class specifies the following methods:
public void service(ServletRequest req, ServletResponse resp)
public void service(HttpServletRequest req, HttpServletResponse resp)
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
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)
85
9 - SERVLETS
The ServletException class extends java.lang.Exception and can be thrown by the
init(), service(), doXXX() and destroy() methods of the Servlet interface
implementations.
The UnavailableException indicates to the web container that the servlet instance is
unavaialble. It also extends the java.lang.Exception class.
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.
86
9 - SERVLETS
public String getRemoteHost()
Most of the above methods are self explanatory. But what is the difference between a parameter
and an attribute? While the parameters of the request are part of the request itself, the attributes of
the request are attached by the web containers or by the servlets/JSPs/JSFs.
There are 3 different ways for attaching and retrieving attributes. The first one is to attach
attributes to the request object. The other two use the HttpSession and ServletContext objects,
respectively. The purpose of attributes is to allow the container to provide additional data to a
servlet, JSP or JSF, or to allow sending data from a servlet to another.
87
9 - SERVLETS
public void flushBuffer()
88
9 - SERVLETS
89
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.
Version 4.1 is specified by a maintenance release of JSR 221 and is be included in Java SE 7.
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.
90
10 - JDBC
91
10 - JDBC
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
92
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
93
10 - JDBC
4. processing the result set
com.ibm.db2.jdbc.app.DB2Driver
oracle.jdbc.driver.OracleDriver
com.borland.datastore.jdbc.DataStoreDriver
com.sybase.jdbc.SybDriver
94
10 - JDBC
sun.jdbc.odbc.JdbcOdbcDriver
weblogic.jdbc.mssqlserver4.Driver
org.postgresql.Driver
The Java code to load the driver name is somewhat obscure, but let's take it for granted:
import java.sql.*;
import java.util.*;
try
{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
} catch (Exception e) {
// driver not found
e.printStackTrace();
}
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?ServiceName=<databaseName>
jdbc:derby:net://<host>:1527/<databaseName>
jdbc:db2://db2.bank11.com:50002/ccards
jdbc:oracle:thin:@loclahost:1521:ORCL
jdbc:postgresql://<host>:5432/<databaseName>
The second step in connecting to an existing database is to open the connection, by using the
connection URL.
Here is some sample code which shows how this is done:
String connURL = "jdbc:mysql://localhost:3306/ccards";
String user = "root";
String passwd = "root"
95
10 - JDBC
Connection conn = DriverManager.getConnection(connURL,
user, passwd);
Since we just used it, let's have a better look in the next section at the DriverManager class.
String passwd)
While the first two forms of getConnection() are pretty straightforward, let's see an example of
how to use the last of the three forms.
Properties prp = new Properties();
prp.put("autocommit", "true");
prp.put("create", "true");
Connection conn = DriverManager.getConnection(connURL, prp);
96
10 - JDBC
CallableStatement prepareCall(String sql)
throws SQLException
execute()
executeQuery()
executeUpdate()
addBatch()
executeBatch()
clearBatch()
setFetchSize()
getFetchSize()
setFetchDirection()
getFetchDirection()
getResultSet()
getResultSetConcurrency()
getResultSetType()
6. other methods:
setQueryTimeout()
getQueryTimeout()
setMaxFieldSize()
getMaxFieldSize()
97
10 - JDBC
cancel()
getConnection()
The Statement interfaces also support the same methods for transaction support as the
Connection objects.
Objects implementing the Connection interface are mainly used for SQL queries execution. Here
is a typical example:
Statement stmt = conn.createStatement();
String sqlString = "CREATE TABLE customer ...";
stmt.executeUpdate(sqlString);
getAsciiStream()
getBoolean()
getDate()
getInt()
getShort()
getTimeStamp()
getBinaryStream()
getBytes()
getFloat()
getObject()
getTime()
getString()
getByte()
getDouble()
getLong()
getBigDecimal()
getMetaData()
getClob()
getWarnings()
98
10 - JDBC
getBlob()
Most of these methods require the column index (which in SQL starts at 1, not at 0) or the
column name, as the argument.
The usage of these retrieval methods assumes the prior knowledge of the type and the index (or
name) of a particular column. What if we don't have this knowledge? Fortunately, all this data about
the DB schema (or metadata) can be retrieved using the ResultSetMetaData interface. The
invocation of the getMetaData() method of a ResultSet object returns an object of
ResultSetMetaData type.
Here are the most important methods specified by the ResultSetMetaData interface:
getCatalogName()
getTableName()
getSchemaName()
getColumnCount()
getColumnName()
getColumnLabel()
getColumnType()
getColumnTypeName()
getColumnClassName()
getColumnDisplaySize()
getScale()
getPrecision()
isNullable()
isCurrency()
isSearchable()
isCaseSensitive()
isSigned()
isAutoIncrement()
isReadOnly()
isDefinitelyWritable()
99
10 - JDBC
10.10.1 ResultSet types
The ResultSet type specifies the following about the ResultSet:
TYPE_FORWARD_ONLY
A cursor that can only be used to process from the beginning of a ResultSet to the end of it. This
is the default type.
TYPE_SCROLL_INSENSITIVE
A cursor that can be used to scroll in various ways through a ResultSet. This type of cursor is
insensitive to changes made to the database while it is open. It contains rows that satisfy the query
when the query was processed or when data is fetched.
TYPE_SCROLL_SENSITIVE
A cursor that can be used to scroll in various ways through a ResultSet. This type of cursor is
sensitive to changes made to the database while it is open. Changes to the database have a direct
impact on the ResultSet data.
JDBC 1.0 ResultSets are always forward only. Scrollable cursors were added in JDBC 2.0.
Note: The blocking enabled and block size connection properties affect the degree of sensitivity
of a TYPE_SCROLL_SENSITIVE cursor. Blocking enhances performance by caching data in the
JDBC driver layer itself.
10.10.2 Concurrency
Concurrency determines whether the ResultSet can be updated. The types are again defined by
constants in the ResultSet interface. The available concurrency settings are as follows:
CONCUR_READ_ONLY
A ResultSet that can only be used for reading data out of the database. This is the default
setting.
CONCUR_UPDATEABLE
A ResultSet that allows you to make changes to it. These changes can be placed into the
underlying database.
JDBC 1.0 ResultSets are always forward only. Updateable ResultSets were added in JDBC 2.0.
Note: According to the JDBC specification, the JDBC driver is allowed to change the ResultSet
type of the ResultSet concurrency setting if the values cannot be used together. In such cases, the
JDBC driver places a warning on the Connection object.
There is one situation where the application specifies a TYPE_SCROLL_INSENSITIVE,
CONCUR_UPDATEABLE ResultSet. Insensitivity is implemented in the database engine by
making a copy of the data. You are then not allowed to make updates through that copy to the
underlying database. If you specify this combination, the driver changes the sensitivity to
TYPE_SCROLL_SENSITIVE and create the warning indicating that your request has been
changed.
10.10.3 Holdability
The holdability characteristic determines whether calling commit on the Connection object closes
the ResultSet. The JDBC API for working with the holdability characteristic is new in version 3.0.
However, the native JDBC driver has provided a connection property for several releases that
allows you to specify that default for all ResultSets created under the connection. The API support
100
10 - JDBC
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
101
10 - JDBC
// Processes requests for both HTTP GET and POST methods.
protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.IOException {
String theCode = req.getParameter(CODE);
String sql = SELECT FIRST_NAME, LAST_NAME, ACCOUNT_NUM from CUSTOMERS
where CNP=+theCode+;;
try {
Statement stmt = conn.getStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String firstName = rs.getString(FIRST_NAME);
String lastName = rs.getString(LAST_NAME);
BigDecimal accountNum = rs.getBigDecimal(ACCOUNT_NUM);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter();
// output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet</title>");
out.println("</head>");
out.println("<body>");
...
out.println("</body>");
out.println("</html>");
out.close();
}
// Handles the HTTP GET method.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.IOException {
processRequest(req, resp);
}
// Handles the HTTP POST method.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.IOException {
processRequest(req, resp);
}
102
10 - JDBC
// Returns a short description of the servlet.
public String getServletInfo() {
return "Short description";
}
}
103
10 - JDBC
stmt.executeUpdate("CREATE TABLE customer (id int, firstName
varchar(32) lastName varchar(24))");
// set parameters for preparedStatement
pstmt.setInt(1, 1021);
pstmt.setString(2, "Vasile");
pstmt.setString(3, "Dumitrascu");
int count = pstmt.executeUpdate();
104
10 - JDBC
uprs.updateInt("TOTAL", 0);
uprs.insertRow();
uprs.beforeFirst();
System.out.println("Table COFFEES after insertion:");
while (uprs.next()) {
String name = uprs.getString("COF_NAME");
int id = uprs.getInt("SUP_ID");
float price = uprs.getFloat("PRICE");
int sales = uprs.getInt("SALES");
int total = uprs.getInt("TOTAL");
System.out.print(name + " " + id + " " + price);
System.out.println(" " + sales + " " + total);
}
uprs.close();
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
10.15 jdbc and sql types and their corresponding java classes
JDBC Type
Purpose
SQL Type
Java Type
ARRAY
SQL array
ARRAY
java.sql.Array
BIGINT
64 bit integer
BIGINT
long
BINARY
binary value
none
byte[]
BIT
BIT
boolean
BLOB
BLOB
java.sql.Blob
CHAR
char string
CHAR
String
CLOB
CLOB
java.sql.Clob
DATE
DATE
java.sql.Date
DECIMAL
decimal value
DECIMAL
DISTINCT
distinct
DISTINCT
none
DOUBLE
double precision
DOUBLE PRECISION
double
FLOAT
double precision
FLOAT
double
INTEGER
32 bit integer
INTEGER
int
JAVA_OBJECT
none
Object
java.math.Big
Decimal
105
10 - JDBC
JDBC Type
Purpose
SQL Type
Java Type
LONGVARBINARY
none
byte[]
LONGVARCHAR
none
String
NULL
null values
NULL
null
NUMERIC
decimal value
NUMERIC
OTHER
db specific types
none
Object
REAL
single precision
REAL
float
16 bit integer
SMALLINT
short
TIME
TIME
java.sql.Time
TIMESTAMP
TIMESTAMP
TINYINT
8 bit integer
TINYINT
short
none
byte[]
VARCHAR
String
java.math.Big
Decimal
REF
SMALLINT
STRUCT
VARBINARY
VARCHAR
java.sql.Timest
amp
106
10 - JDBC
public Connection getConnection() throws SQLException
public Connection getConnection(String user, String pwd)
SQLException
throws
107
10 - JDBC
public void doGet(HttpServletRequest request, HttpServletResponse
IOException, ServletException
{
...
}
}
response) throws
108
11 - JSP
11 - JSP
11.1 java server pages as part of web applications
A Java Server Page (JSP) is a standard HTML or XML file which contains new scripting tags.
A JSP is loaded by a JSP container and is converted to servlet code. If the JSP is modified, the
servlet code is regenerated.
The current JSP specification is JSP 2.1 and is related to the 2.5 Java Servlet specification. JSR
245 is the official document containing the current (and final) 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.
109
11 - JSP
First, the original index.jsp file.
<%-Document : index
Created on : 08.11.2010, 08:17:39
Author : sm
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
The generated servlet follows.
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.Vector _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
110
11 - JSP
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("X-Powered-By", "JSP/2.1");
pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector)
application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n");
out.write(" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write("
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write("
<title>JSP Page</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write("
<h1>Hello World!</h1>\n");
out.write(" </body>\n");
out.write("</html>\n");
} 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);
}
111
11 - JSP
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
A short comment. The class HttpJspBase is a vendor-implemented class, whose declaration
clarifies its relationship with the standard JSP classes and interfaces.
public abstract class HttpJspBase extends javax.servlet.http.HttpServlet implements
javax.servlet.jsp.HttpJspPage
112
11 - JSP
public String getSampleProperty() {
return sampleProperty;
}
public void setSampleProperty(String value) {
String oldValue = sampleProperty;
sampleProperty = value;
propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY, oldValue,
sampleProperty);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener(listener);
}
}
if the URL does not start with / , it is interpreted relative to the position of the current JSP
113
11 - JSP
<%@directive_name attr1="val1" ... attrn="valn" %>
There are three JSP directives: page, include and taglib.
The page directive format:
<%@page attr1="val1" ... %>
attributes:
info
The include directive instructs the container to include inline the content of the resource
specified by "fileName". The format of this directive:
<%@include file="fileName" %>
The taglib directive allows the usage of custom tags (tag extensions). It has the following format:
<%@taglib uri="tagLibUri" prefix="tagPrefix" %>
where the tagPrefix indicates a name scope.
114
11 - JSP
11.7.2 scriptlets
<% valid java statements %>
Block of java code which is executed during request processing. In Tomcat, this code goes to
inside the service() method.
11.7.3 expressions
<%= java expressions to be evaluated %>
A scriptlet that sends a value of a Java expression to back to the client. It is evaluated at request
processing time and the result is converted to a string which is then displayed.
class="className"
class="className" type="typeName"
beanName="beanName" type="typeName"
type="typeName"
115
11 - JSP
Used in conjunction with the <jsp:useBean> action to set the value of the bean properties.
The syntax for this action is:
<jsp:setProperty name="beanName" propertydetails />
where propertydetails is one of the following:
property="*"
property="propertyName"
property="propertyName" param="parameterName"
property="propertyName" value="propertyValue"
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
116
11 - JSP
<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.
The syntax for this action is:
<jsp:param name="paramName" value="paramValue" />
page - the URL of the page, same format as the <%@include> directive.
117
11 - JSP
...
</jsp:params>
</jsp:plugin>
Attributes description:
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.
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.
nspluginurl="URLToPlugin" - the URL where the user can download the JRE plugin for
Netscape Navigator. The value is a full URL, with a protocol name, optional port number,
and domain name.
iepluginurl="URLToPlugin"
118
11 - JSP
11.10 scopes
1. request - an object with request scope is bound to the HttpServletRequest object; the
object can be accessed by invoking the getAttribute() method on the implicit request
object; the generated servlet binds the object to HttpServletRequest object using the
setAttribute(String key, Object value) method
2. session - an object with session scope is bound to the HttpSession object; the object
can be accessed by invoking the getValue() method on the implicit session object; the
generated servlet binds the object to HttpSession object using the
setAttribute(String key, Object value) method
3. application - an object with application scope is bound to the ServletContext object;
the object can be accessed by invoking the getAttribute() method on the implicit
application object; the generated servlet binds the object to the ServletContext object
using the setAttribute(String key, Object value) method
4. page - an object with page scope is bound to the PageContext object; the object can be
accessed by invoking the getAttribute() method on the implicit pageContext object;
the generated servlet binds the object to PageContext object using the
setAttribute(String key, Object value) method
119
11 - JSP
120
11 - JSP
package com.devsphere.examples.mapping.simple;
// Simple bean
public class SimpleBean implements java.io.Serializable {
private String string;
private float number;
private int integer;
private boolean flag;
private String colors[];
private int list[];
private String optional;
private SimpleSubBean subBean;
// No-arg constructor
public SimpleBean() {
}
// Gets the string property
public String getString() {
return this.string;
}
// Sets the string property
public void setString(String value) {
this.string = value;
}
// Gets the number property
public float getNumber() {
return this.number;
}
// Sets the number property
public void setNumber(float value) {
this.number = value;
}
// Gets the integer property
public int getInteger() {
return this.integer;
}
// Sets the integer property
public void setInteger(int value) {
this.integer = value;
121
11 - JSP
}
// Gets the flag property
public boolean getFlag() {
return this.flag;
}
// Sets the flag property
public void setFlag(boolean value) {
this.flag = value;
}
// Gets the colors property
public String[] getColors() {
return this.colors;
}
// Sets the colors property
public void setColors(String values[]) {
this.colors = values;
}
// Gets an element of the colors property
public String getColors(int index) {
return this.colors[index];
}
// Sets an element of the colors property
public void setColors(int index, String value) {
this.colors[index] = value;
}
// Gets the list property
public int[] getList() {
return this.list;
}
// Sets the list property
public void setList(int values[]) {
this.list = values;
}
// Gets an element of the list property
public int getList(int index) {
return this.list[index];
}
122
11 - JSP
// Sets an element of the list property
public void setList(int index, int value) {
this.list[index] = value;
}
// Gets the optional property
public String getOptional() {
return this.optional;
}
// Sets the optional property
public void setOptional(String value) {
this.optional = value;
}
// Gets the subBean property
public SimpleSubBean getSubBean() {
return this.subBean;
}
// Sets the subBean property
public void setSubBean(SimpleSubBean value) {
this.subBean = value;
}
}
SimpleSubBean contains only two standard properties (a String and a float).
SimpleSubBean.java:
package com.devsphere.examples.mapping.simple;
// Simple sub-bean
public class SimpleSubBean implements java.io.Serializable {
private String string;
private float number;
// No-arg constructor
public SimpleSubBean() {
}
// Gets the string property
public String getString() {
return this.string;
}
123
11 - JSP
// Sets the string property
public void setString(String value) {
this.string = value;
}
// Gets the number property
public float getNumber() {
return this.number;
}
// Sets the number property
public void setNumber(float value) {
this.number = value;
}
}
Name
Property type
Element type
string
String
text
number
float
text
integer
int
radio[]
flag
boolean
checkbox
colors
String[]
checkbox[]
list
int[]
select
optional
String
text
subBean.string
String
text
subBean.number
float
text
SimpleForm.html:
<HTML>
<HEAD><TITLE>Simple form</TITLE></HEAD>
<BODY>
<H3>Simple Example</H3>
<FORM METHOD="POST">
<P> String <BR>
124
11 - JSP
<INPUT TYPE="TEXT" NAME="string" SIZE="20">
<P> Number <BR>
<INPUT TYPE="TEXT" NAME="number" SIZE="20">
<P> Integer <BR>
<INPUT TYPE="RADIO" NAME="integer" VALUE="1">Option 1
<INPUT TYPE="RADIO" NAME="integer" VALUE="2">Option 2
<INPUT TYPE="RADIO" NAME="integer" VALUE="3">Option 3
<P> Flag <BR>
<INPUT TYPE="CHECKBOX" NAME="flag">Flag
<P> Colors <BR>
<INPUT TYPE="CHECKBOX" NAME="colors" VALUE="red">Red
<INPUT TYPE="CHECKBOX" NAME="colors" VALUE="green">Green
<INPUT TYPE="CHECKBOX" NAME="colors" VALUE="blue">Blue
<P> List <BR>
<SELECT NAME="list" SIZE="3" MULTIPLE>
<OPTION VALUE="1">Item 1</OPTION>
<OPTION VALUE="2">Item 2</OPTION>
<OPTION VALUE="3">Item 3</OPTION>
</SELECT>
<P> Optional <BR>
<INPUT TYPE="TEXT" NAME="optional" SIZE="20">
<P> String (subBean) <BR>
<INPUT TYPE="TEXT" NAME="subBean.string" SIZE="20">
<P> Number (subBean) <BR>
<INPUT TYPE="TEXT" NAME="subBean.number" SIZE="20">
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>
125
11 - JSP
must be wrapped by a Float and a Boolean in order to be stored as resources. The default values
for the properties of the contained bean could have been defined in another resource bundle called
SimpleSubBeanResources.
There are three error messages. Their role is to help the users to correct the input errors. The
mapping framework contains default error messages for each type of form element.
The list of optional properties has a single element. No error is signaled if the user doesn't
provide a value for this property.
The processing order isn't necessary to this example. It has been included here just for
demonstrative purposes.
The form's name and the processor's name are used by the JSP handler described in the next
section. These two resources aren't accessed by the mapping utilities.
SimpleBeanResources.java:
package com.devsphere.examples.mapping.simple;
public class SimpleBeanResources extends java.util.ListResourceBundle {
private static final Object[][] contents = {
{ "[DEFAULT_VALUE.string]", "abc" },
{ "[DEFAULT_VALUE.number]", new Float(0.123) },
{ "[DEFAULT_VALUE.flag]", new Boolean(true) },
{ "[DEFAULT_VALUE.list]", new int[] { 2, 3 } },
{ "[ERROR_MESSAGE.integer]", "An option must be selected" },
{ "[ERROR_MESSAGE.colors]", "One or more colors must be selected" },
{ "[ERROR_MESSAGE.list]", "One or more items must be selected" },
{
"[OPTIONAL_PROPERTIES]",
new String[] {
"optional"
}
},
{
"[PROCESSING_ORDER]",
new String[] {
"string",
"number",
"integer",
"flag",
"colors",
"list",
"optional",
"subBean"
}
},
{ "[FORM_NAME]", "SimpleForm.html" },
{ "[PROC_NAME]", "SimpleProc.jsp" }
};
126
11 - JSP
public Object[][] getContents() {
return contents;
}
}
127
11 - JSP
if (isPostMethod && errorTable == null) {
// Construct the processor's path
String procPath = basePath + beanRes.getString("[PROC_NAME]").trim();
// Process the valid data bean instance
application.getRequestDispatcher(procPath).forward(request, response);
} else {
if (!isPostMethod)
// Ignore the user errors if the form is requested with GET.
errorTable = HandlerUtils.removeUserErrors(errorTable);
// Construct the form's path
String formPath = basePath + beanRes.getString("[FORM_NAME]").trim();
formPath = application.getRealPath(formPath);
// Get the form template
FormTemplate template = FormUtils.getTemplate(new java.io.File(formPath));
// Get a new document
FormDocument document = template.getDocument();
// Bean-to-form mapping: bean properties are mapped to form elements
FormUtils.beanToForm(simpleBean, errorTable, document, logger);
// Send the form document
document.send(out);
}
%>
128
11 - JSP
<P> colors = <%= toString(simpleBean.getColors()) %>
<P> list = <%= toString(simpleBean.getList()) %>
<P> optional = <jsp:getProperty name="simpleBean" property="optional"/>
<P> subBean.string = <%= simpleBean.getSubBean().getString() %>
<P> subBean.number = <%= simpleBean.getSubBean().getNumber() %>
</BODY>
</HTML>
<%!
public static String toString(String list[]) {
if (list == null || list.length == 0)
return "";
if (list.length == 1 && list[0] != null)
return list[0];
StringBuffer strbuf = new StringBuffer();
strbuf.append("{ ");
for (int i = 0; i < list.length; i++)
if (list[i] != null) {
strbuf.append(list[i]);
strbuf.append(" ");
}
strbuf.append("}");
return strbuf.toString();
}
public static String toString(int list[]) {
if (list == null || list.length == 0)
return "";
if (list.length == 1)
return Integer.toString(list[0]);
StringBuffer strbuf = new StringBuffer();
strbuf.append("{ ");
for (int i = 0; i < list.length; i++) {
strbuf.append(list[i]);
strbuf.append(" ");
}
strbuf.append("}");
return strbuf.toString();
}
%>
129
11 - JSP
debugging easier.
ComplexHndl.jsp uses 150 lines of Java-JSP mixture to set the properties of a bean object to the
values of the request parameters. This is the equivalent of a single FormUtils.formToBean() call.
The adding/removing of a bean property requires changes in both Complex*.jsp files. Using the
framework, you only have to add/remove a form element to/from a pure HTML file.
The localization of the Complex*.jsp files to other languages requires a lot of work and could
make the maintenance very hard. Using the framework you separate the HTML code from the
Java/JSP code. In addition, default values and error messages are kept in localizable resource
bundles. A later chapter shows how to build internationalized applications using the framework.
ComplexForm.jsp:
<%@ page language="java" %>
<jsp:useBean id="simpleBean" scope="request"
class="com.devsphere.examples.mapping.simple.SimpleBean"/>
<jsp:useBean id="errorTable" scope="request"
class="java.util.Hashtable"/>
<HTML>
<HEAD><TITLE>Without using the framework</TITLE></HEAD>
<BODY>
<H3>Equivalent of Simple Example</H3>
<FORM METHOD=POST>
<P> String <BR>
<%= getErrorMessage(errorTable, "string") %>
<INPUT TYPE="TEXT" NAME="string"
VALUE="<jsp:getProperty name="simpleBean" property="string"/>">
<P> Number <BR>
<%= getErrorMessage(errorTable, "number") %>
<INPUT TYPE="TEXT" NAME="number"
VALUE="<jsp:getProperty name="simpleBean" property="number"/>">
<P> Integer <BR>
<%= getErrorMessage(errorTable, "integer") %>
<%
String integerLabels[] = { "Option 1", "Option 2", "Option 3" };
for (int i = 0; i < integerLabels.length; i++) {
int value = i+1;
boolean checked = simpleBean.getInteger() == value;
%>
<INPUT TYPE="RADIO" NAME="integer" VALUE="<%= value %>"
<%= checked ? "CHECKED" : "" %>> <%= integerLabels[i] %>
<%
}
%>
<P> Flag <BR>
130
11 - JSP
<%= getErrorMessage(errorTable, "flag") %>
<INPUT TYPE="CHECKBOX" NAME="flag"
<%= simpleBean.getFlag() ? "CHECKED" : "" %>> Flag
<P> Colors <BR>
<%= getErrorMessage(errorTable, "colors") %>
<%
String colors[] = simpleBean.getColors();
if (colors == null)
colors = new String[0];
String colorLabels[] = { "Red", "Green", "Blue" };
String colorValues[] = { "red", "green", "blue" };
for (int i = 0; i < colorValues.length; i++) {
boolean checked = false;
if (colors != null)
for (int j = 0; j < colors.length; j++)
if (colors[j].equals(colorValues[i])) {
checked = true;
break;
}
%>
<INPUT TYPE="CHECKBOX" NAME="colors" VALUE="<%= colorValues[i] %>"
<%= checked ? "CHECKED" : "" %>> <%= colorLabels[i] %>
<%
}
%>
<P> List <BR>
<%= getErrorMessage(errorTable, "list") %>
<SELECT NAME="list" SIZE="3" MULTIPLE>
<%
int list[] = simpleBean.getList();
if (list == null)
list = new int[0];
String listItems[] = { "Item 1", "Item 2", "Item 3" };
for (int i = 0; i < listItems.length; i++) {
int value = i+1;
boolean selected = false;
if (list != null)
for (int j = 0; j < list.length; j++)
if (list[j] == value) {
selected = true;
break;
}
%>
<OPTION VALUE = "<%= value %>"
131
11 - JSP
<%= selected ? "SELECTED" : "" %>> <%= listItems[i] %>
<%
}
%>
</SELECT>
<P> Optional <BR>
<%= getErrorMessage(errorTable, "optional") %>
<INPUT TYPE="TEXT" NAME="optional"
VALUE="<jsp:getProperty name="simpleBean" property="optional"/>">
<% if (simpleBean.getSubBean() == null) simpleBean.setSubBean(
new com.devsphere.examples.mapping.simple.SimpleSubBean()); %>
<P> String (subBean) <BR>
<%= getErrorMessage(errorTable, "subBean.string") %>
<INPUT TYPE="TEXT" NAME="subBean.string"
VALUE="<%= simpleBean.getSubBean().getString() %>">
<P> Number (subBean) <BR>
<%= getErrorMessage(errorTable, "subBean.number") %>
<INPUT TYPE="TEXT" NAME="subBean.number"
VALUE="<%= simpleBean.getSubBean().getNumber() %>">
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</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"/>
132
11 - JSP
<jsp:useBean id="simpleSubBean" scope="page"
class="com.devsphere.examples.mapping.simple.SimpleSubBean"/>
<jsp:useBean id="errorTable" scope="request"
class="java.util.Hashtable"/>
<%
simpleBean.setSubBean(simpleSubBean);
boolean isPostMethod = request.getMethod().equals("POST");
if (isPostMethod) {
//* string : text
%>
<jsp:setProperty name="simpleBean" property="string"/>
<%
if (simpleBean.getString() == null
|| simpleBean.getString().length() == 0) {
simpleBean.setString("abc");
setErrorMessage(errorTable, "string", "Must be filled");
}
//* number : text
try {
String numberValue = request.getParameter("number");
if (numberValue != null && numberValue.length() != 0)
simpleBean.setNumber(new Float(numberValue).floatValue());
else {
simpleBean.setNumber(0.123f);
setErrorMessage(errorTable, "number", "Must be filled");
}
} catch (NumberFormatException e) {
simpleBean.setNumber(0.123f);
setErrorMessage(errorTable, "number", "Must be a number");
}
//* integer : radio group
%>
<jsp:setProperty name="simpleBean" property="integer"/>
<%
if (simpleBean.getInteger() == 0) {
setErrorMessage(errorTable, "integer", "An option must be selected");
}
//* flag : checkbox
133
11 - JSP
String flagValue = request.getParameter("flag");
if (flagValue != null) {
flagValue = flagValue.trim();
if (flagValue.length() == 0 || flagValue.equals("false"))
flagValue = null;
}
simpleBean.setFlag(flagValue != null);
//* color : checkbox group
%>
<jsp:setProperty name="simpleBean" property="colors"/>
<%
if (simpleBean.getColors() == null
|| simpleBean.getColors().length == 0) {
setErrorMessage(errorTable, "colors",
"One or more colors must be selected");
}
//* list : select
%>
<jsp:setProperty name="simpleBean" property="list"/>
<%
if (simpleBean.getList() == null
|| simpleBean.getList().length == 0) {
simpleBean.setList(new int[] { 2, 3 });
setErrorMessage(errorTable, "list",
"One or more items must be selected");
}
//* optional : text
%>
<jsp:setProperty name="simpleBean" property="optional"/>
<%
if (simpleBean.getOptional() == null)
simpleBean.setOptional("");
//* subBean.string : text
%>
<jsp:setProperty name="simpleSubBean" property="string"
param="subBean.string"/>
<%
134
11 - JSP
if (simpleSubBean.getString() == null
|| simpleSubBean.getString().length() == 0) {
simpleSubBean.setString("");
setErrorMessage(errorTable, "subBean.string", "Must be filled");
}
//* subBean.number : text
try {
String numberValue = request.getParameter("subBean.number");
if (numberValue != null && numberValue.length() != 0)
simpleSubBean.setNumber(new Float(numberValue).floatValue());
else {
setErrorMessage(errorTable, "subBean.number", "Must be filled");
}
} catch (NumberFormatException e) {
setErrorMessage(errorTable, "subBean.number", "Must be a number");
}
} else {
simpleBean.setString("abc");
simpleBean.setNumber(0.123f);
simpleBean.setFlag(true);
simpleBean.setList(new int[] { 2, 3 });
simpleBean.setOptional("");
simpleSubBean.setString("");
}
if (isPostMethod && errorTable.isEmpty()) {
%>
<jsp:forward page="SimpleProc.jsp"/>
<%
} else {
%>
<jsp:forward page="ComplexForm.jsp"/>
<%
}
%>
<%!
void setErrorMessage(java.util.Hashtable errorTable,
String property, String message) {
message = "<FONT COLOR=\"#FF0000\">" + message + "</FONT><BR>";
errorTable.put(property, message);
}
%>
135
11 - JSP
11.12.7 using the framework with servlets and JSPs
The SimpleHndl.jsp handler is basically a Java scriptlet. That was a simple and compact way to
present a handler. The Java code could easily be moved to a utility class. A more elegant solution
is the replacement of the JSP handler with a general Java servlet.
The com.devsphere.helpers.mapping package contains an abstract class called GenericHandler.
This class is extended by BeanDispatcher, which is the bean-independent equivalent of
SimpleHndl.jsp. The JSP handler can be replaced by only a few lines that are added to
servlets.properties or web.xml:
SimpleHndl.code=com.devsphere.helpers.mapping.BeanDispatcher
SimpleHndl.initparams=\
BEAN_NAME=com.devsphere.examples.mapping.simple.SimpleBean,\
BEAN_ID=simpleBean,\
BASE_PATH=/simple
or
<servlet>
<servlet-name>SimpleHndl</servlet-name>
<servlet-class>com.devsphere.helpers.mapping.BeanDispatcher</servlet-class>
<init-param>
<param-name>BEAN_NAME</param-name>
<param-value>com.devsphere.examples.mapping.simple.SimpleBean</param-value>
</init-param>
<init-param>
<param-name>BEAN_ID</param-name>
<param-value>simpleBean</param-value>
</init-param>
<init-param>
<param-name>BASE_PATH</param-name>
<param-value>/simple</param-value>
</init-param>
</servlet>
GenericHandler and BeanDispatcher were presented in a previous chapter.
136
11 - JSP
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
137
12 - javaserver faces
12 - JAVASERVER FACES
12.1 what are javaServer faces?
JavaServer Faces technology is a server-side user interface component framework for Java
based web applications. This technology includes:
1. A set of APIs for:
UI components management
events handling
input validation
error handling
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.
138
12 - javaserver faces
12.3 facelets
Facelet is a view technology for Java Server Faces (JSF) that allows building composite views
more quickly and easily than with JSP which is the default view technology for JSF. JSP pages are
compiled into servlets but its not the case with Facelets because Facelet pages are XML compliant
and its framework uses a fast SAXbased compiler to build views. Facelets can make changes to
pages immediately so developing JSF applications with Facelets is simply faster.
inputs
outputs
commands
selections
layouts
data table
column
commandButton
commandLink
dataTable
form
graphicImage
inputHidden
inputSecret
inputText
inputTextArea
message
messages
outputFormat
139
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" />
</f:facet>
140
12 - javaserver faces
<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/xwww-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}" />
141
12 - javaserver faces
HTML Output
<input id="form:button1" name="form:button1" type="submit"
Out" onclick="someEvent();" />
value="Check
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" />
actionListener
attribute
convertDateTime
converter
convertNumber
facet
loadBundle
142
12 - javaserver faces
param
selectItem
selectItems
subview
validateDoubleRange
validateLength
validateLongRange
validator
valueChangeListener
verbatim
view
12.5.2 f:facet
A facet represents a named section within a container component
The JSF facets specify the requirements and constraints that apply to a JSF project.
The Facet tag registers a named facet on the component associated with the enclosing tag. For
example, you can create a header and a footer facet for a dataTable component.
Example:
<h:dataTable id="reportTable" value="#{reportBean.dailyReport}"
var="item">
<h:column>
<f:facet name="header">
<h:outputText value="Daily Report" />
</f:facet>
<h:outputText value="#{item}" />
</h:column>
</h:dataTable>
HTML Output
<table id="reportTable">
<thead>
<tr><th>Daily Report</th></tr>
</thead>
<tbody>
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
</tbody>
</table>
12.5.3 f:validator
The Validator tag registers a named Validator instance on the component associated with the
143
12 - javaserver faces
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>
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
144
12 - javaserver faces
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!
145
12 - javaserver faces
/WEB-INF
/classes
/lib
jsf-impl.jar
jsf-api.jar
faces-config.xml
web.xml
/pages
Comments on this structure:
/ant directory containing Ant build scripts with a default build.xml file
/WebContent contains the Web application files used by the application server or by the
web container
/classes compiled Java classes and properties files copied from the /JavaSource
directory
/lib - contains libraries required by the application, like third party jar files
jsf-impl.jar, jsf-api.jar files included in the /lib directory, mandatory for any JSF
application
web.xml the deployment descriptor of the application, included in the /WEB-INF directory
146
12 - javaserver faces
12.7.1 creating JSP Pages
Create the inputname.jsp and greeting.jsp files in WebContent/pages/. You only need to
create the JSP files. The directory structure already exists.
These files will act as place holders for now. We will complete the content of the files a little bit
later.
Now that we have the two JSP pages, we can create a navigation rule.
12.7.2 navigation
Navigation is the heart of JavaServer Faces. The navigation rule for this application is described
in the faces-config.xml file. This file already exists in the skeleton directory structure. You just
need to create its contents.
In our application, we just want to go from inputname.jsp to greeting.jsp. As a diagram, it
would look something like this:
147
12 - javaserver faces
after the user clicks the submit button. This way the bean provides a bridge between the JSP page
and the application logic. (Please note that the field name in the JSP file must exactly match the
attribute name in the bean.)
12.7.3.1 PersonBean.java
Put this code in the file:
package myJFSapp;
public class PersonBean {
String personName;
/**
* @return Person Name
*/
public String getPersonName() {
return personName;
}
/**
* @param Person Name
*/
public void setPersonName(String name) {
personName = name;
}
}
Later you will see how to "connect" this bean with the JSP page.
12.7.3.3 faces-config.xml
Your final faces-config.xml file should look like this:
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<navigation-rule>
148
12 - javaserver faces
<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:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="myJFSapp.bundle.messages" var="msg"/>
<html>
<head>
<title>enter your name page</title>
149
12 - javaserver faces
</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.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="myJFSapp.bundle.messages" var="msg"/>
The first line of these three is a directive that tells us where to find JSF tags that define HTML
elements and the second directive tells us where to find JSF tags that define core JSF elements.
The third line loads our properties file (resource bundle) that holds messages that we want to
display in our JSP page.
<h:inputText value="#{msg.inputname_header}" required=true>
This tag simply tells us to look in the resource bundle that we defined at the top of the page. The
required attribute of the h:inputText tag insures that an empty name will not be sent. One can
also add a line like
<f:validateLength minimum="2" maximum="10"/>
to make sure that the length of this field is reasonable long.
Then, look up the value for inputname_header in that file and print it here.
1 <h:form id="helloForm">
2 <h:outputText value="#{msg.prompt}"/>
3 <h:inputText value="#{personBean.personName}" required=true>
4 <f:validateLength minimum="2" maximum="10"/>
5 </h:inputText>
6 <h:commandButton action="greeting" value="#{msg.button_text}" />
7 </h:form>
150
12 - javaserver faces
12.7.5.2 greeting.jsp
Put this coding inside the second JSP file:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="myJFSapp.bundle.messages" var="msg"/>
<html>
<head>
<title>greeting page</title>
</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!
151
12 - javaserver faces
Having an index.jsp file will allow us to start the application like this:
http://localhost:8080/myJFSapp/
Now, put this coding into the file:
<html>
<body>
<jsp:forward page="/pages/inputname.jsf" />
</body>
</html>
If you look at the path for the forward, you'll notice the file suffix is .jsf and not .jsp. This is used
here, because in the web.xml file for the application *.jsf is the URL pattern used to signal that
the forwarded page should be handled by the JavaServer Faces servlet within Tomcat.
We are almost done with this example.
12.7.7 Compiling
An Ant build script is provided for you. To build the application run the build.xml script from the
ant folder:
ant build
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).
152
12 - javaserver faces
12.8.1 Overview
This is a tutorial in which we create a simple JSF application to demonstrate FacesIDE's
functionality. This is a "login" application, which asks an user for an ID and password, verifies the
information, and forwards the user to a success or error page.
The application will use a few JSP pages with JSF elements, and a session-scoped managed
bean to coordinate their interactions. Along the way we'll use the following FacesIDE functionality:
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.
153
12 - javaserver faces
10.Set the output folder: in the Default output folder textbox at the bottom, enter jsflogin/webroot/WEB-INF/classes; click OK to dismiss the properties dialog.
Your folder structure should now be as follows:
jsf-login
|
+-- src
|
+-- webroot
|
+-- WEB-INF
|
|
|
+-- classes (not shown in Java perspective)
|
|
|
+-- lib
|
+-- pages
return action;
154
12 - javaserver faces
4. Use FacesIDE to configure the bean: we use a FacesIDE editor to configure
LoginManager as a session-scoped managed bean.
a. in Package Explorer select jsf-login/webroot/WEB-INF/facesconfig.xml; from its context menu select Open With/faces-config.xml Editor.
The faces-config.xml editor opens.
b. along the bottom of the editor there are 3 tabs; click Managed Bean.
c. click Add; input widgets appear
d. for name enter mgr; for class enter login.LoginManager; for scope select
session.
e. from the menubar select File/Save, then close the editor
155
12 - javaserver faces
<html>
<head>
<title>jsf-login</title>
</head>
<body>
<h2>Error!</h2>
The user-id and or password were invalid.
again.
</body>
</html>
Please try
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 /jsflogin/webroot/pages, and that Use MyFaces Tomahawk components and
Use MyFaces SandBox components are unchecked, and choose default for
Template; click Finish; the FacesIDE JSP Editor opens, with the following
template code.
<%@ page contentType="text/html; charset=Cp1252" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=Cp1252"/>
<title></title>
</head>
<body>
<f:view>
<h:form>
</h:form>
</f:view>
</body>
</html>
We will now edit this page to contain our input widgets, etc.
d. place the cursor between the <title></title> elements; enter jsf-login
e. Open the JSF palette, and dock it along the right. (See Show View Dialog)
f. create a few blank lines between the <h:form> elements; place your cursor in
one of these lines, expand the JSF HTML panel in the palette, and click on the
icon for <h:inputText>; this inserts the corresponding JSF element at the cursor
location.
Note: the JSP editor is aware of referenced tag libraries, and uses them for code
completion as well. Thus if you were to type <h: and hit CTRL + Spacebar, you
would get a popup window of JSF HTML elements.
g. now we want to add attributes to this element, and the JSP Editor can help with
code- completion. To see this in action, place the cursor inside the <h:inputText>
element, and hit CTRL + Spacebar; a code-completion window pops up, as shown
below.
156
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:
157
12 - javaserver faces
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<title>jsf-title</title>
</head>
<body>
<f:view>
<h:form>
UserID: <h:inputText value="#{mgr.userID}"/>
<br/>Password: <h:inputText
value="#{mgr.password}"/>
<br/><h:commandButton value="Login"
action="#{mgr.loginAction}"/>
</h:form>
</f:view>
</body>
</html>
158
12 - javaserver faces
Note that the icon has a small triangle overlay--this indicates that something is wrong,
specifically that FacesIDE could not locate a page at path /page1.jsp
4. in the Properties view, change the value of path to /index.jsp. You can also change it
on the diagram directly (select the page and click once more); notice that the warning
triangle disappears.
5. add 3 more pages, and set them to /pages/login.jsp, /pages/success.jsp and
/pages/error.jsp. Arrange them as shown below:
159
12 - javaserver faces
7. in the Properties view (or direct editing on the diagram), change the value of fromoutcome 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 fromoutcome 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.
160
12 - javaserver faces
12.8.7 Deploying To Tomcat 5.0
1. start Tomcat; open its Manager application in a browser; the default URL for this is
http://localhost:8080/manager/html
2. scroll down to Deploy; we'll deploy our app by providing its directory; for Context path
enter /jsf-login; for WAR or Directory URL enter the path to webroot, as
file:///...; leave XML Configuration File URL blank; click Deploy
3. the Manager application should reload, and you should see /jsf-login in the list of
running applications. Click on its link to launch the application.
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
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.
161
12 - javaserver faces
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 none of the above steps yield a match, the JavaServer Faces implementation specific
class is used.
Application - A set of APIs for representing UI components and managing their state,
handling events and input validation, defining page navigation, and supporting
internationalization and accessibility.
ApplicationFactory - a factory object that creates (if needed) and returns Application
instances. Implementations of JavaServer Faces must provide at least a default
implementation of Application.
StateManager - directs the process of saving and restoring the view between requests.
162
12 - javaserver faces
wrapped ViewHandler.
StateHolder - interface implemented by classes that need to save their state between
requests.
The classes in this package are all UI related. Here they are:
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.
163
12 - javaserver faces
data in the data model, the object for the current row is exposed as a request attribute
under the key specified by the var property.
UIForm - a UIComponent that represents an input form to be presented to the user, and
whose child components represent (among other things) the input fields to be included
when the form is submitted.
UIGraphic - a UIComponent that displays a graphical image to the user. The user cannot
manipulate this component; it is for display purposes only.
UIInput - a UIComponent that represents a component that both displays output to the
user (like UIOutput components do) and processes request parameters on the
subsequent request that need to be decoded.
UIMessages - The renderer for this component is responsible for obtaining the messages
from the FacesContext and displaying them to the user.
UIOutput - a UIComponent that has a value, optionally retrieved from a model tier bean
via a value binding expression, that is displayed to the user. The user cannot directly
modify the rendered value; it is for display purposes only.
UISelectMany - a UIComponent that represents the user's choice of a zero or more items
from among a discrete set of available options. The user can modify the selected values.
Optionally, the component can be preconfigured with zero or more currently selected items,
by storing them as an array in the value property of the component.This component is
generally rendered as a select box or a group of checkboxes.
UISelectOne - a UIComponent that represents the user's choice of zero or one items
from among a discrete set of available options. The user can modify the selected value.
Optionally, the component can be preconfigured with a currently selected item, by storing it
as the value property of the component.
UIViewRoot - the UIComponent that represents the root of the UIComponent tree. This
component has no rendering, it just serves as the root of the component tree.
164
12 - javaserver faces
HtmlForm - represents an HTML form element. Child input components will be submitted
unless they have been disabled.
HtmlPanelGrid - renders child components in a table, starting a new row after the
specified number of columns.
165
12 - javaserver faces
an HTML select element, showing either all available options or the specified number of
options.
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.
BigDecimalConverter
166
12 - javaserver faces
BigIntegerConverter
BooleanConverter
ByteConverter
CharacterConverter
DateTimeConverter
DoubleConverter
EnumConverter
FLoatConverter
IntegerConverter
LongConverter
NumberConverter
ShortConverter
Exceptions:
167
12 - javaserver faces
resolved against a base object.
FacesListener - a generic base interface for event listeners for various types of
FacesEvents.
Classes:
FacesEvent - the base class for user interface and application events that can be fired by
UIComponents.
PhaseId - typesafe enumeration of the legal values that may be returned by the
getPhaseId() method of the FacesEvent interface.
ValueChangeEvent - a notification that the local value of the source component has been
change as a result of user interface activity.
168
12 - javaserver faces
DataModel - an abstraction around arbitrary data binding technologies that can be used to
adapt a variety of data sources for use by JavaServer Faces components that support perrow processing for their child components (such as UIData).
SelectItem - represents a single item in the list of supported items associated with a
UISelectMany or UISelectOne component.
Renderer - converts the internal representation of UIComponents into the output stream
(or writer) associated with the response we are creating for a particular request. Each
Renderer knows how to render one or more UIComponent types (or classes), and
advertises a set of render-dependent attributes that it recognizes for each supported
UIComponent.
169
12 - javaserver faces
AttributeTag - Tag implementation that adds an attribute with a specified name and String
value to the component whose tag it is nested inside, if the component does not already
contain an attribute with the same name.
ConverterTag - a base class for all JSP custom actions that create and register a
Converter instance on the ValueHolder associated with our most immediate
surrounding instance of a tag whose implementation class is a subclass of
UIComponentTag.
FacesServlet - a servlet that manages the request processing lifecycle for web
applications that are utilizing JavaServer Faces to construct the user interface.
UIComponentTag - the base class for all JSP custom actions that correspond to user
interface components in a page that is rendered by JavaServer Faces.
ValidatorTag - a base class for all JSP custom actions that create and register a
Validator instance on the EditableValueHolder associated with our most
170
12 - javaserver faces
immediate surrounding instance of a tag whose implementation class is a subclass of
UIComponentTag.
Of course, you can also have a non-JSF request that generates a non-JSF response. Because
this does not involve JSF in any way, the JSF life cycle does not apply.
JSP pages have a relatively simple life cycle. A JSP page source is compiled into a page
implementation class. When a web server receives a request, that request is passed to the
container, which passes the request to the page class. The page class processes the request and
then writes the response back to the client. When other pages are included or the request is
forwarded, or when an exception occurs, the process includes a few more components or pages,
but basically, a small set of classes processes a request and sends back a response.
When using JSF, the life cycle is more complicated. This is because the core of JSF is the MVC
pattern, which has several implications. User actions in JSF-generated views take place in a client
that does not have a permanent connection to the server. The delivery of user actions or page
events is delayed until a new connection is established. The JSF life cycle must handle this delay
between event and event processing. Also, the JSF life cycle must ensure that the view is correct
before rendering the view. To ensure that the business state is never invalid, the JSF system
includes a phase for validating inputs and another for updating the model only after all inputs pass
validation.
In MVC, the presentation of data (the view) is separate from its representation in the system (the
model). When the model is updated, the controller sends a message to the view, telling the view to
update its presentation. When the user takes some action with the presentation, the controller
sends a message to the model, telling the model to update its data. In JSF, the model is composed
of business objects that are usually implemented as JavaBeans, the controller is the JSF
implementation, and the UI components are the view.
The JSF life cycle has six phases as defined by the JSF specification:
Restore View: In this phase, the JSF implementation restores the objects and data structures
that represent the view of the request. If this is the clients first visit to a page, the JSF
implementation must create the view. When a JSF implementation creates and renders a JSFenabled page, it creates UI objects for each view component. The components are stored in a
component tree, and the state of the UI view is saved for subsequent requests. If this is a
subsequent request, the saved UI view is retrieved for the processing of the current request.
Apply Request Values: Any data that was sent as part of the request is passed to the
appropriate UI objects that compose the view. These objects update their state with the data
values. Data can come from input fields in a web form, from cookies sent as part of the request, or
from request headers. Data for some components, such as components that create HTML input
fields, is validated at this time. Note that this does not yet update the business objects that
compose the model. It updates only the UI components with the new data.
171
12 - javaserver faces
Process Validations: The data that was submitted with the form is validated (if it was not
validated in the previous phase). As with the previous phase, this does not yet update the business
objects in the application. This is because if the JSF implementation began to update the business
objects as data was validated, and a piece of data failed validation, the model would be partially
updated and in an invalid state.
Update Model Values: After all validations are complete, the business objects that make up
the application are updated with the validated data from the request. In addition, if any of the data
needs to be converted to a different format to update the model (for example, converting a String to
a Date object), the conversion occurs in this phase. Conversion is needed when the data type of a
property is not a String or a Java primitive.
Invoke Application: During this phase, the action method of any command button or link that
was activated is called. In addition, any events that were generated during previous phases and
that have not yet been handled are passed to the web application so that it can complete any other
processing of the request that is required.
Render Response: The response UI components are rendered, and the response is sent to
the client. The state of the UI components is saved so that the component tree can be restored
when the client sends another request. For a JSF-enabled application, the thread of execution for a
request/response cycle can flow through each phase, in the order listed here and as shown in the
figure below. However, depending on the request, and what happens during the processing and
response, not every request will flow through all six phases.
In the above figure, you can see a number of optional paths through the life cycle. For example,
if errors occur during any of the phases, the flow of execution transfers immediately to the Render
Response phase, skipping any remaining phases. One way this might occur is if input data is
incorrect or invalid. If data fails validation in either the Apply Request Values or Process Validations
phase, information about the error is saved and processing proceeds directly to the Render
Response phase. Also, if at any point in the life cycle the request processing is complete and a
non-JSF response is to be sent to the client, the flow of execution can exit the life cycle without
completing further phases.
172
13 - WebSocket
13 - WEBSOCKET
13.1 the WebSocket API
WebSocket is an application protocol that provides full-duplex communications between two
peers over the TCP protocol.
In the traditional request-response model used in HTTP, the client requests resources and the
server provides responses. The exchange is always initiated by the client; the server cannot send
any data without the client requesting it first. This model worked well for the World Wide Web when
clients made occasional requests for documents that changed infrequently, but the limitations of
this approach are increasingly relevant as content changes quickly and users expect a more
interactive experience on the web. The WebSocket protocol addresses these limitations by
providing a full-duplex communication channel between the client and the server. Combined with
other client technologies, such as JavaScript and HTML5, WebSocket enables web applications to
deliver a richer user experience. The WebSocket API is defined in JSR-356.
173
13 - WebSocket
operation to the value of the Sec-WebSocket-Key header, and the connection is established
successfully if the result matches the value received from the server. The client and the server can
send messages to each other after a successful handshake.
WebSocket supports text messages (encoded as UTF-8) and binary messages. The control
frames in WebSocket are close, ping, and pong (a response to a ping frame). Ping and pong
frames may also contain application data. WebSocket endpoints are represented by URIs that
have the following form:
ws://host:port/path?query
wss://host:port/path?query
The ws scheme represents an unencrypted WebSocket connection, and the wss scheme
represents an encrypted connection. The port component is optional; the default port number is 80
for unencrypted connections and 443 for encrypted connections. The path component indicates the
location of an endpoint within a server. The query component is optional.
Modern web browsers implement the WebSocket protocol and provide a JavaScript API to
connect to endpoints, send messages, and assign callback methods for WebSocket events (such
as opened connections, received messages, and closed connections).
174
13 - WebSocket
public class EchoEndpoint extends Endpoint {
@Override
public void onOpen(final Session session, EndpointConfig config {
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
}
});
}
}
This endpoint echoes every message received. The Endpoint class defines three lifecycle
methods: onOpen, onClose, and onError. The EchoEndpoint class implements the onOpen
method, which is the only abstract method in the Endpoint class.
The Session parameter represents a conversation between this endpoint and the remote
endpoint. The addMessageHandler method registers message handlers, and the
getBasicRemote method returns an object that represents the remote endpoint. The Session
interface is covered in detail in the rest of this chapter.
The message handler is implemented as an anonymous inner class. The onMessage method of
the message handler is invoked when the endpoint receives a text message.
To deploy this programmatic endpoint, use the following code in your Java EE application:
ServerEndpointConfig.Builder.create(EchoEndpoint.class,
"/echo").build();
When you deploy your application, the endpoint is available at
ws://<host>:<port>/<application>/echo;
for example,
ws://localhost:8080/echoapp/echo.
175
13 - WebSocket
} catch (IOException e) { ... }
}
}
The annotated endpoint is simpler than the equivalent programmatic endpoint, and it is deployed
automatically with the application to the relative path defined in the ServerEndpoint annotation.
Instead of having to create an additional class for the message handler, this example uses the
OnMessage annotation to designate the method invoked to handle messages.
The table below lists the annotations available in the javax.websocket package to designate
the methods that handle lifecycle events. The examples in the table show the most common
parameters for these methods. See the API reference for details on what combinations of
parameters are allowed in each case.
WebSocket Endpoint Lifecycle Annotations
Annotation
Event
OnOpen
OnMessage
OnError
OnClose
Example
176
13 - WebSocket
method return RemoteEndpoint.Basic and RemoteEndpoint.Async objects
respectively. The RemoteEndpoint.Basic interface provides blocking methods to send
messages; the RemoteEndpoint.Async interface provides non-blocking methods.
3. Use the RemoteEndpoint object to send messages to the peer.
The following list shows some of the methods you can use to send messages to the peer:
177
13 - WebSocket
}
@OnMessage
public void binaryMessage(Session session, ByteBuffer msg) {
System.out.println("Binary message: " + msg.toString());
}
@OnMessage
public void pongMessage(Session session, PongMessage msg) {
System.out.println("Pong message: " +
msg.getApplicationData().toString());
}
178
13 - WebSocket
return msgAJsonString;
}
}
And similarly for Encoder.Text<MessageB>. Then, add the encoders parameter to the
ServerEndpoint annotation as follows:
@ServerEndpoint(
value = "/myendpoint",
encoders = { MessageATextEncoder.class, MessageBTextEncoder.class }
)
public class EncEndpoint { ... }
Now you can send MessageA and MessageB objects as WebSocket messages using the
sendObject method as follows:
MessageA msgA = new MessageA(...);
MessageB msgB = new MessageB(...);
session.getBasicRemote.sendObject(msgA);
session.getBasicRemote.sendObject(msgB);
As in this example, you can have more than one encoder for text messages and more than one
encoder for binary messages. Like endpoints, encoder instances are associated with one and only
one WebSocket connection and peer, so there is only one thread executing the code of an encoder
instance at any given time.
179
13 - WebSocket
public Message decode(String string) throws DecodeException {
// Read message...
if ( /* message is an A message */ )
return new MessageA(...);
else if ( /* message is a B message */ )
return new MessageB(...);
}
@Override
public boolean willDecode(String string) {
// Determine if the message can be converted into either a
// MessageA object or a MessageB object...
return canDecode;
}
}
Then, add the decoder parameter to the ServerEndpoint annotation as follows:
@ServerEndpoint(
value = "/myendpoint",
encoders = { MessageATextEncoder.class, MessageBTextEncoder.class },
decoders = { MessageTextDecoder.class }
)
public class EncDecEndpoint { ... }
Now define a method in the endpoint class that receives MessageA and MessageB objects as
follows:
@OnMessage
public void message(Session session, Message msg) {
if (msg instanceof MessageA) {
// We received a MessageA object...
else if (msg instanceof MessageB) {
// We received a MessageB object...
}
}
Like endpoints, decoder instances are associated with one and only one WebSocket connection
and peer, so there is only one thread executing the code of a decoder instance at any given time.
180
13 - WebSocket
13.8.1 Architecture of the dukeetf2 Sample Application
The dukeetf2 example application consists of a WebSocket endpoint, an enterprise
bean, and an HTML page:
The endpoint accepts connections from clients and sends them updates when new data for
price and trading volume becomes available.
The enterprise bean updates the price and volume information once every second.
The HTML page uses JavaScript code to connect to the WebSocket endpoint, parse
incoming messages, and update price and volume information without reloading the page.
181
13 - WebSocket
public void closedConnection(Session session) {
/* Remove this connection from the queue */
queue.remove(session);
}
@OnError
public void error(Session session, Throwable t) {
/* Remove this connection from the queue */
queue.remove(session);
logger.log(Level.INFO, "Connection error.");
}
}
182
13 - WebSocket
<html xmlns="http://www.w3.org/1999/xhtml">
<head>...</head>
<body onload="makeAjaxRequest();">
<table>
...
<td id="price">--.--</td>
...
<td id="volume">--</td>
...
</table>
</body>
</html>
The JavaScript code uses the WebSocket API to connect to the server endpoint and to
designate a callback method for incoming messages. The callback method updates the page with
the new information.
var wsocket;
function connect() {
wsocket = new WebSocket("ws://localhost:8080/dukeetf2/dukeetf");
wsocket.onmessage = onMessage;
}
function onMessage(evt) {
var arraypv = evt.data.split(",");
document.getElementById("price").innerHTML = arraypv[0];
document.getElementById("volume").innerHTML = arraypv[1];
}
window.addEventListener("load", connect, false);
The WebSocket API is supported by most modern browsers, and it is widely used in HTML5 web
client development.
183
14 - JSON processing
14 - JSON PROCESSING
14.1 JSON
JSON is a text-based data exchange format derived from JavaScript that is used in web
services and other connected applications. The following sections provide an introduction to JSON
syntax, an overview of JSON uses, and a description of the most common approaches to generate
and parse JSON.
"postalCode": "12345",
"phoneNumbers": [
{ "Mobile": "111-111-1111" },
{ "Home": "222-222-2222" }
]
Objects are enclosed in braces ({}), their name-value pairs are separated by a comma (,),
and the name and value in a pair are separated by a colon (:). Names in an object are
strings, whereas values may be of any of the six data types, including another object or an
array.
Arrays are enclosed in brackets ([]), and their values are separated by a coma (,). Each
value in an array may be of a different type, including another array or an object.
When objects and arrays contain other objects or arrays, the data has a tree-like structure.
184
14 - JSON processing
data is the following:
Content-Type: application/json
JSON representations are usually more compact than XML representations because JSON does
not have closing tags. Unlike XML, JSON does not have a widely accepted schema for defining
and validating the structure of JSON data.
The javax.json package contains a reader interface, a writer interface, and a model builder
interface for the object model. This package also contains other utility classes and Java
types for JSON elements.
The javax.json.stream package contains a parser interface and a generator interface for
the streaming model.
Table 141 Main classes and interfaces in javax.json
Class or Interface
Description
Json
JsonReader
185
14 - JSON processing
JsonArrayBuilder
JsonWriter
JsonValue
JsonStructure
JsonObject
JsonArray
JsonString
JsonNumber
JsonException
Description
JsonParser
JsonGenerator
186
14 - JSON processing
14.3.2 Creating an Object Model from Application Code
The following code demonstrates how to create an object model from application code:
import javax.json.Json;
import javax.json.JsonObject;
...
JsonObject model = Json.createObjectBuilder()
.add("firstName", "Duke")
.add("lastName", "Java")
.add("age", 18)
.add("streetAddress", "100 Internet Dr")
.add("city", "JavaTown")
.add("state", "JA")
.add("postalCode", "12345")
.add("phoneNumbers", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "mobile")
.add("number", "111-111-1111"))
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "222-222-2222")))
.build();
The object reference model represents the top of the tree, which is created by nesting calls to
the add methods and built by calling the build method. The JsonObjectBuilder class
contains the following add methods:
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
JsonObjectBuilder
The JsonArrayBuilder class contains similar add methods that do not have a name (key)
parameter. You can nest arrays and objects by passing a new JsonArrayBuilder object or a
new JsonObjectBuilder object to the corresponding add method as shown in this example.
The resulting tree represents the JSON data from JSON Syntax.
187
14 - JSON processing
import javax.json.JsonValue;
import javax.json.JsonObject;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonString;
...
public static void navigateTree(JsonValue tree, String key) {
if (key != null)
System.out.print("Key " + key + ": ");
switch(tree.getValueType()) {
case OBJECT:
System.out.println("OBJECT");
JsonObject object = (JsonObject) tree;
for (String name : object.keySet())
navigateTree(object.get(name), name);
break;
case ARRAY:
System.out.println("ARRAY");
JsonArray array = (JsonArray) tree;
for (JsonValue val : array)
navigateTree(val, null);
break;
case STRING:
JsonString st = (JsonString) tree;
System.out.println("STRING " + st.getString());
break;
case NUMBER:
JsonNumber num = (JsonNumber) tree;
System.out.println("NUMBER " + num.toString());
break;
case TRUE:
case FALSE:
case NULL:
System.out.println(tree.getValueType().toString());
break;
}
}
The method navigateTree can be used with the models built in Creating an Object Model
from JSON Data and Creating an Object Model from Application Code as follows:
navigateTree(model, null);
The navigateTree method takes two arguments: a JSON element and a key. The key is only
used to help print the key-value pairs inside objects. Elements in a tree are represented by the
JsonValue type. If the element is an object or an array, a new call to this method is made for every
element contained in the object or array. If the element is a value, it is printed to the standard
output.
188
14 - JSON processing
The JsonValue.getValueType() method identifies the element as an object, an array, or a value.
For objects, the JsonObject.keySet() method returns a set of strings that
contains the keys in the object, and the JsonObject.get(String name) method returns the value of
the element whose key is name. For arrays, JsonArray implements the List<JsonValue> interface.
You can use enhanced for loops with the Set<String> instance returned by JsonObject.keySet()
and with instances of JsonArray as shown in this example.
The output of the navigateTree method for the model built in Creating an Object Model from
Application Code is the following:
OBJECT
Key firstName: STRING Duke
Key lastName: STRING Java
Key age: NUMBER 18
Key streetAddress: STRING 100 Internet Dr
Key city: STRING JavaTown
Key state: STRING JA
Key postalCode: STRING 12345
Key phoneNumbers: ARRAY
OBJECT
Key type: STRING mobile
Key number: STRING 111-111-1111
OBJECT
Key type: STRING home
Key number: STRING 222-222-2222
189
14 - JSON processing
String jsonData = stWriter.toString();
System.out.println(jsonData);
190
14 - JSON processing
advances it to the next event. For the event types KEY_NAME, VALUE_STRING, and
VALUE_NUMBER, you can obtain the content of the element by calling the method
JsonParser.getString(). For VALUE_NUMBER events, you can also use the methods
JsonParser.getNumberType(), JsonParser.getIntValue(),
JsonParser.getLongValue(), and JsonParser.getBigDecimalValue(). See the JSR353 API reference for more information.
The output of this example is the following:
START_OBJECT
KEY_NAME firstName - VALUE_STRING Duke
KEY_NAME lastName - VALUE_STRING Java
KEY_NAME age - VALUE_NUMBER 18
KEY_NAME streetAddress - VALUE_STRING 100 Internet Dr
KEY_NAME city - VALUE_STRING JavaTown
KEY_NAME state - VALUE_STRING JA
KEY_NAME postalCode - VALUE_STRING 12345
KEY_NAME phoneNumbers - START_ARRAY
START_OBJECT
KEY_NAME type - VALUE_STRING mobile
KEY_NAME number - VALUE_STRING 111-111-1111
END_OBJECT
START_OBJECT
KEY_NAME type - VALUE_STRING home
KEY_NAME number - VALUE_STRING 222-222-2222
END_OBJECT
END_ARRAY
END_OBJECT
191
14 - JSON processing
.write("number", "222-222-2222")
.writeEnd()
.writeEnd()
.writeEnd();
gen.close();
This example obtains a JSON generator by calling the Json.createGenerator static
method, which takes a writer or an output stream as a parameter. The example writes JSON data
to the test.txt file by nesting calls to the write, writeStartArray, writeStartObject,
and writeEnd methods. The JsonGenerator.close method closes the underlying writer or
output stream.
The modelcreated.xhtml page contains a text area that displays JSON data.
The parsejson.xhtml page contains a table that shows the elements of the object
model.
2. The ObjectModelBean.java managed bean, which is a session bean that stores the
data from the form and directs the navigation between the JSF pages. This file also
contains code that uses the JSON object model API.
The code used in ObjectModelBean.java to create an object model from the data in the
form is similar to the example in Creating an Object Model from Application Code. The code to
192
14 - JSON processing
write JSON output from the model is similar to the example in Writing an Object Model to a
Stream. The code to navigate the object model tree is similar to the example in Navigating an
Object Model.
The filewritten.xhtml page contains a text area that displays JSON data.
The parsed.xhtml page contains a table that lists the events from the parser.
2. The StreamingBean.java managed bean, which is a session bean that manages the
data from the form and the navigation between the JSF pages. This file also contains code
that uses the JSON streaming API.
The code used in StreamingBean.java to write JSON data to a file is similar to the example
in Writing JSON Data Using a Generator. The code to parse JSON data from a file is similar to the
example in Reading JSON Data Using a Parser.
193
14 - JSON processing
4. Click Open Project.
5. In the Projects tab, right-click the jsonpstreaming project and select Run.
This command builds and packages the application into a WAR file (jsonpstreaming.war)
located in the target/ directory, deploys it to the server, and opens a web browser window with
the following URL:
http://localhost:8080/jsonpstreaming/faces/index.xhtml
194
15 - JNDI
15 - JNDI
15.1 what is JNDI?
JNDI is an API specified in Java technology that provides naming and directory functionality to
applications written in the Java programming language. It is designed especially for the Java
platform using Java's object model. Using JNDI, applications based on Java technology can store
and retrieve named Java objects of any type. In addition, JNDI provides methods for performing
standard directory operations, such as associating attributes with objects and searching for objects
using their attributes.
JNDI is also defined independent of any specific naming or directory service implementation. It
enables applications to access different, possibly multiple, naming and directory services using a
common API. Different naming and directory service providers can be plugged in seamlessly
behind this common API. This enables Java technology-based applications to take advantage of
information in a variety of existing naming and directory services, such as LDAP, NDS, DNS, and
NIS(YP)(Network Information Service), as well as enabling the applications to coexist with legacy
software and systems.
15.2.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.
195
15 - JNDI
The Lightweight Directory Access Protocol (LDAP) naming convention orders components from
right to left, delimited by the comma character (","). Thus the LDAP name cn=Rosanna Lee,
o=Sun, c=US names an LDAP entry cn=Rosanna Lee, relative to the entry o=Sun, which in
turn, is relative to c=us. The LDAP has the further rule that each component of the name must be
a name/value pair with the name and value separated by an equals character ("=").
15.2.2 bindings
The association of a name with an object is called a binding. For example, a file name is bound
to a file.
The DNS contains bindings that map machine names to IP addresses. An LDAP name is bound
to an LDAP entry.
15.2.4 context
A context is a set of name-to-object bindings. Every context has an associated naming
convention. A context provides a lookup (resolution) operation that returns the object and may
provide operations such as those for binding names, unbinding names, and listing bound names. A
name in one context object can be bound to another context object (called a subcontext) that has
the same naming convention.
For example, a file directory, such as /usr, in the UNIX file system is a context. A file directory
named relative to another file directory is a subcontext (some UNIX users refer to this as a
subdirectory). That is, in a file directory /usr/bin, the directory bin is a subcontext of usr. In
another example, a DNS domain, such as COM, is a context. A DNS domain named relative to
another DNS domain is a subcontext. For example, in the DNS domain Sun.COM, the DNS domain
Sun is a subcontext of COM.
Finally, an LDAP entry, such as c=us, is a context. An LDAP entry named relative to another
LDAP entry is a subcontext. For example, in the an LDAP entry o=sun,c=us, the entry o=sun is a
subcontext of c=us.
If we imagine all the resources available for us as a collection of rooted trees, one context can be
196
15 - JNDI
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).
15.3.1 attributes
A directory object can have attributes. For example, a printer might be represented by a directory
object that has as attributes its speed, resolution, and color. A user might be represented by a
directory object that has as attributes the user's e-mail address, various telephone numbers, postal
mail address, and computer account information.
An attribute has an attribute identifier and a set of attribute values. An attribute identifier is a
token that identifies an attribute independent of its values. For example, two different computer
accounts might have a "mail" attribute; "mail" is the attribute identifier. An attribute value is the
contents of the attribute. The email address, for example, might have an attribute identifier of
"mail" and the attribute value of "john.smith@somewhere.com".
197
15 - JNDI
operations for creating, adding, removing, and modifying the attributes associated with objects in a
directory. The service is accessed through its own interface.
Many examples of directory services are possible. The Novell Directory Service (NDS) is a
directory service from Novell that provides information about many networking services, such as
the file and print services. Network Information Service (NIS) is a directory service available on the
Solaris operating system for storing system-related information, such as that relating to machines,
networks, printers, and users. The SunONE Directory Server is a general-purpose directory service
based on the Internet standard LDAP.
15 - JNDI
repository for Java objects, that is to store and retrieve Java objects. For example, a Java print
client program should be able to look up a printer object from the directory and send a data stream
to the printer object for printing.
15.5.1 architecture
The JNDI architecture consists of an API and a service provider interface (SPI). Java
applications use the JNDI API to access a variety of naming and directory services. The SPI
enables a variety of naming and directory services to be plugged in transparently, thereby allowing
the Java application using the JNDI API to access their services.
15.5.2 packaging
The JNDI is included in the Java 2 SDK, v1.3 and later releases. It extends the v1.1 and v1.2
platforms to provide naming and directory functionality.
To use the JNDI, you must have the JNDI classes and one or more service providers. The Java
2 SDK, v1.3 includes three service providers for the following naming/directory services:
Common Object Request Broker Architecture (CORBA) Common Object Services (COS)
name service
Other service providers can be downloaded from the JNDI Web site or obtained from other
vendors. When using the JNDI as a Standard Extension on the JDK 1.1 and Java 2 SDK, v1.2, you
must first download the JNDI classes and one or more service providers.
The JNDI is divided into five packages:
javax.naming
javax.naming.directory
javax.naming.event
javax.naming.ldap
javax.naming.spi
15.6.1 context
The javax.naming package defines a Context interface, which is the core interface for
199
15 - JNDI
looking up, binding/unbinding, renaming objects and creating and destroying subcontexts.
The most commonly used operation is lookup(). You supply lookup() the name of the object
you want to look up, and it returns the object bound to that name. For example, the following code
fragment looks up a printer and sends a document to the printer object to be printed.
Printer printer = (Printer)ctx.lookup("treekiller");
printer.print(report);
15.6.2 names
Every naming method in the Context interface has two overloads: one that accepts a Name
argument and one that accepts a java.lang.String name. Name is an interface that represents
a generic name--an ordered sequence of zero or more components. For the methods in the
Context interface, a Name argument that is an instance of CompositeName represents a
composite name , so you can name an object using a name that spans multiple namespaces. A
Name argument of any other type represents a compound name. The overloads that accept Name
are useful for applications that need to manipulate names, that is, composing them, comparing
components, and so on.
A java.lang.String name argument represents a composite name. The overloads that
accept java.lang.String names are likely to be more useful for simple applications, such as
those that simply read in a name and look up the corresponding object.
15.6.3 bindings
listBindings() returns an enumeration of name-to-object bindings. Each binding is
represented by an instance of the Binding class. A binding is a tuple containing the name of the
bound object, the name of the object's class, and the object itself.
list() is similar to listBindings(), except that it returns an enumeration of
NameClassPair. NameClassPair contains an object's name and the name of the object's class.
list() is useful for applications such as browsers that want to discover information about the
objects bound within a context but that don't need all of the actual objects. Although
listBindings() provides all of the same information, it is potentially a much more expensive
operation.
15.6.4 references
Objects are stored in naming and directory services in different ways. A service that supports
storing Java objects might support storing an object in its serialized form. However, some naming
and directory services do not support the storing of Java objects. Furthermore, for some objects in
the directory, Java programs are but one group of applications that access them. In this case, a
serialized Java object might not be the most appropriate representation. A reference might be a
very compact representation of an object, whereas its serialized form might contain a lot more
state.
The JNDI defines the Reference class to represent a reference. A reference contains
information on how to construct a copy of the object. The JNDI will attempt to turn references
looked up from the directory into the Java objects that they represent so that JNDI clients have the
illusion that what is stored in the directory are Java objects.
200
15 - JNDI
15.6.6 exceptions
The JNDI defines a class hierarchy for exceptions that can be thrown in the course of performing
naming and directory operations. The root of this class hierarchy is NamingException. Programs
interested in dealing with a particular exception can catch the corresponding subclass of the
exception. Otherwise, they should catch NamingException.
15.7.2 searches
DirContext contains methods for performing content-based searching of the directory. In the
simplest and most common form of usage, the application specifies a set of attributes--possibly
with specific values--to match and submits this attribute set to the search() method. Other
overloaded forms of search() support more sophisticated search filters.
201
15 - JNDI
represents a listener interested in object change events.
To receive event notifications, a listener must be registered with either an EventContext or an
EventDirContext. Once registered, the listener will receive event notifications when the
corresponding changes occur in the naming/directory service.
15.9.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.
202
15 - JNDI
be reached from the initial context.
203
15 - JNDI
15.11.4 catching NamingException
The creation of the initial context and the lookup() method can throw a NamingException.
For this reason, you need to enclose these calls inside a try/catch clause. Here's the code
fragment repeated with the try/catch clause.
try {
} catch (NamingException e) {
System.err.println("Problem looking up " + name + ":" + e);
204
15 - JNDI
javax.naming.Context;
javax.naming.directory.InitialDirContext;
javax.naming.directory.DirContext;
javax.naming.directory.Attributes;
javax.naming.NamingException;
205
15 - JNDI
try {
ou=People");
} catch (NamingException e) {
System.err.println("Problem getting attribute:" + e);
206
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.
In the point-to-point or queuing model, a producer posts messages to a particular queue and a
consumer reads messages from the queue. Here, the producer knows the destination of the
message and posts the message directly to the consumer's queue. It is characterized by following:
207
208
209
210
211
212
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.
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.
persistence - DB interaction
scalability
portability
213
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
214
throws
215
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);
}
find the home interface of the bean
216
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:
217
218
Although not an exhaustive one, here is a typical list of entries (elements) in a deployment
descriptor:
1. access control entries - security issues; which users can access a bean or a particular
method of a bean
2. bean home name - name under which the bean is registered under JNDI
3. control descriptors - specifies control attributes for transactions
4. EJB class name
5. environment properties
6. the home interface name
7. the remote interface name
8. session specific elements
9. entity specific elements
10. attributes - like transaction, isolation level, security
Keeping in mind that the application assembler is to follow, here is how the deployment
descriptor may look like:
<?xnm version="1.1"?>
<ejb-jar>
<entrprise-beans>
<session>
<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>
219
220
...
</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>
221
18 - session beans
18 - SESSION BEANS
There are two types of session beans, namely stateful and stateless beans.
A stateful session bean preserves data between client accesses. A stateless bean does not.
When an EJB server needs to conserve its resources, it can evict stateful session beans from
memory. This reduces the number of instances maintained by the server. To passivate the bean
and preserve its conversational state, the bean's state is serialized to a secondary storage. When a
client invokes a method on the EJB object, the object is activated, that is, a new stateful instance
is instantiated and populated from the passivated storage.
222
18 - session beans
223
18 - session beans
224
19 - entity beans
19 - ENTITY BEANS
Entity beans represent actual data (usually, stored in a Database).
The EJB container provides the developer several persistence services:
1. container callbacks to manage caching within a transaction
2. support for concurrent access
3. maintaining a cache between transactions
4. providing all the persistence management code (no SQL code necessary)
There are 2 main types of entity beans.
BMPs (Bean Managed Persistence) for which the bean developer provides the actual
persistence (SQL) code
For CMPs:
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>
225
19 - entity beans
In the case of CMP using a simple type as primary key, the field is specified:
<prim-key-field>sportsTeamID</prim-key-field>
19.3 create
When a client calls a create() method on a session bean's home interface, an instance of that
bean is created. On the other side, when a client calls create() on an entity bean's home
interface, state data is stored into data store (usually, a Database) (we actually insert a record in a
database). This is transactional data that is accessible to multiple clients. We can have more
create() methods, all throwing RemoteException, CreateException.
Each create() method from the Home interface of the bean has 2 correspondent methods in
the bean implementation class, namely ejbCreate() and ejbPostCreate(), methods which
have the same parameters, in the same order, as the parameters in the original create()
method.
the return type of the ejbCreate() is the same as the primary key, but the developer returns
null for CMP.
for BMP, ejbCreate() must have insertion SQL code and returns an instance of the primary
key, not null.
226
19 - entity beans
has been assigned to an EJB object, so when the bean is available.In an CMP Entity EJB, this
method is normally used to manage the beans' container-managed relationship fields.
19.4 read
ejbLoad(), left empty most of the time in CMP, but needs actual SQL code in BMP
the bean's persistence implementation may choose to defer loading until it is used
19.5 update
ejbStore() in CMP; the method can be used for preprocessing data to be stored, but in
general, it is empty.
in BMP, actual SQL update code; the updated data is to be stored immediately
19.6 delete
data is deleted from DB (in the CMP case), for BMPs, the programmer will create actual
SQL code.
227
19 - entity beans
228
20 - message-driven beans
20 - MESSAGE-DRIVEN BEANS
20.1 what are the message driven beans?
A message-driven bean is an enterprise bean that allows J2EE applications to process
messages asynchronously. It acts as a JMS message listener, which is similar to an event listener
except that it receives messages instead of events. The messages may be sent by any J2EE
component - an application client, another enterprise bean, or a Web component - or by a JMS
application or system that does not use J2EE technology.
Message-driven beans currently process only JMS messages, but in the future they may be used
to process other kinds of messages.
Session beans and entity beans allow you to send JMS messages and to receive them
synchronously, but not asynchronously. To avoid tying up server resources, you may prefer not to
use blocking synchronous receives in a server-side component. To receive messages in an
asynchronous manner, message-driven bean can be used.
The instance variables of the message-driven bean instance can contain some state across the
handling of client messages - for example, a JMS API connection, an open database connection,
or an object reference to an enterprise bean object.
When a message arrives, the container calls the message-driven bean's onMessage() method
to process the message. The onMessage() method normally casts the message to one of the five
JMS message types and handles it in accordance with the application's business logic. The
onMessage() method may call helper methods, or it may invoke a session or entity bean to
process the information in the message or to store it in a database.
A message may be delivered to a message-driven bean within a transaction context, so that all
operations within the onMessage() method are part of a single transaction. If message
processing is rolled back, the message will be redelivered.
20 - message-driven beans
Although the dynamic creation and allocation of message-driven bean instances mimics the
behavior of stateless session EJB instances, message-driven beans are different from stateless
session EJBs (and other types of EJBs) in several significant ways:
message-driven beans have no home or remote interface, and therefore cannot be directly
accessed by internal or external clients. Clients interact with message-driven beans only
indirectly, by sending a message to a JMS Queue or Topic.
230
20 - message-driven beans
public MessageTraderBean() {...};
// An EJB constructor is required, and it must not
// accept parameters. The constructor must not be declared as
// final or abstract.
public void onMessage(javax.jms.Message MessageName) {...}
// onMessage() is required, and must take a single parameter of
// type javax.jms.Message. The throws clause (if used) must not
// include an application exception. onMessage() must not be
// declared as final or static.
public void ejbRemove() {...}
// ejbRemove() is required and must not accept parameters.
// The throws clause (if used) must not include an application
//exception. ejbRemove() must not be declared as final or static.
finalize{};
// The EJB class cannot define a finalize() method
}
getCallerPrincipal()
isCallerInRole()
setRollbackOnly()- The EJB can use this method only if it utilizes containermanaged transaction demarcation.
getRollbackOnly() - The EJB can use this method only if it utilizes containermanaged transaction demarcation.
getUserTransaction()- The EJB can use this method only if it utilizes bean-managed
transaction demarcation.
231
20 - message-driven beans
Note: Although getEJBHome() is also inherited as part of the MessageDrivenContext
interface, message-driven EJBs do not have a home interface. Calling getEJBHome()
from within a message-driven EJB instance yields an IllegalStateException.
232
20 - message-driven beans
the message receipt is always outside the scope of the bean's transaction, as described in the EJB
2.0 specification. For EJBs that use container-managed transaction demarcation, the EJB
container includes the message receipt as part of the bean's transaction only if the bean's
transaction attribute is set to Required.
JMS acknowledgment semantics to use for beans that demarcate their own transactions
The EJB 2.0 specification adds the following new XML deployment elements for deploying
message-driven beans.
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
233
20 - message-driven beans
</jms-destination-type>
</message-driven-destination>
...
</message-driven>
...
</enterprise-beans>
In addition to the new ejb-jar.xml elements, the weblogic-ejb-jar.xml file includes a
new message-driven-descriptor stanza to associate the message-driven bean with an actual
destination in the EJB container.
234