0% found this document useful (0 votes)
82 views

JAVA Minor Notes

The RMI (Remote Method Invocation) API allows objects to invoke methods on objects residing in other Java Virtual Machines (JVMs). It uses stub and skeleton objects to enable remote communication between applications. The stub acts as a proxy for remote objects on the client side, while the skeleton acts as a proxy on the server side. Together they allow clients to invoke methods on remote objects as if they were local.

Uploaded by

Yash Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

JAVA Minor Notes

The RMI (Remote Method Invocation) API allows objects to invoke methods on objects residing in other Java Virtual Machines (JVMs). It uses stub and skeleton objects to enable remote communication between applications. The stub acts as a proxy for remote objects on the client side, while the skeleton acts as a proxy on the server side. Together they allow clients to invoke methods on remote objects as if they were local.

Uploaded by

Yash Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

RMI

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM.

The RMI provides remote communication between the applications using two objects stub and
skeleton.

Understanding stub and skeleton

RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM. Let's understand
the stub and skeleton objects:

stub

The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton

The skeleton is an object, acts as a gateway for the server side object. All the incoming requests
are routed through it. When the skeleton receives the incoming request, it does the following
tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.

1) create the remote interface

For creating the remote interface, extend the Remote interface and declare the RemoteException
with all the methods of the remote interface. Here, we are creating a remote interface that
extends the Remote interface. There is only one method named add() and it declares
RemoteException.

1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }

2) Provide the implementation of the remote interface

Now provide the implementation of the remote interface. For providing the implementation of
the Remote interface, we need to

• Either extend the UnicastRemoteObject class,


• or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }

3) create the stub and skeleton objects using the rmic tool.

Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the
RMI compiler and creates stub and skeleton objects.

1. rmic AdderRemote

4) Start the registry service by the rmiregistry tool

Now start the registry service by using the rmiregistry tool. If you don't specify the port number,
it uses a default port number. In this example, we are using the port number 5000.

1. rmiregistry 5000

5) Create and run the server application

Now rmi services need to be hosted in a server process. The Naming class provides methods to
get and store the remote object. The Naming class provides 5 methods.

1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
6) Create and run the client application

At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object. In this example, we are running the server and client
applications, in the same machine so we are using localhost. If you want to access the remote
object from another machine, change the localhost to the host name (or IP address) where the
remote object is located.

1. import java.rmi.*;
2. public class MyClient{
3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
6. System.out.println(stub.add(34,4));
7. }catch(Exception e){}
8. }
9. }

RMI ARCHITECTURE

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

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 loosing
object persistence. For this reason, the RMI mechanism implicitly serialize the 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.

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
JDBC (Java Database Connectivity)
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.

Why use JDBC

Before JDBC, ODBC API was the database API to connect and execute query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
What is API

API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc

5 Steps to connect to the database in java

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLException


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.

Statement stmt=con.createStatement();

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.

con.close();

Program Example

1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }

JDBC 4.0 API

JDBC 4.0 API is mainly divided into two package

1. java.sql
2. javax.sql

java.sql package

This package include classes and interface to perform almost all JDBC operation such as creating
and executing SQL Queries.
Important classes and interface of java.sql package
classes/interface Description

java.sql.BLOB Provide support for BLOB(Binary Large Object) SQL type.

java.sql.Connection creates a connection with specific database

java.sql.CallableStatement Execute stored procedures

java.sql.CLOB Provide support for CLOB(Character Large Object) SQL type.

java.sql.Date Provide support for Date SQL type.

java.sql.Driver create an instance of a driver with the DriverManager.

java.sql.DriverManager This class manages database drivers.

java.sql.PreparedStatement Used to create and execute parameterized query.

It is an interface that provide methods to access the result row-by-


java.sql.ResultSet
row.

java.sql.Savepoint Specify savepoint in transaction.

java.sql.SQLException Encapsulate all JDBC related exception.

java.sql.Statement This interface is used to execute SQL statements.

javax.sql package

This package is also known as JDBC extension API. It provides classes and interface to access
server-side data.

Important classes and interface of javax.sql package


classes/interface Description

javax.sql.ConnectionEvent Provide information about occurence of event.

Used to register event generated by PooledConnection


javax.sql.ConnectionEventListener
object.

Represent the DataSource interface used in an


javax.sql.DataSource
application.
javax.sql.PooledConnection provide object to manage connection pools

JDBC Drivers

JDBC Driver is a software component that enables java application to interact with the database.There
are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin
driver.

Advantages:

• easy to use.
• can be easily connected to any database.
Disadvantages:

• Performance degraded because JDBC method call is converted into the ODBC function calls.
• The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.

Advantage:

• performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

• The Native driver needs to be installed on the each client machine.


• The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:

• No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.

Disadvantages:

• Network support is required on client machine.


• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.
Advantage:

• Better performance than all other drivers.


• No software is required at client side or server side.

Disadvantage:

• Drivers depends on the Database.

HTTP (Hyper Text Transfer Protocol)


