SlideShare a Scribd company logo
1 of 94
Download to read offline
1 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
What is JDBC?
It is Java Database Connectivity technology.
This technology is an API(Application Programming Interface)
for the java programming language that define how
a client may access a database.
It provides methods for querying and updating data in database.
What are JDBC Drivers?
It is a software component enabling a java application to interact with a database.
JDBC Driver Types
JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
Type 1 JDBC Driver
JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC
driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for
experimental use or when no other alternative is available.
2 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
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
1. This 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.
3 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Type 2 JDBC Driver
Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are
that Type 2 drivers convert JDBC calls into database-specific calls
i.e. this driver is specific to a particular database.
Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will
have oracle native api.
Type 2: Native api/ Partly Java Driver
4 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
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.
3. This driver is not written in Java Language .Type 2 drivers are not portable.
4. If we change the Database we have to change
the native api as it is specific to a database.
5. Usually not thread safe.
Type 3 JDBC Driver
All Java/Net-protocol driver
Type 3 database requests are passed through
the network to the middle-tier server.
The middle-tier then translates the request to the database.
If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
5 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
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 it is Portable.
3. It is suitable for the web.
4. There are many opportunities to optimize portability,
performance, and scalability.
5. The net protocol can be designed to make
the client JDBC driver very small and fast to load.
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
6 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
It requires another server application to install and maintain.
Type 4 JDBC Driver
Native-protocol/all-Java driver
The Type 4 uses java networking libraries
to communicate directly with the database server.
Type 4: Native-protocol/all-Java driver
Advantage
1.They are written in java so that it is portable.
2.It is most suitable for the web.
3. 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.It don’t need to install special software on the client or server. Further, these drivers can be
downloaded dynamically.
7 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access.
1. Two-tier
In such an architecture, the Java application communicates directly with the data source (or
database). The database may reside on the same machine or may be on another machine to which
the clinet machine needs to be connected through a network
2. Three-tier
8 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
In such an architecture, the client machine will send the database access statements to the
middleware, which will then send the statements to the database residing on the third tier of the
architecture, which is normally referred to as the back end. The statements will be processed
there and the result be returned back to the client through the middle tier. This approach will
have all the advantages associated with the 3-tier architecture, such as better maintainability,
easier deployment, scalability, etc.
BASIC JDBC STEPS
1.Load the driver
Loading Database driver is very first step towards making JDBC connectivity with the database.
It is necessary to load the JDBC drivers before attempting to connect to the database.
Syntax
Class.forName(drivername)
E.g
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”).
9 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
2.Establishing Connection
After loading driver, now Establishing Connection with the database with user name and
password.
Syntax
con = DriverManager.getConnection(url+db, user, pass);
E.g
con = DriverManager.getConnection("jdbc:odbc:vision")
3.Create a statement object:
There are three basic types of SQL statements used in the JDBC API:
1.Statement:A Statement represents a general SQL statement without parameters. The method
createStatement() creates a Statement object.
Eg
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from student ");
2.Prepared Statement: A PreparedStatement represents a precompiled SQL statement, with
or without parameters. It is used for SQL commands that need to be executed repeatedly.
Eg 1
PreparedStatement ps = con.prepareStatement(“select * from student where rollno=?”);
ps.setString(1,1);
ResultSet rs = stmt.executeQuery();
Eg2
10 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
PreparedStatement ps = con.prepareStatement(“insert into student values(?,?,?)”);
ps.setInt(1,1);
ps.setString(2,’amol’);
ps.setFloat(3,66.55f);
ResultSet rs = ps.executeUpdate();
3.CallableStatement - CallableStatement objects are used to execute SQL stored procedures
Eg
CallableStatement cstmt=conn.prepareCall(“call student”);
4.Execute a query
An SQL statement can either be a query that return result or operation that manipulates the
database
1.ResultSet executeQuery(String sql):
It is used for statements that return an output result(for only select query)
2.int executeUpdate(String sql): Returns an integer representing the number of rows affected
by the SQL statement. (For only INSERT, DELETE, or UPDATE SQL statements).
5.Process a query:ResultSet provides access to a table of data generated by executing a
Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to
its current row of data. The next() method is used to successively step through the rows of the
tabular results.
To access these values, there are getXXX() methods where XXX is a type for example,
getString(), getInt(),getFloat etc.
There are two forms of the getXXX methods:
i. Using columnName: getXXX(String columnName)
ii. Using columnNumber: getXXX(int columnNumber)
Example
11 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
rs.getString(“stuname”));
rs.getString(1);
6.Close the connections
After all work is done, it is important to close the connection. But before the connection is
closed , close the ResultSet and the statement objects.
e.g
rs.close();
stmt.close();
conn.close();
Interface Description
CallableStatement The interface used to execute SQL stored
procedures.
Connection A connection (session) with a specific
database.
PreparedStatement An object that represents a precompiled SQL
statement.
ResultSet A table of data representing a database result
set, which is usually generated by executing
a statement that queries the database.
Statement The object used for executing a static SQL
statement and returning the results it
produces.
CallableStatement The interface used to execute SQL stored
procedures.
12 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
ResultSet their Scroll Types
TYPE_FORWARD_ONLY The result set is not scrollable.
TYPE_SCROLL_INSENSITIVE The result set is scrollable but not sensitive to database
changes.
TYPE_SCROLL_SENSITIVE The result set is scrollable and sensitive to database
changes.
13 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
JDBC-ODBC - Creating DSN for MS Access
➢ Run Control Panel > Administrative Tools > Data Sources (ODBC).
➢ Click the System DSN tab. Then click the Add button.
➢ From the ODBC driver list, select Microsoft Access Driver (*.mdb), ODBCJT32.DLL,
and click the Finish button.
➢ Now fill in the DSN header information as below:
14 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
1.Simple Program
import java.sql.*;
public class OdbcAccessConnection
{
public static void main(String [] args)
15 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
{
Connection con = null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:vision");
System.out.println("Connection ok.");
con.close();
}
catch (Exception e)
{
System.err.println(“error”+e);
}
}
}
2.Using select Query
import java.sql.*;
public class OdbcAccessQuery
{
public static void main(String [] args)
{
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:visionstud");
Statement sta = con.createStatement();
ResultSet rs=sta.executeQuery("select * from student");
16 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
while(rs.next())
{
System.out.println("rollno"+rs.getInt(1));
System.out.println("name"+rs.getString(2));
System.out.println("Percentage"+rs.getFloat(3));
}
rs.close();
sta.close();
con.close();
}
catch (Exception e) {
System.err.println(“error”+e);
}
}
}
3 Insertion
import java.sql.*;
import java.io.*;
public class InsQuery
{
public static void main(String [] args)
{
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:visionstud");
Statement sta = con.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Roll no: ");
17 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
int rno=Integer.parseInt(br.readLine());
System.out.println("Enter Name: ");
String name=br.readLine();
System.out.println("Enter percentage: ");
float per=Float.parseFloat(br.readLine());
String str="insert into student values("+rno+",'"+name+"',"+per+")";
int k=sta.executeUpdate(str);
if(k>0)
System.out.println("Insert "+k);
else
System.out.println("Insert "+k);
ResultSet rs=sta.executeQuery("select * from student");
while(rs.next())
{ System.out.println("rollno"+rs.getInt(1));
System.out.println("name"+rs.getString(2));
System.out.println("Percentage"+rs.getFloat(3));
}
rs.close();
sta.close();
con.close();
}
catch (Exception e) {
System.err.println("Error"+e);
}
18 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
}
}
4.Update
import java.sql.*;
import java.io.*;
public class UpsQuery
{
public static void main(String [] args)
{
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:visionstud");
Statement sta = con.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter roll no to update: ");
int rno=Integer.parseInt(br.readLine());
System.out.println("Enter name to update: ");
String name=br.readLine();
System.out.println("Enter percentage: ");
float per=Float.parseFloat(br.readLine());
String str="update student set name='"+name+"'"+","+"per="+per+" "+"where
rollno="+rno;
int k=sta.executeUpdate(str);
if(k>0)
System.out.println("Update "+k);
else
System.out.println("Update "+k);
ResultSet rs=sta.executeQuery("select * from student");
while(rs.next())
{
System.out.println("rollno"+rs.getInt(1));
System.out.println("name"+rs.getString(2));
System.out.println("Percentage"+rs.getFloat(3));
19 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
}
rs.close();
sta.close();
con.close();
}
catch (Exception e) {
System.err.println("Exception: "+e);
}
}
}
5.Delete
import java.sql.*;
import java.io.*;
public class DelQuery
{
public static void main(String [] args)
{
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:visionstud");
Statement sta = con.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter roll no to delete: ");
int rno=Integer.parseInt(br.readLine());
String str="Delete from student where rollno="+rno;
int k=sta.executeUpdate(str);
if(k>0)
System.out.println("Delete "+k);
else
System.out.println("Delete "+k);
ResultSet rs=sta.executeQuery("select * from student");
while(rs.next())
{
20 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
System.out.println("rollno"+rs.getInt(1));
System.out.println("name"+rs.getString(2));
System.out.println("Percentage"+rs.getFloat(3));
}
rs.close();
sta.close();
con.close();
}
catch (Exception e)
{
System.err.println("Exception: "+e);
}
}
}
6.Searching
import java.sql.*;
import java.io.*;
public class SearchQuery
{
public static void main(String [] args)
{
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:visionstud");
Statement sta = con.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter rno which U want to search.");
int rno=Integer.parseInt(br.readLine());
String str="select * from student where rollno="+rno;
ResultSet rs=sta.executeQuery(str);
21 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
while(rs.next())
{
System.out.println("tRoll No: "+rs.getInt(1)+"ntName: "+rs.getString(2)+
"ntPercentage: "+ rs.getFloat(3));
}
rs.close();
sta.close();
con.close();
}
catch (Exception e) {
System.err.println("error "+e);
}
}
}
22 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
MultiThreading
MuliProcessing
• This allows many processes to run simultaneously.
• Process is a running instance of the program. i.e. an operating system process.
CPU time is shared between different processes.
• OS provides context switching mechanism, which enables to switch between the
processes.
• Program’s entire contents (e.g. variables, global variables, functions) are stored
separately in their own context.
Example:- MS-Word and MS-Excel applications running simultaneously. (or any
two applications for that matter)
MultiThreading
• It allows many tasks within a program (process) to run simultaneously.
• Each such task is called as a Thread.
• Each Thread runs in a separate context.
• Each Thread has a beginning , a body,& an end
• Example:- Lets take a typical application like MS-Word. There are various independent
tasks going on, like displaying GUI, auto-saving the file, typing in text, spell-checking,
printing the file contents etc…
23 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Thread
• Thread is an independent sequential path of execution within a program. i.e.
separate call stack.
• Many threads run concurrently within a program.
• At runtime, threads in a program exist in a common memory space and can share both
data and code.
Start Start Start
Switching switching
How To Thread Created?
Threads can be achieved in one of the two ways –
1 Extending java.lang.Thread class.
2 Implementing java.lang.Runnable interface
1.Using Extending java.lang.Thread class.
To Define a class that extends Thread class & override its run() with code required by
thread.
Steps as Follows
Main Thread
Threads A Threads B Threads C
24 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
1.Declare the class as extending the Thread class
Class Vision extends Thread
{
-----------
}
Where Vision is name of thread.
2.Implement the run() method.i.e Responsible for executing of code the thread will execute.
public void run()
{
-------
-----
}
3.Create a thread object & call the start() method to initiate the thread execution.
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("n From Thread A:i="+i);
}
System.out.println("n Exit from A");
}
}
class B extends Thread
{
public void run()
{
25 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
for(int j=1;j<=5;j++)
{
System.out.println("n From Thread B:j="+j);
}
System.out.println("n Exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("n From Thread C:k="+k);
}
System.out.println("n Exit from C");
}
}
class ThreadTest
{
public static void main(String args[])
{
A t1=new A();
//new A().start();
t1.start();//invoke run method
B t2=new B();
t2.start();//invoke run method
26 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
C t3=new C();
t3.start();//invoke run method
}
}
2.Implementing java.lang.Runnable interface
Steps as follows
1.Declare the class as implementing the runnable interface.
2.Implement the run() method.
3.Create a thread by defining an object that is instantiated from “runnable” class as the
target of the thread.
4.Call the thread’s start() method to run the thread.
class A implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("tThread A :"+i);
}
System.out.println("End of thread A");
}
}
class RunnableTest
{
public static void main(String args[])
{
27 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
A r=new A();
Thread tx=new Thread(r);
tx.start();
System.out.println("End of main thread");
}
}
Life Cycle of thread
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
newborn
Running
Runnable
Blocked
Dead
stop
stop
stop
Resume
Notify
Suspend
Sleep
wait
start
yield
Active
Thread
New
Thread
Idle
Thread
28 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
1 Newborn state
It create a thread object, the thread is born & is said to be newborn state.
2. Runnable state
It means thread is ready for execution & is waiting for the availability of processor.
The processor of assigning time to threads is known as timing-slicing.
yield
……
Runnable thread
If a thread to leave control to another thread of equal priority before its turn comes,it can
done by using yield() method
3.Running state
It means that the processor has given its time to the thread for its execution.
The thread runs until it leaves control on its own or it is preempted by higher priority
thread.A running thread my leaves its control in one of the following
1.suspend():
It has been suspended using suspend() method. A suspended thread can be received by
using resume() method.
Resume()
Running Runable Suspended
29 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
2.sleep()
It can put thread to sleep for a specified time period using sleep(t) method.(t is time
milliseconds).
Sleep(t)
After t
Running Runable Sleeping
3.wait()
It has been hold to wait until some event occurs. This is done using wait() method. The
thread can be scheduled to run again using notify() method.
Wait Notify()
Running Runable waiting
4.Blocked state
A thread is said to be blocked when it is prevented from entering into runnable state &
subsequently the running state. This happens when the thread is suspended,sleeping or waiting.
A blocked thread is considered “not runnable” but not dead .
5.Dead state
Every Thread has a life cycle. A running threads ends its life when it has completed executing its
run() method.
30 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Display the main Thread.
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t.getName());
try
{
for(int n = 6; n > 0; n--)
{
System.out.println(n);
}
}
catch (Exception e)
{
}
}
}
Threads priority
Each thread is assigned a priority, which affects the order it is scheduled for running.
i.e Threads are assigned priorities that the thread scheduler can use to determine how the threads
will be scheduled.
31 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
The following static final integer constants are defined in the Thread class:
• MIN_PRIORITY =0( Lowest Priority)
• NORM_PRIORITY =5 (Default Priority)
• MAX_PRIORITY =10 (Highest Priority)
setPriority():It can modify a thread’s priority at any time after its creation using the
setPriority() method.
Threadname.setPriority(int number)
Where number is priority number.
getPriority(): It retrieve the thread priority value
class A extends Thread
{ public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("n From Thread A:i="+i);
}
System.out.println("n Exit from A");
}
}
class B extends Thread
{ public void run()
{
for(int j=1;j<=5;j++)
{ System.out.println("n From Thread B:j="+j);
}
System.out.println("n Exit from B");
}
}
32 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
class C extends Thread
{ public void run()
{
for(int k=1;k<=5;k++)
{ System.out.println("n From Thread C:k="+k);
}
System.out.println("n Exit from C");
}
}
public class ThreadPriority
{ public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t3.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.MIN_PRIORITY);
t3.start();
t1.start();
t2.start();
}
}
Threads Method
1. isAlive() method:
Returns true if the thread is alive, otherwise false.
public final boolean isAlive()
2.join() method:
33 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
The join() method waits for a thread to die.(A thread to wait until the completion of
another
thread before continue.
public void join()
class A extends Thread
{
public void run()
{
System.out.println("A Thread");
}
}
class B extends Thread
{
public void run()
{
System.out.println("B Thread");
}
}
class ThreadTest
{
public static void main(String args[])
{
try
{
A t1=new A();
34 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
t1.start();//invoke run method
B t2=new B();
t2.start();//invoke run method
t1.join();
t2.join();
System.out.println("Main parent thread");
System.out.println("A thread "+t1.isAlive());
System.out.println("B thread "+t2.isAlive());
}
catch(Exception e)
{
System.out.println("error"+e);
}
}
}
What is mean by Synchronization?
When two or more threads need access to a shared resource,
they need to ensure that the resource will be used by only one thread at a time.
This process by which this is achieved is called Synchronization.
This is the general form of the synchronized statement:
synchronized method1 ()
{
// statements to be synchronized
}
35 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
When it declare a method synchronized, Java creates a “Monitor” & hands it over to the
thread that calls the method first time. As long as the thread holds the monitor, no other thread
can enter the synchronized section of code.
When thread has completed its work of using synchronized method(or block of code),it
will hand over the monitor to the next thread that is ready to use same resource.
Using synchronized
class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run()
{
36 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
target.call(msg);
}
}
public class Synch
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
}
}
Java - Interthread Communication
When multiple threads are running in an application, it become necessary for the threads to
communicate(talk) with each other such communication called as interthread communication.
The thread can communicate by either sharing data or indicating when a specific activity has
completed.
Methods for interthread communication
wait( ): Causes the current thread to wait until another thread invokes the notify().
Notify( ): Wakes up a single thread that is waiting on this object's monitor.
notifyAll( ): Wakes up all the threads that called wait( ) on the same object.
Join():The join() method waits for a thread to die.(A thread to wait until the completion of
another thread before continue.
37 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
NETWORKING
Networking Basics
Protocol
A protocol is a set of rules and standards for communication. A protocol specifies the
format of data being sent over the Internet, along with how and when it is sent. Three
important protocols used in the Internet are:
1. IP (Internet Protocol): is a network layer protocol that breaks data into small packets
and routes them using IP addresses.
2. TCP (Transmission Control Protocol): This protocol is used for connection-oriented
communication between two applications on two different machines. It is most reliable
and implements a connection as a stream of bytes from source to destination.
2. UDP (User Datagram Protocol): It is a connection less protocol
and used typically for
request and reply services. It is less reliable but faster than TCP.
Addressing
1. MAC Address: Each machine is uniquely identified by a physical address, address of
the network interface card. It is 48-bit address represented as 12 hexadecimal characters:
For Example: 00:09:5B:EC:EE:F2
3. IP Address: It is used to uniquely identify a network
and a machine in the network.
It
is referred as global addressing scheme.
Also called as logical address. Currently used
type of IP addresses is: Ipv4 – 32-bit address and Ipv6 – 128-bit address.
For Example:
Ipv4 – 192.168.16.1
Ipv6 – 0001:0BA0:01E0:D001:0000:0000:D0F0:0010
38 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
4. Port Address: It is the address used in the network to
identify the application on the network.
Domain Name Service (DNS)
It is very difficult to remember the IP addresses of machines
in a network. Instead, we
can identify a machine using a “domain name”
which is character based naming
mechanism. Example: www.google.com.
The mapping between the domain name and the
IP address is done by a service called DNS.
URL
A URL (Uniform Resource Locator) is a unique identifier for any resource located on the
Internet. The syntax for URL is given as:
<protocol>://<hostname>[:<port>][/<pathname>][/<filename>[#<section>]]
Sockets
A socket represents the end-point of the network communication. It provides a simple
read/write interface and hides the implementation details network and transport layer
protocols. It is used to indicate one of the two end-points of a communication link
between two processes. When client wishes to make connection to a server, it will create
a socket at its end of the communication link.
The socket concept was developed in the first networked version of UNIX developed at
the University of California at Berkeley. So sockets are also known as Berkeley Sockets.
Ports
A port number identifies a specific application running in the machine.
A port number is a
number in the range 1-65535.
Reserved Ports: TCP/IP protocol reserves port number
in the range 1-1023 for the use of
specified standard services, often referred to as “well-known” services.
39 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
The java.net Package
The java.net package provides classes and interfaces for implementing network
applications such as sockets, network addresses, Uniform Resource Locators (URLs) etc.
some important interfaces, classes and exceptions as follows :
InetAddress Class
Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.google.com, www.facebook.com etc.
Method Description
public static InetAddress getByName(String
host) throws UnknownHostException
it returns the instance of InetAddress
containing LocalHost IP and name.
public static InetAddress getLocalHost() throws
UnknownHostException
it returns the instance of InetAdddress
containing local host name and address.
public String getHostName() it returns the host name of the IP
address.
public String getHostAddress() it returns the IP address in string format.
URL Class
As the name suggests, it provides a uniform way to locate resources on the web. Every
browser uses them to identify information on the web. The URL class provides a simple
API to access information across net using URLs.
The class has the following constructors:
1. URL(String url_str): Creates a URL object based on the string parameter. If the
URL cannot be correctly parsed, a MalformedURLException will be thrown.
2. URL(String protocol, String host, String path): Creates a URL object with the
specified protocol, host and path.
3. URL(String protocol, String host, int port, String path): Creates a URL object
with the specified protocol, host, port and file path.
4. URL(URL urlObj, String urlSpecifier): Allows you to use an existing URL as a
reference context and then create a new URL from that context.
40 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public URLConnection
openConnection()
it returns the instance of URLConnection i.e.
associated with this URL.
URLConnection Class
The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred by the
URL.
public class URLConnectionExample
{
public static void main(String[] args)
{
try
{
URL url=new URL("http://www.visionacademe.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1)
{
System.out.print((char)i);
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
Connection Oriented Communication
Using Socket Java performs the network communication. Sockets enables to transfer data
41 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
through certain port. Socket class of Java makes it easy to write the socket program
Sockets are broken into two types:
1. Datagram sockets (UDP Socket)
1.A Datagram socket uses user datagram protocol (UDP) to send datagrams (self contained units
of information) in a connectionless manner.
2.This method does not guarantee delivery of the datagram.
3.The advantage is the datagram sockets require relatively few resources and so communication
is faster.
4.Typically request-reply types of application use datagram socket.
5.Java uses java.net.DatagramSocket class to create datagram socket. The
java.net.DatagramPacket represents a datagram.
2. Stream Socket (TCP Socket)
1.A stream socket is a “connected” socket through which data is transferred continuously.
2. It use TCP to create a connection between the client and server. TCP/IP sockets are used to
implement reliable, bidirectional, persistent, point to point, stream-based connection between
hosts on the internet.
3. The benefit of using a stream socket is the communication is reliable. because once
connected ,the communication link is available till it is disconnected. So data transmission is
done in real-time and data arrives reliably in the same order that it was sent. however this
requires more resource. Application like file transfer require a reliable communication. For such
application stream sockets are better.
4. Java uses java.net.Socket class to create stream socket for client and java.net.ServerSocket
for server.
Difference between Datagram and Stream socket
1.DatagramSocket is for sending UDP datagram
Stream socket is used for sending TCP packets.
42 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
2. DatagramSocket is a packet based socket.
Stream socket is a byte oriented socket.
3. DatagramSocket are unreliable. They may be dropped ,duplicate and delivered out of order.
Stream socket is reliable ,if datas are lost on the way, TCP automatically re-sends.
4. DatagramSocket have less overheads and so faster.
Stream sockets require more overhead and are slower.
5.Application which use datagram sockets are request-reply type of application such as DNS
lookups,PING and SMTP.
Stream sockets are used for application like file transfer which require reliability.
6.For Datagram Socket used following class
java.net.DatagramSocket class
java.net.DatagramPacket class
For Stream Socket used following class
java.net.Socket class
java.net.ServerSocket class
7Datagram Socket uses connection less mechanism
Stream Socket uses connection oriented mechanism
ServerSocket Class
This class is used to create a server that listens for incoming connections from clients. It
is possible for client to connect with the server when server socket binds itself to a
specific port. The various constructors of the ServerSocket class are:
43 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
1. ServerSocket(int port): binds the server socket to the specified port number. If 0 is
passed, any free port will be used. However, clients will be unable to access the
service unless notified the port number.
2. ServerSocket(int port, int numberOfClients): Binds the server socket to the
specified port number and allocates sufficient space to the queue to support the
specified number of client sockets.
3. ServerSocket(int port, int numberOfClients, InetAddress address): Binds the
server socket to the specified port number and allocates sufficient space to the queue
to support the specified number of client sockets and the IP address to which this
socket binds
The various methods of this class are:
Method Description
Socket Class
This class is used to represents a TCP client socket, which connects to a server socket and
initiate protocol exchanges. The various constructors of this class are:
1. Socket(InetAddress address, int port): creates a socket connected to the specified
IP address and port. Can throw an IOException.
44 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
2. Socket(String host, int port): creates a socket connected to the specified host and
port. Can throw an UnknownHostException or an IOException.
How to create a server socket
1. Create a ServerSocket object which listen to a specific port.
2. Call the accept() method which accepts client request. This method return the client
socket object.
3. Use the socket object to communication with the client
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String[] ar)
45 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
{
try
{
int port = 6666;
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for a client...");
Socket socket = ss.accept();
InputStream sin = socket.getInputStream();
DataInputStream in = new DataInputStream(sin);
String line = null;
while(true)
{
line = in.readUTF();
System.out.println(“Receving line from client : " + line);
System.out.println();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
How to create a client socket
1.Create an object of the socket class using the server names and port as parameter.
2.Communication with the server.
3.Close the socket
//Client
import java.net.*;
46 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
import java.io.*;
public class Client
{
public static void main(String[] ar)
{
try
{
int serverPort = 6666;
String address = "127.0.0.1";
InetAddress ipAddress = InetAddress.getByName(address);
Socket socket = new Socket(ipAddress, serverPort);
OutputStream sout = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(sout);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while(true)
{
line = keyboard.readLine();
System.out.println("Sending this line to the server...");
out.writeUTF(line); // send the above line to the server.
out.flush();
System.out.println();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
47 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Servlet
What Web server?
➢ Apache is a very popular server
➢ 66% of the web sites on the Internet use Apache
Apache is:
• Full-featured and extensible
• Efficient
• Robust
• Secure (at least, more secure than other servers)
• Up to date with current standards
• Open source
• Free
What is Tomcat?
Tomcat is the Servlet Engine that handles servlet requests for Apache.
➢Tomcat is a “helper application” for Apache
➢It’s best to think of Tomcat as a “servlet container”
What is servlet?
A servlet is a web component,managed by a container, that generates dynamic content.
➢ Client sends a request to server
➢ Server starts a servlet
➢ Servlet computes a result for server and does not quit
➢ Server returns response to client
48 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
➢ Another client sends a request
➢ Server calls the servlet again
The Life Cycle of a Servlet
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:
public void init(ServletConfig config) throws ServletException
4) service method is invoked
The service() method of the Servlet is invoked to inform the Servlet about the client requests.
This method uses ServletRequest object to collect the data requested by the client.
49 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
This method uses ServletResponse object to generate the output content.
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5) destroy method is invoked
When a servlet is unloaded by the servlet container, its destroy() method is called. This step is
only executed once, since a servlet is only unloaded once.
public void destroy()
The Servlet API
It includeTwo packages:
▪ javax.servlet
▪ javax.servlet.http
1.The javax.servlet Package
50 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
The javax.servlet package contains a number of interfaces and classes that establish
the framework in which servlets operate.
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access
Information about their environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
SingleThreadModel Indicates that the servlet is thread safe.
Class Description
GenericServlet Implements the Servlet and ServletConfig
interfaces.
ServletInputStream Provides an input stream for reading requests from a
client.
ServletOutputStream Provides an output stream for writing responses to a
client.
2.javax.servlet.http Package
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP request.
HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound
from a session.
51 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Class Description
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses.
1.doGet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
Where
Input is from the HttpServletRequest parameter
Output is via the HttpServletResponse object, which we have named response
2.doPost
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
52 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B> Hi Vision Academy!");
pw.close();
}
}
How to Run
Setting:
1.To install Apache tomcat software
2.Go to the browser(Internet explorer)
3.Start tomcat service.
& type the following URL in the Internet explorer(For Testing)
http://localhost:8080[The server listen to port 8080]
53 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
1. To go to the following path
C:Program FilesApache Software FoundationTomcat 6.0lib
5 To copy the servlet-api & jsp-api file & paste to the following path
C:Program FilesJavajdk1.6.0jrelibext
1.To save above file(HelloServlet.java) following path
C:Program FilesApache Software FoundationTomcat 6.0webappsexamplesWEB-
INFclasses
2 Compile the servlet source code
javac HelloServlet.java
3 To go to the following path
C:Program FilesApache Software FoundationTomcat 6.0webappsexamplesWEB-INF
54 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
4 Open the following file(web.xml)& enter the following entry in the file & save it.
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlets/servlet/HelloServlet</url-pattern>
</servlet-mapping>
5.To open internet explorer & type following URL
http://localhost:8080/examples/servlets/servlet/HelloServlet
How To retrieve value from the component
Using doGet method
<html>
<body>
55 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
<center>
<form name="Form1"
method="get"
action="http://localhost:8080/examples/servlets/servlet/GetServlet">
Enter name
<input type=text name=”t”>
<br>
<input type=submit value="Submit">
</body>
</html>
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String s = request.getParameter("t");
pw.println(s);
pw.close();
}
}
Using doPost method
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servlet/PostServlet">
Enter name
56 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
<input type=text name=”t”>
<br>
<input type=submit value="Submit">
</body>
</html>
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String s = request.getParameter("t");
pw.println(s);
pw.close();
}
}
2
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examples/servlets/servlet/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
57 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
What is a Cookie?
A "cookie" is a small piece of information sent by a web server to store on a web browser so it
can later be read back from that browser. A cookie’s value identify user
Constructor of Cokkie class
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.
Method of Cookie class
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
58 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
expiry)
public String getName()
Returns the name of the cookie. The name cannot be changed
after creation.
public String getValue() Returns the value of the cookie.
public void setName(String
name)
changes the name of the cookie.
public void setValue(String
value)
changes the value of the cookie.
Interface Method Description
Public void addCookie(Cookie ck) method of HttpServletResponse interface is
used to add cookie in response object.
Public Cookie[] getCookies() method of HttpServletRequest interface is used
to return all the cookies from the browser.
Add cookie’s value
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servlets/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
SOFTWARE DEVELOPMENT
59 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
USING JAVA
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
//cookie.setMaxAge( 60 * 60 * 24 );//24 hours
response.addCookie(cookie);
// Write output to browser.
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
Accessing cookie’s value
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
for(int i = 0; i < cookies.length; i++)
{
60 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +"; value = " + value);
}
pw.close();
}
}
Session Tracking
HTTP is a stateless protocol.
i.e Each request is independent of the previous one.
In some applications,
it is necessary to save state information so that
information can be collected from several interactions
between a browser and a server. Sessions provide
such a mechanism.
There are several ways through which it can provide unique identifier in request and response.
1. User Authentication – This is the very common way where we user can provide
authentication from the login page and then we can pass the authentication information
between server and client to maintain the session. This is not very effective method
because it wont work if the same user is logged in from different browsers.
2. HTML Hidden Field – We can create a unique hidden field in the HTML and when user
starts navigating, we can set its value unique to the user and keep track of the session.
This method can’t be used with links because it needs the form to be submitted every
time request is made from client to server with the hidden field. Also it’s not secure
because we can get the hidden field value from the HTML source and use it to hack the
session.
3. URL Rewriting – We can append a session identifier parameter with every request and
response to keep track of the session. This is very tedious because we need to keep track
of this parameter in every response and make sure it’s not clashing with other parameters.
4. Cookies: A "cookie" is a small piece of information sent by a web server to store on a
web browser so it can later be read back from that browser. It can maintain a session with
cookies but if the client disables the cookies, then it won’t work.
61 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
5. Session Management API:The servlet API provide methods and classes specifically
designed to handle session.The HttpSession class provide various session tracking
methods
public void setAttribute( String name, Object value )
public Object getAttribute( String name )
public Object removeAttribute( String name )
USING JAA
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException
{
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}
62 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Servlet CGI(Common Gateway
Interface)
1. It is written in Java only.
2.It is portable
3. Servlets execute within the
address space of a Web server.
It is not necessary to create a
separate process to handle each
client request.
4 It was inexpensive in terms
of processor and memory
resources.
1.It is written in Perl,C &
C++
2. It is not portable
3. It is to create a separate
process for each client
request.
4.It was also expensive in
terms of processor and
memory resources.
JDBC USING SERVLET
import java.io.*;
import java.sql.*;
import javax.servlet.*;
63 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
import javax.servlet.http.*;
public class Jdconn extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Get a Connection to the database
con = DriverManager.getConnection("jdbc:odbc:vision2");
// Create a Statement object
stmt = con.createStatement();
// Execute an SQL query, get a ResultSet
rs = stmt.executeQuery("SELECT sname,address FROM stud");
while(rs.next())
{
out.println( rs.getString("sname") + " " + rs.getString("address"));
}
con.close();
}
catch(Exception e)
{
out.println(“error”+e);
}
}
}
64 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
JSP(Java Server Page)
• JSP is a server side program.
• JSP tags to enable dynamic content creation (Combination of HTML & JSP tag).
• JSP provide excellent server side scripting support for creating database driven web
applications
• JSP enable the developers to directly insert java code into jsp file, this makes the
development process very simple and its maintenance also becomes very easy.
• JSP pages are efficient, it loads into the web servers memory on receiving the request very
first time and the subsequent calls are served within a very short period of time.
There are 3 methods in JSP(Life cycle of JSP)
A JSP page undergoes 3 phases during life cycle.
1.Translation phase:In this phase,JSP pages get translated into servlet code.
2.Compilation phase:In this phase, the servlet code compiled. The compilation is done only if
the page is requested the first time or it is modified.
3.Excution phase:This is final phase where jsp servlet methods are executed.These are
jspInit(),_jspService(),jspDestroy()
65 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
1.jspInt()
• This method is identical to the init() method in Java servlet.
• This method is called first when the JSP is requested and is used to initialize objects &
variables that are used throughout the life of the JSP.
public void jspInit()
{
// Initialization code...
}
2.jspDestroy()
• This method is identical to the destroy() method in Java servlet.
• This method is automatically called when JSP terminates normally.
• This method is used for cleanup where resources used during execution of JSP are released.
public void jspDestroy()
66 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
{
// Your cleanup code goes here.
}
3._jspService()
• This method is automatically called & retrieves a connection to HTTP.
public void _jspService(HttpServletRequest request, HttpServletResponse response) {
// Service handling code...
}
JSP Architecture
67 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of
.html.
• The JSP engine loads the JSP page from disk and converts it into a servlet content.
• The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format, which the servlet
engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static HTML
content.
JSP Tags
1.Comment Tags:
It is denoted by
<%--
--%>
68 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
e.g
<%-- This comment will not be visible in the page source --%>
2.Declaration statement tags: This tag is used for defining the functions and variables to be
used in the JSP.
It is denoted by
<%!
%>
Eg
<%! int age=25;%>
3.Scriptlet tags: It is used for Java control statements & loop.
It is denoted by
<%
Eg. %>
<% for(int i=0;i<=3;i++)
{
---
---
}
%>
4.Expression tags: The expression is evaluated and the result is inserted into the HTML page
It is denoted by
<%= expression %>
Eg.
<%=age%>
5.Directive tags:
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
69 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
There are three types of directives:
o page directive
o include directive
o taglib directive
1.page directive
The page directive defines attributes that apply to an entire JSP page.
It is denoted by
<%@ directive attribute="" %>
Attribute as follows
1.language: It defines the programming language (underlying language) being used in the page.
Syntax of language:
<%@ page language="value" %>
e.g
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
2.Extends: This attribute is used to extend (inherit) the class like JAVA does
Syntax of extends:
<%@ page extends="value" %>
e.g
<%@ page extends="demotest.DemoClass" %>
3.Import: It is used to import Java package into the JSP program.
Syntax of import:
70 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
<%@ page import="value" %>
e.g
<%@page import=” java.sql.*” %
4.contentType:
• It defines the character encoding scheme i.e. it is used to set the content type and the
character set of the response
• The default type of contentType is "text/html; charset=ISO-8859-1".
Syntax of the contentType:
<%@ page contentType="value" %>
e.g
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
5.Session
Specifies whether or not the JSP page participates in HTTP sessionsSyntax of session
Syntax
<%@ page session="true/false"%>
e.g
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
session="false"%>
6.errorPage:
This attribute is used to set the error page for the JSP page if JSP throws an exception and then it
redirects to the exception page.
Syntax of errorPage:
<%@ page errorPage="value" %>
71 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
e.g
<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"
errorPage="errorHandler.jsp"%>
7. PageEncoding:
The "pageEncoding" attribute defines the character encoding for JSP page.The default is
specified as "ISO-8859-1" if any other is not specified.
Syntax
<%@ page pageEncoding="vaue" %>
Here value specifies the charset value for JSP
Example:
<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"
isErrorPage="true"%>
2.include directive:
• include directive is used to include one file to the another file
• This included file can be HTML, JSP, text files, etc.
<%@ include file="/header.jsp" %>
e.g
a.jsp
<%="HELLO bcs"%>
p.jsp
<%@ include file="p.jsp" %>
<%="HELLO mcs"%>
3.taglib directive:
72 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
JSP taglib directive is used to define the tag library with "taglib" as the prefix, which we can use
in JSP. (custom tags allows us to defined our own tags).
Syntax of taglib directive:
<%@ taglib uri="uri" prefix="value"%>
Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is a tag
name.
e.g
<%@ taglib prefix="vtag" uri="http://java.sun.com/jsp/jstl/core" %>
How To run JSP?
<html>
<head>
<title>
Sachin Sir 9823037693
</title>
</head> JSP CODE
<body>
<%="HELLO Sachin Sir"%>
<body>
</html>
Step1 Save the file Hello.jsp into the following path
C:Program FilesApache Software FoundationTomcat 6.0webappsexamplesjsp
Step2 Open the browser & type it in the address bar
http://localhost:8080/examples/jsp/Hello.jsp
73 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Variables
It can declare your own variables, as usual
Using Function
<html>
<head>
<title>
Sachin Sir 9823037693 Sum of first n numbers
</title>
</head>
<body>
<%! int sumoffirst(int n)
{
int sum=0;
for(int i=1;i<=n;i++)
sum=sum+i;
return(sum);
}
%>
JSP CODE
<p>Sum of first n number:
</p>
<body>
</html>
<%=sumoffirst(5)%>
74 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
JSP provides several predefined variables(implicit object)
Implicit object:These objects are created automatically by JSP container. It can directly use
these object.JSP Implicit Objects are also called pre-defined variables
No. Object & Description
1
request
This is the HttpServletRequest object associated
with the request.
2
response
This is the HttpServletResponse object associated
with the response to the client.
3
out
This is the PrintWriter object used to send output to
the client.
4
session
This is the HttpSession object associated with the
request.
5
application
This is the ServletContext object associated with the
application context.
6
config
This is the ServletConfig object associated with the
page.
7
pageContext
This encapsulates use of server-specific features like
higher performance JspWriters.
75 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
8
page
This is simply a synonym for this, and is used to call
the methods defined by the translated servlet class.
9
Exception
The Exception object allows the exception data to be
accessed by designated JSP.
1.Display html & jsp page separate
l.html
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="post" action="http://localhost:8080/examples/jsp/login.jsp">
Username:<input type="text" name="t1">
<br>
Password:<input type="password"name="t2">
<br>
<input type="submit" value="Login">
<input type="reset" value="Clear">
</body>
</html>
76 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Login.jsp
<%
String s1=request.getParameter("t1");
String s2=request.getParameter("t2");
if(s1.equals("sachin")&&s2.equals("sachin"))
out.println("Login Sucessfully");
else
out.println("Login incorrect");
%>
77 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Database connection using jsp
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<html>
<body>
<%
try
{
78 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:visionstud");
Statement sta = con.createStatement();
ResultSet rs=sta.executeQuery("select * from student");
while(rs.next())
{
out.println("rollno"+rs.getInt(1));
out.println("name"+rs.getString(2));
out.println("Percentage"+rs.getFloat(3));
}
rs.close();
sta.close();
con.close();
}
catch(Exception e)
{
}
%>
</body>
</html>
79 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
JSP Benefits
• Easy to combine static templates,including HTML or XML.
• JSP pages compile dynamically into servlets.
• JSP makes it easier to author pages "by hand"
• JSP tags for invoking JavaBeansTM components
Compare servlet &jsp
JSP Servlets
JSP is a webpage scripting language that can generate
dynamic content.
Servlets are Java programs that are already
compiled which also creates dynamic web
content.
JSP run slower compared to Servlet as it takes
compilation time to convert into Java Servlets.
Servlets run faster compared to JSP.
It’s easier to code in JSP than in Java Servlets. Its little much code to write here.
In MVC, jsp act as a view. In MVC, servlet act as a controller.
JSP are generally preferred when there is not much
processing of data required.
servlets are best for use when there is more
processing and manipulation involved.
The advantage of JSP programming over servlets is that
we can build custom tags which can directly call Java
beans.
There is no such custom tag facility in servlets.
We can achieve functionality of JSP at client side by
running JavaScript at client side.
There are no such methods for servlets.
80 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Remote Method Invocation(RMI)
Definition: Java RMI is a mechanism that allows a Java program running on one computer to
apply a method to an object living on a different computer.
OR
RMI enables the programmer to create distributed Java applications, in which the methods of
remote Java objects can be invoked from other Java virtual machines, possibly on different hosts.
OR
The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual
machine to invoke methods on an object running in another Java virtual machine.
RMI is an implementation of the of the Distributed Object programming
model
RMI Architecture Layers
81 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
It consist of following parts
Client: user interface
Server : data source
Stubs
1.The client side object participating object communication is known as stub or proxy.
2. The stub acts as a gateway for client side objects & outgoing requests to server side objects
that are routed through it.
3. The stub wraps client object functionality & by adding the network logic ensures the reliable
communication channel between client & server.
Stub responsibility
1.Initiating the communication towards the server selection
2.Translating calls from caller object
3.Marshaling of arguments: It refers to the process of converting the data or the objects
inbto a byte-stream.
4.Informing the skeleton that the call should be invoked.
5. Passing arguments to skeleton over network.
6. Unmarshalling (converting the byte-stream back to their original data or object) of the
response from skeleton.
7. informing skeleton that call is complete
82 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Skeletons:
1.The server side object participating object communication is known as skeleton.
2.A skeleton acts as gateways for server side object & all incoming clients requests are routed
through it.
3. The skeleton wraps server object functionality & by adding the network logic ensures the
reliable communication channel between client & server.
Skeleton responsibility
1.Translating incoming data from stub to correct up-calls to server objects.
2.unmarshalling of arguments from received data.
3.To pass arguments to server objects.
4.marshalling of the returned values from server objects.
5. To pass values back to the client stub over the network.
Remote Reference Layer:
(RRL) Part of Java's Remote Method Invocation protocol. RRL exists in both the
RMI client and server. It is used by the stub or skeleton protocol layer and uses the transport
layer. RRL is reponsible for transport-independent functioning of RMI, such as connection
management or unicast/multicast object invocation
Various invocation protocols can be carried out at this layer. Examples are:
• Unicast point-to-point invocation.
• Invocation to replicated object groups.
• Support for a specific replication strategy.
• Support for a persistent reference to the remote object (enabling activation of the remote
object).
• Reconnection strategies (if remote object becomes inaccessible).
Transport Layer:
83 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
The Transport Layer makes the connection between JVMs. All connections are stream-based
network connections that use TCP/IP.
RMI Registry
The Java RMI registry is a remote object that maps name to remote object
i.e For a client communication with a server, the client has to find the location of remote
object.Each &every object to be accessed remotely has to be register with RMI registry with
unique name.so if there is any request for particular object, the registry will direct the request to
the correct object.
public static java.rmi.Remote
lookup(java.lang.String) throws
java.rmi.NotBoundException,
java.net.MalformedURLException,
java.rmi.RemoteException;
It returns the
reference of
the remote
object.
public static void bind(java.lang.String,
java.rmi.Remote) throws
java.rmi.AlreadyBoundException,
It binds the
remote object
with the given
84 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
java.net.MalformedURLException,
java.rmi.RemoteException;
name.
public static void unbind(java.lang.String)
throws java.rmi.RemoteException,
java.rmi.NotBoundException,
java.net.MalformedURLException;
It destroys the
remote object
which is bound
with the given
name.
public static void rebind(java.lang.String,
java.rmi.Remote) throws
java.rmi.RemoteException,
java.net.MalformedURLException;
It binds the
remote object
to the new
name.
public static java.lang.String[]
list(java.lang.String) throws
java.rmi.RemoteException,
java.net.MalformedURLException;
It returns an
array of the
names of the
remote objects
bound in the
registry.
Steps for implementing RMI 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
85 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Step 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 Exception;
public long sub(long a, long b)
throws Exception;
public long mul(long a, long b)
throws Exception;
public long div(long a, long b)
throws Exception;
}
Copy this file to your directory and compile it with the Java compiler:
C:>rmi>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
{
public CalculatorImpl() throws Exception
{
super();
}
86 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
public long add(long a, long b) throws Exception
{
return a + b;
}
public long sub(long a, long b) throws Exception
{
return a - b;
}
public long mul(long a, long b) throws Exception
{
return a * b;
}
public long div(long a, long b) throws Exception
{
return a / b;
}
}
Again, copy this code into your directory and compile it.
C:>rmi>javac CalculatorImpl.java
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.
C:>rmi >rmic CalculatorImpl
Try this in your directory. After you run rmic you should find the file
CalculatorImpl_Stub.class. , if you are running the Java 2 SDK,
CalculatorImpl_Skel.class.
87 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Note: rmic is used for stub generator.
4. Server
Remote RMI services must be hosted in a server process.
import java.rmi.Naming;
public class CalculatorServer
{
public CalculatorServer()
{
try
{
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService",c);//Binding for specified
name where 1st argument object is the remote object being registered & 2nd argument is the
String that names the remote object.
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}
public static void main(String args[]) {
new CalculatorServer();
}
}
Again, copy this code into your directory and compile it.
C:>rmi>javac CalculatorServer.java
5.Client
The source code for the client follows:
import java.rmi.Naming;
import java.rmi.RemoteException;
88 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
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 (Exception e)
{
System.out.println("error"+e);
}
}
}
Again, copy this code into your directory and compile it.
C:>rmi>javac CalculatorClient.java
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
C:>rmi>start rmiregistry
89 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
• Start the another console for server hosting
C:>rmi>java CalculatorServer
It will start, load the implementation into memory and wait for a client connection.
90 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
• Start the client program.
C:>rmi>java CalculatorClient
91 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
What is JavaBeans?
In Java Platform, JavaBeans are classes that encapsulate many objects into a single object (the
bean). They are serializable, have a zero-argument constructor, and allow access to properties
using getter and setter methods.
Advantages of Java Beans
1. Exposure to other applications
One of the most important advantages of a JavaBean is, the events properties and the methods of
a bean can be exposed directly to another application.
2. Registration to receive events
A JavaBean can be registered to receive events from other objects. However, It can also generate
events that can be sent to other objects.
3. Ease of configuration
We can easily use auxiliary software to configure the JavaBean. However, It can also save the
configuration setting of a JavaBean to persistent storage.
4. Portable
As JavaBeans are built in Java, It can easily port them to any other platform that contains JRE.
5. Lightweight
JavaBeans are light weighted, I.e., we don't need to fulfill any special requirement to use it. Also,
it is very easy to create them. However, it doesn't need a complex system to register components
with JRE.
The other advantages of JavaBeans include reusability, deployment, and customization that can
be archived using JavaBeans.
92 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
Features of JavaBeans
Support for introspection
❖ so that a builder tool can analyze how a bean works
Support for customization
❖ so that when using an application builder a user can customize the
appearance and behavior of a bean
Support for events
❖ as a simple communication metaphor than can be used to connect
up beans
Support for properties
❖ both for customization and for programmatic use
Support for persistence
❖ A bean can be customized in an application builder and then have
its customized state saved away and reloaded later
Using the Bean Developer Kit (BDK)
JavaBeans are reusable software components written in Java. These components may be built
into an application using an appropriate building environment. The Bean Development Kit
(BDK) from Sun includes a simple example of a building environment which uses beans, called
the beanbox.
It displays four windows on the screen:
• ToolBox which lists all beans the BeanBox has found,
93 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
• The BeanBox which is a canvas where you will drop beans and connect them together,
• The Properties sheet which is used to set the properties of the current bean,
• the MethodTracer simple debugging facility.
JAR(Java Archive File)
JAR (Java Archive) is a package file format typically used to aggregate many Java class files
and associated metadata and resources (text, images, etc.) into one file to distribute application
software or libraries on the Java platform.
OR
94 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
A Java Archive File, commonly referred to as a Jar File is nothing more than a compressed
archive file.
Benefits of using Jar files are:
• Decreased download time, since the archive is compressed it takes less time to download
as compare to downloading each individual file.
• Package Versioning, A Jar file may contain vendor and version information about the
files it contains.
• Portability, all Java Runtime Environments know how to handle Jar files.
Creating JAR File
jar cf jar-filename input-files
The c option indicates that you wish to create a jar and the f option indicates that output should
be sent to a file, jar-filename is the name of the resulting Jar file and input-files are the files you
wish to include.
Mainfest File
The Jar file automatically adds a manifest file to the jar file, the file is always in a directory
named META-INF and file is named MANIFEST.MF.This file contains information about the
jar file.
Vision Academy Since 2005
Prof. Sachin Sir(MCS,SET)
9822506209/9823037693
www.visionacademe.com
Branch1:Nr Sm Joshi College,Abv Laxmi zerox,Ajikayatara Build,Malwadi Rd,Hadapsar
Branch2:Nr AM College,Aditya Gold Society,Nr Allahabad Bank ,Mahadevnager

