SlideShare a Scribd company logo
1 of 78
Download to read offline
1 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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)
{
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 {
14 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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())
{
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 {
15 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Roll no: ");
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();
}
16 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
catch (Exception e) {
System.err.println("Error"+e);
}
}
}
4.Update
import java.sql.*;
import java.io.*;
public class UpsQuery
{
public static void main(String [] args)
{
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vision", "root", "");
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");
17 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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("Exception: "+e);
}
}
}
5.Delete
import java.sql.*;
import java.io.*;
public class DelQuery
{
public static void main(String [] args)
{
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vision", "root", "");
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
18 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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("Delete "+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("Exception: "+e);
}
}
}
6.Searching
import java.sql.*;
import java.io.*;
public class SearchQuery
{
public static void main(String [] args)
{
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vision","root","");
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());
19 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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 str="select * from student where rollno="+rno;
ResultSet rs=sta.executeQuery(str);
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);
}
}
}
20 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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…
21 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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
22 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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()
{
23 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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
24 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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[])
{
25 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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
26 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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
27 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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.
28 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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.
29 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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");
}
}
30 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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:
31 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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();
t1.start();//invoke run method
32 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
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
}
33 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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()
{
34 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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.
35 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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 Method & Description
static Thread currentThread()
This method returns a reference to the currently
executing thread object.
String getName()
This method returns this thread's name.
int getPriority()
This method Returns this thread's priority.
boolean isAlive()
This method tests if this thread is alive.
void join()
Waits for this thread to die.
void run()
If this thread was constructed using a separate
Runnable run object, then that Runnable object's run
method is called; otherwise, this method does nothing
and returns
void setName(String name)
This method changes the name of this thread to be
equal to the argument name.
void setPriority(int newPriority)
This method changes the priority of this thread.
36 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
static void sleep(long millis)
This method causes the currently executing thread to
sleep (temporarily cease execution) for the specified
number of milliseconds, subject to the precision and
accuracy of system timers and schedulers.
void start()
This method causes this thread to begin execution; the
Java Virtual Machine calls the run method of this
thread.
static void yield()
This method causes the currently executing thread
object to temporarily pause and allow other threads to
execute.
37 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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[] args)
45 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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 www.visionacademe.com)
(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.
5. Session Management API:The servlet API provide methods and classes specifically
designed to handle session.The HttpSession class provide various session tracking
methods
61 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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 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();
String s = (String)hs.getAttribute("course");
if(s!= null)
{
hs.setAttribute("course", “bcs”);
}
else
pw.println("data is: " + s);
}
}
62 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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 USING SERVLET
import java.io.*;
import java.sql.*;
import javax.servlet.*;
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");
63 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET)
Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp)
Advance Java Note
// 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);
}
}
}
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.
64 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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.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()
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.
65 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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 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()
{
// 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
66 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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
<%--
--%>
67 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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.
68 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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:
69 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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" %>
70 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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="value" %>
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:
71 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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
72 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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)%>
73 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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.
74 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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>
75 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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");
%>
76 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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
{
77 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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>
78 Vision Academy
(9822506209/9823037693 www.visionacademe.com)
(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.
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

Similar to Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf

Java Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptxJava Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptxmukeshprasanth909
 
Airline report
Airline reportAirline report
Airline reportSimranBani
 
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 singhSudeep Singh
 
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 DB2Vladimir Bacvanski, PhD
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05Ankit Dubey
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05JONDHLEPOLY
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivityweb360
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
Module4_Annotations_JDBC.pdf
Module4_Annotations_JDBC.pdfModule4_Annotations_JDBC.pdf
Module4_Annotations_JDBC.pdfRoopeshGT
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 

Similar to Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf (20)

Java Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptxJava Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptx
 
Jdbc new
Jdbc newJdbc new
Jdbc new
 
Airline report
Airline reportAirline report
Airline report
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
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
 
jdbc
jdbcjdbc
jdbc
 
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
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Module4_Annotations_JDBC.pdf
Module4_Annotations_JDBC.pdfModule4_Annotations_JDBC.pdf
Module4_Annotations_JDBC.pdf
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 

Recently uploaded

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 

Recently uploaded (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 

Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf

  • 1. 1 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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) { 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 {
  • 14. 14 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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()) { 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 {
  • 15. 15 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Roll no: "); 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(); }
  • 16. 16 Vision Academy (9822506209/9823037693 www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note catch (Exception e) { System.err.println("Error"+e); } } } 4.Update import java.sql.*; import java.io.*; public class UpsQuery { public static void main(String [] args) { Connection con = null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vision", "root", ""); 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");
  • 17. 17 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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("Exception: "+e); } } } 5.Delete import java.sql.*; import java.io.*; public class DelQuery { public static void main(String [] args) { Connection con = null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vision", "root", ""); 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
  • 18. 18 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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("Delete "+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("Exception: "+e); } } } 6.Searching import java.sql.*; import java.io.*; public class SearchQuery { public static void main(String [] args) { Connection con = null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vision","root",""); 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());
  • 19. 19 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 str="select * from student where rollno="+rno; ResultSet rs=sta.executeQuery(str); 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); } } }
  • 20. 20 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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…
  • 21. 21 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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
  • 22. 22 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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() {
  • 23. 23 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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
  • 24. 24 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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[]) {
  • 25. 25 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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
  • 26. 26 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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
  • 27. 27 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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.
  • 28. 28 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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.
  • 29. 29 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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"); } }
  • 30. 30 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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:
  • 31. 31 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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(); t1.start();//invoke run method
  • 32. 32 Vision Academy (9822506209/9823037693 www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note 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 }
  • 33. 33 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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() {
  • 34. 34 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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.
  • 35. 35 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 Method & Description static Thread currentThread() This method returns a reference to the currently executing thread object. String getName() This method returns this thread's name. int getPriority() This method Returns this thread's priority. boolean isAlive() This method tests if this thread is alive. void join() Waits for this thread to die. void run() If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns void setName(String name) This method changes the name of this thread to be equal to the argument name. void setPriority(int newPriority) This method changes the priority of this thread.
  • 36. 36 Vision Academy (9822506209/9823037693 www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note static void sleep(long millis) This method causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. void start() This method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. static void yield() This method causes the currently executing thread object to temporarily pause and allow other threads to execute.
  • 37. 37 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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[] args)
  • 45. 45 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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 www.visionacademe.com) (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. 5. Session Management API:The servlet API provide methods and classes specifically designed to handle session.The HttpSession class provide various session tracking methods
  • 61. 61 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 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(); String s = (String)hs.getAttribute("course"); if(s!= null) { hs.setAttribute("course", “bcs”); } else pw.println("data is: " + s); } }
  • 62. 62 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 USING SERVLET import java.io.*; import java.sql.*; import javax.servlet.*; 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");
  • 63. 63 Vision Academy (9822506209/9823037693 www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ,SET) Classes For BCA/BBA(CA)/BCS/MCS/MC/MCS/BE(Comp) Advance Java Note // 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); } } } 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.
  • 64. 64 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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.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() 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.
  • 65. 65 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 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() { // 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
  • 66. 66 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 <%-- --%>
  • 67. 67 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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.
  • 68. 68 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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:
  • 69. 69 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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" %>
  • 70. 70 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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="value" %> 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:
  • 71. 71 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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
  • 72. 72 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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)%>
  • 73. 73 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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.
  • 74. 74 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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>
  • 75. 75 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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"); %>
  • 76. 76 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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 {
  • 77. 77 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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>
  • 78. 78 Vision Academy (9822506209/9823037693 www.visionacademe.com) (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. 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