Download I - Introduction

Document related concepts
no text concepts found
Transcript
I - Introduction
1. communication protocols
A communication protocol is a set of rules that the end points in a telecom connection
use when they communicate.
A protocol is specified in an industry or international standard. All internet related
protocols are defined within the frame of IETF (Internet Engineering Task Force) via a
mechanism called RFC (Request For Comments).
Each (potential) protocol is defined by such a document. For a comprehensive list of all
the RFCs, check the official site www.ietf.org (which present the RFCs in .txt format) or
www.cis.ohio-state.edu/cgi-bin/rfc (which presents the RFCs in .html format, with up to
date links embedded in the documents).
2. the OSI model
OSI stands for Open System Interconnection,
The seven layers in the OSI model are:
1. Application
2. Presentation
3. Session
4. Transport
5. Network
6. Data Link
7. Physical
For a detailed description of these layers, check the site:
http://www.geocities.com/SiliconValley/Monitor/3131/ne/osimodel.html .
3. sockets - basics
A socket is a logical entity which describes the end point(s) of a communication link
between two IP entities (entities which implement the Internet Protocol).
4. posix sockets
To create a client socket, two calls are necessary. The first one creates a file descriptor
(fd) which is basicly a number which identifies an I/O channel (not different from the file
descriptor resulted from a fopen() call which opens a file).
The prototype of this call is the following:
int socket(int family, int type, int protocol);
The second call connects the client to the server. Here is the signature of the
connect() call.
int connect(int sock_fd, struct sockaddr * server_addr, int
addr_len);
To create a server socket, four calls are necessary. Here are the prototypes of
these calls:
int socket(int family, int type, int protocol);
int bind(int sock_fd, struct sockaddr * my_addr, int
addr_len);
int listen(int sock_fd, int backlog);
int accept(int sock_fd, struct sockaddr * client_addr, int
addr_len);
II - HTTP
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.cis.ohio-state.edu/cgi-bin/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.
2. the structure of http transactions
HTTP follows the client – server model. The client sends a request message to the server.
The server answers with a response message. These messages may have different
contents, but they also have some common structural elements, as follows:
1. an initial line
2. zero or more header lines
3. a blank line (CR/LF)
4. an optional message body
<initial line>
Header1: value1
...
Headern: valuen
<optional data block>
3. the initial request line
Contains 3 elements, separated by spaces:
o
a command (method) name (like GET, POST, HEAD, ...)
o
a file specification (path) (the part of the URL after the host name)
o
the HTTP version (usually, HTTP/1.0).
Here is an example of an initial request line:
GET /path/to/the/file/index.html HTTP/1.0
4. http commands (methods)
As of HTTP 1.1, there are 8 HTTP commands (methods). Here is their list:
1. GET
2. HEAD
3. POST
4. CONNECT
5. DELETE
6. OPTIONS
7. PUT
8. TRACE
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.
5. the initial response (status) line
Contains 3 elements, separated by spaces (although the reason phrase may contain
spaces, as well):
o
the HTTP version of the response
o
a response status code (a number)
o
a response status reason phrase (a human readable response status)
Here is an example of an initial response line:
HTTP/1.0 404 Not Found
6. the status code
A three-digit integer, where the first digit identifies the general category of
response:
o
1xx indicates an informational message only
o
2xx indicates success of some kind
o
3xx redirects the client to another URL
o
4xx indicates an error on the client's part
o
5xx indicates an error on the server's part
The most common status codes are:
o
200 OK - the request succeeded, and the resulting resource (e.g.
file or script output) is returned in the message body.
o
404 Not Found - the requested resource doesn't exist.
o
301 Moved Permanently
o
302 Moved Temporarily
o
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.
o
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).
7. header lines
A header line consists of two parts, header name and header value, separated a
semicolon. The HTTP 1.0 version specifies 16 headers, none of them mandatory, while
the HTTP 1.1 version specifies 46 of them, out of which, one (Host) is mandatory.
Although the header names are not case sensitive, header values are.
A couple of examples of header lines:
User-agent: Mozilla/3.0Gold
Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT
Header lines which begin with spaces or tabs are parts of the previous header
line.
8. the message body
An HTTP message may have a body of data sent after the header lines. The
most common use of the message body is in a response, that is, where the
requested resource is returned to the client, or perhaps explanatory text if there's
an error. In a request, this is where user-entered data or uploaded files are sent
to the server.
If an HTTP message includes a body, the header lines of the message are used
to describe the body. In particular,
o
the Content-Type: header gives the MIME-type of the data in the
body, such as text/html or image/jpg.
o
the Content-Length: header gives the number of bytes in the
body.
9. mime types/subtypes
MIME stands for Multipurpose Internet Mail Extensions. Each extension consists
of a type and a subtype. RFC 1521 (www.cis.ohio-state.edu/cgibin/rfc/rfc1521.html) defines 7 types and several subtypes, although the list of
admissible subtypes is much longer.
Here is the list of the seven types, together with the subtypes defined in this
particular RFC.
1. text, with subtype plain
2. multipart, with subtypes mixed, alternative, digest, parallel
3. message, with subtypes rfc822, partial, external-body
4. applictaion, with subtypes octet-stream, postscript
5. image, with subtypes jpeg, gif
6. audio, with subtype basic
7. video, with subtype mpeg
10. an example of an http transaction
To retrieve the file at the URL
http://web.info.uvt.ro/path/file.html
first open a socket to the host web.info.uvt.ro, port 80 (use the default port of 80
because none is specified in the URL). Then, send something like the following
through the socket:
GET /path/file.html HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
[blank line here]
The server should respond with something like the following, sent back through
the same socket:
HTTP/1.0 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/html
Content-Length: 1354
<html>
<body>
<h1>Happy birthday!</h1>
(more file contents)
.
.
.
</body>
</html>
After sending the response, the server closes the socket.
III - HTML
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, much in the way an editor marks up
his symbols.
The first version of HTML, namely HTML 1.0, appeared in summer 1991 and was
supported by the first popular web browser, Mosaic. The first official version – HTML
2.0 - was approved as a standard in September 1995 (as RFC 1866 (www.cis.ohiostate.edu/cgi-bin/rfc/rfc1866.html) and was widely supported. A newer standard, HTML
3.2 (3.0 was not widely accepted) appeared a W3C recommendation in January 1997.
Version 4.0 introduces the Cascading Style Sheets.
The newest (and, most likely, the last) version of HTML is 4.01. It is a revision of 4.0
and was accepted in December 1997.
From 1999 on, HTML is part of a new specification – XHTML. The XHTML 1.0 draft
was released in 01.99. The latest version (XHTML 2.0) dates from 08.02 and is not
intended to be backwards compatible.
For a complete specification of the different HTML versions, check the official HTML
site – www.w3c.org/Markup . As a practical reference site we recommend –
www.blooberry.com/indexdot/html .
2. language definition
3. html elements
A comment section in an HTML document starts with <!-- and end at the first occurrence
of -->. An example:
<!-- acesta este un comentariu. <><> -->
4. 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:
5. table related elements
The specific elements defining a table, its rows, columns, headers and cells are
<TABLE>, <THEAD>, <TR>, <TH> and <TD>. Here is their description and attributes.
the <TABLE> element
attributes:
o
BORDER
o
CELLSPACING
o
CELLPADDING
o
WIDTH
o
ALIGN
o
VALIGN
o
TBODY
o
BORDERCOLOR
o
FRAME
o
RULES
o
COLORGROUP
o
BACKGROUND
the <THEAD> element
attributes:
o
ALIGN
o
BGCOLOR
o
CHAR
o
CHAROFF
o
VALIGN
the <TH> element
attributes:
o
ABBR
o
AXIS
o
CHAR
o
CHAROFF
o
HEADERS
o
SCOPE
the <TR> element
attributes:
o
ALIGN
o
BGCOLOR
o
CHAR
o
CHAROFF
o
VALIGN
the <TD> element
attributes:
o
ABBR
o
ALIGN
o
CHAR
o
CHAROFF
o
COLSPAN
o
ROWSPAN
o
SCOPE
o
VALIGN
o
WIDTH
6. forms
A form is a basic component container, allowing user input and paarmeter 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:
o
"POST"- sends the form values in 2 steps: contacts first the server then the
form values are sent in a separate transmission.
o
"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:
o
"application/x-www-form-urlencoded" - the default value; however, since
it converts spaces to '+' and non-alphanumerical to '%HH', where 'HH' is
the hexadecimal ASCII code of the character.
Other possible values for this attribute:
o
"multipart/form-data" - used with forms that contain a file-selection field,
data is sent as a single document with multiple sections.
o
"text/plain"
7. form related elements
<INPUT> - defines input fields for the form. Main attributes:

TYPE - required, specifies the type of the input which can have one of the
following values: "text", "password", "checkbox", "radio", "submit", "image",
"reset", "button", "hidden", "file".

NAME - required, specifies the parameter name.
<SELECT> - used to create a list of choices, either as a drop-down menu or as a list box.
Each of the listed choices is an OPTION element.
Main attributes:

NAME

MULTIPLE - if specified, allows multiple selections from the choice list.

SIZE - maximum number of options visible to the user.
<OPTION> - used inside a <SELECT> element to list the selection choices. Main
attributes:

SELECTED

VALUE - if not specified, the contents of the OPTION element will become the
"value" of the element
IV - JAVA PRIMER
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 officialy announced at Sun World in 05.95. The first commercial version was
delivered to the first customer (Netscape, Inc.) in 08.95.
2. java the interpreter, jit
From source to execution, A java program goes thru the following phases:
1. Java source – a file with extension .java
2. Java bytecode – a file with extension .class
3. The Java interpreter (which is part of the Java Virtual Machine) parses and
executes the Java bytecode.
Example:
Edit the file prog1.java. The java compiler (javac) translates it to bytecode –
prog1.class. The java interpreter (as part of the JVM) parses and executes the
prog1.class file.
In terms of execution time, a Java interpreted program is about 10 times slower than a
compiled and linked one. To overcome this significant shortage, a tool named Just In
Time compiler, allows the compilation of the Java source into machine-dependent binary
executable. The first time a class is loaded, the compilation process occurs, which
accounts for a pretty slow execution, but next time execution is much faster, pretty much
comparable to that of a binary executable.
The java compiler is (in general) a command line tool, with the following main options:
o
-classpath <path>
o
-sourcepath <path>
o
-d <directory> : specifies where to put the .class file.
o
-g : generate all debugging info.
One example of command line compilation:
javac -classpath .;C:\TW\mySource;C:\TW\myPackages -g login.java
3. java applications
There exist 2 types of programs that can be written in Java. The first type are embedded
in web pages – applets, the others are the standalone programs – Java applications.
4. object oriented concepts
1. inheritance
2. encapsulation
3. polymorphism
5. java as programming language
integer data types:
o
byte
o
short
o
int
o
long
floating point data types:
o
float
o
double
other types:
o
boolean - 1 bit
o
char - Unicode (16 bits)
All basic types have associated classes which extend their functionality, namely: Byte,
Short, Integer, Long, Float, Double, Boolean, Character.
Other peculiarities: no pointers (only references), automatic garbage collection, no
templates.
6. access specifiers and modificators in java
The access attributes of a member variable or method of a class are specified by the
access specifiers. Except for the "package" concept, they have the same basic meaning as
in C++.
o
no specifier - the default value allows access from any class in the same
package
o
public - access from any class anywhere
o
private - no access from outside the class itself
o
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:
o
no specifier - the default value makes the class visible only to the classes
in the same package
o
public - the class is visible from any class, anywhere
o
abstract - the class is abstract (some of its methods (inherited or specified
by some interface) are to be implemented by some of its subclasses)
An example. The declaration:
abstract class myFirstClass extends
javax.servlet.http.HttpServlet implements Serializable
{
...
}
declares an abstract class, which is visible only to the classes in the same
package, which extends the class javax.servlet.http.HttpServlet and
which implements the Serializable interface.
The modificators of the variables and methods of a class specify their range and stability.
A static variable or method is one which is implemented at class level, rather than at
class instance. A final variable (method, class) is one which cannot be modified
(overridden, inherited). More precisely:
A static (or class):
o
variable - one which is defined at class level, has the same value for all
class instances.
o
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:
o
variable - one which is constant
o
method - the method implementation cannot be overriden by some
subclass.
o
class - does not have any subclasses.
8. exceptions in java
An exception signals an abnormal situation or an error in an application, due to a variety
of execution factors or due to programming errors.
In Java, an exception is an object which is created when the abnormal situation occurs.
Exception categories:
1. code or data errors - like invalid cast, array index out of bounds, division
by 0.
2. standard method exceptions
3. programmer defined exceptions
4. java errors - JVM execution errors (mostly caused by programming
errors).
All exceptions (even programmer defined) must inherit from the standard class
Throwable.
All the standard exceptions are derived from 2 direct subclasses of Throwable, namely
class Error and the class Exception.
Error Exceptions
Represent conditions which are not expected to be caught in our code. Therte are 3 direct
subclasses of the class Error - ThreadDeath, Linkage Error and VirtualMachineError.
Exception Exceptions
Except for the RuntimeException exceptions, all then exceptions in this category must be
caught in our code.
RuntimeException Exceptions
Usually, these exceptions take place because of serious code errors and they are supposed
to be fixed in the coding phase, not at execution time.
The subclasses of the RuntimeException class, as defined in the java.lang package are:
o
ArithmeticException
o
IndexOutOfBoundException
o
NegativeArraySizeException
o
NullPointerException
o
ArrayStoreException
o
ClassCastException
o
IllegalArgumentException
o
SecurityException
o
IllegalMonitorStateException
o
IllegalStateException
o
UnsupportedOperationException
Handling Exceptions
There are 2 ways to deal with exceptions:
o
supply then code to deal with the exception inside the method - this can be
done by providing a try, catch, finally construct.
o
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.
9. java packages
A Java package is a named collection of classes. Each class belongs to a package (even if
a package name is not specified, the default package is used). The names in a package are
qualified by the package name, therefore, they have to be unique inside a package.
Package names
The default package has no name. The package containing the standard classes is
java.lang (automatically available). All other packages must be explicitly imported. As a
general rule, the package statement is the first one in a java source file, followed by the
import statements. An example:
package com.bank11.ccards.servlets;
import javax.sql.*;
import.java.util.Properties;
...
The name of the package is directly linked to the directory structure in which it is stored.
In the example above, the class (the .class file, rather) defined in the java source must be
stored in a directory called servlets, which is a subdirectory of ccards (which itself, is a
subdirectory of a directory called bank11).
10. standard Java packages
o
java.lang - default, don't have to import
o
java.io
o
java.awt - support for user interface
o
java.awt.event - support for event handling
o
java.awt.geom - support for operations with 2D geometric figures
o
javax.swing - swing GUI components (minimal dependence on native
code)
o
java.swing.event - support for event handling
o
java.util - provides support for data collections, string analyzers, date and
time info
o
java.util.zip - support for java archives creation
o
java.sql
11. 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
V - WEB APPLICATIONS
1. the structure of a web application
A web application is a collection of Java servlets, JSP pages, other helper classes and
class libraries, other static resources (HTML, images, etc.) and an xml file, the
deployment descriptor.
A web application consists of 4 parts:
1. a public directory – containing html, jsp files and other public resources.
This is the root directory of the application.
2. a WEB-INF/web.xml file – the deployment descriptor.
3. a WEB-INF/classes directory.
4. a WEB-INF/lib directory.
Example:
Assume that we use a Tomcat web server and that the environment variable
%TOMCAT_HOME% is set to C:\TW\Tomcat. Then, the root directory of some web
application can be:
C:\TW\Tomcat\webapps\bank11\ccards
and the mandatory directories are:
C:\TW\Tomcat\webapps\bank11\ccards\WEB-INF\classes
C:\TW\Tomcat\webapps\bank11\ccards\WEB-INF\lib
2. web containers
A web container is a Java runtime providing implementation of the Java servlet API and
some other facilities to the JSP pages. It responsible for initializing, invoking and
managing the life cycle of servlets and JSPs.
A web container may either implement the basic HTTP services or delegates these
services to an external web server.
Web containers can be part of an application or web server or a separate runtime. Here is
a description of these situations.

web container in a J2EE application server. Commercial implementations of
the J2EE specifications, like WebLogic, Inprise Application Server or IBM's
WebSphere include web containers.

web container built into web servers. Most known cases are the Sun's Java
WebServer and the Jakarta Tomcat web server (which will be used in our
applications).

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.
3. deployment descriptor
The deployment descriptor is an xml file (namely, web.xml) which allows the
customization of the web application at deployment time.
4. practical deployment issues
There are several issues with the web applications deployment. Behind a very benign
URL, like "http://localhost:8080/ccards/servlet/Enroll" there are 3 things which have to
be fixed in order to make things work properly.
Assume that we work with Tomcat and that the environment variable
%TOMCAT_HOME% (or $TOMCAT_HOME, in an UNIX environment) is set to
"C:\TW\Tomcat".
1. The "/servlet" part of the URL tells the web server (Tomcat, in our case)
to execute the invoker servlet. This association is made in the file
"%TOMCAT_HOME%\conf\web.xml". Unfortunately, the lines which
deal with this issue are commented out in the latest version of Tomcat (for
so-called "security issues"). To make anything work:

de-comment the following section:
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
in the configuration file "%TOMCAT_HOME%\conf\web.xml"
1. 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" />
1. 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>
VI - SERVLETS
1. the servlets as part of web applications
Java servlets – small, platform independent programs, which extend the functionality of
the web server.
Technically speaking, a servlet is a Java class that extends the GenericServlet (or, more
often, the HttpServlet) class.
The Java servlet API provides a simple frame for building web applications on web
servers.
2. servlet packages and classes
The Java servlet API consists of 2 packages, which are part of the J2 SDK, Enterprise
Edition. These packages are:
o
javax.servlet
o
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 an interfaces of the Java servlet API can be divided in several categories,
namely:
o
servlet implementation
o
servlet configuration
o
servlet exceptions
o
request and responses
o
session tracking
o
servlet context
o
servlet collaboration
o
miscellaneous
3. the Servlet interface
The Servlet interface is part of the javax.servlet package. It declares the
following methods:
public void init(ServletConfig config)
throws ServletException;
public void service(ServletRequest req, ServletResponse
resp) throws ServletException, IOException;
public void destroy() throws ServletException;
public ServletConfig getServletConfig();
public String getServletInfo();
After instantiating the servlet, the web container calls its init() method. The
method performs all initialization required, before the servlet processes any HTTP
request. The servlet specification insures that the init() method is called just once for
any given instance of the servlet.
The web container calls the service() method in response to any incoming request.
This method has two arguments, arguments which implement the ServletRequest
and ServletResponse interfaces, respectively.
More on the servlet lifecycle, in a different section.
4. the GenericServlet class
public abstract class GenericServlet implements
Servlet, ServletConfig, Serializable
This class provides a basic implementation of the Servlet interface. Since this class
implements the ServletConfig interface, as well, the developer may call
ServletConfig methods directly, without having to obtain a ServletConfig
object first. All classes extending the GenericServlet class should provide an
implementation for the service() method.
Methods specific to this class:
public void init()
public void log(String msg)
public void log(String msg, Throwable t)
5. the HttpServlet class
It is very likely that the only implementation of the Servlet interface we'll ever use is
one that processes an HTTP request. The servlet API provides such a specific class,
namely the HttpServlet class.
public abstract class HttpServlet extends GenericServlet
implements Serializable
The HttpServlet provides an HTTP specific implementation of the Servlet interface. This
abstract class specifies the following methods:
public void service(ServletRequest req, ServletResponse
resp)
public void service(HttpServletRequest req,
HttpServletResponse resp)
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
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)
6. the ServletConfig interface
This interface specifies the following methods:
public String getInitParameter(String name)
public Enumeration getInitParameterNames()
public ServletContext getServletContext()
public String getServletName()
7. servlet exceptions
The Java servlet API specifies two servlet specific exceptions:
javax.servlet.ServletException
javax.servlet.UnavailableException
The ServletException class extends java.lang.Exception and can be
thrown by the init(), service(), doXXX() and destroy() methods of the
Servlet interface implementations.
The UnavailableException indicates to the web container that the servlet instance
is unavaialble. It also extends the java.lang.Exception class.
8. the servlet lifecycle
Generally, a servlet instance goes through the following stages:
o
instantiation
o
initialization
o
service
o
destroy
o
unavailable
The container creates a servlet instance as first response to an incoming (HTTP) request
or at container startup. Typically, the web container creates a single instance of the
servlet, which will service all incoming requests. If the servlet does not implement the
javax.servlet.SingleThreadModel, concurrent requests are serviced in more
than one service thread, which requires that the service() method be thread safe.
After instantiation, the container calls the init() method of the servlet, method which
performs the initialization of the servlet. Typically, this method contains JDBC driver
loading, DB connection opening, etc.
The web container makes sure that the init() method of the servlet will be completed
before invoking its service() method. Also, the servlet's destroy() method will be
called before the servlet itself is destroyed.
9. the ServletRequest interface
Here are some of the methods of this interface:
public Object getAttribute(String name)
public Object setAttribute(String name, Object attr)
public Enumeration getAttributeNames()
public int getContentLength()
public String getContentType()
public String getParameter(String name)
public Enumeration getParameterNames()
public Enumeration getParameterValues()
public String getServerName()
public int getServerPort()
public String getRemoteAddr()
public String getRemoteHost()
Most of the above methods are self explanatory. But what is the difference between a
parameter and an attribute? While the parameters of the request are part of the
request itself, the attributes of the request are attached by the web containers or
by the servlets/JSPs.
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 is to
allow the container to additional data to a servlet or JSP or to allow dending data
from a servlet to another.
9. the HttpServletRequest interface
public interface HttpServletRequest
extends ServletRequest
This interface contains HTTP specific methods. One has to take in account the structure
of an HTTP request when overviewing the most important methods of this interface. Here
are some of them:
public Cookie[] getCookies()
public long getDateHeader()
public String getHeader(String name)
public Enumeration getHeaders(String name)
public Enumeration getHeaderNames()
public String getContextPath()
public String getPathInfo()
public String getQueryString()
public String getRemoteUser()
10. the ServletResponse interface
This interface defines methods for constructing responses to servlet requests.
Here are the most important ones:
public ServletOutputStream getOutputStream()
public PrintWriter getWriter()
public void setContentLength(int len)
public void setContentType(String type)
public void setBufferSize(int size)
public int getBufferSize()
public void flushBuffer()
11. the HttpServletResponse interface
This interface extends the ServletResponse interface and defines methods specific
for constructing responses to HTTP requests.
Here are the most important ones:
public void addCokie(Cookie cookie)
public String encodeURL(String url)
public void sendError(int status)
public void sendError(int status, String message)
public void setHeader(String headerName, String value)
public void addHeader(String headerName, String value)
public void setStatus(int statusCode)
12. the ServletContext interface
A sevlet context defines servlet's view of the web application and provides access to
resources common to all servlets of the web application. Each servlet context is rooted at
aspecific path in the web server. The deployment of a web application involves adding an
application specific <context> tag which associates the the name of the application
with its root directory. This is done in server's (container's) server.xml file.
The ServletContext interface abstracts the context of a web application. A reference
to an object of this type can be obtained by invoking the getServletContext()
method of the HttpServlet object.
public String getMIMEType(String fileName)
public String getResource(String path)
public ServletContext getContext(String urlPath)
public String getInitParameter(String name)
public Enumeration getInitParameterNames()
public Object getAttribute(String name)
public Enumeration getAttributeNames()
public void setAttribute(String name, Object attr)
public String removeAttribute(String name)
13. the Enroll servlet
The Enroll servlet services the request sent by the web browser when we submit the
Enroll form (file Enroll.html)
Here is its abbreviated form (topics which are DB related are postponed) of the
"EnrollServlet.java" file:
package com.bank11.ccards.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EnrollServlet extends HttpServlet
{
public void init(ServletConfig config)
throws ServletException
{
super.init(config);
}
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
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("merge");
out.println("<br>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
VII - JDBC
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.
2. db drivers
Each database vendor offers its own version of DB access API. A JDBC driver is a
middleware layer that translates JDBC calls into vendor specific calls. These drivers fall
into four standard categories, as recognised by the DB industry.
Type 1. JDBC – ODBC Bridge
The driver translates the JDBC calls into equivalent ODBC calls. Both the JDBC and the
JDBC-ODBC calls are invoked within the client application. This solution is inefficient,
due to the multiple layers of indirection involved and to the limitations imposed to the
JDBC layer by the ODBC frame.
The standard JDK includes all the classes for this bridge , namely
sun.jdbc.odbc.JdbcOdbcDriver .
Type 2. Part Java, Part Native Driver
The drivers in this category use a combination of Java implementation and vendor
specific APIs for DB access. The driver translates JDBC specific calls into vendor
specific API calls. The DB returns the result of the call to the API, which in turn,
forwards them to the JDBC driver. It is much faster than the Type 1 drivers, because it
eliminates one level of indirection.
Type 3. Intermediate Database Access Server
Type 3 drivers are DataBase servers which act as intermediate tier between multiple
clients and multible Database servers. The client application sends a JDBC call through a
JDBC driver to the intermediate Database servers. These servers translate the call into a
native driver call which handles the actual DB connection. This type of drivers are
implemented by several application servers, like WebLogic (of BEA) or Inprise
Application Server (of Borland).
Type 4. Pure Java Drivers
These are the most efficient drivers. The JDBC API calls are converted to direct network
calls using vendor provided protocols. All major vendors provide type 4 JDBC drivers for
their Database products.
For an extensive list of JDBC drivers, check the site:
http://industry.java.sun..com/products.j/jdbc/drivers .
3. connecting to a database
There two main steps in connecting to an existing database. The first one is
loading a database driver.
A database driver is specified by the driver name. Here are some examples of actual
database driver names:
o
com.borland.datastore.jdbc.DataStoreDriver
o
com.sybase.jdbc.SybDriver
o
com.ibm.db2.jdbc.net.DB2Driver
o
oracle.jdbc.driver.OracleDriver
o
sun.jdbc.odbc.JdbcOdbcDriver
The Java code to load the driver name is somewhat obscure, but let's take it for granted:
import java.sql.*;
import java.util.*;
try
{
Class.forName("org.gjt.mm.mysql.Driver").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 driver URL has 3 parts separated by colons, as follows:
jdbc:<subprotocol>:subname
o
jdbc is the protocol name (actually, the only protocol allowed in JDBC).
o
the sub-protocol is used to identify the JDBC driver, as specified by the
driver vendor.
o
subname – the syntax of this field is vendor specific and allows the
identification
Here are some examples of JDBC driver URLs:
o
jdbc:sybase:localhost:2025
o
jdbc:db2://db2.bank11.com:50002/ccards
o
jdbc:oracle:thin:@loclahost:1521:ORCL
The second step in connecting to an existing database is to open the connection, by
using the connection URL.
Here is some sample code which shows how this is done:
String connURL = "jdbc.mysql://localhost:3306/ccards";
String user = "root";
String passwd = "root"
Connection conn = DriverManager.getConnection(connURL,
user, passwd);
Since we just used it, let's have a better look in the next section at the DriverManager
class.
4. the DriverManager class
This class belongs to the javax.sql package and offers a common access layer on top
of different JDBC drivers. Each driver used by the application must be registered
(loaded) before the DriverManager class tries to obtain a connection.
There are 3 versions of the getConnection() method of the DriverManager
class. Here they are:
public static Connection getConnection(String connURL)
throws SQLException
public static Connection getConnection(String connURL,
String user, String passwd) throws SQLException
public static Connection getConnection(String connURL,
java.util.Properties info) throws SQLException
While the first two forms of getConnection() are pretty straightforward, let's see
an example of hou 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);
5. the Connection interface
The Connection interface is part of then javax.sql package. Once we get the hold
of a Connection object, we can use it for various purposes, but we will restrict
ourselves to creating SQL statements. Public methods for creating statements:
Statement createStatement() throws SQLException
Statement createStatement(int resultType, int
resultSetConcurrency) throws SQLException
PreparedStatement prepareStatement(String sql)
throws SQLException
CallableStatement prepareCall(String sql)
throws SQLException
6. statement interfaces
The objects we encountered in the previous section , namely, Statement,
PreparedStatement and CallableStatement abstract regular SQL statements,
prepared statements and stored procedures, respectively.
The Statement interface has (among others) the following methods:
1. methods for executing statements:
o
execute()
o
executeQuery()
o
executeUpdate()
1. methods for batch updates:
o
addBatch()
o
executeBatch()
o
clearBatch()
1. methods for result set fetch size and direction:
o
setFetchSize()
o
getFetchSize()
o
setFetchDirection()
o
getFetchDirection()
1. method to get the current result set:
o
getResultSet()
1. methods for result set concurrency and type:
o
getResultSetConcurrency()
o
getResultSetType()
1. other methods:
o
setQueryTimeout()
o
getQueryTimeout()
o
setMaxFieldSize()
o
getMaxFieldSize()
o
cancel()
o
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);
7. the ResultSet interface
The result of a query by a Statement object is a java.sql.ResultSet object
which is available to the user and allows access to the data retrieved. The interface
ResultSet is implemented by driver vendors.
Methods to retrieve data:
o
getAsciiStream()
o
getBoolean()
o
getDate()
o
getInt()
o
getShort()
o
getTimeStamp()
o
getBinaryStream()
o
getBytes()
o
getFloat()
o
getObject()
o
getTime()
o
getString()
o
getByte()
o
getDouble()
o
getLong()
o
getBigDecimal()
o
getMetaData()
o
getClob()
o
getWarnings()
o
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 rertrieval 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 invokation 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:
o
getCatalogName()
o
getTableName()
o
getSchemaName()
o
getColumnCount()
o
getColumnName()
o
getColumnLabel()
o
getColumnType()
o
getColumnTypeName()
o
getColumnClassName()
o
getColumnDisplaySize()
o
getScale()
o
getPrecision()
o
isNullable()
o
isCurrency()
o
isSearchable()
o
isCaseSensitive()
o
isSigned()
o
isAutoIncrement()
o
isReadOnly()
o
isDefinitelyWritable()
8. the PreparedStatement interface
If an SQL statement is used several times and its different forms differ only with respect
to the data they specify, a better choice is the usage of a PreparedStatement object.
Prepared statements are parametrized and each parameter (usually, a field (column) value
or name) is represented by a question mark '?'.
The following lines of Java code give an example of how to use PreparedStatement
objects:
Statement stmt = con.createStatement();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO
customer VALUES (?, ?, ?)");
stmt.executeUpdate("CREATE TABLE customer (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();
9. jdbc and sql types and their corresponding java classes
JDBC Type
Purpose
SQL Type
Java Type
ARRAY
SQL array
ARRAY
java.sql.Array
BIGINT
64 bit integer
BIGINT
long
BINARY
binary value
none
byte[]
BIT
one bit value
BIT
boolean
BLOB
binary large object BLOB
java.sql.Blob
CHAR
char string
CHAR
String
CLOB
character large
object
CLOB
java.sql.Clob
DATE
day, month, year
DATE
java.sql.Date
DECIMAL
decimal value
DECIMAL
java.math.BigDecimal
DISTINCT
distinct
DISTINCT
none
DOUBLE
double precision
DOUBLE
PRECISION
double
FLOAT
double precision
FLOAT
double
INTEGER
32 bit integer
INTEGER
int
JDBC Type
Purpose
SQL Type
Java Type
JAVA_OBJECT
stores Java objects none
Object
LONGVARBINARY
variable length
binary value
none
byte[]
LONGVARCHAR
variable length
char string
none
String
NULL
null values
NULL
null
NUMERIC
decimal value
NUMERIC
java.math.BigDecimal
OTHER
db specific types
none
Object
REAL
single precision
REAL
float
16 bit integer
SMALLINT
short
TIME
hrs, mins, secs
TIME
java.sql.Time
TIMESTAMP
date, time,
nanoseconds
TIMESTAMP
java.sql.Timestamp
TINYINT
8 bit integer
TINYINT
short
VARBINARY
variable length
binary value
none
byte[]
VARCHAR
variable length
char string
VARCHAR
String
REF
SMALLINT
STRUCT
10. JDBC Data Sources
In the JDBC 2.0 optional package, the DriverManager interface is replaced by the
DataSource interface as main method of obtaining DB connections.
While the DriverManager interface was used at run time to load explicitly a JDBC
driver, the new mechanism uses a centralized JNDI service to locate a
javax.sql.DataSource object.
This interface is, basicly, a factory for creating DB connections. It is part of the
javax.sql package.
Main methods:
public Connection getConnection() throws SQLException
public Connection getConnection(String user, String pwd)
throws SQLException
VIII - JSP
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.
2. the java.servlet.jsp.JspPage interface
This interface has 2 methods:
public void jspInit()
public void jspDestroy()
The javax.servlet.HttpJspPage interface has a single method:
public void jspService(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
The implementation of this method is generated by the web container – never by
the developer.
2. jsp tags
There are 3 categories of JSP tags (elements):
1. directives – affect the dtructure of the whole jsp
2. scripting elements – java code inserted in the JSP page
3. actions – special tags affecting the run time behaviour of the JSP
Rules for JSP tags:
o
attribute values are always quoted (single or double quotes)
o
URLs follow the servlet conventions
o
if the URL does not start with / , it is interpreted relative to the position of
the current JSP
3. jsp directives
The JSP directives are messages sent by the Java Server Page to the JSP container. These
directives do not produce any client output and affect the whole JSP file.
The general format of a JSP directive is as follows:
<%@directive_name attr1="val1" ... attrn="valn" %>
Ther are three JSP directives: page, include and taglib.
The page directive format:
<%@page attr1="val1" ... %>
attributes:
o
language – values: "java"
o
extends – superclass of the generated class
o
import – list of packages classes
o
session – "true" or "false", the implicit session object is available
o
buffer – buffering model for the output stream
o
autoflush – if "true", the buffer is flushed automatically if full
o
isThreadSafe – "true" or "false"
o
isErrorPage – "true" or "false"
o
contentType – MIME type of the response
o
info
o
errorPage – the URL of an error page, in case of error
The include directive instructs the container to include inline the content of the
resource specified by "fileName". The format of this directive:
<%@include file="fileName" %>
The taglib directive allows the usage of custom tags (tag extensions). It has the
following format:
<%@taglib uri="tagLibUri" prefix="tagPrefix" %>
where the tagPrefix indicates a name scope.
4. scripting elements
declarations
<%! java vars and method declarations %>
Basicly, a bloc of java code used to define class-wide variables and methods in the
generated servlet.
scriptlets
<% valid java statements %>
Block of java code which is executed during request processing. In Tomcat, this code
goes to inside the service() method.
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.
standard actions
Tags that affect the runtime behaviour of the JSP and the response to the client. A tag can
be embedded into a JSP page. The standard actions are detailed in the next paragraphs.
5. the useBean standard action
<jsp:useBean>
Used to instantiate a Java bean or locate a bean instance. Assigns it to available name or
id.
The syntax for this action is:
<jsp:useBean id="beanName" scope="sName" beandetails />
where beandetails is one of the following:
o
class="className"
o
class="className" type="typeName"
o
beanName="beanName" type="typeName"
o
type="typeName"
6. the setProperty standard action
<jsp:setProperty>
Used in conjunction with the <jsp:useBean> action to set the value of the bean properties.
The syntax for this action is:
<jsp:setProperty name="beanName" propertydetails />
where propertydetails is one of the following:
o
property="*"
o
property="propertyName"
o
property="propertyName" param="parameterName"
o
property="propertyName" value="propertyValue"
where propertyValue is a string or a scriptlet.
Attributes description:

name - the name of a bean instance, already defined in a <jsp:useBean>
7. the getProperty standard action
<jsp:getProperty>
Used to access the properties of a bean, converts them to string and displays the output to
the client.
The syntax for this action is:
<jsp:getProperty name="beanName" property="propName" />
Attributes description:

name - the name of a bean instance whose property is to be retrieved

property - name of the property to be retrieved
8. the param standard action
<jsp:param>
Provide other tags with additional information in the form of name:value pairs. It is used
in conjunction with the <jsp:include>, <jsp:forward>, <jsp:plugin> actions.
The syntax for this action is:
<jsp:param name="paramName" value="paramValue" />
9. the include standard action
<jsp:include>
Used for the inclusion of a static or dynamic resource into the current JSP page at request
processing time. An included page has access only to the JspWriter object and cannot set
headers or cookies. While the <%@include> directive is executed at compile time and
has static content, the <jsp:include> action is executed at request processing time and has
static or dynamic content.
The syntax for this action is:
<jsp:include page="pageURL" flush="true" />
Attributes description:

page - the URL of the page, same format as the <%@include> directive.

flush - only the "true" value is supported.
10. the forward standard action
<jsp:forward>
Used to forward the the request to another JSP, servlet or to a static resource..
The syntax for this action is:
<jsp:forward page="pageURL" />
The action may include several <jsp:param> tags, as well. It is used mainly, when we
want to separate the application into different views, depending on request.
11. the plugin standard action
<jsp:plugin>
Used in pages to generate client browser specific HTML tags (<OBJECT> or
<EMBED>) that result in download of Java plugins(if required), followed by the
execution of the applet or JavaBeans component specified by the tag.
The syntax for this action is:
<jsp:plugin type="bean|applet" code="objCode"
codeBase="objCodeBase" align="align" archive="archiveList"
height="height" hspace="hSpace" jreversion="jreVersion"
name="componentName" vspace="vSpace" width="width"
nspluginurl="netscapeURL" iepluginurl="IEURL">
<jsp:params>
<jsp:param name="paramName" value="paramValue" />
...
</jsp:params>
</jsp:plugin>
Attributes description:

name - the name of a bean instance, already defined in a <jsp:useBean>
12. implicit objects
JSP provides several implicit objects, based on the servlet API, objects which are
automaticly available.
1. request - represents the object that triggered the service() method invokation and
has type HttpServletRequest with scope request
2. response - represents server's response to the request, it has
HttpServletResponse type and page scope
3. pageContext - provides a single point of access to attributes and shared data
within the page, it has type PageContext with scope page
4. session - it has HttpSession type and session scope
5. application - represents the servlet context, it has type ServletContext and scope
application
6. out - it represents the buffered version of java.io.PrintWriter, writes to
the output stream to the client, it has javax.servlet.jsp.JspWriter type and scope
page
7. config - it is the SevletConfig for the current JSP page, it is of type
ServletConfig and has page scope
8. page - it is an instance of the page's implementation of the servlet class, it has
java.lang.Object type and scope page
13. 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
IX - Enterprise Java Beans
1. enterprise java beans versus (ordinary) java beans
(Ordinary) Java beans provide a format for general-purpose components, while the EJB
(Enterprise Java Beans) architecture provides a format for highly specialized business
logic components.
What are Entreprise Java Beans? A collection of Java classes together with an xml file,
bundled into a single unit. The Java classes must follow certain rules and must offer
certain callback methods.
The EJBs will run in an EJB container which is part of an application server.
Version 1.1 of EJB specification provides two EJB types:
o
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
o
entity beans - object oriented representation of data in a DB; multiple
clients can access it simultaneously while its life-span is the same as the
data it represents
The 2.0 EJB specification adds another bean type:
o
message driven beans
2. the ejb container and its services
The EJB container provides an execution environment for a component. The component
lives inside a container, container which offers services to the component. On the other
side, the container lives (in general) in an application server, server which provides an
execution environment for containers.
The main reason for using EJBs is to take advantage of the services provided by the
container.
These services are:
o
persistency - DB interaction
o
transactions - transaction management can be complex, especially if we
have more databases and more access components
o
data caching - no developer coding, improved performance
o
security - EJB access can be stated without extra coding
o
error handling - consistent error handling framework - logging, component
recovery
o
scalability
o
portability
o
manageability
3. the home interface
The home interface is an interface that extends the EJBHome interface. It provides
methods named create() with application specific arguments, returning the remote
interface and throwing CreateException and RemoteException. It uses only
argument types allowed by the RMI standard.
The methods specified by the EJBHome interface (not implemented (in general) by the
programmer) are the following:
public void remove(Handle han) throws RemoteException,
RemoveException
public void remove(Object primaryKey) throws
RemoteException, RemoveException
public EJBMetaData getEJBMetaData() throws
RemoteException
public HomeHandle getHomeHandle() throws RemoteException
Code example for the a home interface, called MyBenHome:
package myBeans;
import.javax.ejb.*;
import java.rmi.RemoteException;
public interface MyBeanHome extends EJBHome
{
MyBeanObject create() throws CreateException,
RemoteException;
}
4. the remote interface
The remote interface of a bean is a standard Java interface that extends EJBObject and
Remote and declares the business logic methods of the bean. The developer
does not implement this interface.
While the Remote interface declares no methods, the EJBObject declares the
following ones:
public EJBHome getEJBHome() throws RemoteException
public Object getPrimaryKey() throws RemoteException
public Handle getHandle() throws RemoteException
public boolean isIdentical(EJBObject obj) throws
RemoteException
public void remove() throws RemoteException,
RemoveException
Code example for a remote interface called MyBeanObject:
package myBeans;
import.javax.ejb.*;
import java.rmi.RemoteException;
public interface MyBeanObject extends EJBObject
{
// assume that we have two business logic methods
void processEntry(String firstName, String lastName,
int custId) throws RemoteException;
void deleteEntry(int custId) throws RemoteException;
}
5. client programmer's viewpoint
For an EJB client application, we need to know:
1. how to create or find the bean
2. what methods to use (know its interface)
3. how to release its its resources
The client is able to create an EJB thru an object implementing an interface called
EJBHome. This object acts like a factory for EJBs, creating them for the client
application.
The client gains access to the EJB through a remote interface, implemented by an object
built by the EJB host in the deployment process.
Here are the main part of the client code:
authentification
Client's authentification is done in a way which is server specific. In the case of an web
application, this can be done (for example) thru SSL.
getting an initial context

if the client is another EJB executing in the same container and the bean to be
used is declared as a resource in the deployment descriptor, the InitialContext is
already available:
Context ctx = new InitialContext;

try
{
if the client executes outside the container, getting the InitialContext requires the
usage of some server-side properties. Here is an example:
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory";
prop.put(Context.PROVIDER_URL,
"localhost:1099");
Context ctx = new InitialContext(prop);
}
find the home interface of the bean

for a client executing inside the container, the code may look like:
Object homeRef = ctx.lookup("java:comp/env/ejb/MyBean");

if the client executes outside the container, the bean can be associated to
any name in the JNDI name space. It is JNDI's task to identify the
resource associated to the name provided:
Object homeRef = ctx.lookup("MyBean");
cast the home interface reference
To make sure that the client works with the underlying communication protocol,
the client should use the narrow() method of javax.rmi.PortableRemoteObject:
MyBeanHome home =
(MyBeanHome)PortableRemoteObject.narrow(homeRef,
MyBeanHome.class);
create an instance of the bean
The instance of the bean is created on the server. The client only has a remote
interface to this instance (i.e. the client has a stub).
Here is the code:
MyBeanObject myBeanObject = home.create();
call business methods on the bean
myBeanObject.processEntry("Dumitrascu", "Vasile", 1102);
remove the bean instance
myBeanObject.remove();
6. bean programmer's viewpoint
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
Since the home interface and the remote interface have been detailed in the previous
sections, we concentrate now on the bean class itself. Besides the implementation of the
business methods (which were declared in the remote interface, as well), the bean class
must implement (although the implementation itself may be empty) a certain set of
methods, set which is specific to each major type of beans (session or entity).
Assuming that our bean (called MyBean) is a session bean, the code implementing this
class may look like this:
package myBeans;
import.javax.ejb.SessionContext;
public class MyBean implements javax.ejb.SessionBean
{
public void processEntry(String firstName, String
lastName, int custId)
{
// method implementation
...
}
public void deleteEntry(int custId)
{
// method implementation
...
}
// mandatory methods for session beans
// method implementations may be empty
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext ctx) {}
}
The deployment descriptor of the bean will be detailed in another section.
7. 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.
8. container callbacks for session beans
There are 5 mandatory callbacks for classes implementing the SessionBean interface.
public void ejbActivate()
public void ejbPassivate()
public void ejbCreate()
public void ejbRemove()
public void setSessionContext(SessionContext ctx)
The first two methods will never be called for stateless session beens, because
the container will never activate a stateless session bean.
9. entity beans
Entity beans represend actual data (usually, sstored in a Database).
The EJB container provides the developer several persidtence 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 persistency management code (no SQL code necessary)
There 2 main types of entity beans.
o
CMPs (Container Managed Persistence)
o
BMPs (Bean Managed Persistence) for which the bean developer provides
the actual persistance (SQL) code
10. primary keys
Every entity bean has a primary key . This primary key must be represented by a primary
key class. The requirements that must be satisfied by the primary key are different for the
two main types of entiry beans.
For BMPs:
o
the primary key can be any legal RMI/IIOP type
o
it must provide suitable implementations for hashCode(), equals()
o
must have a unique value among beans of a particular type
o
the container must be able to create a primary key
o
the key class must have a no argument constructor
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-keyclass>
or
<prim-key-class>java.lang.String</prim-key-class>
In the case of CMP using a simple type as primary key, the field is specified:
<prim-key-field>sportsTeamID</prim-key-field>
11. mandatory callbacks for entity beans
Besides the CRUD callbacks which are discusses later in this section, an entity bean must
implement (although this implementation may be left empty) the following methods:
public void ejbActivate()
public void ejbPassivate()
public void setEntityContext(EntityContext ctx)
public void unsetEntityContext()
CRUD translates through Create, Read, Update and Delete. These methods are
mandatory for entity beans.
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.
read

ejbLoad(), left empty most of the time in CMP, but needs actual SQL code in
BMP

the bean's peristence implementation may choose to defer loading until it is used

ejbLoad() may contain processing code
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
delete

the correspondinng method in the bean implementation class is ejbRemove()

data is deleted from DB (in the CMP case), for BMPs, the programmer will create
actual SQL code.
bmp callbacks versus cmp callbacks

for CMPs, callbacks are used for fine tunning

for BMPs, call backs implement DB synchronization
12. the deployment descriptor
The deployment descriptor of an EJB contains information about the bean in relation to
the application it belongs to.
This information can be divided into two main categories:

structural information related to a particular EJB.

application assembly information
Although not an exhaustive one, here is a typical list of entries (elements) in a
deployment descriptor:
1. access control entries - security issues; which users can access a bean or a
particular method of a bean
2. bean home name - name under which the bean is registered under JNDI
3. control descriptors - specifies control attributes for transactions
4. EJB class name
5. environment properties
6. the home interface name
7. the remote interface name
8. session specific elements
9. entity specific elements
10. attributes - like transaction, isolation level, security
Keeping in mind that the application assembler is to follow, here is how the deployment
descriptor may look like:
<?xnm version="1.1"?>
<ejb-jar>
<entrprise-beans>
<session>
<ejb-name>CCEnroll</ejb-name>
<home>com.bank11.ccards.ejb.CCEnrollHome</home>
<remote>com.bank11.ccards.CCEnrollObject</remote>
<ejb-class>com.bank11.ccards.CCEnroll</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container<transaction-type>
<ejb-ref>
<ejb-ref-name>ejb/CCAccount</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<home>com.bank11.ccards.ejb.AccountHome</home>
<remote>com.bank11.ccards.ejb.AccountObj</remote>
</ejb-ref>
<security-role-ref>
<description>
This role relates to cash advances from ATMs
</description>
<role-name>CashAdvATM</role-name>
<security-role-ref>
</session>
<entity>
<ejb-name>Account</ejb-name>
<home>com.bank11.ccards.ejb.AccountHome</home>
<remote>com.bank11.ccards.Accountbject</remote>
<ejb-class>com.bank11.ccards.Account</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Integer</prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>accountNumber</field-name>
</cmp-field>
<cmp-field>
<field-name>userName</field-name>
</cmp-field>
<cmp-field>
<field-name>customerID</field-name>
</cmp-field>
<cmp-field>
<prim-key-field>accountNumber</prim-key-field>
</cmp-field>
<env-entry>
<env-entry-name>env/minPaymentPerc</env-entry-name>
<env-entry-type>java.lang.Float</env-entry-type>
<env-entry-value>2.5</env-entry-value>
</env-entry>
</entity>
</enterprise-beans>
</ejb-jar>
The assembly descriptor combines EJBs into a deployable application. Here is a very lean
one:
</ejb-jar>
<enterprise-beans>
...
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>CCEnroll</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>