The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems. It is the data communication protocol used to
establish communication between client and server.

HTTP is TCP/IP based communication protocol, which is used to deliver the data like image
files, query results, HTML files etc on the World Wide Web (WWW) with the default port is
TCP 80. It provides the standardized way for computers to communicate with each other.
The Basic Characteristics of HTTP (Hyper Text Transfer Protocol):

• It is the protocol that allows web servers and browsers to exchange data over the web.
• It is a request response protocol.
• It uses the reliable TCP connections by default on TCP port 80.
• It is stateless means each request is considered as the new request. In other words, server
doesn't recognize the user by default.

The Basic Features of HTTP (Hyper Text Transfer Protocol):

There are three fundamental features that make the HTTP a simple and powerful protocol used
for communication:

• HTTP is media independent: It refers to any type of media content can be sent by HTTP as long
as both the server and the client can handle the data content.
• HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a browser
initiates the HTTP request and after the request is sends the client disconnects from server and
waits for the response.
• HTTP is stateless: The client and server are aware of each other during a current request only.
Afterwards, both of them forget each other. Due to the stateless nature of protocol, neither the
client nor the server can retain the information about different request across the web pages.

J2EE Architecture

The JEE platform provides the environment to develop enterprise applications / services using
multitier architecture.

- The highly intensified technology made the need for scalable, efficient, faster solutions for
information management.

- The JEE technology is rightly apt for meeting these requirements.

- JEE provides a programming development environment which improves the productivity of


development, standards for hosting / deploying enterprise applications.
J2EE architecture supports component-based development of multi-tier enterprise applications.
A J2EE application system typically includes the following tiers:

Client tier
In the client tier, Web components, such as Servlets and JavaServer Pages (JSPs), or
standalone Java applications provide a dynamic interface to the middle tier.
Middle tier
In the server tier, or middle tier, enterprise beans and Web Services encapsulate reusable,
distributable business logic for the application. These server-tier components are
contained on a J2EE Application Server, which provides the platform for these
components to perform actions and store data.
Enterprise data tier
In the data tier, the enterprise's data is stored and persisted, typically in a relational
database.

What is a Servlet?

Servlet can be described in many ways, depending on the context.

• Servlet is a technology i.e. used to create web application.


• Servlet is an API that provides many interfaces and classes including documentations.
• Servlet is an interface that must be implemented for creating any servlet.
• Servlet is a class that extend the capabilities of the servers and respond to the incoming request.
It can respond to any type of requests.
• Servlet is a web component that is deployed on the server to create dynamic web page.
Advantage of Servlets

1. better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak,
garbage collection etc.
4. Secure: because it uses java language..

Life Cycle of a Servlet (Servlet Life Cycle)

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:

1. public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only
once. The syntax of the service method of the Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is given below:

1. public void destroy()

Servlet collaboration

The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the content of
another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.


Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML file) on the server.
2. public void include(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP
page, or HTML file) in the response.

As you see in the above figure, response of second servlet is sent to the client. Response of the
first servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in the response of the
first servlet that is being sent to the client.

Send Direct in servlet

The sendRedirect() method of HttpServletResponse interface can be used to redirect response


to another resource, it may be servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another request. So, it
can work inside and outside the server.

Example of sendRedirect() method

1. response.sendRedirect("http://www.javatpoint.com");

Context

An object of ServletContext is created by the web container at time of deploying the project.
This object can be used to get configuration information from web.xml file. There is only one
ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file using
the <context-param> element.

Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available
for all the servlet. We provide this information from the web.xml file, so if the information is
changed, we don't need to modify the servlet. Thus it removes maintenance problem.

Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:

1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.

Session Tracking

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each
time user requests to the server, server treats the request as the new request. So we need to
maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

JSP

JSP technology is used to create web application just like Servlet technology. It can be thought
of as an extension to servlet because it provides more functionality than servlet such as
expression language, jstl etc.

A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than
servlet because we can separate designing and development. It provides some additional features
such as Expression Language, Custom Tag etc.

Advantage of JSP over Servlet

There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet

JSP technology is the extension to servlet technology. We can use all the features of servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and
Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation
logic. In servlet technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.

Life cycle of a JSP Page

The JSP pages follows these phases:

• Translation of JSP Page


• Compilation of JSP Page
• Classloading (class file is loaded by the classloader)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( jspInit() method is invoked by the container).
• Reqeust processing ( _jspService() method is invoked by the container).
• Destroy ( jspDestroy() method is invoked by the container).

As depicted in the above diagram, JSP page is translated into servlet by the help of JSP translator. The
JSP translator is a part of webserver that is responsible to translate the JSP page into servlet. Afterthat
Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all the
processes that happens in servlet is performed on JSP later like initialization, committing response to the
browser and destroy.
JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1. <% java source code %>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response. So
you need not write out.print() to write data. It is mainly used to print the values of variable or
method.

Syntax of JSP expression tag

1. <%= statement %>


JSP declaration tag
The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>

You might also like