J2EE, Rmi and Jdbc
J2EE, Rmi and Jdbc
aminotes
Q1. What is an Application Server?
An application server is software that runs between web-based client programs and
back-end databases and legacy applications. Application servers help separate system
complexity from business logic, enabling developers to focus on solving business
problems. Application servers reduce the size and complexity of client programs by
enabling these programs to share capabilities and resources in an organized and
efficient way.
The varying degrees of compliance to J2EE standards can make migrating applications
from one application server to another a daunting task. Some of the challenges in
migrating J2EE applications from one application server to another are:
These challenges make the migration work unpredictable and difficult to reliably plan
and schedule. This document addresses the challenges in migrating your applications
from JBoss to Oracle Application Server, providing an approach to migration with
solutions based on the J2EE version 1.3 specification.
The J2EE platform provides a multi-tiered distributed application model. Central to the
J2EE component-based development model is the concept of containers. Containers
are standardized runtime environments that provide specific services to components.
Thus, Enterprise Java Beans (EJB) developed for a specific purpose in any organization
can expect generic services such as transaction and EJB life cycle management to be
available on any J2EE platform from any vendor.
aminotes
Containers also provide standardized access to enterprise information systems; for
example, providing database access through the JDBC API. Containers also provide a
mechanism for selecting application behavior at assembly or deployment time.
J2EE Architecture"
Migration Issues
Given the inherent challenges outlined above, it is helpful to examine the applications to
be migrated in terms of the following before quantifying the migration effort.
• Portability
• Dependence on Vendor Specific Implementation
• Deviations from the J2EE Specification
Portability
Code may not be portable because it contains embedded references to vendor- specific
extensions to the J2EE specification. In such cases, runtime exceptions, (for example,
aminotes
"class not found") may occur when applications are migrated and run from one J2EE-
compliant application server to another. In addition, some J2EE application servers still
support deprecated APIs and others are strictly compliant to the J2EE specifications.
JBoss contains extensions to servlets, JSPs, EJBs, JNDI, and JDBC. In such cases,
evaluating code and planning for its modification may be a significant part of the
migration effort.
1. Component Technology
2. Service Technology
3. Communication Technology
Component Technologies
Component technologies are used by developers to create essential parts of the
enterprise application, namely user interface and business logic. In addition to
JavaBeans, which are part of the J2SE platform, the J2EE platform supports different
type of components that can be classified as client-side components and server-side
components.
Client-side Components
Client-side components are developed by the application developers to provide user
interface for enterprise application clients. These components can be classified as
follows:
Application clients
Browser-based clients
Application clients are Java programs that execute on desktop computers. They are
often referred to as standalone applications because they run on their own JVM. J2EE
specification refers to application clients as GUI components.
J2EE must support application components and provide a container to run the
application clients. However, an application client runs on the client machine and not on
The J2EE server. The application client container is required to provide runtime support
for standalone applications.
Brower-based clients are developed by the application developers to provide user
interface for web clients. Web client applications are generally developed using simple
HTML pages, although applets are also used at times.
aminotes
Browser-based clients do not have an associated J2EE container. In order to access
enterprise resources, web clients should communicate through the web container of the
J2EE server. Applets embedded in HTML pages are deployed and managed on the
J2EE server, although they run on client machines.
Server-Side Components
Server-side components are used for providing dynamic user interface and business
logic. Server-side components are deployed in the J2EE server. Based on the
functionality provided by server-side components, they are classified as:
Web components
EJB components
Web components are software entities that provide responses to requests. A web
component typically generates the dynamic user interface for web-based clients. J2EE
specifies two types of web components. They are as mentioned below:
Servlet
Servlet is a Java program that extends the functionalities of a web server. They
dynamically generate and send responses to the requests received from the client.
JSP
JSP provides an extensible way to generate dynamic content for a web client. It is a text-
based document, containing information on creating a response for a request.
EJB components are developed by application developers to provide business logic for
the enterprise application. J2EE provides an EJB specification for developing and
deploying EJB components. EJB components, termed enterprise beans, are scalable,
transactional (i.e., they participate in a transaction) and provide multi-user support.
There are two types of beans:
Session Bean
It is created to provide service on behalf of a client and usually exists only for the
duration of a single client-server session.
Entity Bean
It is a persistent object that represents data maintained in the data store; its focus is
data-centric.
The EJB 2.0 specification introduces a new bean called Message Driven Bean (MDB),
which is used for messaging.
Service Technologies
Since most enterprise applications require access to existing EISs, J2EE supports APls
that provide access to database, transaction and JNDI services. J2EE service
aminotes
technologies allow applications to access these services in a uniform manner.
Database Access
J2EE provides database access to applications based on the JDBC specification. An
application's components can use JDBC to handle data from relational databases.
JDBC APls provide database-independent connectivity between wide ranges of
relational data sources. JDBC APls can also be divided into two parts, an application
level interface used by components for accessing databases and a service provider
interface to attach providers to the platform.
J2EE requires JDBC 2.0 core APls and extension APls, which provide row sets,
connection naming via JNDI, connection pooling, and distributed transaction support.
The JDBC drivers use the connection pooling and distributed transaction to co-ordinate
with the J2EE server.
Java Naming and Directory Interface (JNDI)
This API allows the J2EE components to lookup other remote objects that they may
need to access. Using JNDI, an application can store and retrieve any type of named.
Java objects. The JNDI API was designed to standardize access to a variety of naming
and directory interfaces and has two parts. They are as follows:
An application-level interface used by the application components to access naming and
directory services.
A service provider interface used to attach a provider of a naming and directory services
to the J2EE platform.
Transaction Service
Transaction services in J2EE environment is based on Java Transaction API (JTA) and
Java Transaction Service (JTS).
JTA provides a way for J2EE components and clients to manage their own transactions.
It allows multiple components to participate in a single transaction. JTA specifies
standard Java interfaces between the transaction manager and the parties involved in a
distributed transaction system, such as the application which needs transaction support.
Communication Technologies
Communication technologies provide mechanisms for communication between client
and server and between collaborating objects hosted by different servers. J2EE
specification requires support for the following protocols and APls under communication
technologies:
HTTP
HTTP (S)
Remote Method Invocation (RMI)
Object Management Group (OMG)
JMS
aminotes
JavaMail/JAF
Connector architecture
RMI Notes
aminotes
Difference Between local and Remote Object
Garbage When all local references The distributed garbage collector works
Collection to an object have been with the local garbage collector. If there are
dropped, an object no remote references and all local
becomes a candidate for references to a remote object have been
garbage collection. dropped, then it becomes a candidate for
garbage collection through the normal
means.
Exceptions Exceptions are either RMI forces programs to deal with any
Runtime exceptions or possible RemoteException objects that
Exceptions. The Java may be thrown. This was done to ensure
compiler forces a the robustness of distributed applications.
program to handle all
Exceptions.
The RMI Architecture is very simple involving a client program, a server program, a stub
and skeleton.
In RMI, the client and server do not communicate directly; instead communicates
through stub and skeleton (a special concept of RMI and this is how designers
achieved distributed computing in Java). They are nothing but special programs
generated by RMI compiler. They can be treated as proxies for the client and server.
Stub program resides on client side and skeleton program resides on server. That is,
the client sends a method call with appropriate parameters to stub. The stub in turn calls
the skeleton on the server. The skeleton passes the stub request to the server to
execute the remote method. The return value of the method is sent to the skeleton by
aminotes
the server. The skeleton, as you expect, sends back to the stub. Finally the return value
reaches client through stub.
Note: The method existing on the server is a remote method to the client (because
client and server may be far away anywhere in the globe); but for the server, it is local
method only. So, for the client, the server is remote server (okay, in server point of view,
the client is remote client, but in RMI, we do not call client as remote client), a program
on the remote server is remote program and finally the method in the remote program is
remote method. Know the meaning of remote server, remote program, remote method;
this must be very clear to the beginner else the RMI concept is very confusing at the
outset. So, anything residing on server is remote to client.
The RMI Architecture process is explained figuratively as under.
As the figure illustrates, there comes three layers in the RMI Architecture – Application
layer, Proxy layer and Remote reference layer (Transport layer is part of Remote
reference layer).
1. Application Layer
aminotes
This layer is nothing but the actual systems (client and server) involved in
communication. A client Java program communicates with the other Java program on
the server side. RMI is nothing but a communication between two JVMs placed on
different systems.
2. Proxy Layer
The proxy layer consists of proxies (named as stub and skeleton by designers) for
client and server. Stub is client side proxy and Skeleton is server side proxy. Stub
and skeleton, as many people confuse, are not separate systems but they are after all
programs placed on client and server. The stub and skeleton are not hard coded by the
Programmer but they are generated by RMI compiler (this is shown in execution part
later). Stub is placed on client side and skeleton is placed on server side. The client
server communication goes through these proxies. Client sends its request of method
invocation (to be executed on remote server) to stub. Stub inturn sends the request to
skeleton. Skeleton passes the request to the server program. Server executes the
method and sends the return value to the skeleton (to route to client). Skeleton sends to
stub and stub to client program.
Marshaling and Unmarshaling
One more job of proxies is marshaling and unmarshaling. Marshaling is nothing but
converting data into a special format suitable to pass through the distributed
environment without losing object persistence. For this reason, the RMI mechanism
implicitly serializethe objects involved in communication. The stub marshals the data of
client and then sends to the skeleton. As the format is not understood by the server
program, it is unmarshaled by the skeleton into the original format and passed to server.
Similarly from server to client also.
A marshal stream includes a stream of objects that are used to transport parameters,
exceptions, and errors needed for these streams for communicating with each other.
Marshaling and unmarshaling are done by the RMI runtime mechanism implicitly without
any programmers extra coding.
Using RMI
It is now time to build a working RMI system and get hands-on experience. In this
section, you will build a simple remote calculator service and use it from a client
program.
In the next sections, you will build a simple RMI system in a step-by-step fashion. You
are encouraged to create a fresh subdirectory on your computer and create these files
as you read the text.
To simplify things, you will use a single directory for the client and server code. By
running the client and the server out of the same directory, you will not have to set up
an HTTP or FTP server to provide the class files. (Details about how to use HTTP and
FTP servers as class file providers will be covered in the section on Distributing and
Installing RMI Software)
Assuming that the RMI system is already designed, you take the following steps to build
a system:
Notice this interface extends Remote, and each method signature declares that it
may throw a RemoteException object.
Copy this file to your directory and compile it with the Java compiler:
>javac Calculator.java
2. Implementation
Next, you write the implementation for the remote service. This is
the CalculatorImpl class:
Again, copy this code into your directory and compile it.
The implementation class uses UnicastRemoteObject to link into the RMI system. In
the example the implementation class directly extends UnicastRemoteObject. This is
not a requirement. A class that does not extend UnicastRemoteObject may use
its exportObject() method to be linked into RMI.
>rmicCalculatorImpl
Try this in your directory. After you run rmic you should find the
file Calculator_Stub.class and, if you are running the Java 2 SDK, Calculator_Skel.class.
Options for the JDK 1.1 version of the RMI compiler, rmic, are:
4. Host Server
Remote RMI services must be hosted in a server process. The
class CalculatorServer is a very simple server that provides the bare essentials for
hosting.
import java.rmi.Naming;
public CalculatorServer() {
try {
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService", c);
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}
5. Client
The source code for the client follows:
aminotes
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
Start with the Registry. You must be in the directory that contains the classes you
have written. From there, enter the following:
rmiregistry
If all goes well, the registry will start running and you can switch to the next console.
In the second console start the server hosting the CalculatorService, and enter the
following:
>java CalculatorServer
It will start, load the implementation into memory and wait for a client connection.
>java CalculatorClient
QUESTIONS
A method of a Java program placed on any other system (not in your own system) in
the world.
3. Then what is invocation?
aminotes
Sending a request to the other system (say, a server) to execute the method (say, to
call as remote method) available on it by passing sufficient parameters required for the
execution of the method and asking to return the return value of the method.
Finally, RMI is nothing but communication between two JVMs loaded on two different
systems.
Take an example of a Bank ATM operation. Suppose you are to ATM to know the
account balance. You know the balance is available on the bank server and not on ATM
machine (say, ATM client). When you swipe your card your account number goes into
the machine and inform the machine that you need to know the balance by clicking the
button. Now there are two values to be send to the server (we call these as parameters
later), one is account number and the other is what the operation you need.
Now imagine, there is a method on the server (we call remote method as it is not
avilable on your local ATM system) which will take care of your need, say "public double
getBalance(int accountNumber, double retrieveBalance)". Now RMI job is to take your
information and send it as parameters to the remote method, execute the method and
send back the account balance as return value to the ATM client to print the label.
The client should be able to communicate with the remote objects. This is taken care
byRMI runtime environment. RMI programming feels in such way the remote method
invocation is as if invoking on a local system. Small difference comes in Server side
program where binding is performed by the remote object with the RMI runtime
mechanism through RMI registry.
To load methods for objects used in invocation. RMI passes objects between client and
server and loads methods as per need.
No, RMI job is communication only – sending parameters to the remote method and
getting back the return value of the remote method to the client. To take care of
transactions, takes the help of EJB (Enterprise Java Beans). The backbone of EJB is
RMI. EJB uses RMI for communication and adds extra features like transaction
management, security, atomicity, load balancing and logging etc.
First of all you know it is not a Web based technology. So, RMI does not use browsers
and HTTP protocol. It comes with its own protocol known as RMI protocol with a default
port number 1099 (which you can configure of your own). The protocol involves RMI
runtime environment, Remote references for remote objects, RMI registry and some
naming service etc.
It is multithreaded.
RMI has different type of garbage collection known as Distributed garbage collection.
Everyone knows what is garbage collection in Java – removing objects that do not have
any reference (not used) in the remaining part of the Java program being executed. All
this happens on a single system. But distributed garbage collection is very different as it
occurs between two systems. In RMI, the server exports a object to the client by storing
a reference with it. When the client communication is over or disconnects with the
server, the reference of client is lost on the server remote object. If the reference of the
client no more exists, the remote object on the server is eligible for garbage collection.
This is known as distributed garbage collection. Remote objecct and the reference are
explained in RMI Application Step by Step Programs Explanation (in 4th Program –
client program).
Basically there are three layers – Application layer, Proxy layer and Remote reference
layer. These are discussed in RMI architecture clearly.
Java Database Connectivity
aminotes
What is JDBC Driver ?
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK contains various classes with their
behaviours defined and their actual implementaions are done in third-party drivers.
Third party vendors implements the java.sql.Driver interface in their database driver.
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types
into four categories, Types 1, 2, 3, and 4, which is explained below:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each
client machine. Using ODBC requires configuring on your system a Data Source Name
(DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only
supported ODBC access but now this type of driver is recommended only for
experimental use or when no other alternative is available.
aminotes
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of
driver.
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are
unique to the database. These drivers typically provided by the database vendors and
used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must
be installed on each client machine.
This kind of driver is extremely flexible, since it requires no code installed on the client
and a single driver can actually provide access to multiple databases.
aminotes
You can think of the application server as a JDBC "proxy," meaning that it makes calls
for the client application. As a result, you need some knowledge of the application
server's configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the
database, understanding the nuances will prove helpful.
In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's
database through socket connection. This is the highest performance driver available
for the database and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the
client or server. Further, these drivers can be downloaded dynamically.
aminotes
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the
preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type
3 is the preferred driver.
Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet
for your database.
The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available.
Disadvantages
aminotes
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC
driver, then to the database, and this applies even in the reverse process. They are the
slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better
performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are
less than that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be
used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a
database
4. Mostly obsolete now
5. Usually not thread safe.
Advantage
1. This driver is server-based, so there is no need for any vendor database library to be
present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast
to load.
5. The type 3 driver typically provides support for features such as caching
(connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
aminotes
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset
may take longer, since the data comes through the backend server.
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written in
Java to achieve platform independence and eliminate deployment administration issues.
It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to
translate database requests to ODBC or a native connectivity interface or to pass the
request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these
drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
Connection interface
aminotes
A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object
of Connection can be used to get the object of Statement and DatabaseMetaData. The
Connection interface provide many methods for transaction management like commit(),
rollback() etc.
Statement interface
The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the object
of ResultSet.
1) public ResultSetexecuteQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONC
UR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
aminotes
How to get the instance of PreparedStatement?
package project1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
aminotes
c=DriverManager.getConnection("jdbc:odbc:progdsn");
Statement s=c.createStatement();
}
out.println("</body>");
}
catch(SQLException se) {
out.println(se);
}
catch(ClassNotFoundExceptioncn) {
out.println(cn);
}
out.close();
}
}
aminotes
A Servlet does not run in a separate process. This removes the overhead of
creating a new process for each request.
A Servlet stays in memory between requests. A CGI program (and probably also
an extensive runtime system or interpreter) needs to be loaded and started for
each CGI request.
There is only a single instance which answers all requests concurrently. This
saves memory and allows a Servlet to easily manage persistent data.
Several web.xml conveniences
A handful of removed restrictions
Some edge case clarifications
Servlet interface
aminotes
The central abstraction in the Servlet API is the Servlet interface. All servlets implement
this interface, either directly or , more commonly by extending a class that implements
it.