More Related Content

What's hot

What Your Jvm Has Been Trying To Tell You
What Your Jvm Has Been Trying To Tell YouWhat Your Jvm Has Been Trying To Tell You
What Your Jvm Has Been Trying To Tell YouJohn Pape
 
Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)Atit Patumvan
 
Mobile Application Development MAD J2ME
Mobile Application Development  MAD J2MEMobile Application Development  MAD J2ME
Mobile Application Development MAD J2MEPallepati Vasavi
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2msafad
 
J2EE and layered architecture
J2EE and layered architectureJ2EE and layered architecture
J2EE and layered architectureSuman Behara
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overviewodedns
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-onhomeworkping7
 
A dynamic application using jboss
A dynamic application using jbossA dynamic application using jboss
A dynamic application using jbossijcax
 
Designing JEE Application Structure
Designing JEE Application StructureDesigning JEE Application Structure
Designing JEE Application Structureodedns
 
Introduction To J2ME(FT - Prasanjit Dey)
Introduction To J2ME(FT - Prasanjit Dey)Introduction To J2ME(FT - Prasanjit Dey)
Introduction To J2ME(FT - Prasanjit Dey)Fafadia Tech
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05Ankit Dubey
 
J2 ee architecture
J2 ee architectureJ2 ee architecture
J2 ee architectureKrishna Mer
 

