JAVA Minor Notes
JAVA Minor Notes
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.
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:
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:
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. }
Now provide the implementation of the remote interface. For providing the implementation of
the Remote interface, we need to
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
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
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.
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.
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.
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.
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
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");
The getConnection() method of DriverManager class is used to establish connection with the database.
Example
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
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();
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. }
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. }
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
javax.sql package
This package is also known as JDBC extension API. It provides classes and interface to access
server-side data.
JDBC Drivers
JDBC Driver is a software component that enables java application to interact with the database.There
are 4 types of JDBC drivers:
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:
Disadvantage:
Advantage:
• No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
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:
Disadvantage:
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.
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.
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?
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..
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.
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:
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:
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:
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.
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.
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.
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.
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 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:
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.
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.
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.
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.
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:
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.