0% found this document useful (0 votes)
6 views34 pages

J2EE, Rmi and Jdbc

The document provides an overview of J2EE architecture, detailing the role of application servers in separating business logic from system complexity and the challenges involved in migrating J2EE applications between different servers. It explains the multi-tiered architecture of J2EE applications, including client-side and server-side components, as well as service and communication technologies. Additionally, it discusses the RMI architecture, highlighting the use of stubs and skeletons for remote method invocation and the process of marshaling and unmarshaling data between client and server.

Uploaded by

dsnrorbit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views34 pages

J2EE, Rmi and Jdbc

The document provides an overview of J2EE architecture, detailing the role of application servers in separating business logic from system complexity and the challenges involved in migrating J2EE applications between different servers. It explains the multi-tiered architecture of J2EE applications, including client-side and server-side components, as well as service and communication technologies. Additionally, it discusses the RMI architecture, highlighting the use of stubs and skeletons for remote method invocation and the process of marshaling and unmarshaling data between client and server.

Uploaded by

dsnrorbit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

J2EE Architecture

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.

Application servers provide benefits in the areas of usability, flexibility, scalability,


maintainability, and interoperability.

J2EE Application Migration Challenges

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:

• Though in theory any J2EE application can be deployed on any J2EE-compliant


application server, in practice this is not strictly true.
• Lack of knowledge of the implementation details of the given J2EE application.
• Ambiguity in the meaning of 'J2EE-compliant' (usually, this means the application
server has J2EE-compliant features, not code-level compatibility with the J2EE
specification).
• The number of vendor-supplied extensions to the J2EE standards in use, which
differ in deployment methods and reduce portability of Java code from one
application server to another.
• Differences in clustering, load balancing, and failover implementations among
application servers. These differences are sparsely documented, and are thus an
even bigger challenge to the migration process.

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.

Q2. Explain J2EE Application Architecture

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.

As shown in Figure , the J2EE application architecture is a multi-tiered application


model. In the middle tier, components are managed by containers; for example, J2EE
Web containers invoke servlet behavior, and EJB containers manage life cycle and
transactions for EJBs. The container-based model separates business logic from
system infrastructure.

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.

Dependence on Vendor Specific Implementation

If JBoss-specific services are in use, migration of those components becomes difficult or


unfeasible. These components may need to be redesigned and reimplemented, instead
of being identified as migration candidates. This guide does not address complete
redesign toward J2EE specifications.

Q: Explain J2EE Architecture and discuss.

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

Local Object Remote Object

Object Definition A local object is defined A remote object's exported behavior is


by a Java class. defined by an interface that must extend
the Remote interface.

Object A local object is A remote object's behavior is executed by


Implementation implemented by its Java a Java class that implements the remote
class. interface.

Object Creation A new instance of a local A new instance of a remote object is


object is created by created on the host computer with
the new operator. the new operator. A client cannot directly
create a new remote object (unless using
Java 2 Remote Object Activation).

Object Access A local object is A remote object is accessed via an object


accessed directly via an reference variable which points to a proxy
object reference variable. stub implementation of the remote
interface.

References In a single JVM, an A "remote reference" is a pointer to a proxy


object reference points object (a "stub") in the local heap. That
directly at an object in the stub contains information that allows it to
heap. connect to a remote object, which contains
the implementation of the methods.

Active In a single JVM, an In a distributed environment, remote JVMs


References object is considered may crash, and network connections may
"alive" if there is at least be lost. A remote object is considered to
one reference to it. have an active remote reference to it if it
has been accessed within a certain time
period (the lease period). If all remote
references have been explicitly dropped, or
if all remote references have expired
leases, then a remote object is available for
aminotes
distributed garbage collection.

Finalization If an object implements If a remote object implements


the finalize() method, it is the Unreferenced interface, the
called before an object is unreferenced method of that interface is
reclaimed by the garbage called when all remote references have
collector. been dropped.

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.

3. Remote Reference Layer


Proxies are implicitly connected to RMI mechanism through Remote reference layer, the
layer responsible for object communication and transfer of objects between client and
server. It is responsible for dealing with semantics of remote invocations and
implementation – specific tasks with remote objects. In this layer, actual implementation
of communication protocols is handled.
aminotes
Transport layer does not exist separately but is a part of Remote reference layer.
Transport layer is responsible for actually setting up connections and handling the
transport of data from one machine to another. It can be modified to handle encrypted
streams, compression algorithms and a number of other security/performance related
enhancements.
The marshaled stream is passed to RRL(Remote Reference Layer). Task of RRL is to
identify the host, that is, remote machine. The marshaled stream is passed to Transport
layer which performs routing.

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.