What's hot (17)

08 Midlet Basic
08 Midlet Basic08 Midlet Basic
08 Midlet Basic
 
What Your Jvm Has Been Trying To Tell You
What Your Jvm Has Been Trying To Tell YouWhat Your Jvm Has Been Trying To Tell You
What Your Jvm Has Been Trying To Tell You
 
Spring
SpringSpring
Spring
 
Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)
 
Mobile Application Development MAD J2ME
Mobile Application Development  MAD J2MEMobile Application Development  MAD J2ME
Mobile Application Development MAD J2ME
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
J2EE and layered architecture
J2EE and layered architectureJ2EE and layered architecture
J2EE and layered architecture
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overview
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-on
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
 
A dynamic application using jboss
A dynamic application using jbossA dynamic application using jboss
A dynamic application using jboss
 
Designing JEE Application Structure
Designing JEE Application StructureDesigning JEE Application Structure
Designing JEE Application Structure
 
Introduction To J2ME(FT - Prasanjit Dey)
Introduction To J2ME(FT - Prasanjit Dey)Introduction To J2ME(FT - Prasanjit Dey)
Introduction To J2ME(FT - Prasanjit Dey)
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
J2EE Introduction
J2EE IntroductionJ2EE Introduction
J2EE Introduction
 
J2 ee architecture
J2 ee architectureJ2 ee architecture
J2 ee architecture
 

Similar to JDBC Driver Types and Architecture

Similar to JDBC Driver Types and Architecture (20)

Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
JDBC
JDBCJDBC
JDBC
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Jdbc new
Jdbc newJdbc new
Jdbc new
 
jdbc
jdbcjdbc
jdbc
 
Module4_Annotations_JDBC.pdf
Module4_Annotations_JDBC.pdfModule4_Annotations_JDBC.pdf
Module4_Annotations_JDBC.pdf
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Jdbc
JdbcJdbc
Jdbc
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
Synopsis on online shopping by sudeep singh
Synopsis on online shopping by  sudeep singhSynopsis on online shopping by  sudeep singh
Synopsis on online shopping by sudeep singh
 
Airline report
Airline reportAirline report
Airline report
 
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Jdbc
JdbcJdbc
Jdbc
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

JDBC Driver Types and Architecture

  • 1. 1 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note What is JDBC? It is Java Database Connectivity technology. This technology is an API(Application Programming Interface) for the java programming language that define how a client may access a database. It provides methods for querying and updating data in database. What are JDBC Drivers? It is a software component enabling a java application to interact with a database. JDBC Driver Types JDBC drivers are divided into four types or levels. The different types of jdbc drivers are: Type 1: JDBC-ODBC Bridge driver (Bridge) Type 2: Native-API/partly Java driver (Native) Type 3: AllJava/Net-protocol driver (Middleware) Type 4: All Java/Native-protocol driver (Pure) Type 1 JDBC Driver JDBC-ODBC Bridge driver The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.
  • 2. 2 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 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 1. This 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.
  • 3. 3 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Type 2 JDBC Driver Native-API/partly Java driver The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api. Type 2: Native api/ Partly Java Driver
  • 4. 4 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 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. 3. This driver is not written in Java Language .Type 2 drivers are not portable. 4. If we change the Database we have to change the native api as it is specific to a database. 5. Usually not thread safe. Type 3 JDBC Driver All Java/Net-protocol driver Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
  • 5. 5 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 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 it is Portable. 3. It is suitable for the web. 4. There are many opportunities to optimize portability, performance, and scalability. 5. The net protocol can be designed to make the client JDBC driver very small and fast to load. 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
  • 6. 6 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note It requires another server application to install and maintain. Type 4 JDBC Driver Native-protocol/all-Java driver The Type 4 uses java networking libraries to communicate directly with the database server. Type 4: Native-protocol/all-Java driver Advantage 1.They are written in java so that it is portable. 2.It is most suitable for the web. 3. 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.It don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.
  • 7. 7 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Disadvantage With type 4 drivers, the user needs a different driver for each database. JDBC Architecture The JDBC API supports both two-tier and three-tier processing models for database access. 1. Two-tier In such an architecture, the Java application communicates directly with the data source (or database). The database may reside on the same machine or may be on another machine to which the clinet machine needs to be connected through a network 2. Three-tier
  • 8. 8 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note In such an architecture, the client machine will send the database access statements to the middleware, which will then send the statements to the database residing on the third tier of the architecture, which is normally referred to as the back end. The statements will be processed there and the result be returned back to the client through the middle tier. This approach will have all the advantages associated with the 3-tier architecture, such as better maintainability, easier deployment, scalability, etc. BASIC JDBC STEPS 1.Load the driver Loading Database driver is very first step towards making JDBC connectivity with the database. It is necessary to load the JDBC drivers before attempting to connect to the database. Syntax Class.forName(drivername) E.g Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”).
  • 9. 9 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 2.Establishing Connection After loading driver, now Establishing Connection with the database with user name and password. Syntax con = DriverManager.getConnection(url+db, user, pass); E.g con = DriverManager.getConnection("jdbc:odbc:vision") 3.Create a statement object: There are three basic types of SQL statements used in the JDBC API: 1.Statement:A Statement represents a general SQL statement without parameters. The method createStatement() creates a Statement object. Eg Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from student "); 2.Prepared Statement: A PreparedStatement represents a precompiled SQL statement, with or without parameters. It is used for SQL commands that need to be executed repeatedly. Eg 1 PreparedStatement ps = con.prepareStatement(“select * from student where rollno=?”); ps.setString(1,1); ResultSet rs = stmt.executeQuery(); Eg2
  • 10. 10 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note PreparedStatement ps = con.prepareStatement(“insert into student values(?,?,?)”); ps.setInt(1,1); ps.setString(2,’amol’); ps.setFloat(3,66.55f); ResultSet rs = ps.executeUpdate(); 3.CallableStatement - CallableStatement objects are used to execute SQL stored procedures Eg CallableStatement cstmt=conn.prepareCall(“call student”); 4.Execute a query An SQL statement can either be a query that return result or operation that manipulates the database 1.ResultSet executeQuery(String sql): It is used for statements that return an output result(for only select query) 2.int executeUpdate(String sql): Returns an integer representing the number of rows affected by the SQL statement. (For only INSERT, DELETE, or UPDATE SQL statements). 5.Process a query:ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results. To access these values, there are getXXX() methods where XXX is a type for example, getString(), getInt(),getFloat etc. There are two forms of the getXXX methods: i. Using columnName: getXXX(String columnName) ii. Using columnNumber: getXXX(int columnNumber) Example
  • 11. 11 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note rs.getString(“stuname”)); rs.getString(1); 6.Close the connections After all work is done, it is important to close the connection. But before the connection is closed , close the ResultSet and the statement objects. e.g rs.close(); stmt.close(); conn.close(); Interface Description CallableStatement The interface used to execute SQL stored procedures. Connection A connection (session) with a specific database. PreparedStatement An object that represents a precompiled SQL statement. ResultSet A table of data representing a database result set, which is usually generated by executing a statement that queries the database. Statement The object used for executing a static SQL statement and returning the results it produces. CallableStatement The interface used to execute SQL stored procedures.
  • 12. 12 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note ResultSet their Scroll Types TYPE_FORWARD_ONLY The result set is not scrollable. TYPE_SCROLL_INSENSITIVE The result set is scrollable but not sensitive to database changes. TYPE_SCROLL_SENSITIVE The result set is scrollable and sensitive to database changes.
  • 13. 13 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note JDBC-ODBC - Creating DSN for MS Access ➢ Run Control Panel > Administrative Tools > Data Sources (ODBC). ➢ Click the System DSN tab. Then click the Add button. ➢ From the ODBC driver list, select Microsoft Access Driver (*.mdb), ODBCJT32.DLL, and click the Finish button. ➢ Now fill in the DSN header information as below:
  • 14. 14 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 1.Simple Program import java.sql.*; public class OdbcAccessConnection { public static void main(String [] args)
  • 15. 15 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:vision"); System.out.println("Connection ok."); con.close(); } catch (Exception e) { System.err.println(“error”+e); } } } 2.Using select Query import java.sql.*; public class OdbcAccessQuery { public static void main(String [] args) { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:visionstud"); Statement sta = con.createStatement(); ResultSet rs=sta.executeQuery("select * from student");
  • 16. 16 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note while(rs.next()) { System.out.println("rollno"+rs.getInt(1)); System.out.println("name"+rs.getString(2)); System.out.println("Percentage"+rs.getFloat(3)); } rs.close(); sta.close(); con.close(); } catch (Exception e) { System.err.println(“error”+e); } } } 3 Insertion import java.sql.*; import java.io.*; public class InsQuery { public static void main(String [] args) { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:visionstud"); Statement sta = con.createStatement(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Roll no: ");
  • 17. 17 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note int rno=Integer.parseInt(br.readLine()); System.out.println("Enter Name: "); String name=br.readLine(); System.out.println("Enter percentage: "); float per=Float.parseFloat(br.readLine()); String str="insert into student values("+rno+",'"+name+"',"+per+")"; int k=sta.executeUpdate(str); if(k>0) System.out.println("Insert "+k); else System.out.println("Insert "+k); ResultSet rs=sta.executeQuery("select * from student"); while(rs.next()) { System.out.println("rollno"+rs.getInt(1)); System.out.println("name"+rs.getString(2)); System.out.println("Percentage"+rs.getFloat(3)); } rs.close(); sta.close(); con.close(); } catch (Exception e) { System.err.println("Error"+e); }
  • 18. 18 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note } } 4.Update import java.sql.*; import java.io.*; public class UpsQuery { public static void main(String [] args) { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:visionstud"); Statement sta = con.createStatement(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter roll no to update: "); int rno=Integer.parseInt(br.readLine()); System.out.println("Enter name to update: "); String name=br.readLine(); System.out.println("Enter percentage: "); float per=Float.parseFloat(br.readLine()); String str="update student set name='"+name+"'"+","+"per="+per+" "+"where rollno="+rno; int k=sta.executeUpdate(str); if(k>0) System.out.println("Update "+k); else System.out.println("Update "+k); ResultSet rs=sta.executeQuery("select * from student"); while(rs.next()) { System.out.println("rollno"+rs.getInt(1)); System.out.println("name"+rs.getString(2)); System.out.println("Percentage"+rs.getFloat(3));
  • 19. 19 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note } rs.close(); sta.close(); con.close(); } catch (Exception e) { System.err.println("Exception: "+e); } } } 5.Delete import java.sql.*; import java.io.*; public class DelQuery { public static void main(String [] args) { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:visionstud"); Statement sta = con.createStatement(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter roll no to delete: "); int rno=Integer.parseInt(br.readLine()); String str="Delete from student where rollno="+rno; int k=sta.executeUpdate(str); if(k>0) System.out.println("Delete "+k); else System.out.println("Delete "+k); ResultSet rs=sta.executeQuery("select * from student"); while(rs.next()) {
  • 20. 20 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note System.out.println("rollno"+rs.getInt(1)); System.out.println("name"+rs.getString(2)); System.out.println("Percentage"+rs.getFloat(3)); } rs.close(); sta.close(); con.close(); } catch (Exception e) { System.err.println("Exception: "+e); } } } 6.Searching import java.sql.*; import java.io.*; public class SearchQuery { public static void main(String [] args) { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:visionstud"); Statement sta = con.createStatement(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter rno which U want to search."); int rno=Integer.parseInt(br.readLine()); String str="select * from student where rollno="+rno; ResultSet rs=sta.executeQuery(str);
  • 21. 21 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note while(rs.next()) { System.out.println("tRoll No: "+rs.getInt(1)+"ntName: "+rs.getString(2)+ "ntPercentage: "+ rs.getFloat(3)); } rs.close(); sta.close(); con.close(); } catch (Exception e) { System.err.println("error "+e); } } }
  • 22. 22 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note MultiThreading MuliProcessing • This allows many processes to run simultaneously. • Process is a running instance of the program. i.e. an operating system process. CPU time is shared between different processes. • OS provides context switching mechanism, which enables to switch between the processes. • Program’s entire contents (e.g. variables, global variables, functions) are stored separately in their own context. Example:- MS-Word and MS-Excel applications running simultaneously. (or any two applications for that matter) MultiThreading • It allows many tasks within a program (process) to run simultaneously. • Each such task is called as a Thread. • Each Thread runs in a separate context. • Each Thread has a beginning , a body,& an end • Example:- Lets take a typical application like MS-Word. There are various independent tasks going on, like displaying GUI, auto-saving the file, typing in text, spell-checking, printing the file contents etc…
  • 23. 23 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Thread • Thread is an independent sequential path of execution within a program. i.e. separate call stack. • Many threads run concurrently within a program. • At runtime, threads in a program exist in a common memory space and can share both data and code. Start Start Start Switching switching How To Thread Created? Threads can be achieved in one of the two ways – 1 Extending java.lang.Thread class. 2 Implementing java.lang.Runnable interface 1.Using Extending java.lang.Thread class. To Define a class that extends Thread class & override its run() with code required by thread. Steps as Follows Main Thread Threads A Threads B Threads C
  • 24. 24 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 1.Declare the class as extending the Thread class Class Vision extends Thread { ----------- } Where Vision is name of thread. 2.Implement the run() method.i.e Responsible for executing of code the thread will execute. public void run() { ------- ----- } 3.Create a thread object & call the start() method to initiate the thread execution. class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("n From Thread A:i="+i); } System.out.println("n Exit from A"); } } class B extends Thread { public void run() {
  • 25. 25 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note for(int j=1;j<=5;j++) { System.out.println("n From Thread B:j="+j); } System.out.println("n Exit from B"); } } class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("n From Thread C:k="+k); } System.out.println("n Exit from C"); } } class ThreadTest { public static void main(String args[]) { A t1=new A(); //new A().start(); t1.start();//invoke run method B t2=new B(); t2.start();//invoke run method
  • 26. 26 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note C t3=new C(); t3.start();//invoke run method } } 2.Implementing java.lang.Runnable interface Steps as follows 1.Declare the class as implementing the runnable interface. 2.Implement the run() method. 3.Create a thread by defining an object that is instantiated from “runnable” class as the target of the thread. 4.Call the thread’s start() method to run the thread. class A implements Runnable { public void run() { for(int i=1;i<=5;i++) { System.out.println("tThread A :"+i); } System.out.println("End of thread A"); } } class RunnableTest { public static void main(String args[]) {
  • 27. 27 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note A r=new A(); Thread tx=new Thread(r); tx.start(); System.out.println("End of main thread"); } } Life Cycle of thread 1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state newborn Running Runnable Blocked Dead stop stop stop Resume Notify Suspend Sleep wait start yield Active Thread New Thread Idle Thread
  • 28. 28 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 1 Newborn state It create a thread object, the thread is born & is said to be newborn state. 2. Runnable state It means thread is ready for execution & is waiting for the availability of processor. The processor of assigning time to threads is known as timing-slicing. yield …… Runnable thread If a thread to leave control to another thread of equal priority before its turn comes,it can done by using yield() method 3.Running state It means that the processor has given its time to the thread for its execution. The thread runs until it leaves control on its own or it is preempted by higher priority thread.A running thread my leaves its control in one of the following 1.suspend(): It has been suspended using suspend() method. A suspended thread can be received by using resume() method. Resume() Running Runable Suspended
  • 29. 29 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 2.sleep() It can put thread to sleep for a specified time period using sleep(t) method.(t is time milliseconds). Sleep(t) After t Running Runable Sleeping 3.wait() It has been hold to wait until some event occurs. This is done using wait() method. The thread can be scheduled to run again using notify() method. Wait Notify() Running Runable waiting 4.Blocked state A thread is said to be blocked when it is prevented from entering into runnable state & subsequently the running state. This happens when the thread is suspended,sleeping or waiting. A blocked thread is considered “not runnable” but not dead . 5.Dead state Every Thread has a life cycle. A running threads ends its life when it has completed executing its run() method.
  • 30. 30 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Display the main Thread. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t.getName()); try { for(int n = 6; n > 0; n--) { System.out.println(n); } } catch (Exception e) { } } } Threads priority Each thread is assigned a priority, which affects the order it is scheduled for running. i.e Threads are assigned priorities that the thread scheduler can use to determine how the threads will be scheduled.
  • 31. 31 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note The following static final integer constants are defined in the Thread class: • MIN_PRIORITY =0( Lowest Priority) • NORM_PRIORITY =5 (Default Priority) • MAX_PRIORITY =10 (Highest Priority) setPriority():It can modify a thread’s priority at any time after its creation using the setPriority() method. Threadname.setPriority(int number) Where number is priority number. getPriority(): It retrieve the thread priority value class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("n From Thread A:i="+i); } System.out.println("n Exit from A"); } } class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("n From Thread B:j="+j); } System.out.println("n Exit from B"); } }
  • 32. 32 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("n From Thread C:k="+k); } System.out.println("n Exit from C"); } } public class ThreadPriority { public static void main(String args[]) { A t1=new A(); B t2=new B(); C t3=new C(); t3.setPriority(Thread.MAX_PRIORITY); t1.setPriority(Thread.MIN_PRIORITY); t3.start(); t1.start(); t2.start(); } } Threads Method 1. isAlive() method: Returns true if the thread is alive, otherwise false. public final boolean isAlive() 2.join() method:
  • 33. 33 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note The join() method waits for a thread to die.(A thread to wait until the completion of another thread before continue. public void join() class A extends Thread { public void run() { System.out.println("A Thread"); } } class B extends Thread { public void run() { System.out.println("B Thread"); } } class ThreadTest { public static void main(String args[]) { try { A t1=new A();
  • 34. 34 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note t1.start();//invoke run method B t2=new B(); t2.start();//invoke run method t1.join(); t2.join(); System.out.println("Main parent thread"); System.out.println("A thread "+t1.isAlive()); System.out.println("B thread "+t2.isAlive()); } catch(Exception e) { System.out.println("error"+e); } } } What is mean by Synchronization? When two or more threads need access to a shared resource, they need to ensure that the resource will be used by only one thread at a time. This process by which this is achieved is called Synchronization. This is the general form of the synchronized statement: synchronized method1 () { // statements to be synchronized }
  • 35. 35 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note When it declare a method synchronized, Java creates a “Monitor” & hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code. When thread has completed its work of using synchronized method(or block of code),it will hand over the monitor to the next thread that is ready to use same resource. Using synchronized class Callme { synchronized void call(String msg) { System.out.print("[" + msg); System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } public void run() {
  • 36. 36 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note target.call(msg); } } public class Synch { public static void main(String args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); } } Java - Interthread Communication When multiple threads are running in an application, it become necessary for the threads to communicate(talk) with each other such communication called as interthread communication. The thread can communicate by either sharing data or indicating when a specific activity has completed. Methods for interthread communication wait( ): Causes the current thread to wait until another thread invokes the notify(). Notify( ): Wakes up a single thread that is waiting on this object's monitor. notifyAll( ): Wakes up all the threads that called wait( ) on the same object. Join():The join() method waits for a thread to die.(A thread to wait until the completion of another thread before continue.
  • 37. 37 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note NETWORKING Networking Basics Protocol A protocol is a set of rules and standards for communication. A protocol specifies the format of data being sent over the Internet, along with how and when it is sent. Three important protocols used in the Internet are: 1. IP (Internet Protocol): is a network layer protocol that breaks data into small packets and routes them using IP addresses. 2. TCP (Transmission Control Protocol): This protocol is used for connection-oriented communication between two applications on two different machines. It is most reliable and implements a connection as a stream of bytes from source to destination. 2. UDP (User Datagram Protocol): It is a connection less protocol and used typically for request and reply services. It is less reliable but faster than TCP. Addressing 1. MAC Address: Each machine is uniquely identified by a physical address, address of the network interface card. It is 48-bit address represented as 12 hexadecimal characters: For Example: 00:09:5B:EC:EE:F2 3. IP Address: It is used to uniquely identify a network and a machine in the network. It is referred as global addressing scheme. Also called as logical address. Currently used type of IP addresses is: Ipv4 – 32-bit address and Ipv6 – 128-bit address. For Example: Ipv4 – 192.168.16.1 Ipv6 – 0001:0BA0:01E0:D001:0000:0000:D0F0:0010
  • 38. 38 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 4. Port Address: It is the address used in the network to identify the application on the network. Domain Name Service (DNS) It is very difficult to remember the IP addresses of machines in a network. Instead, we can identify a machine using a “domain name” which is character based naming mechanism. Example: www.google.com. The mapping between the domain name and the IP address is done by a service called DNS. URL A URL (Uniform Resource Locator) is a unique identifier for any resource located on the Internet. The syntax for URL is given as: <protocol>://<hostname>[:<port>][/<pathname>][/<filename>[#<section>]] Sockets A socket represents the end-point of the network communication. It provides a simple read/write interface and hides the implementation details network and transport layer protocols. It is used to indicate one of the two end-points of a communication link between two processes. When client wishes to make connection to a server, it will create a socket at its end of the communication link. The socket concept was developed in the first networked version of UNIX developed at the University of California at Berkeley. So sockets are also known as Berkeley Sockets. Ports A port number identifies a specific application running in the machine. A port number is a number in the range 1-65535. Reserved Ports: TCP/IP protocol reserves port number in the range 1-1023 for the use of specified standard services, often referred to as “well-known” services.
  • 39. 39 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note The java.net Package The java.net package provides classes and interfaces for implementing network applications such as sockets, network addresses, Uniform Resource Locators (URLs) etc. some important interfaces, classes and exceptions as follows : InetAddress Class Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.google.com, www.facebook.com etc. Method Description public static InetAddress getByName(String host) throws UnknownHostException it returns the instance of InetAddress containing LocalHost IP and name. public static InetAddress getLocalHost() throws UnknownHostException it returns the instance of InetAdddress containing local host name and address. public String getHostName() it returns the host name of the IP address. public String getHostAddress() it returns the IP address in string format. URL Class As the name suggests, it provides a uniform way to locate resources on the web. Every browser uses them to identify information on the web. The URL class provides a simple API to access information across net using URLs. The class has the following constructors: 1. URL(String url_str): Creates a URL object based on the string parameter. If the URL cannot be correctly parsed, a MalformedURLException will be thrown. 2. URL(String protocol, String host, String path): Creates a URL object with the specified protocol, host and path. 3. URL(String protocol, String host, int port, String path): Creates a URL object with the specified protocol, host, port and file path. 4. URL(URL urlObj, String urlSpecifier): Allows you to use an existing URL as a reference context and then create a new URL from that context.
  • 40. 40 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Method Description public String getProtocol() it returns the protocol of the URL. public String getHost() it returns the host name of the URL. public String getPort() it returns the Port Number of the URL. public String getFile() it returns the file name of the URL. public URLConnection openConnection() it returns the instance of URLConnection i.e. associated with this URL. URLConnection Class The Java URLConnection class represents a communication link between the URL and the application. This class can be used to read and write data to the specified resource referred by the URL. public class URLConnectionExample { public static void main(String[] args) { try { URL url=new URL("http://www.visionacademe.com/java-tutorial"); URLConnection urlcon=url.openConnection(); InputStream stream=urlcon.getInputStream(); int i; while((i=stream.read())!=-1) { System.out.print((char)i); } }catch(Exception e) { System.out.println(e); } } } Connection Oriented Communication Using Socket Java performs the network communication. Sockets enables to transfer data
  • 41. 41 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note through certain port. Socket class of Java makes it easy to write the socket program Sockets are broken into two types: 1. Datagram sockets (UDP Socket) 1.A Datagram socket uses user datagram protocol (UDP) to send datagrams (self contained units of information) in a connectionless manner. 2.This method does not guarantee delivery of the datagram. 3.The advantage is the datagram sockets require relatively few resources and so communication is faster. 4.Typically request-reply types of application use datagram socket. 5.Java uses java.net.DatagramSocket class to create datagram socket. The java.net.DatagramPacket represents a datagram. 2. Stream Socket (TCP Socket) 1.A stream socket is a “connected” socket through which data is transferred continuously. 2. It use TCP to create a connection between the client and server. TCP/IP sockets are used to implement reliable, bidirectional, persistent, point to point, stream-based connection between hosts on the internet. 3. The benefit of using a stream socket is the communication is reliable. because once connected ,the communication link is available till it is disconnected. So data transmission is done in real-time and data arrives reliably in the same order that it was sent. however this requires more resource. Application like file transfer require a reliable communication. For such application stream sockets are better. 4. Java uses java.net.Socket class to create stream socket for client and java.net.ServerSocket for server. Difference between Datagram and Stream socket 1.DatagramSocket is for sending UDP datagram Stream socket is used for sending TCP packets.
  • 42. 42 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 2. DatagramSocket is a packet based socket. Stream socket is a byte oriented socket. 3. DatagramSocket are unreliable. They may be dropped ,duplicate and delivered out of order. Stream socket is reliable ,if datas are lost on the way, TCP automatically re-sends. 4. DatagramSocket have less overheads and so faster. Stream sockets require more overhead and are slower. 5.Application which use datagram sockets are request-reply type of application such as DNS lookups,PING and SMTP. Stream sockets are used for application like file transfer which require reliability. 6.For Datagram Socket used following class java.net.DatagramSocket class java.net.DatagramPacket class For Stream Socket used following class java.net.Socket class java.net.ServerSocket class 7Datagram Socket uses connection less mechanism Stream Socket uses connection oriented mechanism ServerSocket Class This class is used to create a server that listens for incoming connections from clients. It is possible for client to connect with the server when server socket binds itself to a specific port. The various constructors of the ServerSocket class are:
  • 43. 43 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 1. ServerSocket(int port): binds the server socket to the specified port number. If 0 is passed, any free port will be used. However, clients will be unable to access the service unless notified the port number. 2. ServerSocket(int port, int numberOfClients): Binds the server socket to the specified port number and allocates sufficient space to the queue to support the specified number of client sockets. 3. ServerSocket(int port, int numberOfClients, InetAddress address): Binds the server socket to the specified port number and allocates sufficient space to the queue to support the specified number of client sockets and the IP address to which this socket binds The various methods of this class are: Method Description Socket Class This class is used to represents a TCP client socket, which connects to a server socket and initiate protocol exchanges. The various constructors of this class are: 1. Socket(InetAddress address, int port): creates a socket connected to the specified IP address and port. Can throw an IOException.
  • 44. 44 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 2. Socket(String host, int port): creates a socket connected to the specified host and port. Can throw an UnknownHostException or an IOException. How to create a server socket 1. Create a ServerSocket object which listen to a specific port. 2. Call the accept() method which accepts client request. This method return the client socket object. 3. Use the socket object to communication with the client import java.net.*; import java.io.*; public class Server { public static void main(String[] ar)
  • 45. 45 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note { try { int port = 6666; ServerSocket ss = new ServerSocket(port); System.out.println("Waiting for a client..."); Socket socket = ss.accept(); InputStream sin = socket.getInputStream(); DataInputStream in = new DataInputStream(sin); String line = null; while(true) { line = in.readUTF(); System.out.println(“Receving line from client : " + line); System.out.println(); } } catch(Exception e) { System.out.println(e); } } } How to create a client socket 1.Create an object of the socket class using the server names and port as parameter. 2.Communication with the server. 3.Close the socket //Client import java.net.*;
  • 46. 46 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note import java.io.*; public class Client { public static void main(String[] ar) { try { int serverPort = 6666; String address = "127.0.0.1"; InetAddress ipAddress = InetAddress.getByName(address); Socket socket = new Socket(ipAddress, serverPort); OutputStream sout = socket.getOutputStream(); DataOutputStream out = new DataOutputStream(sout); BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); String line = null; while(true) { line = keyboard.readLine(); System.out.println("Sending this line to the server..."); out.writeUTF(line); // send the above line to the server. out.flush(); System.out.println(); } } catch(Exception e) { System.out.println(e); } } }
  • 47. 47 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Servlet What Web server? ➢ Apache is a very popular server ➢ 66% of the web sites on the Internet use Apache Apache is: • Full-featured and extensible • Efficient • Robust • Secure (at least, more secure than other servers) • Up to date with current standards • Open source • Free What is Tomcat? Tomcat is the Servlet Engine that handles servlet requests for Apache. ➢Tomcat is a “helper application” for Apache ➢It’s best to think of Tomcat as a “servlet container” What is servlet? A servlet is a web component,managed by a container, that generates dynamic content. ➢ Client sends a request to server ➢ Server starts a servlet ➢ Servlet computes a result for server and does not quit ➢ Server returns response to client
  • 48. 48 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note ➢ Another client sends a request ➢ Server calls the servlet again The Life Cycle of a Servlet 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: public void init(ServletConfig config) throws ServletException 4) service method is invoked The service() method of the Servlet is invoked to inform the Servlet about the client requests. This method uses ServletRequest object to collect the data requested by the client.
  • 49. 49 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note This method uses ServletResponse object to generate the output content. public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException 5) destroy method is invoked When a servlet is unloaded by the servlet container, its destroy() method is called. This step is only executed once, since a servlet is only unloaded once. public void destroy() The Servlet API It includeTwo packages: ▪ javax.servlet ▪ javax.servlet.http 1.The javax.servlet Package
  • 50. 50 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. Interface Description Servlet Declares life cycle methods for a servlet. ServletConfig Allows servlets to get initialization parameters. ServletContext Enables servlets to log events and access Information about their environment. ServletRequest Used to read data from a client request. ServletResponse Used to write data to a client response. SingleThreadModel Indicates that the servlet is thread safe. Class Description GenericServlet Implements the Servlet and ServletConfig interfaces. ServletInputStream Provides an input stream for reading requests from a client. ServletOutputStream Provides an output stream for writing responses to a client. 2.javax.servlet.http Package Interface Description HttpServletRequest Enables servlets to read data from an HTTP request. HttpServletResponse Enables servlets to write data to an HTTP response. HttpSession Allows session data to be read and written. HttpSessionBindingListener Informs an object that it is bound to or unbound from a session.
  • 51. 51 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Class Description Cookie Allows state information to be stored on a client machine. HttpServlet Provides methods to handle HTTP requests and responses. 1.doGet public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException Where Input is from the HttpServletRequest parameter Output is via the HttpServletResponse object, which we have named response 2.doPost public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  • 52. 52 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B> Hi Vision Academy!"); pw.close(); } } How to Run Setting: 1.To install Apache tomcat software 2.Go to the browser(Internet explorer) 3.Start tomcat service. & type the following URL in the Internet explorer(For Testing) http://localhost:8080[The server listen to port 8080]
  • 53. 53 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 1. To go to the following path C:Program FilesApache Software FoundationTomcat 6.0lib 5 To copy the servlet-api & jsp-api file & paste to the following path C:Program FilesJavajdk1.6.0jrelibext 1.To save above file(HelloServlet.java) following path C:Program FilesApache Software FoundationTomcat 6.0webappsexamplesWEB- INFclasses 2 Compile the servlet source code javac HelloServlet.java 3 To go to the following path C:Program FilesApache Software FoundationTomcat 6.0webappsexamplesWEB-INF
  • 54. 54 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 4 Open the following file(web.xml)& enter the following entry in the file & save it. <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/servlets/servlet/HelloServlet</url-pattern> </servlet-mapping> 5.To open internet explorer & type following URL http://localhost:8080/examples/servlets/servlet/HelloServlet How To retrieve value from the component Using doGet method <html> <body>
  • 55. 55 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note <center> <form name="Form1" method="get" action="http://localhost:8080/examples/servlets/servlet/GetServlet"> Enter name <input type=text name=”t”> <br> <input type=submit value="Submit"> </body> </html> import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class GetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String s = request.getParameter("t"); pw.println(s); pw.close(); } } Using doPost method <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/examples/servlets/servlet/PostServlet"> Enter name
  • 56. 56 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note <input type=text name=”t”> <br> <input type=submit value="Submit"> </body> </html> import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PostServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String s = request.getParameter("t"); pw.println(s); pw.close(); } } 2 <html> <body> <center> <form name="Form1" action="http://localhost:8080/examples/servlets/servlet/ColorGetServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select>
  • 57. 57 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note <br><br> <input type=submit value="Submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorGetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close(); } } What is a Cookie? A "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. A cookie’s value identify user Constructor of Cokkie class Constructor Description Cookie() constructs a cookie. Cookie(String name, String value) constructs a cookie with a specified name and value. Method of Cookie class Method Description public void setMaxAge(int Sets the maximum age of the cookie in seconds.
  • 58. 58 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note expiry) public String getName() Returns the name of the cookie. The name cannot be changed after creation. public String getValue() Returns the value of the cookie. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie. Interface Method Description Public void addCookie(Cookie ck) method of HttpServletResponse interface is used to add cookie in response object. Public Cookie[] getCookies() method of HttpServletRequest interface is used to return all the cookies from the browser. Add cookie’s value <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/examples/servlets/servlets/AddCookieServlet"> <B>Enter a value for MyCookie:</B> <input type=textbox name="data" size=25 value=""> <input type=submit value="Submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; SOFTWARE DEVELOPMENT
  • 59. 59 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note USING JAVA public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); // Get parameter from HTTP request. String data = request.getParameter("data"); // Create cookie. Cookie cookie = new Cookie("MyCookie", data); // Add cookie to HTTP response. //cookie.setMaxAge( 60 * 60 * 24 );//24 hours response.addCookie(cookie); // Write output to browser. pw.println("<B>MyCookie has been set to"); pw.println(data); pw.close(); } } Accessing cookie’s value import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetCookiesServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); // Get cookies from header of HTTP request. Cookie[] cookies = request.getCookies(); for(int i = 0; i < cookies.length; i++) {
  • 60. 60 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note String name = cookies[i].getName(); String value = cookies[i].getValue(); pw.println("name = " + name +"; value = " + value); } pw.close(); } } Session Tracking HTTP is a stateless protocol. i.e Each request is independent of the previous one. In some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. There are several ways through which it can provide unique identifier in request and response. 1. User Authentication – This is the very common way where we user can provide authentication from the login page and then we can pass the authentication information between server and client to maintain the session. This is not very effective method because it wont work if the same user is logged in from different browsers. 2. HTML Hidden Field – We can create a unique hidden field in the HTML and when user starts navigating, we can set its value unique to the user and keep track of the session. This method can’t be used with links because it needs the form to be submitted every time request is made from client to server with the hidden field. Also it’s not secure because we can get the hidden field value from the HTML source and use it to hack the session. 3. URL Rewriting – We can append a session identifier parameter with every request and response to keep track of the session. This is very tedious because we need to keep track of this parameter in every response and make sure it’s not clashing with other parameters. 4. Cookies: A "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. It can maintain a session with cookies but if the client disables the cookies, then it won’t work.
  • 61. 61 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 5. Session Management API:The servlet API provide methods and classes specifically designed to handle session.The HttpSession class provide various session tracking methods public void setAttribute( String name, Object value ) public Object getAttribute( String name ) public Object removeAttribute( String name ) USING JAA import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { // Get the HttpSession object. HttpSession hs = request.getSession(true); // Get writer. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print("<B>"); // Display date/time of last access. Date date = (Date)hs.getAttribute("date"); if(date != null) { pw.print("Last access: " + date + "<br>"); } // Display current date/time. date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date); } }
  • 62. 62 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Servlet CGI(Common Gateway Interface) 1. It is written in Java only. 2.It is portable 3. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. 4 It was inexpensive in terms of processor and memory resources. 1.It is written in Perl,C & C++ 2. It is not portable 3. It is to create a separate process for each client request. 4.It was also expensive in terms of processor and memory resources. JDBC USING SERVLET import java.io.*; import java.sql.*; import javax.servlet.*;
  • 63. 63 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note import javax.servlet.http.*; public class Jdconn extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Connection con = null; Statement stmt = null; ResultSet rs = null; res.setContentType("text/html"); PrintWriter out = res.getWriter(); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Get a Connection to the database con = DriverManager.getConnection("jdbc:odbc:vision2"); // Create a Statement object stmt = con.createStatement(); // Execute an SQL query, get a ResultSet rs = stmt.executeQuery("SELECT sname,address FROM stud"); while(rs.next()) { out.println( rs.getString("sname") + " " + rs.getString("address")); } con.close(); } catch(Exception e) { out.println(“error”+e); } } }
  • 64. 64 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note JSP(Java Server Page) • JSP is a server side program. • JSP tags to enable dynamic content creation (Combination of HTML & JSP tag). • JSP provide excellent server side scripting support for creating database driven web applications • JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy. • JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the subsequent calls are served within a very short period of time. There are 3 methods in JSP(Life cycle of JSP) A JSP page undergoes 3 phases during life cycle. 1.Translation phase:In this phase,JSP pages get translated into servlet code. 2.Compilation phase:In this phase, the servlet code compiled. The compilation is done only if the page is requested the first time or it is modified. 3.Excution phase:This is final phase where jsp servlet methods are executed.These are jspInit(),_jspService(),jspDestroy()
  • 65. 65 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 1.jspInt() • This method is identical to the init() method in Java servlet. • This method is called first when the JSP is requested and is used to initialize objects & variables that are used throughout the life of the JSP. public void jspInit() { // Initialization code... } 2.jspDestroy() • This method is identical to the destroy() method in Java servlet. • This method is automatically called when JSP terminates normally. • This method is used for cleanup where resources used during execution of JSP are released. public void jspDestroy()
  • 66. 66 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note { // Your cleanup code goes here. } 3._jspService() • This method is automatically called & retrieves a connection to HTTP. public void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... } JSP Architecture
  • 67. 67 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note JSP Processing: The following steps explain how the web server creates the web page using JSP: • As with a normal page, your browser sends an HTTP request to the web server. • The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html. • The JSP engine loads the JSP page from disk and converts it into a servlet content. • The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. • A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response. • The web server forwards the HTTP response to your browser in terms of static HTML content. JSP Tags 1.Comment Tags: It is denoted by <%-- --%>
  • 68. 68 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note e.g <%-- This comment will not be visible in the page source --%> 2.Declaration statement tags: This tag is used for defining the functions and variables to be used in the JSP. It is denoted by <%! %> Eg <%! int age=25;%> 3.Scriptlet tags: It is used for Java control statements & loop. It is denoted by <% Eg. %> <% for(int i=0;i<=3;i++) { --- --- } %> 4.Expression tags: The expression is evaluated and the result is inserted into the HTML page It is denoted by <%= expression %> Eg. <%=age%> 5.Directive tags: The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.
  • 69. 69 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note There are three types of directives: o page directive o include directive o taglib directive 1.page directive The page directive defines attributes that apply to an entire JSP page. It is denoted by <%@ directive attribute="" %> Attribute as follows 1.language: It defines the programming language (underlying language) being used in the page. Syntax of language: <%@ page language="value" %> e.g <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 2.Extends: This attribute is used to extend (inherit) the class like JAVA does Syntax of extends: <%@ page extends="value" %> e.g <%@ page extends="demotest.DemoClass" %> 3.Import: It is used to import Java package into the JSP program. Syntax of import:
  • 70. 70 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note <%@ page import="value" %> e.g <%@page import=” java.sql.*” % 4.contentType: • It defines the character encoding scheme i.e. it is used to set the content type and the character set of the response • The default type of contentType is "text/html; charset=ISO-8859-1". Syntax of the contentType: <%@ page contentType="value" %> e.g <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 5.Session Specifies whether or not the JSP page participates in HTTP sessionsSyntax of session Syntax <%@ page session="true/false"%> e.g <%@ page language="java" contentType="text/html; charset=ISO-8859-1" session="false"%> 6.errorPage: This attribute is used to set the error page for the JSP page if JSP throws an exception and then it redirects to the exception page. Syntax of errorPage: <%@ page errorPage="value" %>
  • 71. 71 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note e.g <%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1" errorPage="errorHandler.jsp"%> 7. PageEncoding: The "pageEncoding" attribute defines the character encoding for JSP page.The default is specified as "ISO-8859-1" if any other is not specified. Syntax <%@ page pageEncoding="vaue" %> Here value specifies the charset value for JSP Example: <%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1" isErrorPage="true"%> 2.include directive: • include directive is used to include one file to the another file • This included file can be HTML, JSP, text files, etc. <%@ include file="/header.jsp" %> e.g a.jsp <%="HELLO bcs"%> p.jsp <%@ include file="p.jsp" %> <%="HELLO mcs"%> 3.taglib directive:
  • 72. 72 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note JSP taglib directive is used to define the tag library with "taglib" as the prefix, which we can use in JSP. (custom tags allows us to defined our own tags). Syntax of taglib directive: <%@ taglib uri="uri" prefix="value"%> Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is a tag name. e.g <%@ taglib prefix="vtag" uri="http://java.sun.com/jsp/jstl/core" %> How To run JSP? <html> <head> <title> Sachin Sir 9823037693 </title> </head> JSP CODE <body> <%="HELLO Sachin Sir"%> <body> </html> Step1 Save the file Hello.jsp into the following path C:Program FilesApache Software FoundationTomcat 6.0webappsexamplesjsp Step2 Open the browser & type it in the address bar http://localhost:8080/examples/jsp/Hello.jsp
  • 73. 73 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Variables It can declare your own variables, as usual Using Function <html> <head> <title> Sachin Sir 9823037693 Sum of first n numbers </title> </head> <body> <%! int sumoffirst(int n) { int sum=0; for(int i=1;i<=n;i++) sum=sum+i; return(sum); } %> JSP CODE <p>Sum of first n number: </p> <body> </html> <%=sumoffirst(5)%>
  • 74. 74 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note JSP provides several predefined variables(implicit object) Implicit object:These objects are created automatically by JSP container. It can directly use these object.JSP Implicit Objects are also called pre-defined variables No. Object & Description 1 request This is the HttpServletRequest object associated with the request. 2 response This is the HttpServletResponse object associated with the response to the client. 3 out This is the PrintWriter object used to send output to the client. 4 session This is the HttpSession object associated with the request. 5 application This is the ServletContext object associated with the application context. 6 config This is the ServletConfig object associated with the page. 7 pageContext This encapsulates use of server-specific features like higher performance JspWriters.
  • 75. 75 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 8 page This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. 9 Exception The Exception object allows the exception data to be accessed by designated JSP. 1.Display html & jsp page separate l.html <html> <head> <title>Login</title> </head> <body> <form method="post" action="http://localhost:8080/examples/jsp/login.jsp"> Username:<input type="text" name="t1"> <br> Password:<input type="password"name="t2"> <br> <input type="submit" value="Login"> <input type="reset" value="Clear"> </body> </html>
  • 76. 76 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Login.jsp <% String s1=request.getParameter("t1"); String s2=request.getParameter("t2"); if(s1.equals("sachin")&&s2.equals("sachin")) out.println("Login Sucessfully"); else out.println("Login incorrect"); %>
  • 77. 77 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Database connection using jsp <%@page import="java.sql.*"%> <%@page import="java.io.*"%> <html> <body> <% try {
  • 78. 78 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:visionstud"); Statement sta = con.createStatement(); ResultSet rs=sta.executeQuery("select * from student"); while(rs.next()) { out.println("rollno"+rs.getInt(1)); out.println("name"+rs.getString(2)); out.println("Percentage"+rs.getFloat(3)); } rs.close(); sta.close(); con.close(); } catch(Exception e) { } %> </body> </html>
  • 79. 79 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note JSP Benefits • Easy to combine static templates,including HTML or XML. • JSP pages compile dynamically into servlets. • JSP makes it easier to author pages "by hand" • JSP tags for invoking JavaBeansTM components Compare servlet &jsp JSP Servlets JSP is a webpage scripting language that can generate dynamic content. Servlets are Java programs that are already compiled which also creates dynamic web content. JSP run slower compared to Servlet as it takes compilation time to convert into Java Servlets. Servlets run faster compared to JSP. It’s easier to code in JSP than in Java Servlets. Its little much code to write here. In MVC, jsp act as a view. In MVC, servlet act as a controller. JSP are generally preferred when there is not much processing of data required. servlets are best for use when there is more processing and manipulation involved. The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans. There is no such custom tag facility in servlets. We can achieve functionality of JSP at client side by running JavaScript at client side. There are no such methods for servlets.
  • 80. 80 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Remote Method Invocation(RMI) Definition: Java RMI is a mechanism that allows a Java program running on one computer to apply a method to an object living on a different computer. OR RMI enables the programmer to create distributed Java applications, in which the methods of remote Java objects can be invoked from other Java virtual machines, possibly on different hosts. OR The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine. RMI is an implementation of the of the Distributed Object programming model RMI Architecture Layers
  • 81. 81 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note It consist of following parts Client: user interface Server : data source Stubs 1.The client side object participating object communication is known as stub or proxy. 2. The stub acts as a gateway for client side objects & outgoing requests to server side objects that are routed through it. 3. The stub wraps client object functionality & by adding the network logic ensures the reliable communication channel between client & server. Stub responsibility 1.Initiating the communication towards the server selection 2.Translating calls from caller object 3.Marshaling of arguments: It refers to the process of converting the data or the objects inbto a byte-stream. 4.Informing the skeleton that the call should be invoked. 5. Passing arguments to skeleton over network. 6. Unmarshalling (converting the byte-stream back to their original data or object) of the response from skeleton. 7. informing skeleton that call is complete
  • 82. 82 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Skeletons: 1.The server side object participating object communication is known as skeleton. 2.A skeleton acts as gateways for server side object & all incoming clients requests are routed through it. 3. The skeleton wraps server object functionality & by adding the network logic ensures the reliable communication channel between client & server. Skeleton responsibility 1.Translating incoming data from stub to correct up-calls to server objects. 2.unmarshalling of arguments from received data. 3.To pass arguments to server objects. 4.marshalling of the returned values from server objects. 5. To pass values back to the client stub over the network. Remote Reference Layer: (RRL) Part of Java's Remote Method Invocation protocol. RRL exists in both the RMI client and server. It is used by the stub or skeleton protocol layer and uses the transport layer. RRL is reponsible for transport-independent functioning of RMI, such as connection management or unicast/multicast object invocation Various invocation protocols can be carried out at this layer. Examples are: • Unicast point-to-point invocation. • Invocation to replicated object groups. • Support for a specific replication strategy. • Support for a persistent reference to the remote object (enabling activation of the remote object). • Reconnection strategies (if remote object becomes inaccessible). Transport Layer:
  • 83. 83 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note The Transport Layer makes the connection between JVMs. All connections are stream-based network connections that use TCP/IP. RMI Registry The Java RMI registry is a remote object that maps name to remote object i.e For a client communication with a server, the client has to find the location of remote object.Each &every object to be accessed remotely has to be register with RMI registry with unique name.so if there is any request for particular object, the registry will direct the request to the correct object. public static java.rmi.Remote lookup(java.lang.String) throws java.rmi.NotBoundException, java.net.MalformedURLException, java.rmi.RemoteException; It returns the reference of the remote object. public static void bind(java.lang.String, java.rmi.Remote) throws java.rmi.AlreadyBoundException, It binds the remote object with the given
  • 84. 84 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note java.net.MalformedURLException, java.rmi.RemoteException; name. public static void unbind(java.lang.String) throws java.rmi.RemoteException, java.rmi.NotBoundException, java.net.MalformedURLException; It destroys the remote object which is bound with the given name. public static void rebind(java.lang.String, java.rmi.Remote) throws java.rmi.RemoteException, java.net.MalformedURLException; It binds the remote object to the new name. public static java.lang.String[] list(java.lang.String) throws java.rmi.RemoteException, java.net.MalformedURLException; It returns an array of the names of the remote objects bound in the registry. Steps for implementing RMI 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
  • 85. 85 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Step 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 Exception; public long sub(long a, long b) throws Exception; public long mul(long a, long b) throws Exception; public long div(long a, long b) throws Exception; } Copy this file to your directory and compile it with the Java compiler: C:>rmi>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 { public CalculatorImpl() throws Exception { super(); }
  • 86. 86 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note public long add(long a, long b) throws Exception { return a + b; } public long sub(long a, long b) throws Exception { return a - b; } public long mul(long a, long b) throws Exception { return a * b; } public long div(long a, long b) throws Exception { return a / b; } } Again, copy this code into your directory and compile it. C:>rmi>javac CalculatorImpl.java 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. C:>rmi >rmic CalculatorImpl Try this in your directory. After you run rmic you should find the file CalculatorImpl_Stub.class. , if you are running the Java 2 SDK, CalculatorImpl_Skel.class.
  • 87. 87 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Note: rmic is used for stub generator. 4. Server Remote RMI services must be hosted in a server process. import java.rmi.Naming; public class CalculatorServer { public CalculatorServer() { try { Calculator c = new CalculatorImpl(); Naming.rebind("rmi://localhost:1099/CalculatorService",c);//Binding for specified name where 1st argument object is the remote object being registered & 2nd argument is the String that names the remote object. } catch (Exception e) { System.out.println("Trouble: " + e); } } public static void main(String args[]) { new CalculatorServer(); } } Again, copy this code into your directory and compile it. C:>rmi>javac CalculatorServer.java 5.Client The source code for the client follows: import java.rmi.Naming; import java.rmi.RemoteException;
  • 88. 88 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 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 (Exception e) { System.out.println("error"+e); } } } Again, copy this code into your directory and compile it. C:>rmi>javac CalculatorClient.java 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 C:>rmi>start rmiregistry
  • 89. 89 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note • Start the another console for server hosting C:>rmi>java CalculatorServer It will start, load the implementation into memory and wait for a client connection.
  • 90. 90 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note • Start the client program. C:>rmi>java CalculatorClient
  • 91. 91 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note What is JavaBeans? In Java Platform, JavaBeans are classes that encapsulate many objects into a single object (the bean). They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. Advantages of Java Beans 1. Exposure to other applications One of the most important advantages of a JavaBean is, the events properties and the methods of a bean can be exposed directly to another application. 2. Registration to receive events A JavaBean can be registered to receive events from other objects. However, It can also generate events that can be sent to other objects. 3. Ease of configuration We can easily use auxiliary software to configure the JavaBean. However, It can also save the configuration setting of a JavaBean to persistent storage. 4. Portable As JavaBeans are built in Java, It can easily port them to any other platform that contains JRE. 5. Lightweight JavaBeans are light weighted, I.e., we don't need to fulfill any special requirement to use it. Also, it is very easy to create them. However, it doesn't need a complex system to register components with JRE. The other advantages of JavaBeans include reusability, deployment, and customization that can be archived using JavaBeans.
  • 92. 92 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note Features of JavaBeans Support for introspection ❖ so that a builder tool can analyze how a bean works Support for customization ❖ so that when using an application builder a user can customize the appearance and behavior of a bean Support for events ❖ as a simple communication metaphor than can be used to connect up beans Support for properties ❖ both for customization and for programmatic use Support for persistence ❖ A bean can be customized in an application builder and then have its customized state saved away and reloaded later Using the Bean Developer Kit (BDK) JavaBeans are reusable software components written in Java. These components may be built into an application using an appropriate building environment. The Bean Development Kit (BDK) from Sun includes a simple example of a building environment which uses beans, called the beanbox. It displays four windows on the screen: • ToolBox which lists all beans the BeanBox has found,
  • 93. 93 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note • The BeanBox which is a canvas where you will drop beans and connect them together, • The Properties sheet which is used to set the properties of the current bean, • the MethodTracer simple debugging facility. JAR(Java Archive File) JAR (Java Archive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file to distribute application software or libraries on the Java platform. OR
  • 94. 94 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note A Java Archive File, commonly referred to as a Jar File is nothing more than a compressed archive file. Benefits of using Jar files are: • Decreased download time, since the archive is compressed it takes less time to download as compare to downloading each individual file. • Package Versioning, A Jar file may contain vendor and version information about the files it contains. • Portability, all Java Runtime Environments know how to handle Jar files. Creating JAR File jar cf jar-filename input-files The c option indicates that you wish to create a jar and the f option indicates that output should be sent to a file, jar-filename is the name of the resulting Jar file and input-files are the files you wish to include. Mainfest File The Jar file automatically adds a manifest file to the jar file, the file is always in a directory named META-INF and file is named MANIFEST.MF.This file contains information about the jar file. Vision Academy Since 2005 Prof. Sachin Sir(MCS,SET) 9822506209/9823037693 www.visionacademe.com Branch1:Nr Sm Joshi College,Abv Laxmi zerox,Ajikayatara Build,Malwadi Rd,Hadapsar Branch2:Nr AM College,Aditya Gold Society,Nr Allahabad Bank ,Mahadevnager