A working RMI system is composed of several parts.

• Interface definitions for the remote services


• Implementations of the remote services
• Stub and Skeleton files
• A server to host the remote services
• An RMI Naming service that allows clients to find the remote services
• A class file provider (an HTTP or FTP server)
• A client program that needs the remote services

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:

1. Write and compile Java code for interfaces


2. Write and compile Java code for implementation classes
3. Generate Stub and Skeleton class files from the implementation classes
4. Write Java code for a remote service host program
5. Develop Java code for RMI client program
6. Install and run RMI system
aminotes
1. Interfaces
The first step is to write and compile the Java code for the service interface.
The Calculator interface defines all of the remote features offered by the service:

public interface Calculator


extends java.rmi.Remote {
public long add(long a, long b)
throws java.rmi.RemoteException;

public long sub(long a, long b)


throws java.rmi.RemoteException;

public long mul(long a, long b)


throws java.rmi.RemoteException;

public long div(long a, long b)


throws java.rmi.RemoteException;
}

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:

public class CalculatorImpl


extends
java.rmi.server.UnicastRemoteObject
implements Calculator {
// Implementations must have an
aminotes
//explicit constructor
// in order to declare the
//RemoteException exception
public CalculatorImpl()
throws java.rmi.RemoteException {
super();
}

public long add(long a, long b)


throws java.rmi.RemoteException {
return a + b;
}

public long sub(long a, long b)


throws java.rmi.RemoteException {
return a - b;
}

public long mul(long a, long b)


throws java.rmi.RemoteException {
return a * b;
}

public long div(long a, long b)


throws java.rmi.RemoteException {
return a / b;
}
}

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.

When a class extends UnicastRemoteObject, it must provide a constructor that declares


that it may throw a RemoteException object. When this constructor calls super(), it
aminotes
activates code inUnicastRemoteObject that performs the RMI linking and remote object
initialization.

3. Stubs and Skeletons


You next use the RMI compiler, rmic, to generate the stub and skeleton files. The
compiler runs on the remote service implementation class file.

>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:

Usage: rmic<options><class names>

where <options> includes:


-keep Do not delete intermediate
generated source files
-keepgenerated (same as "-keep")
-g Generate debugging info
-depend Recompile out-of-date
files recursively
-nowarn Generate no warnings
-verbose Output messages about
what the compiler is doing
-classpath<path> Specify where
to find input source
and class files
-d <directory> Specify where to
place generated class files
-J<runtime flag> Pass argument
to the java interpreter

The Java 2 platform version of rmic add three new options:

-v1.1 Create stubs/skeletons


for JDK 1.1 stub
protocol version
aminotes
-vcompat (default)
Create stubs/skeletons compatible
with both JDK 1.1 and Java 2
stub protocol versions
-v1.2 Create stubs for Java 2 stub protocol
version only

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 class CalculatorServer {

public CalculatorServer() {
try {
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService", c);
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}

public static void main(String args[]) {


new CalculatorServer();
}
}

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;

public class CalculatorClient {

public static void main(String[] args) {


try {
Calculator c = (Calculator)
Naming.lookup(
"rmi://localhost
/CalculatorService");
System.out.println( c.sub(4, 3) );
System.out.println( c.add(4, 5) );
System.out.println( c.mul(3, 6) );
System.out.println( c.div(9, 3) );
}
catch (MalformedURLExceptionmurle) {
System.out.println();
System.out.println(
"MalformedURLException");
System.out.println(murle);
}
catch (RemoteException re) {
System.out.println();
System.out.println(
"RemoteException");
System.out.println(re);
}
catch (NotBoundExceptionnbe) {
System.out.println();
System.out.println(
"NotBoundException");
System.out.println(nbe);
}
catch (
java.lang.ArithmeticException
ae) {
aminotes
System.out.println();
System.out.println(
"java.lang.ArithmeticException");
System.out.println(ae);
}
}
}

6. Running the RMI System


You are now ready to run the system! You need to start three consoles, one for the
server, one for the client, and one for the RMIRegistry.

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.

In the last console, start the client program.

>java CalculatorClient

QUESTIONS

1. What is Java RMI?

RMI stands for "Remote Method Invocation", the technology of Java.

2. What is remote method?

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.

4. Give a practical example, to be more clear in this RMI tutorial?

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.

This is exactly what RMI application does.

5. What is distributed communication? Explain for beginners

RMI sort of communication is an example of distributed communication where systems


are distributed across the globe. Here Internet is not used and where it differs with
Servletcommunication. The systems involved in communication are known as
distributed systemsand programming is known as distributed computing. If required,
RMI can be connected to Internet to communicate with Web servers.

6. What a distributed application should satisfy?

A distributed application needs the following to do.


aminotes
The client should be able to locate the remote objects existing on remote server. For
example, RMI uses a naming service given by Naming class to bind remote objects with
the rmi registry.

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.

7. As it given an example of bank transaction, does RMI take care of transaction


management also?

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.

8. What protocol RMI uses?

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.

9. What is object communication?

In RMI, objects communicate; an object on client side communicates with another


object on server side. This is known as object-to-object communication. Through
distributed network, objects pass in between client and server (having reference to each
other). For this purpose, RMI internally serialize objects. This is good example where
Java uses objects most extensively in programming.

10. What is remote object?


aminotes
An object created on the server (by the server program) is known as remote object. To
put technically, any object that implements java.rmi.Remote interface is known as
remote object. This we is shown how to create in RMI Application Step by Step
Programs Explanation (in 3rd Program – server program).

11. What are the features of RMI?

It is object-oriented and communication is between Java-to-Java objects distributed.

It is multithreaded.

All the features of Java are applicable to RMI.

The extended Java features are: a) Distributed connectivity b) Connecting legacy


systems. Legacy means that we do not know in advance what type of server it is going
to be connected in the network.

RMI is seamless integration. Seamless implies communication through an object and


information about operating system where the object developed is not known to the
programmer when he writes the code.

RMI has different type of garbage collection known as Distributed garbage collection.

12. What is 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).

14. How many layers exists in RMI Architecture?

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 Drivers Types:

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:

Type 1: JDBC-ODBC Bridge Driver:

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.

Type 2: JDBC-Native API:

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.

If we change the Database we have to change the native API as it is specific to a


database and they are mostly obsolete now but you may realize some speed increase
with a Type 2 driver, because it eliminates ODBC's overhead.
aminotes

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java:

In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC


clients use standard network sockets to communicate with an middleware application
server. The socket information is then translated by the middleware application server
into the call format required by the DBMS, and forwarded to the database server.

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.

Type 100: 100% pure Java:

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

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of


their network protocols, database vendors usually supply type 4 drivers.

Which Driver should be used?

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.

Type 1: JDBC-ODBC Bridge

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.

Type 2: Native api/ Partly Java Driver

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.

Type 3 JDBC Driver

Type 3: All Java/ Net-Protocol Driver

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.

Type 4 JDBC Driver

Type 4: Native-protocol/all-Java driver

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.

Commonly used methods of Statement interface:

The important methods of Statement interface are as follows:

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.

4) public int[] executeBatch(): is used to execute batch of commands.

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. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


2. ResultSet.CONCUR_UPDATABLE);
Example of Scrollable ResultSet
aminotes
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.

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.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.

Why use 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?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws SQLException{}


aminotes
Write a program to provide database connectivity using Type 1 Driver to a
employee table to insert, update,delete data using Servlets

Insert a Row in a Table:

package project1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Program1 extends HttpServlet{


private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
Connection c;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}

public void doGet(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
aminotes
c=DriverManager.getConnection("jdbc:odbc:progdsn");
Statement s=c.createStatement();

s.executeUpdate("insert into employ values('sahil', '1st jan 1988')");

ResultSetrs=s.executeQuery("Select * from Employ");


out.println("<body>");
out.println("A row is Inserted in Emloyee table");
out.println();
out.println("<table border = 1><th>Employee Name</th><th>Date of Birth</>");
while(rs.next()) {
out.println("<tr><td><b>" + rs.getString(1) + "</td>");
out.println("<td>" + rs.getString(2) + "</td></tr>");

}
out.println("</body>");
}
catch(SQLException se) {
out.println(se);
}
catch(ClassNotFoundExceptioncn) {
out.println(cn);
}
out.close();
}
}
aminotes

What are the advantages of Servlet over CGI?

Servlets have several advantages over CGI:

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy