Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
J2EE (Advanced) JAVA
By Mr. K. V. R Page 1
Advanced JAVA (J2EE)
Day - 1:
In IT we are developing two types of applications; they are standalone applications and
distributed applications.
• A standalone application is one which runs in the context of local disk. With standalone
applications we cannot achieve the concept of data sharing. For example C, C++, COBOL,
PASCAL, etc.
• A distributed application is one which always runs in the context of Browser or World Wide
Web. All distributed applications can be accessed across the globe. For example JAVA and
DOT NET.
JAVA always provides a facility called server independent, platform independent language.
JAVA supports a concept called design patterns (design patterns are predefined proved rules by
industry experts to avoid side effects [recurring problems] which are occurring in software
development).
Day - 2:
In real time applications, in the case of server side programming one must follow the
architecture to develop a distributed application.
To develop any distributed application, it is always recommended to follow either 3-tier
architecture or 2-tier architecture or n-tier architecture.
3-tier architecture is also known as MVC architecture. M stands for Model (database
programming), V stands for View (client side programming, HTML/AWT/APPLET/Swing/JSP) and C
stands for Controller (server side programming, Servlets).
The general architecture of MVC or 3-tier:
1. Client makes a request.
2. Server side program receives the request.
3. The server looks for or search for the appropriate resource in the resource pool.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 2
4. If the resource is not available server side program displays a user friendly message (page
cannot be displayed). If the resource is available, that program will execute gives its result to
server, server interns gives response to that client who makes a request.
5. When server want to deals with database to retrieve the data, server side program sends a
request to the appropriate database.
6. Database server receives the server request and executes that request.
7. The database server sends the result back to server side program for further processing.
8. The server side program is always gives response to ‘n’ number of clients concurrently.
Day - 3:
REFLECTION
“Reflection is the process of obtaining runtime information about the class or interface.”
Runtime information is nothing but deal with the following:
1. Finding the name of the class or interface.
2. Finding the data members of the class or interface.
3. Finding number of constructors (default constructor and number of parameterized
constructors).
4. Number of instance methods.
5. Number of static methods.
6. Determining modifiers of the class (modifiers of the class can be public, final, public + final,
abstract and public + abstract).
7. Obtaining super class of a derived class.
8. Obtaining the interfaces which are implemented by various classes.
Real time applications of reflection:
1. Development of language complier, debuggers, editors and browsers.
2. In order to deal with reflection in java, we must import a predefined package called
java.lang.reflect.*
3. The package reflect contains set of predefined classes and interfaces which are used by the
programmer to develop reflection applications.
Number of ways to obtain runtime information about a class (or) number of ways to get an object
of a class called Class:
The predefined class called Class is present in a package called java.lang.Class (fully
qualified name of a class called Class is java.lang.Class).
In java we have 4 ways to deal with or to create an object of java.lang.Class, they are:
1) When we know that class name at compile time and to get runtime information about the
class, we must use the following:
2) When we know the object name at runtime, to get the class name or class type of the
runtime object, we must use the following:
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 3
getClass is the predefined method present in a predefined class called java.lang.Object and
whose prototype is given below:
3) When an object is given at runtime, we must find runtime information about current class
and its super class.
Write a java program to print name of the current class and its super class name?
Answer:
class First
{
public static void main (String [] args)
{
String s=new String ("HELLO");
printSuperclass (s);
}
static void printSuperclass (Object s)
{
Class c=s.getClass ();
Class sc=c.getSuperclass ();
System.out.println ("NAME OF CURRENT CLASS : "+c.getName ());
System.out.println ("NAME OF THE SUPER CLASS : "+sc.getName ());
}
};
Output:
java First
NAME OF CURRENT CLASS : java.lang.String
NAME OF THE SUPER CLASS : java.lang.Object
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 4
Day - 4:
4) We know the class name at runtime and we have to obtain the runtime information about
the class.
To perform the above we must use the method java.lang.Class and whose prototype is given
below:
When we use the forName as a part of java program it performs the following operations:
• It can create an object of the class which we pass at runtime.
• It returns runtime information about the object which is created.
For example:
try
{
Class c=Class.forName (“java.awt.Button”);
}
catch (ClassNotFoundException cnfe)
{
System.out.println (“CLASS DOES NOT EXIST...”);
}
forName is taking String as an argument. If the class is not found forName method
throws an exception called ClassNotFoundException.
Here, forName method is a factory method (a factory method is one which return type is
similar to name of the class where it presents).
Every factory method must be static and public. The class which contains a factory
method is known as Singleton class (a java class is said to be Singleton class through which
we can create single object per JVM).
For example:
java.lang.Class is called Singleton class
Write a java program to find name of the class and its super class name by passing the class name
at runtime?
Answer:
class ref1
{
public static void main (String [] args)
{
if (args.length==0)
{
System.out.println ("PLEASE PASS THE CLASS NAME..!");
}
else
{
try
{
Class c=Class.forName (args [0]);
printSuperclass (c);
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 5
}
catch (ClassNotFoundException cnfe)
{
System.out.println (args [0]+" DOES NOT EXISTS...");
}
}// else
}// main
static void printSuperclass (Class c)
{
String s=c.getName ();
Class sc=c.getSuperclass ();
String sn=sc.getName ();
System.out.println (sn+" IS THE SUPER CLASS OF "+s);
}// printSuperclass
}// ref1
Output:
java ref1 java.awt.TextField
java.awt.TextComponent IS THE SUPER CLASS OF java.awt.TextField
Write a java program to print super class hierarchy at a current class which is passed from command
prompt?
Answer:
class Hierarchy
{
public static void main (String [] args)
{
if (args.length==0)
{
System.out.println ("PLEASE PASS THE CLASS NAME..!");
}
else
{
try
{
Class c=Class.forName (args [0]);
printHierarchy (c);
}
catch (ClassNotFoundException cnfe)
{
System.out.println (args [0]+" DOES NOT EXISTS...");
}
}
}
static void printHierarchy (Class c)
{
Class c1=c;
String cname=c1.getName ();
System.out.println (cname);
Class sc=c1.getSuperclass ();
while (sc!=null)
{
cname=sc.getName ();
System.out.println (cname);
c1=sc;
sc=c1.getSuperclass ();
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 6
}
}
};
Output:
java Hierarchy java.awt.TextField
java.awt.TextField
java.awt.TextComponent
java.awt.Component
java.lang.Object
Obtaining information about CONSTRUCTORS which are present in a class:
In order to get the constructor of the current class we must use the following method:
For example:
Constructor cons []=c.getConstructors ();
System.out.println (“NUMBER OF CONSTRUCTORS = ”+cons.length);
In order to get the parameters of the constructor we must use the following method:
For example:
Class ptype []=cons [0].getParameterTypes ();
Day - 5:
Write a java program to obtain constructors of a class?
Answer:
class ConsInfo
{
public static void main (String [] args)
{
if (args.length==0)
{
System.out.println ("PLEASE PASS THE CLASS NAME..!");
}
else
{
try
{
Class c=Class.forName (args [0]);
printConsts (c);
}
catch (ClassNotFoundException cnfe)
{
System.out.println (args [0]+" DOES NOT EXISTS...");
}
}
}
static void printConsts (Class c)
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 7
{
java.lang.reflect.Constructor Cons []=c.getConstructors ();
System.out.println ("NUMBER OF CONSTRUCTORS = "+Cons.length);
System.out.println ("NAME OF THE CONSTRUCTOR : "+c.getName());
for (int i=0; i<Cons.length; i++)
{
System.out.print (c.getName ()+"(");
Class cp []=Cons [i].getParameterTypes ();
for (int j=0; j<cp.length; j++)
{
System.out.print (cp [j].getName ()+")");
}
System.out.println ("b"+")");
}
}
};
Obtaining METHODS information:
In order to obtain information about methods we must use the following methods:
For example:
Method m []=c.getMethods ();
System.out.println (“NUMBER OF METHODS = ”+m.length);
Associated with methods we have return type of the method, name of the method and types of
parameters passed to a method.
The Method class contains the following methods:
1. public Class getReturnType ();
2. public String getName ();
3. public Class [] getParameterTypes ();
Method-1 gives return type of the method, Method-2 gives name of the method and
Method-3 gives what parameters the method is taking.
Write a java program to obtain information about methods which are present in a class?
Answer:
import java.lang.reflect.*;
class MetInfo
{
public static void main (String [] args)
{
try
{
if (args.length==0)
{
System.out.println ("PLEASE PASS THE CLASS NAME..!");
}
else
{
Class c=Class.forName (args [0]);
printMethods (c);
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 8
}
}
catch (ClassNotFoundException cnfe)
{
System.out.println (args [0]+" DOES NOT EXISTS...");
}
}
static void printMethods (Class c)
{
Method m []=c.getMethods ();
System.out.println ("NUMBER OF METHODS = "+m.length);
System.out.println ("NAME OF THE CLASS : "+c.getName ());
for (int i=0; i<m.length; i++)
{
Class c1=m [i].getReturnType ();
String rtype=c1.getName ();
String mname=m [i].getName ();
System.out.print (rtype+" "+mname+"(");
Class mp []=m [i].getParameterTypes ();
for (int j=0; j<mp.length; j++)
{
String ptype=mp [i].getName ();
System.out.print (ptype+",");
}
System.out.println ("b"+")");
}
}
};
Obtaining FIELDS or DATA MEMBERS of a class:
In order to obtain information about fields or data members of the class we must use the following
method.
For example:
Field f []=c.getFields ();
System.out.println (“NUMBER OF FIELDS = ”+f.length);
Associated with field or data member there is a data type and field name:
The Field class contains the following methods:
1. public Class getType ();
2. public String getName ();
Method-1 is used for obtaining data type of the field and Method-2 is used for obtaining
name of the field.
Write a java program to print fields or data members of a class?
Answer:
import java.lang.reflect.Field;
class Fields
{
void printFields (Class c)
{
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 9
Field f []=c.getFields ();
System.out.println ("NUMBER OF FIELDS : "+f.length);
for (int i=0; i<f.length; i++)
{
String fname=f [i].getName ();
Class s=f [i].getType ();
String ftype=s.getName ();
System.out.println (ftype+" "+fname);
}
}
};
class FieldsDemo
{
public static void main (String [] args)
{
if (args.length==0)
{
System.out.println ("PLEASE PASS THE CLASS NAME..!");
}
else
{
try
{
Class c=Class.forName (args [0]);
Fields fs=new Fields ();
fs.printFields (c);
}
catch (ClassNotFoundException cnfe)
{
System.out.println (args [0]+"NOT FOUND...");
}
}
}
};
Day - 6:
JDBC (Java Database Connectivity)
“JDBC is a kind of specification developed by SUN Microsystems to store the data
permanently”.
In Information Technology we have two approaches’ to store the data permanently. They
are through files and through database.
Whatever data we store permanently in the form of a file, the file will not provide enough
security to the data from unauthorized users.
In order to save or store the data permanently in the form of a file we must use the concept
of serialization.
Serialization: Serialization is the mechanism of saving the state of the object permanently in the
form of a file.
Steps for developing SERIALIZABLE SUB CLASS:
A Serializable sub class is one which implements a predefined interface called
java.io.Serializable
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 10
1. Choose the appropriate package to keep Serializable sub class.
2. Choose the user defined class whose object participates in Serializable process.
3. Every user defined class must implements a predefined interface called Serializable.
4. Choose the set of data members for Serializable sub class.
5. Develop the set of set methods for each and every data members of the class.
6. Develop the set of get methods for each and every data members of the class.
The above class is known as java bean class or component style based programming or
POJO (Plain Old Java Object) class.
For example:
package ep; //step-1
import java.io.*;
public class Emp implements Serializable // Emp (step-2) & Serializable (step-3)
{
int empno;
String ename;
float sal;
// above data members (step-4)
public void setEmpno (int empno)
{
this.empno=empno;
}
public void setEname (String ename)
{
this.ename=ename;
}
public void setSal (float sal)
{
this.sal=sal;
} // above set methods (step-5)
public int getEmpno ()
{
return empno;
}
public String getEname ()
{
return ename;
}
public float getSal ()
{
return sal;
} // above get methods (step-6)
};
Day - 7:
Serializable process:
Steps for SERIALIZATION process:
1. Create an object of Serializable sub class.
For example:
sp.emp eo=new sp.emp ();
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 11
2. Call set of set methods to place user defined values in a Serializable sub class object.
For example:
eo.setEmpno (10);
eo.setEname (“KVR”);
eo.setSal (10000.00f);
3. Choose the file name and open it into write mode or output mode with the help of
java.io.FileOutputStream
For example:
FileOutputStream fos=new FileOutputStream (“employee”);
4. Since an object of FileOutputStream cannot write the entire object at a time to the file.
Hence, it is recommended to use a predefined class called ObjectOutputStream class.
ObjectOutputStream class contains the following constructor which takes an object of
FileOutputStream class.
For example:
ObjectOutputStream oos=new ObjectOutputStream (fos);
5. In order to write the entire object at a time to the file ObjectOutputStream contains the
following method:
For example:
oos.writeObject (eo);
6. Close the files which are opened in write mode.
For example:
oos.close ();
fos.close ();
Write a java program which will save the Serializable sub class object into a file?
Answer:
import ep.Emp;
import java.io.*;
class serp
{
public static void main (String [] args) throws Exception
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 12
{
Emp eo=new Emp ();
eo.setEmpno (100);
eo.setEname ("KVR");
eo.setSal (10000.00f);
FileOutputStream fos=new FileOutputStream ("employee");
ObjectOutputStream oos=new ObjectOutputStream (fos);
oos.writeObject (eo);
System.out.println ("EMPLOYEE OBJECT SAVED SUCCESSFULLY...");
oos.close ();
fos.close ();
}
};
Output:
EMPLOYEE OBJECT SAVED SUCCESSFULLY...
De-Serializable process: It is the process of retrieving the record from the file into main memory of
the computer.
Steps for DE-SERIALIZATION process:
1. Create an object of Serializable sub class.
For example:
emp eo1=new emp ();
2. Choose the file name and open it into read mode with the help of FileInputStream class.
For example:
FileInputStream fis=new FileInputStream (“employee”);
3. Since an object of FileInputStream cannot read the entire object at a time from the file.
Hence, it is recommended to create an object of ObjectInputStream class.
ObjectInputStream class contains the following constructor which takes object of
FileInputStream as a parameter.
For example:
ObjectInputStream ois=new ObjectInputStream (fis);
4. ObjectInputStream class contains the following method which will read the entire object at a
time where ever ObjectInputStream is pointing.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 13
For example:
Object obj=ois.readObject ();
5. An object of Object does not contain set of get methods and they are defined in its sub class
called emp. Hence, an object of Object must be type casted to Serializable sub class object.
For example:
eo1= (emp) obj;
6. Apply set of get methods to obtain the data from de-serialized object i.e., eo1.
For example:
System.out.println (“empno : ”+eo1.getEmpno ());
System.out.println (“empname : ”+eo1.getEname ());
System.out.println (“empsal : ”+eo1.getSal ());
7. Close the files which are opened in read mode or input mode.
For example:
ois.close ();
fis.close ();
Write a java program which will de-Serializable from the specified file?
Answer:
import ep.Emp;
import java.io.*;
class dserp
{
public static void main (String [] args) throws Exception
{
Emp eo1=new Emp ();
FileInputStream fis=new FileInputStream ("employee");
ObjectInputStream ois=new ObjectInputStream (fis);
Object obj=ois.readObject ();
eo1= (Emp) obj;
System.out.println ("EMP NO : "+eo1.getEmpno ());
System.out.println ("EMP NAME : "+eo1.getEname ());
System.out.println ("EMP SALARY : "+eo1.getSal ());
ois.close ();
fis.close ();
}
};
Output:
EMP NO : 100
EMP NAME : KVR
EMP SAL : 10000.0
Day - 8:
When we don’t want the variables to participate in serialization process, which type of
variables must be made it as transient i.e., transient variables will not participate in serialization
process.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 14
In general we have four types of serializations, they are:
1. Complete serialization:
It is one in which all the data members of the class will participate in serialization
process.
2. Selective serialization:
It is one in which selective data members of the class (non-transient variables) will
participate in serialization process.
3. Manual serialization:
It is one in which the derived class explicitly implements a predefined interface
called java.io.Serializable. The interface Serializable does not contain any abstract methods
and this type of interface is known as marked or tagged interface.
4. Automatic serialization:
It is one in which the user defined derived class extends sub class of Serializable
interface.
For example:
class Bank extends Emp
{
……………..;
……………..;
};
In real world application we cannot store the data permanently in the form of files. Since, a
file does not provide any security to prevent unauthorized modifications. Hence, it is recommended
to store the data permanently in the form of database.
JDBC:
In the initial days of database technology various database vendors has developed various
database products. Anybody who want to deal with any database the programmer must have
complete knowledge about the database which they are using i.e., in the initial days all the
databases are available with a specific library (native library) which was developed in ‘C’ language. In
the context the programmer must have complete knowledge about the native library of the
database which is a complex process.
In later stages all database vendors gathered and developed XOPEN/CLI (Call Level Interface)
software along with Microsoft which is known as ODBC (Open Database Connectivity).
ODBC is having a common API or library for various databases and it is also developed in ‘C’
language and it is a platform dependent.
In later stages SUN micro systems has developed a general specification called JDBC which
contains a common API for all databases with platform independent.
In order to deal with any database to represent the data permanently, we must use driver (a
driver is a software which acts as a middle layer between database and front end application i.e.,
java) of the specific database. In real world we have various drivers are available for various
database products.
Types of DRIVERS:
SUN micro systems has divided various database drivers of various database products into
four types, they are:
1. Type-1 (JDBC-ODBC bridge driver).
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 15
2. Type-2 (Native or partial java drivers).
3. Type-3 (Net protocol or intermediate database server access drivers) and
4. Type-4 (Thin drivers or pure drivers or all java drivers).
Steps for developing a JDBC program:
1. Loading the drivers.
2. Obtain the connection or specify the URL.
3. Pass the query.
4. Process the result which is obtained from database.
5. Close the connection.
Day - 9:
JDBC is the standard specification released by SUN micro systems to develop the
applications in database world. JDBC contains set of interfaces and these interfaces are implemented
by various database vendors and server vendors.
A driver is nothing but a java class which acts as a middle layer between java program and
database program. As on today all the drivers are developed by either database vendors or server
vendors.
For example:
class x implements ___
{
…………;
…………;
…………;
};
Here, x is driver and ___ is JDBC interface.
In database world, each and every database vendor has developed their drivers and released
to the market in the form of jar files.
TYPE-1 DRIVERS
These are developed by SUN micro systems. The name of the Type-1 driver is
JdbcOdbcDriver. The driver JdbcOdbcDriver is found in a package called sun.jdbc.odbc. Using this
driver we can develop only 2-tier applications (a java program and database). This type of driver is
purely implemented in ‘C’ language and this driver is platform dependent in nature.
Loading the drivers:
Loading the drivers is nothing but creating an object of appropriate Driver class. In order to
load the drivers we have two ways, they are:
1) Using Class.forName
For example:
Class.forName (Sun.jdbc.odbc.JdbcOdbcDriver);
Class.forName (oracle.jdbc.driver.OracleDriver);
2) Using DriverManager.registerDriver
DriverManager class contains the following method which will load the driver at
runtime.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 16
For example:
public static void registerDriver (java.sql.Driver);
Driver is an interface which is implemented by various database vendors and server
vendors. If the appropriate driver object is created that driver object will act as a middle
layer between program and database. If the driver is not found we get an exception called
java.sql.SQLException
For example:
DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver);
[for oracle driver is – classes111.jar]
Day - 10:
How to obtain the connection: After loading the drivers, it is required to obtain the connection
from the database.
Syntax or URL for obtaining connection:
Here, jdbc is the main protocol which takes java request and hand over into database
environment through Data Source Name. odbc is the sub protocol which takes the database result
and gives to java environment. Data Source Name is the configuration tool in the current working
machine through which the data is passing from java environment to database and database to java
environment.
In order to obtain the connection from the database, as a part of jdbc we have a predefined
class called java.sql.DriverManager which contains the following methods:
1. public static Connection getConnection (String URL);
2. public static Connection getConnection (String URL, String username, String password);
Method-1, we use to obtain the connection from those databases where there is no
username and password databases. Method-2 is used for those databases where there is username
and password.
For example:
Connection con1=DriverManager.getConnection (“jdbc : odbc : Access”);
Connection con2=DriverManager.getConnection (“jdbc : odbc : oracle”,”scott”,”tiger”);
Pass the query: A query is nothing but a request or question to the database.
Queries are of three types; they are static query, dynamic or pre-compiled query and stored
procedures.
STATIC QUERY: Static query is one in which the data is passed in the query itself.
For example:
1. select * from Student where marks>50;
2. insert into Student values (100, ‘abc’, 90.86);
In order to execute static queries we must obtain an object of java.sql.Statement interface.
In the interface java.sql.Connection we have the following method for obtaining an object of
Statement interface.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 17
For example:
Statement st=con1.createStatement ();
On database three categories of operations takes place, they are insertion, deletion and
updation. In order to perform these operations we must use the following method which is present
in Statement interface.
Here, String represents either static insertion or static deletion or static updation. The return
type int represents the status of the query. If the query is not successful it returns zero and if the
query is successful it returns non-zero.
Write a jdbc program which will insert a record in the Student database?
Answer:
import java.sql.*;
class InsertRec
{
public static void main (String [] args)
{
try
{
Driver d=new Sun.jdbc.odbc.JdbcOdbcDriver ();
DriverManager.registerDriver (d);
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
Statement st=con.createStatement ();
int i=st.executeUpdate ("insert into student values (10,'suman',60.87);");
System.out.println (i+" ROWS SELECTED...");
con.close ();
}
catch (Exception e)
{
System.out.println ("DRIVER CLASS NOT FOUND...");
}
}
};
Day - 11:
Processing the query result:
In order to execute the select statement or in order to retrieve the data from database we
must use the following method which is present in java.sql.Statement interface.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 18
Here, String represents a query which contains select statement. executeQuery returns an
object of ResultSet to hold the number of records returned by select statement. ResultSet is an
interface whose object contains all the records returned by a query and it will point to just before
the first record.
For example:
ResultSet rs=st.executeQuery (“select * from Student”);
The ResultSet object is pointing by default just before the first record, in order to bring first
record we must use the below given method. Method returns true when rs contains next record
otherwise it returns false.
public boolean next ();
In order to obtain the data of the record (collection of field values) we must use the
following method:
public String getString (int colno);
Whatever the data retrieving from the record that data will be treated as string data.
For example:
String s1=rs.getString (1);
String s1=rs.getString (2);
String s1=rs.getString (3);
Write a java program to retrieve the data from emp database?
Answer:
import java.sql.*;
class SelectData
{
public static void main (String [] args) throws Exception
{
DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver ());
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from dept");
while (rs.next ())
{
System.out.println (rs.getString (1)+" "+rs.getString (2)+" "+rs.getString (3));
}
con.close ();
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 19
}
};
ResultSet:
1. An object of ResultSet allows us to retrieve the data by default only in forward direction but
not in backward direction and random retrieval.
2. Whenever we get the database data in ResultSet object which will be temporarily
disconnected from the database.
3. ResultSet object does not allows us to perform any modifications on ResultSet object.
4. Hence, the ResultSet is by default non-scrollable disconnected ResultSet.
DYNAMIC or PRE-COMPILED QUERIES:
1. Dynamic queries are those for which the data is passed at runtime.
2. To execute dynamic queries we must obtain an object of PreparedStatement.
Differentiate between Statement and PreparedStatement?
Answer:
Statement PreparedStatement
1. This interface is used for executing static
queries.
1. This interface is used for executing
dynamic queries.
2. When we execute static queries with
respect to Statement object;
compilation, parsing and execution of
the query takes place each and every
time.
2. When we execute dynamic queries using
PreparedStatement object; compilation,
parsing and execution of the query takes
place first time and from second time
onwards only execution phase takes
place.
3. There is a possibility of loosing
performance of a jdbc program. Since,
compilation, parsing and execution
taking place each and every time.
3. We can get the performance of jdbc
program. Since, compilation and parsing
takes place only one time.
In order to obtain an object of PreparedStatement we must use the following method:
Here, String represents dynamic query.
For example:
PreparedStatement ps=con.prepareStatement (“select * from dept where deptno=?”);
Here, the ‘?’ is known as dynamic substitution operator or positional parameter. The
position of the positional parameters must always starts from left to right with the numbers 1,
2……n.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 20
In order to set the values to the positional parameters, we must use the following methods which
are present in prepared statement interface.
public void setByte (int, byte);
public void setShort (int, short);
public void setInt (int, int);
public void setLong (int, long);
public void setFloat (int, float);
public void setDouble (int, double);
public void setChar (int, char);
public void setString (int, string);
In general PreparedStatement interface contains the following generalized method to set the values
for positional parameters.
public void setXXX (int, XXX);
Here, int represents position number of the positional parameter. XXX represents value of
either fundamental data type or string or date.
For example:
ps.setInt (1, 10);
In order to execute the DCL statements (select) and DML statements (insert, delete and update) we
must use the following methods which are present in PreparedStatement interface.
public int executeUpdate (); Dynamic DML/DDL
public ResultSet executeQuery (); Dynamic DCL (select)
For example:
ResultSet rs=ps.executeQuery ();
Close connection
For example:
con.close ();
Day - 12:
Write a java program to insert a record in dept database by accepting the data from keyboard at
runtime using dynamic queries?
Answer:
import java.sql.*;
import java.io.*;
class InsertRecRun
{
public static void main (String [] args)
{
try
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ());
System.out.println ("DRIVERS LOADED...");
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 21
Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:
BudDinu","scott","tiger");
System.out.println ("CONNECTION OBTAINED...");
PreparedStatement ps=con.prepareStatement ("insert into dept values (?,?,?)");
DataInputStream dis=new DataInputStream (System.in);
System.out.println ("ENTER DEPARTMENT NUMBER : ");
String s1=dis.readLine ();
int dno=Integer.parseInt (s1);
System.out.println ("ENTER DEPARTMENT NAME : ");
String dname=dis.readLine ();
System.out.println ("ENTER LOCATION NAME : ");
String loc=dis.readLine ();
ps.setInt (1, dno);
ps.setString (2, dname);
ps.setString (3, loc);
int i=ps.executeUpdate ();
System.out.println (i+"ROW(s) INSERTED...");
con.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
}// main
};// InsertRecRun
Write a java program to retrieve the records from a specified database by accepting input from
keyboard?
Answer:
import java.sql.*;
import java.io.*;
class SelectDataRun
{
public static void main (String [] args)
{
try
{
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
PreparedStatement ps=con.prepareStatement ("select * from dept where deptno");
DataInputStream dis=new DataInputStream (System.in);
System.out.println ("ENTER DEPARTMENT NUMBER : ");
String s1=dis.readLine ();
int dno=Integer.parseInt (s1);
ps.setInt (1, dno);
ResultSet rs=ps.executeQuery ();
while (rs.next ())
{
System.out.print (rs.getString (1)+" "+rs.getString (2)+" "+rs.getString (3));
}
con.close ();
}
catch (Exception e)
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 22
{
e.printStackTrace ();
}
}// main
};// SelectDataRun
TYPE – 4 DRIVERS
In order to avoid the disadvantages of Type-1 drivers, we have to deal with Type-4 drivers.
Disadvantages of Type-1:
1. Since, it is developed in ‘C’ language; this type of driver is treated as platform dependent.
2. These are a waste of memory space. Since, we are creating a DSN (Data Source Name) for
each and every database connection and it leads to less performance.
3. We are unable to develop 3-tier applications.
Advantages of Type-4:
1. This driver gives affective performance for every jdbc application. Since, there is no DSN.
2. Since, this driver is developed in java by database vendors, internally JVM need not to
convert platform dependent to platform independent.
The only disadvantage of Type-4 is we are unable to develop 3-tier applications.
Type-4 drivers are supplied by Oracle Corporation by developing into java language.
OracleDriver is the name of Type-4 driver which is released by Oracle Corporation in the form of
classes111.jar
When we want to make use of Type-4 driver as a part of a java program, we must first set classpath
for oracle driver by using the following:
set CLASSPATH=C:oracleora92jdbclibclasses111.jar;.;
For example:
Class.forName (“oracle.jdbc.driver.OracleDriver”);
In order to obtain the connection from oracle database we must follow the following syntax:
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 23
For example:
Connection con=DriverManager.getConnection (“jdbc : oracle : thin :@ localhost
: 1521 : AshaKrishna”, “scott”, “tiger”)
In order to obtain port number and service ID of oracle database we must look for tnsnames.ora
which is found in C:oracleora92networkadmin
Day - 13:
STORED PROCEDURES:
In general, we are performing the database operations by using ordinary SQL statements.
When we want to execute n number of SQL statements through java program, the java environment
is executing those queries one at a time which leads to lack of performance to a jdbc application.
In order to improve the performance of jdbc application, it is recommended to write all n
number of SQL statements in a single program (in case of oracle it is called PL/SQL program) and that
program will execute at a time irrespective of number of SQL statements which improves the
performance of a java application.
A program which contains n number of SQL statements and residing a database
environment is known as stored procedure.
Stored procedures are divided into two types, they are procedure and function.
• A procedure is one which contains block of statements which will return either zero or more
than one value.
Syntax for creating a procedure:
create or replace procedure <procedure name> (parameters if any)
as/is
local variables;
begin
block of statements;
end;
/
In order to call a procedure from java environment we must call on the name of procedure.
For example:
create or replace procedure proc1
as
i out number;
a out number;
b number;
c number;
x in out number;
begin
i:=40+42;
b:=10;
c:=20;
a:=b+c;
x:=x+b+c;
end;
/
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 24
Create an oracle procedure which takes two input numbers and it must return sum of two numbers,
multiplication and subtraction?
Answer:
create or replace procedure proc2 (a in number, b number, n out number, n2 out
number, n3 out number)
as
begin
n1:=a+b;
n2:=a*b;
n3:=a-b;
end;
/
• A function is one which contains n number of block of statements to perform some
operation and it returns a single value only.
Syntax for creating a function:
create or replace function (a in number, b in number) return <return type>
as
n1 out number;
begin
n1:=a+b;
return (n1);
end;
/
In order to execute the stored procedures from jdbc we must follow the following steps:
1. Create an object of CallableStatement by using the following method:
Here, String represents a call for calling a stored procedure from database environment.
2. Prepare a call either for a function or for a procedure which is residing in database.
Syntax for calling a function:
“{? = call <name of the function> (?,?,?….)}”
For example:
CallableStatement cs=con.prepareCall (“{? = call fun1 (?,?)}”);
The positional parameters numbering will always from left to right starting from 1. In the
above example the positional parameter-1 represents out parameter and the positional parameter-2
and parameter-3 represents in parameters.
Syntax for calling a procedure:
“{call <name of the procedure> (?,?,?….)}”
For example:
CallableStatement cs=con.prepareCall (“{call fun1 (?,?,?,?,?)}”);
3. Specify which input parameters are by using the following generalized method:
Public void setXXX (int, XXX);
For example:
cs.setInt (2, 10);
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 25
cs.setInt (3, 20);
4. Specify which output parameters are by using the following generalized method:
In jdbc we have a predefined class called java.sql.Types which contains various data types of
jdbc which are equivalent to database data types.
Java Jdbc Database
int INTEGER number
String VARCHAR varchar2
Short TINY INTEGER number
Byte SMALL INTEGER number
All the data members which are available in Types class are belongs to public static final
data members.
For example:
cs.registerOutParameter (1, Types.INTEGER);
5. Execute the stored procedure by using the following method:
For example:
cs.execute ();
6. Get the values of out parameters by using the following method:
public XXX getXXX (int);
Here, int represents position of out parameter. XXX represents fundamental data type or
string or date.
For example:
int x=cs.getInt (1);
System.out.println (x);
Day - 14:
Write a java program which illustrates the concept of function?
Answer:
StuFun:
create or replace function StuFun
(a in number, b in number, n1 out number) return number
as
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 26
n2 number;
begin
n1:=a*b;
n2:=a+b;
return (n2);
end;
/
FunConcept.java:
import java.sql.*;
import java.io.*;
class FunConcept
{
public static void main (String [] args)
{
try
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ());
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:
BudDinu","scott","tiger");
System.out.println ("CONNECTION OBTAINED...");
DataInputStream dis=new DataInputStream (System.in);
System.out.println ("ENTER FIRST NUMBER : ");
String s1=dis.readLine ();
System.out.println ("ENTER SECOND NUMBER : ");
String s2=dis.readLine ();
int n1=Integer.parseInt (s1);
int n2=Integer.parseInt (s2);
CallableStatement cs=con.prepareCall ("{?=call ArthFun (?,?,?)}");
cs.setInt (2, n1);
cs.setInt (3, n2);
cs.registerOutParameter (1, Types.INTEGER);
cs.registerOutParameter (4, Types.INTEGER);
cs.execute ();
int res=cs.getInt (1);
int res1=cs.getInt (4);
System.out.println ("SUM OF THE NUMBERS : "+res);
System.out.println ("MULTIPLICATION OF THE NUMBERS : "+res1);
}
catch (Exception e)
{
e.printStackTrace ();
}
}// main
}// FunConcept
Write a java program which illustrates the concept of procedure?
Answer:
StuPro:
create or replace procedure StuPro
(no in number, name in varchar2, loc1 out varchar2)
as
begin
select dname, loc into name, loc1 from dept
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 27
where deptno=no;
insert int abc values (no, name, loc1);
end;
/
ProConcept.java:
import java.sql.*;
import java.io.*;
class ProConcept
{
public static void main (String [] args)
{
try
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ());
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:
BudDinu","scott","tiger");
DataInputStream dis=new DataInputStream (System.in);
System.out.println ("ENTER DEPARTMENT NUMBER : ");
String s1=dis.readLine ();
int n1=Integer.parseInt (s1);
CallableStatement cs=con.prepareCall ("{call StuPro (?,?,?)}");
cs.setInt (1,n1);
cs.registerOutParameter (2, Types.VARCHAR);
cs.registerOutParameter (3, Types.VARCHAR);
cs.execute ();
String res=cs.getString (2);
String res1=cs.getString (3);
System.out.println ("DEPARTMENT NAME : "+res);
System.out.println ("DEPARTMENT LOCATION : "+res1);
}
catch (Exception e)
{
System.out.println (e);
}
}// main
}// ProConcept
Retrieving the data from CONVENTIONAL DATABASE (MS-Excel):
In real world applications, there is a possibility of retrieving the data from conventional data
bases like ms-excel.
Steps for retrieving data from ms-excel:
1. Create an excel sheet, enter the column names along with data, rename the sheet1 as user
defined name which is treated as table name.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 28
2. Save the excel sheet in a current working directory.
For example:
D:advancedjdbcstbook.xls
3. Create DSN for excel
4. Use xldsn while obtaining a connection from excel.
For example:
Connection con=DriverManager.getConnetion (“jdbc : odbc : xldsn”);
NOTE: In order to refer excel sheet name as a database sheet name we should use the format
[<sheet name> $]
Write a jdbc program to retrieve the data from excel?
Answer:
import java.sql.*;
class XSelect
{
public static void main (String [] args)
{
try
{
DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver ());
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:xldsn");
System.out.println ("CONNECTION ESTABLISHED...");
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from [student$]");
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 29
while (rs.next ())
{
System.out.println (rs.getString (1)+" "+rs.getString (2)+" "+rs.getString (3));
}
con.close ();
}
catch (SQLException sqle)
{
sqle.printStackTrace ();
}
}// main
};// XSelect
Day - 15:
Metadata:
Data about data is known as metadata. Metadata can be obtained at two levels, they are
user database details and universal database details.
Obtaining user database details:
In order to obtain user database details we must follow the following procedure:
1. Obtain an object of ResultSetMetaData by using the following method which is present in
ResultSet.
For example:
ResultSetMetaData rsmd=rs.getMetaData ();
2. In general every user database contains number of columns, name of the columns and type
of columns. In order to obtain the above information we must use the following methods
which are present in ResultSetMetaData interface.
public int getColumnCount ();
public String getColumnName ();
public String getColumnLabel ();
public String getColumnType ();
Obtaining universal database details:
When we get a connection from the database we can come to know which database we are using.
To obtain information about universal database we must use the following steps:
1. Obtain an object of DatabaseMetaData by calling the following method which is present in
Connection interface.
For example:
DatabaseMetaData dmd=con.getMetaData ();
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 30
2. In general every universal database contains database name, database version, driver name,
driver version, driver major version and driver minor version. To obtain these information,
DatabaseMetaData interface contains the following methods:
public String getDatabaseProductName ();
public String getDatabaseProductVersion ();
public String getDriverName ();
public String getDriverVersion ();
public String getDriverMajorVersion ();
public String getDriverMinorVersion ();
Write a java program which illustrates the concept of DatabaseMetaData and ResultSetMetaData?
Answer:
import java.sql.*;
class MetaData
{
public static void main (String [] args)
{
try
{
DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver ());
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc : odbc : oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
// UNIVERSAL DATABASE DETAILS
DatabaseMetaData dmd=con.getMetaData ();
System.out.println ("DATABASE NAME : "+dmd.getDatabaseProductName ());
System.out.println ("DATABASE VERSION : "+dmd.getDatabaseProductVersion ());
System.out.println ("NAME OF THE DRIVER : "+dmd.getDriverName ());
System.out.println ("VERSION OF THE DRIVER : "+dmd.getDriverVersion ());
System.out.println ("MAJOR VERSION OF DRIVER : "+dmd.getDriverMajorVersion ());
System.out.println ("MINOR VERSION OF DRIVER : "+dmd.getDriverMinorVersion ());
// USER DATABASE DETAILS
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from dept");
ResultSetMetaData rsmd=rs.getMetaData ();
System.out.println ("NUMBER OF COLUMNS : "+rsmd.getColumnCount ());
for (int i=1; i<=rsmd.getColumnCount (); i++)
{
System.out.println ("NAME OF THE COLUMN : "+rsmd.getColumnName (i));
System.out.println ("TYPE OF THE COLUMN : "+rsmd.getColumnType (i));
}
con.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
}// main
};// MetaData
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 31
Write a java program which points the data of a table along with its column names?
Answer:
import java.sql.*;
class Table
{
public static void main (String [] args)
{
try
{
DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver ());
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from dept");
ResultSetMetaData rsmd=rs.getMetaData ();
System.out.println ("==================================================");
// PRINTING COLUMN NAME
for (int i=1; i<=rsmd.getColumnCount (); i++)
{
System.out.print (rsmd.getColumnName (i)+" ");
}
System.out.println ("");
System.out.println ("==================================================");
// PRINTING THE DATA OF THE TABLE
while (rs.next ())
{
for (int j=1; j<=rsmd.getColumnCount (); j++)
{
System.out.print (rs.getString (j)+" ");
}
System.out.println ("");
}
con.close ();
}
catch (SQLException sqle)
{
sqle.printStackTrace ();
}
}// main
};// Table
Day - 16:
Developing flexible jdbc applications:
When we write any jdbc application, we use to specify the specific details regarding driver
names, URL, which database we are using and table names. When we want to change the jdbc
application for some other details regarding driver name, URL, etc., we must change into java
program and we need to compile which leads to higher maintenance activities.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 32
In order to avoid recompiling a jdbc application we must develop a flexible jdbc application
with the help of resource bundle file or properties file.
A resource bundle file or properties file is one which contains the data in the form of (key,
value) pair.
For example:
<file name>.<rbf/prop>
NOTE: After creating resource bundle file that file must be stored into current working directory.
How to read the data from RESOURCE BUNDLE FILE:
1. In order to read the data from resource bundle file, open the resource bundle file in read
mode with the help of FileInputStream class.
For example:
FileInputStream fis=new FileInputStream (“db.prop”);
2. Since files does not support to read the data separately in the form of (key, value). Hence, it
is recommended to get the data of the file we must create an object of a predefined class
called java.util.Properties
For example:
Properties p=new Properties ();
3. In order to link ‘fis’ and ‘p’ objects we must use the following method:
For example:
p.load (fis);
4. Obtain the property value by passing property name by using the following method:
public Object get (String);
public Object getProperty (String);
Here, String represents property name or key name.
For example:
String dname= (String) p.get (“Dname”);
String url= (String) p.get (“URL”);
String username= (String) p.get (“Uname”);
String password= (String) p.get (“Pwd”);
String table= (String) p.get (“Tablename”);
Here, Dname, URL, Uname, Pwd and Tablename are the property names present in resource
bundle file. dname, url, username, password and table are the property values present in resource
bundle file.
Write a java program which illustrates the concept of resource bundle file or how to develop a
flexible jdbc application along with its metadata?
Answer:
rbfdb.prop:
Dname=oracle.jdbc.driver.OracleDriver
URL=jdbc:oracle:thin:@127.0.0.1:1521:oradsn
Uname=scott
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 33
Pwd=tiger
Tablename=student
RBFConcept:
import java.sql.*;
import java.io.*;
import java.util.*;
class RBFConcept
{
public static void main (String [] args)
{
try
{
FileInputStream fis=new FileInputStream ("rbfdb.prop");
Properties p=new Properties ();
p.load (fis);
String dname= (String) p.get ("Dname");
String url= (String) p.get ("URL");
String username= (String) p.get ("Uname");
String password= (String) p.get ("Pwd");
String tablename= (String) p.get ("Tablename");
// loading drivers and obtaining connection
Class.forName (dname);
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection (url, username, password);
System.out.println ("CONNECTION CREATED...");
// executing query
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from"+tablename);
ResultSetMetaData rsmd=rs.getMetaData ();
// printing column names
System.out.println ("=================================");
for (int i=1; i<=rsmd.getColumnCount (); i++)
{
System.out.print (rsmd.getColumnName (i)+" ");
}
System.out.println ("");
System.out.println ("=================================");
// printing the data
while (rs.next ())
{
for (int j=1; j<=rsmd.getColumnCount (); j++)
{
System.out.print (rs.getString (j)+" ");
}
}
con.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 34
}// main
};// RSFConcept
Scrollable ResultSet’s and Updatable ResultSet’s:
Whenever we create an object of ResultSet by default, it allows us to retrieve in forward
direction only and we cannot perform any modifications on ResultSet object. Therefore, by default
the ResultSet object is non-scrollable and non-updatable ResultSet.
Day - 17:
Scrollable ResultSet:
A scrollable ResultSet is one which allows us to retrieve the data in forward direction as well
as backward direction but no updations are allowed. In order to make the non-scrollable ResultSet as
scrollable ResultSet as scrollable ResultSet we must use the following createStatement which is
present in Connection interface.
Type represents type of scrollability and Mode represents either read only or updatable. The
value of Type and value of Mode are present in ResultSet interface as constant data members and
they are:
int Type
TYPE_FORWARD_ONLY 1
TYPE_SCROLL_INSENSITIVE 2
int Mode
CONCUR_READ_ONLY 3
For example:
Statement st=con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs=st.executeQuery (“select * from student”);
Whenever we create a ResultSet object, by default, constant-1 as a Type and constant-2 as a
Mode will be assigned.
The following methods which are available in ResultSet interface which allows us to retrieve the data
either in forward direction or in backward direction or in random retrieval:
public boolean next (); 1
public void beforeFirst (); 2
public boolean isFirst (); 3
public void first (); 4
public boolean isBeforeFirst (); 5
public boolean previous (); 6
public void afterLast (); 7
public boolean isLast (); 8
public void last (); 9
public boolean isAfterLast (); 10
public void absolute (int); 11
public void relative (int); 12
• Method-1 returns true when rs contains next record otherwise false.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 35
• Method-2 is used for making the ResultSet object to point to just before the first record (it is
by default).
• Method-3 returns true when rs is pointing to first record otherwise false.
• Method-4 is used to point the ResultSet object to first record.
• Method-5 returns true when rs pointing to before first record otherwise false.
• Method-6 returns true when rs contains previous record otherwise false.
• Method-7 is used for making the ResultSet object to point to just after the last record.
• Method-8 returns true when rs is pointing to last record otherwise false.
• Method-9 is used to point the ResultSet object to last record.
• Method-10 returns true when rs is pointing after last record otherwise false.
• Method-11 is used for moving the ResultSet object to a particular record either in forward
direction or in backward direction with respect to first record and last record respectively. If
int value is positive, rs move in forward direction to that with respect to first record. If int
value is negative, rs move in backward direction to that with respect to last record.
• Method-12 is used for moving rs to that record either in forward direction or in backward
direction with respect to current record.
Write a java program which illustrates the concept of scrollable ResultSet?
Answer:
import java.sql.*;
class ScrollResultSet
{
public static void main (String [] args)
{
try
{
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
Statement st=con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.
CONCUR_READ_ONLY);
ResultSet rs=st.executeQuery ("select * from emp");
System.out.println ("RECORDS IN THE TABLE...");
while (rs.next ())
{
System.out.println (rs.getInt (1)+" "+rs.getString (2));
}
rs.first ();
System.out.println ("FIRST RECORD...");
System.out.println (rs.getInt (1)+" "+rs.getString (2));
rs.absolute (3);
System.out.println ("THIRD RECORD...");
System.out.println (rs.getInt (1)+" "+rs.getString (2));
rs.last ();
System.out.println ("LAST RECORD...");
System.out.println (rs.getInt (1)+" "+rs.getString (2));
rs.previous ();
rs.relative (-1);
System.out.println ("FIRST RECORD...");
System.out.println (rs.getInt (1)+" "+rs.getString (2));
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 36
con.close ();
}
catch (Exception e)
{
System.out.println (e);
}
}// main
};// ScrollResultSet
Day - 18:
Updatable ResultSet:
Whenever we create a ResultSet object which never allows us to update the database
through ResultSet object and it allows retrieving the data only in forward direction. Such type of
ResultSet is known as non-updatable and non-scrollable ResultSet.
In order to make the ResultSet object as updatable and scrollable we must use the following
constants which are present in ResultSet interface.
int Type
TYPE_SCROLL_SENSITIVE
int Mode
CONCUR_UPDATABLE
The above two constants must be specified while we are creating Statement object by using
the following method:
For example:
Statement st=con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
On ResultSet we can perform the following three operations, they are inserting a record,
deleting a record and updating a record.
Steps for INSERTING a record through ResultSet object:
1. Decide at which position we are inserting a record by calling absolute method.
For example:
rs.absolute (3);
2. Since we are inserting a record we must use the following method to make the ResultSet
object to hold the record.
For example:
rs.moveToInsertRow ();
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 37
3. Update all columns of the database or provide the values to all columns of database by using
the following generalized method which is present in ResultSet interface.
For example:
rs.updateInt (1, 5);
rs.updateString (2, “abc”);
rs.updateInt (3, 80);
4. Upto step-3 the data is inserted in ResultSet object and whose data must be inserted in the
database permanently by calling the following method:
It throws an exception called SQLException.
For example:
rs.insertRow ();
Steps for DELETING a record through ResultSet object:
1. Decide which record you want to delete.
For example:
rs.absolute (3); // rs pointing to 3rd
record & marked for deletion
2. To delete the record permanently from the database we must call the following method
which is present in ResultSet interface.
For example:
rs.deleteRow ();
Steps for UPDATING a record through ResultSet object:
1. Decide which record to update.
For example:
rs.absolute (2);
2. Decide which columns to be updated.
For example:
rs.updateString (2, “pqr”);
rs.updateInt (3, 91);
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 38
3. Using step-2 we can modify the content of ResultSet object and the content of ResultSet
object must be updated to the database permanently by calling the following method which
is present in ResultSet interface.
For example:
rs.updateRow ();
Write a java program which illustrates the concept of updatable ResultSet?
Answer:
import java.sql.*;
class UpdateResultSet
{
public static void main (String [] args)
{
try
{
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
Statement st=con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.
CONCUR_UPDATABLE);
ResultSet rs=st.executeQuery ("select * from emp1");
rs.next ();
rs.updateInt (2,8000);
rs.updateRow ();
System.out.println ("1 ROW UPDATED...");
rs.moveToInsertRow ();
rs.updateInt (1, 104);
rs.updateInt (2, 2000);
rs.insertRow ();
System.out.println ("1 ROW INSERTED...");
rs.absolute (2);
rs.deleteRow ();
System.out.println ("1 ROW DELETED...");
con.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
}// main
};// UpdateResultSet
NOTE:
The scrollability and updatability of a ResultSet depends on the development of the driver of
the driver vendors. OracleDriver and JdbcOdbcDriver will support the concept of scrollability and
updatability of a ResultSet but there may be same drivers which are available in the industry which
are not supporting the concept of scrollability and updatability.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 39
BATCH PROCESSING
In traditional jdbc programming, to perform any transaction (insert, update and delete) we
must send a separate request to database. If there is ‘n’ number of transactions then we must make
‘n’ number of request to the database and finally it leads to poor performance.
Disadvantages of NON-BATCH PROCESSING applications:
1. There is a possibility of leading the database result in inconsistent in the case of interrelated
transactions.
2. Number of Network Round Trips or to and fro calls are more between frontend and backend
application.
To avoid the above disadvantages we must use batch processing.
Batch processing is the process of grouping ‘n’ number of interrelated transactions in a
single unit and processing at a same time.
Day - 19:
Advantages of BATCH PROCESSING:
1. Batch processing always leads consistency of the database.
2. Number of network round trips or to and fro calls will be reduced.
Steps for developing BATCH PROCESSING application:
1. Every batch processing application must contain only DML (insert, delete and update)
statements.
2. Set the auto commit as false. Since, in jdbc environment by default auto commit is true. In
order to make auto commit as false we must use the following method:
For example:
con.setAutoCommit (false);
3. Prepare set of SQL DML statements and add to batch.
For example:
st.addBatch (“insert into dept values (10,”abc”,”hyd”)”);
4. Execute batch of DML statements by using the following method:
For example:
int res []=st.executeBatch ();
This method returns individual values of DML statements.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 40
5. After completion of batch of statements, commit the database by using the following
method:
For example:
con.commit ();
6. If a single batch statement is not executing then we must rollback the database if required to
its original state by using the following method:
For example:
con.rollback ();
Write a java program which illustrates the concept of Batch processing?
Answer:
import java.sql.*;
class BatchProConcept
{
public static void main (String [] args) throws Exception
{
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
con.setAutoCommit (false);
Statement st=con.createStatement ();
st.addBatch ("insert into student values (3, 'j2ee')");
st.addBatch ("delete from student where sno=1");
st.addBatch ("update student set sname='java' where sno=2");
int res []=st.executeBatch ();
for (int i=0; i<res.length; i++)
{
System.out.println ("NUMBER OF ROWS EFFECTED : "+res [i]);
}
con.commit ();
con.rollback ();
con.close ();
}// main
};// BatchProConcept
With batch processing we can obtain effective performance to the jdbc applications by
executing group of SQL DML statements.
Write a java program to create a table through frontend application?
Answer:
import java.sql.*;
class CreateTable
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 41
{
public static void main (String [] args)
{
try
{
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger");
System.out.println ("CONNECTION ESTABLISHED...");
Statement st=con.createStatement ();
int i=st.executeUpdate ("create table kalyan (eno number (4), ename varchar2 (15))");
System.out.println ("TABLE CREATED...");
con.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
}// main
};// CreateTable
Dealing with DATE
• In order to deal with java date or frontend application date we should use a class called
java.util.Date
• In order to deal with database date or backend application date we should use a class called
java.sql.Date
• java.sql.Date is the subclass of java.util.Date
Converting java.util.Date into java.sql.Date:
When we are dealing with frontend application we must always take an object of
java.util.Date for representing date and time information but when we are dealing with database
date’s we must take an object of java.sql.Date
In order to convert java.util.Date into java.sql.Date we have two ways:
First way:
Read the date in string format
For example:
System.out.println (“ENTER THE DATE IN DD-MM-YYYY”);
String d1=dis.readLine ();
To convert string date into java.sql.Date we have the following method:
For example:
java.sql.Date sd=java.sql.Date.valueOf (d1);
Second way:
In order to convert string date into java.util.Date we must use the following class:
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 42
For example:
SimpleDateFormat sdf=new SimpleDateFormat (“DD-MM-YYYY”);
java.util.Date ud=sdf.parse (d1);
To convert java.util.Date into java.sql.Date we must use the following statement:
For example:
java.sql.Date sd=new java.util.Date (ud.getTime ());
Day - 20:
SERVLETS
Any company want to develop the website that can be developed in two ways, they are
static website and dynamic website.
• A static website is one where there is no interaction from the end user. To develop static
website we can use the markup languages like HTML, DHMTL, XML, JavaScript etc.
• A dynamic website is one in which there exist end user interaction. To develop dynamic
websites, in industry we have lot of technologies such as CGI (Common Gateway Interface),
java, dot net, etc.
In the recent years SUN micro systems has developed a technology called Servlets to
develop the dynamic websites and also for developing distributed applications.
A distributed application is one which always runs in the context of browser or www. The
result of distributed application is always sharable across the globe. To develop distributed
application one must follow the following:
Client-Server architecture:
• 2-tier architecture (Client program, Database program).
• 3-tier or MVC (Model [Database] View [JSP] Controller [Servlets]) architecture (Client
program, Server program, Database program).
• n-tier architecture (Client program, Firewall program, Server program, Database program).
To exchange the data between client and server we use a protocol caller http which is a part
of TCP/IP.
• A client is the program which always makes a request to get the service from server.
• A server is the program which always receives the request, process the request and gives
response to ‘n’ number of clients concurrently.
A server is the third party software developed by third party vendors according to SUN micro
systems specification. All servers in the industry are developed in java language only. The basic
purpose of using server is that to get concurrent access to a server side program.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 43
According to industry scenario, we have two types of servers; they are web server and
application server.
WEB SERVER
1. A web server is one which always
supports http protocol only.
2. Web server does not contain enough
security to prevent unauthorized
users.
3. Web server is not able to provide
enough services to develop effective
server side program.
4. For examples Tomcat server, web
logic server, etc.
APPLICATION SERVER
1. Any protocol can be supported.
2. An application server always provides
100% security to the server side
program.
3. An application server provides effective
services to develop server side program.
4. For examples web logic server, web
sphere server, pramathi server, etc.
NOTE: Web logic server acts as both web server and as well as application server.
In the initial days of server side programming there is a concept called CGI and this was
implemented in the languages called C and PERL. Because of this approach CGI has the following
disadvantages.
1. Platform dependency.
2. Not enough security is provided.
3. Having lack of performance. Since, for each and every request a new and separate process is
creating (for example, if we make hundreds of requests, in the server side hundreds of new
and separate processes will be created)
To avoid the above problems SUN micro system has released a technology called Servlets.
A servlet is a simple platform independent, architectural neutral server independent java
program which extends the functionality of either web server or application server by running in the
context of www.
Advantages of SERVLETS over CGI:
1. Servlets are always platform independent.
2. Servlets provides 100% security.
3. Irrespective of number of requests, a single process will be created at server side. Hence,
Servlets are known as single instance multiple thread technology.
Day - 21:
Servlets is the standard specification released by SUN micro systems and it is implemented
by various server vendors such as BEA corporation (Web logic server), Apache Jakarta (Tomcat
server).
In order to run any servlet one must have either application server or web server. In order to
deal with servlet programming we must import the following packages:
javax.servlet.*;
javax.servlet.http.*;
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 44
Servlet Hierarchy:
• In the above hierarchy chart Servlet is an interface which contains three life cycle methods
without definition.
• GenericServlet is an abstract class which implements Servlet interface for defining life cycle
methods i.e., life cycle methods are defined in GenericServlet with null body.
• Using GenericServlet class we can develop protocol independent applications.
• HttpServlet is also an abstract class which extends GenericServlet and by using this class we
can develop protocol dependent applications.
• To develop our own servlet we must choose a class that must extends either GenericServlet
or HttpServlet.
LIFE CYCLE METHODS of servlets:
In servlets we have three life cycle methods, they are
public void init ();
public void service (ServletRequest req, ServletResponse res);
public void destroy ();
public void init ():
Whenever client makes a request to a servlet, the server will receive the request and it
automatically calls init () method i.e., init () method will be called only one time by the server
whenever we make first request.
In this method, we write the block of statements which will perform one time operations,
such as, opening the file, database connection, initialization of parameters, etc.
public void service (ServletRequest, ServletResponse):
After calling init () method, service () method will be called when we make first request from
second request to further subsequent requests, server will call only service method. Therefore,
service () method will be called each and every time as and when we make a request.
In service () method we write the block of statements which will perform repeated
operations such as retrieving data from database, retrieving data from file, modifications of
parameters data, etc. Hence, in service () method we always write business logic.
Whenever control comes to service () method the server will create two objects of
ServletRequest and ServletResponse interfaces.
Object of ServletRequest contains the data which is passed by client. After processing client
data, the resultant data must be kept in an object of ServletResponse.
An object of ServletRequest and ServletResponse must be used always within the scope of
service () method only i.e., we cannot use in init () method and destroy () method.
Once the service () method is completed an object of ServletRequest and an object of
ServletResponse will be destroyed.
public void destroy ():
The destroy () method will be called by the server in two situations; they are when the
server is closed and when the servlet is removed from server context. In this method we write the
block of statements which are obtained in init () method.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 45
NOTE: Life cycle methods are those which will be called by the server at various times to perform
various operations.
Write a servlet which displays a message “I LOVE MY MOM”?
Answer:
import javax.servlet.*;
import java.io.*;
public class First extends GenericServlet
{
public First ()
{
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
}
public void init ()
{
System.out.println ("I AM FROM init METHOD...");
}
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
{
System.out.println ("I LOVE MY MOM...");
System.out.println ("I AM FROM service METHOD...");
}
public void destroy ()
{
System.out.println ("I AM FROM destroy METHOD...");
}
};
Day - 22:
web.xml:
1. Whenever client makes a request to a servlet that request is received by server and server
goes to a predefined file called web.xml for the details about a servlet.
2. web.xml file always gives the details of the servlets which are available in the server.
3. If the server is not able to find the requested servlet by the client then server generates an
error (resource not found) [A resource is a program which resides in server].
4. If the requested servlet is available in web.xml then server will go to the servlet, executes
the servlet and gives response back to client.
Every web.xml will contain the following entries:
<web-app>
<servlet>
<servlet-name>Asha</servlet-name>
<servlet-class>First</servlet-class>
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 46
</servlet>
<servlet-mapping>
< servlet-name>Asha</servlet-name>
<url-pattern>Krishna</url-pattern>
</servlet-mapping>
</web-app>
• While server is executing web.xml control goes to <url-pattern> of <servlet-mapping>
tag. If the requested url and <url-name> web.xml is same then control goes to <servlet-
class> tag of <servlet> and takes the <servlet-name> and executes.
• If the <url-pattern> is not matching, server generates an error.
How to execute the servlets:
In order to execute a servlet we must follow the following directory structure:
Day - 23:
Steps for DEVELOPING a servlet:
1. Import javax.servlet.*, javax.servlet.http.* and other packages if required.
2. Choose user defined class.
3. Whichever class we have chosen in step-2 must extend either GenericServlet or HttpServlet.
4. Override the life cycle methods if required.
FLOW OF EXECUTION in a servlet:
1. Client makes a request. The general form of a request is http://(IP address or DNS
[Domain Naming Service] name of the machine where server is installed) :
(port number of the server) / (Document root) : (Resource name).
For example:
http://localhost:7001/DateSer/suman
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 47
2. Server receives the request.
3. Server will scan web.xml (contains declarative details) if the requested resource is not
available in web.xml server generates an error called resource not available otherwise server
goes to a servlet.
4. Server will call the servlet for executing.
5. Servlet will execute in the context of server.
6. While server is executing a servlet, server loads an object of servlet class only once (by
calling default constructor).
7. After loading the servlet, the servlet will call init () method only once to perform one time
operations.
8. After completion of init () method, service () method will be called each and every time. As
long as we make number of requests only service () method will be called to provide
business logic.
9. Servlet will call destroy () method either in the case of servlet is removed or in the case of
server is closed.
HOW TO EXECUTE a servlet:
1. Prepare a directory structure.
2. Write a servlet program save it into either document root or document rootSRC.
3. Compile a servlet by setting a classpath.
For Tomcat:
Set classpath=
4. Copy *.class file into document root/WEB-INF/classes folder and write web.xml file.
5. Start the server and copy document root into:
6. Open the browser and pass a request or url
Write a servlet which displays current system date and time?
Answer:
Servlet program: (Since, it’s a package to compile use javac –d . DateServ.java)
package ds;
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class DateServ extends GenericServlet
{
public DateServ ()
{
System.out.println ("SERVLET LOADED...");
}
public void init ()
{
System.out.println ("I AM FROM init METHOD...");
}
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
Date d=new Date ();
String s=d.toString ();
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 48
pw.println ("<h1> WELCOME TO SERVLETS <h1>");
pw.println ("<h2> CURRENT DATE & TIME IS : "+s+"<h2>");
}
public void destroy ()
{
System.out.println ("I AM FROM destroy METHOD...");
}
};
web.xml:
<web-app>
<servlet>
<servlet-name>kalyan</servlet-name>
<servlet-class>ds.DateServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>kalyan</servlet-name>
<url-pattern>/suman</url-pattern>
</servlet-mapping>
</web-app>
Day - 24:
HttpServlet:
• HttpServlet is the sub-class of GenericServlet.
• HttpServlet contains all the life cycle methods of GenericServlet and the service () method of
GenericServlet is further divided into the following two methods, they are
public void doGet (HttpServletRequest, HttpServletResponse) throws ServletException, IOException
public void doPost (HttpServletRequest, HttpServletResponse) throws ServletException, IOException
• Whenever client makes a request, the servlet container (server) will call service () method,
the service () method depends on type of the method used by the client application.
• If client method is get then service () method will call doGet () method and doGet () method
internally creates the objects of HttpServletRequest and HttpServletResponse. Once doGet ()
method is completed its execution, the above two objects will be destroyed.
LIMITATIONS of get method:
1. Whatever data we sent from client by using get method, the client data will be populated or
appended as a part of URL.
For example:
http://localhost:7001/servlet/DDservlet?uname=scott&pwd=tiger
2. Large amount of data cannot be transmitted from client side to server side.
• When we use post method to send client data, that data will be send as a part of method
body and internally the service () method will called doPost () method by creating the
objects of HttpServletRequest and HttpServletResponse.
ADVANTAGES of post method:
1. Security is achieved for client data.
2. We can send large amount of data from client to server.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 49
• HttpServletRequest extends ServletRequest and HttpServletResponse extends
ServletResponse.
• HttpServlet, HttpServletRequest and HttpServletResponse belong to a package called
javax.servlet.http.*
• The request which we make from the client side that requests are known as http requests
where as the responses which are given by a servlet are known as http responses.
NOTE: All real world applications always extends HttpServlet only and it is always recommended to
overwrite either doGet () method or doPost () method.
Associated with servlet we have three names which are specified in web.xml, they are public
URL name (known to everybody), deployer URL name or dummy name (known to that person who
is deploying) and secret or internal URL name (known to servlet container or server).
• The purpose of <servlet-mapping> is that it maps public URL name to deployer URL name.
• The purpose of <servlet> is that it maps deployer URL name to actual Servlet class name.
Write a servlet which retrieves the data from database?
Answer:
Servlet program:
package ddrs;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class RetrieveDataBaseServ extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res)
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
try
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ());
Connection con=DriverManager.getConnection ("oracle:jdbc:thin:@localhost:1521:
Hanuman", "scott","tiger");
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from emp");
while (rs.next ())
{
pw.println (rs.getString (1)+" "+rs.getString (2));
}
}
catch (Exception e)
{
res.sendError (504,"PROBLEM IN SERVLET...");
}
}
};
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 50
web.xml:
<web-app>
<servlet>
<servlet-name>Babu</servlet-name>
<serclet-class>ddrs.RetrieveDataBaseServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Babu</servlet-name>
<url-pattern>Dinesh</url-pattern>
</servlet-mapping>
</web-app>
Day - 25:
In the above program we are making use of ‘n’ number of servlet classes, OracleDriver class;
it is required to set the classpath for servlet-Api.jar and classes111.jar
For weblogic:
set classpath=F:beaweblogic81serverlibweblogic.jar;F:oracleora92jdbc
libclasses111.jar;
For Tomcat:
set classpath=F:Program FilesApache Software FoundationTomcat 5.5common
libservlet-api.jar;F:oracleora92jdbclibclasses111.jar;
When we run the above program on weblogic, it is not necessary to copy classes111.jar into
lib folder of document root. Since, the weblogic server itself contains an existing jar file called
ojdbc14.jar to deal with OracleDriver.
How to generate a war file:
A war file is the compressed form of ‘n’ number of .class files, web.xml, *.html files and the
jar files available in lib folder.
Syntax:
jar cfv (name of the war file) WEB-INF [*.html] [*.jsp]
Here, in cfv, ‘c’ represents create, ‘f’ represents file and ‘v’ represents verbose (used to
compress)
Copy the war file from the current directory and paste it into applications folder of weblogic
or webapps folder of Tomcat.
ServletConfig (one per SERVLET):
• ServletConfig is an interface which is present in javax.servlet.* package.
• The purpose of ServletConfig is to pass some initial parameter values, technical information
(driver name, database name, data source name, etc.) to a servlet.
• An object of ServletConfig will be created one per servlet.
• An object of ServletConfig will be created by the server at the time of executing public void
init (ServletConfig) method.
• An object of ServletConfig cannot be accessed in the default constructor of a Servlet class.
Since, at the time of executing default constructor ServletConfig object does not exist.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 51
• By default ServletConfig object can be accessed with in init () method only but not in doGet
and doPost. In order to use, in the entire servlet preserve the reference of ServletConfig into
another variable and declare this variable into a Servlet class as a data member of
ServletConfig.
For example:
class x extends HttpServlet
Day - 26:
• When we want to give some global data to a servlet we must obtain an object of
ServletConfig.
• web.xml entries for ServletConfig
<servlet>
………….
<init-param>
<param-name>Name of the parameter</param-name>
<param-value>Value of the parameter</param-value>
</init-param>
………….
</servlet>
For example:
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>serv1</servlet-class>
<init-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param-name>v2</param-name>
<param-value>20</param-value>
</init-param>
</servlet>
The data which is available in ServletConfig object is in the form of (key, vlaue)
OBTAINING an object of ServletConfig:
An object of ServletConfig can be obtained in two ways, they are by calling getServletConfig
() method and by calling init (ServletConfig).
By calling getServletConfig () method:
getServletConfig () is the method which is available in javax.servlet.Servlet interface. This
method is further inherited and defined into a class called javax.servlet.GenericServlet and that
method is further inherited into another predefined class called javax.servlet.http.HttpServlet and it
can be inherited into our own servlet class.
For example:
public class serv1 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 52
…………
…………
ServletConfig config=this.getServletConfig ();
…………
…………
}
};
In the above example an object config contains (key, value) pair data of web.xml file which
are written under <init-param> tag of <servlet> tag.
By calling init (ServletConfig):
For example:
public class serv2 extends HttpServlet
{
ServletConfig sc;
public void init (ServletConfig sc)
{
Super.init (sc); // used for calling init (ServletConfig) method of HttpServlet
this.sc=sc; // ServletConfig object sc is referenced
}
…………
…………
};
RETRIEVING DATA from ServletConfig interface object:
In order to get the data from ServletConfig interface object we must use the following
methods:
public String getInitParameter (String); 1
public Enumeration getInitParameterNames (); 2
Method-1 is used for obtaining the parameter value by passing parameter name.
String val1=config.getInitParameter (“v1”);
String val2=config.getInitParameter (“v2”);
String val3=config.getInitParameter (“v3”);
Method-2 is used for obtaining all parameter names and their corresponding parameter values.
For example:
Enumeration en=config.getInitParameterNames ();
while (en.hasMoreElements ())
{
Object obj=en.nextElement ();
String pname= (String) obj;
String pvalue=config.getInitParameter (pname);
out.println (pvalue+” is the value of ”+pname);
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 53
}
Day - 27:
Serv1.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv1 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
ServletConfig config=getServletConfig ();
String val1=config.getInitParameter ("v1");
String val2=config.getInitParameter ("v2");
String val3=config.getInitParameter ("v3");
String val4=config.getInitParameter ("v4");
pw.println ("<h3> Value of v1 is "+val1+"</h3>");
pw.println ("<h3> Value of v2 is "+val2+"</h3>");
pw.println ("<h3> Value of v3 is "+val3+"</h3>");
pw.println ("<h3> Value of v4 is "+val4+"</h3>");
}
};
Serv2.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv2 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
ServletConfig config=getServletConfig ();
Enumeration en=config.getInitParameterNames ();
while (en.hasMoreElements ())
{
Object obj=en.nextElement ();
String pname= (String) obj;
String pvalue=config.getInitParameter (pname);
pw.println ("</h2>"+pvalue+" is the value of "+pname+"</h2>");
}
}
};
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 54
<init-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param-name>v2</param-name>
<param-value>20</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
<init-param>
<param-name>v3</param-name>
<param-value>30</param-value>
</init-param>
<init-param>
<param-name>v4</param-name>
<param-value>40</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/firstserv</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/secondserv</url-pattern>
</servlet-mapping>
</web-app>
Develop a flexible servlet that should display the data of the database irrespective driver name, table
name and dsn name?
Answer:
DbServ.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class DbServ extends HttpServlet
{
ServletConfig sc=null;
public void init (ServletConfig sc) throws ServletException
{
super.init (sc);
this.sc=sc;
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
String dname=sc.getInitParameter ("dname");
String url=sc.getInitParameter ("url");
String tab=sc.getInitParameter ("tab");
try
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 55
{
Class.forName (dname);
Connection con=DriverManager.getConnection (url,"scott","tiger");
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from "+tab);
while (rs.next ())
{
pw.println ("<h2>"+rs.getString (1)+""+rs.getString (2)+""+rs.getString (3)+"</h2>");
}
con.close ();
}
catch (Exception e)
{
res.sendError (503,"PROBLEM IN DATABASE...");
}
}
};
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DbServ</servlet-class>
<init-param>
<param-name>dname</param-name>
<param-value>oracle.jdbc.driver.OracleDriver ()</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:Hanuman</param-value>
</init-param>
<init-param>
<param-name>tab</param-name>
<param-value>emp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/dbdata</url-pattern>
</servlet-mapping>
</web-app>
Day - 28:
ServletContext (one per WEB APPLICATION):
• ServletContext is an interface which is present in javax.servlet.* package.
• Whenever we want to give a common data or global data to the group of servlets which
belongs to same web application then we must create an object of ServletContext interface.
• An object of ServletContext will be created by servlet container (server) whenever we deploy
into the server.
• In order to provide a common data to a group of servlets, we must write that data into
web.xml file with the tag called <context-param>…</context-param>. This tag must be
written with in <web-app>…</web-app> before <servlet>.
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 56
• xml entries related to ServletContext interface.
<web-app>
<context-param>
<param-name>Name of the param</param-name>
<param-value>Value of the param</param-value>
</context-param>
<servlet>
…………..
…………..
</servlet>
<servlet-mapping>
…………..
…………..
</servlet-mapping>
</web-app>
• Whatever the data we write with in <context-param>…</context-param> that data will
be paste automatically in the object of ServletContext interface and this object contains the
in the form of (key, value) pair. Here, key represents context parameter name and value
represents context parameter value.
• The value of key must be always unique; if duplicate values are placed we get recent
duplicate value for the key by overlapping previous values.
For example:
<web-app>
<context-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:Hanuman</param-value>
</context-param>
<servlet>
…………..
…………..
</servlet>
<servlet-mapping>
…………..
…………..
</servlet-mapping>
</web-app>
Number of ways to OBTAIN AN OBJECT of ServletContext:
In order to get an object of ServletContext we have two ways, they are by calling
getServletContext () method directly and by making use of ServletConfig interface.
By using getServletContext () method:
getServletContext () method is defined in GenericServlet and it is inherited into HttpServlet
and it is further inherited into our own servlet class. Hence, we can call getServletContext () method
directly.
For example:
public class Serv1 extends HttpServlet
{
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 57
public doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
……………
……………
ServletContext ctx=this.getServletContext ();
……………
……………
}
};
By using ServletConfig interface:
In ServletConfig interface we have the following method which gives an object of
ServletContext.
In order to call the above method first we must obtain an object of ServletConfig interface
and later with that object we can call getServletContext () method.
For example:
public class Serv2 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
…………
…………
ServletConfig config=this.getServletConfig ();
ServletContext ctx=config.getServletContext ();
………….
………….
}
};
Number of ways to RETRIEVE THE DATA from an OBJECT of ServletContext:
In ServletContext interface we have the following methods to retrieve the value of context
parameter by passing context parameter name.
For example:
ServletContext ctx=getServletContext ();
String val1=ctx.getInitParameter (“v1”);
String val2=ctx.getInitParameter (“v2”);
For example:
ServletContext ctx=getServletContext ();
Enumeration en=ctx.getInitParameterNames ();
While (en.hasMoreElements ())
{
String cpn= (String) en.nextElement ();
String cpv=ctx.getInitParameter (cpn);
pw.println (cpv+” is the value of ”+cpn);
}
http://javabynataraj.blogspot.com
J2EE (Advanced) JAVA
By Mr. K. V. R Page 58
Differences between ServletConfig and ServletContext interfaces:
ServletConfig
1. An object of ServletConfig exists one
per servlet.
2. An object of ServletConfig will be
created when init (ServletConfig)
method is executed.
3. ServletConfig object contains a
specific data to a particular servlet.
4. The data to a servlet which related to
ServletConfig object must be written
in <init-param>…</init-param>
with in <servlet>…</servlet> of
web.xml
5. An object of ServletConfig will exists
as long as a specific servlet is
executing.
ServletContext
1. An object of ServletContext exists one per
web application.
2. An object of ServletContext will be created
when we deploy the web application in servlet
container or servlet execution environment.
3. ServletContext object contains a common or
global data to ‘n’ number of servlets and ‘n’
number of JSP’s.
4. The common data or global data related to
ServletContext must be written under
<context-param>…</context-param> with
in <web-app>…</web-app> and outside of
<servlet>…</servlet> of web.xml
5. An object of ServletContext will exists until the
entire web application completed its
execution.
Day - 29:
Write a servlet which illustrate the concept of ServletContext?
Answer:
web.xml:
<web-app>
<context-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</context-param>
<context-param>
<param-name>v2</param-name>
<param-value>20</param-value>
</context-param>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
<init-param>
<param-name>v3</param-name>
<param-value>30</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
http://javabynataraj.blogspot.com
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir

More Related Content

Advanced java jee material by KV Rao sir

  • 1. J2EE (Advanced) JAVA By Mr. K. V. R Page 1 Advanced JAVA (J2EE) Day - 1: In IT we are developing two types of applications; they are standalone applications and distributed applications. • A standalone application is one which runs in the context of local disk. With standalone applications we cannot achieve the concept of data sharing. For example C, C++, COBOL, PASCAL, etc. • A distributed application is one which always runs in the context of Browser or World Wide Web. All distributed applications can be accessed across the globe. For example JAVA and DOT NET. JAVA always provides a facility called server independent, platform independent language. JAVA supports a concept called design patterns (design patterns are predefined proved rules by industry experts to avoid side effects [recurring problems] which are occurring in software development). Day - 2: In real time applications, in the case of server side programming one must follow the architecture to develop a distributed application. To develop any distributed application, it is always recommended to follow either 3-tier architecture or 2-tier architecture or n-tier architecture. 3-tier architecture is also known as MVC architecture. M stands for Model (database programming), V stands for View (client side programming, HTML/AWT/APPLET/Swing/JSP) and C stands for Controller (server side programming, Servlets). The general architecture of MVC or 3-tier: 1. Client makes a request. 2. Server side program receives the request. 3. The server looks for or search for the appropriate resource in the resource pool. http://javabynataraj.blogspot.com
  • 2. J2EE (Advanced) JAVA By Mr. K. V. R Page 2 4. If the resource is not available server side program displays a user friendly message (page cannot be displayed). If the resource is available, that program will execute gives its result to server, server interns gives response to that client who makes a request. 5. When server want to deals with database to retrieve the data, server side program sends a request to the appropriate database. 6. Database server receives the server request and executes that request. 7. The database server sends the result back to server side program for further processing. 8. The server side program is always gives response to ‘n’ number of clients concurrently. Day - 3: REFLECTION “Reflection is the process of obtaining runtime information about the class or interface.” Runtime information is nothing but deal with the following: 1. Finding the name of the class or interface. 2. Finding the data members of the class or interface. 3. Finding number of constructors (default constructor and number of parameterized constructors). 4. Number of instance methods. 5. Number of static methods. 6. Determining modifiers of the class (modifiers of the class can be public, final, public + final, abstract and public + abstract). 7. Obtaining super class of a derived class. 8. Obtaining the interfaces which are implemented by various classes. Real time applications of reflection: 1. Development of language complier, debuggers, editors and browsers. 2. In order to deal with reflection in java, we must import a predefined package called java.lang.reflect.* 3. The package reflect contains set of predefined classes and interfaces which are used by the programmer to develop reflection applications. Number of ways to obtain runtime information about a class (or) number of ways to get an object of a class called Class: The predefined class called Class is present in a package called java.lang.Class (fully qualified name of a class called Class is java.lang.Class). In java we have 4 ways to deal with or to create an object of java.lang.Class, they are: 1) When we know that class name at compile time and to get runtime information about the class, we must use the following: 2) When we know the object name at runtime, to get the class name or class type of the runtime object, we must use the following: http://javabynataraj.blogspot.com
  • 3. J2EE (Advanced) JAVA By Mr. K. V. R Page 3 getClass is the predefined method present in a predefined class called java.lang.Object and whose prototype is given below: 3) When an object is given at runtime, we must find runtime information about current class and its super class. Write a java program to print name of the current class and its super class name? Answer: class First { public static void main (String [] args) { String s=new String ("HELLO"); printSuperclass (s); } static void printSuperclass (Object s) { Class c=s.getClass (); Class sc=c.getSuperclass (); System.out.println ("NAME OF CURRENT CLASS : "+c.getName ()); System.out.println ("NAME OF THE SUPER CLASS : "+sc.getName ()); } }; Output: java First NAME OF CURRENT CLASS : java.lang.String NAME OF THE SUPER CLASS : java.lang.Object http://javabynataraj.blogspot.com
  • 4. J2EE (Advanced) JAVA By Mr. K. V. R Page 4 Day - 4: 4) We know the class name at runtime and we have to obtain the runtime information about the class. To perform the above we must use the method java.lang.Class and whose prototype is given below: When we use the forName as a part of java program it performs the following operations: • It can create an object of the class which we pass at runtime. • It returns runtime information about the object which is created. For example: try { Class c=Class.forName (“java.awt.Button”); } catch (ClassNotFoundException cnfe) { System.out.println (“CLASS DOES NOT EXIST...”); } forName is taking String as an argument. If the class is not found forName method throws an exception called ClassNotFoundException. Here, forName method is a factory method (a factory method is one which return type is similar to name of the class where it presents). Every factory method must be static and public. The class which contains a factory method is known as Singleton class (a java class is said to be Singleton class through which we can create single object per JVM). For example: java.lang.Class is called Singleton class Write a java program to find name of the class and its super class name by passing the class name at runtime? Answer: class ref1 { public static void main (String [] args) { if (args.length==0) { System.out.println ("PLEASE PASS THE CLASS NAME..!"); } else { try { Class c=Class.forName (args [0]); printSuperclass (c); http://javabynataraj.blogspot.com
  • 5. J2EE (Advanced) JAVA By Mr. K. V. R Page 5 } catch (ClassNotFoundException cnfe) { System.out.println (args [0]+" DOES NOT EXISTS..."); } }// else }// main static void printSuperclass (Class c) { String s=c.getName (); Class sc=c.getSuperclass (); String sn=sc.getName (); System.out.println (sn+" IS THE SUPER CLASS OF "+s); }// printSuperclass }// ref1 Output: java ref1 java.awt.TextField java.awt.TextComponent IS THE SUPER CLASS OF java.awt.TextField Write a java program to print super class hierarchy at a current class which is passed from command prompt? Answer: class Hierarchy { public static void main (String [] args) { if (args.length==0) { System.out.println ("PLEASE PASS THE CLASS NAME..!"); } else { try { Class c=Class.forName (args [0]); printHierarchy (c); } catch (ClassNotFoundException cnfe) { System.out.println (args [0]+" DOES NOT EXISTS..."); } } } static void printHierarchy (Class c) { Class c1=c; String cname=c1.getName (); System.out.println (cname); Class sc=c1.getSuperclass (); while (sc!=null) { cname=sc.getName (); System.out.println (cname); c1=sc; sc=c1.getSuperclass (); http://javabynataraj.blogspot.com
  • 6. J2EE (Advanced) JAVA By Mr. K. V. R Page 6 } } }; Output: java Hierarchy java.awt.TextField java.awt.TextField java.awt.TextComponent java.awt.Component java.lang.Object Obtaining information about CONSTRUCTORS which are present in a class: In order to get the constructor of the current class we must use the following method: For example: Constructor cons []=c.getConstructors (); System.out.println (“NUMBER OF CONSTRUCTORS = ”+cons.length); In order to get the parameters of the constructor we must use the following method: For example: Class ptype []=cons [0].getParameterTypes (); Day - 5: Write a java program to obtain constructors of a class? Answer: class ConsInfo { public static void main (String [] args) { if (args.length==0) { System.out.println ("PLEASE PASS THE CLASS NAME..!"); } else { try { Class c=Class.forName (args [0]); printConsts (c); } catch (ClassNotFoundException cnfe) { System.out.println (args [0]+" DOES NOT EXISTS..."); } } } static void printConsts (Class c) http://javabynataraj.blogspot.com
  • 7. J2EE (Advanced) JAVA By Mr. K. V. R Page 7 { java.lang.reflect.Constructor Cons []=c.getConstructors (); System.out.println ("NUMBER OF CONSTRUCTORS = "+Cons.length); System.out.println ("NAME OF THE CONSTRUCTOR : "+c.getName()); for (int i=0; i<Cons.length; i++) { System.out.print (c.getName ()+"("); Class cp []=Cons [i].getParameterTypes (); for (int j=0; j<cp.length; j++) { System.out.print (cp [j].getName ()+")"); } System.out.println ("b"+")"); } } }; Obtaining METHODS information: In order to obtain information about methods we must use the following methods: For example: Method m []=c.getMethods (); System.out.println (“NUMBER OF METHODS = ”+m.length); Associated with methods we have return type of the method, name of the method and types of parameters passed to a method. The Method class contains the following methods: 1. public Class getReturnType (); 2. public String getName (); 3. public Class [] getParameterTypes (); Method-1 gives return type of the method, Method-2 gives name of the method and Method-3 gives what parameters the method is taking. Write a java program to obtain information about methods which are present in a class? Answer: import java.lang.reflect.*; class MetInfo { public static void main (String [] args) { try { if (args.length==0) { System.out.println ("PLEASE PASS THE CLASS NAME..!"); } else { Class c=Class.forName (args [0]); printMethods (c); http://javabynataraj.blogspot.com
  • 8. J2EE (Advanced) JAVA By Mr. K. V. R Page 8 } } catch (ClassNotFoundException cnfe) { System.out.println (args [0]+" DOES NOT EXISTS..."); } } static void printMethods (Class c) { Method m []=c.getMethods (); System.out.println ("NUMBER OF METHODS = "+m.length); System.out.println ("NAME OF THE CLASS : "+c.getName ()); for (int i=0; i<m.length; i++) { Class c1=m [i].getReturnType (); String rtype=c1.getName (); String mname=m [i].getName (); System.out.print (rtype+" "+mname+"("); Class mp []=m [i].getParameterTypes (); for (int j=0; j<mp.length; j++) { String ptype=mp [i].getName (); System.out.print (ptype+","); } System.out.println ("b"+")"); } } }; Obtaining FIELDS or DATA MEMBERS of a class: In order to obtain information about fields or data members of the class we must use the following method. For example: Field f []=c.getFields (); System.out.println (“NUMBER OF FIELDS = ”+f.length); Associated with field or data member there is a data type and field name: The Field class contains the following methods: 1. public Class getType (); 2. public String getName (); Method-1 is used for obtaining data type of the field and Method-2 is used for obtaining name of the field. Write a java program to print fields or data members of a class? Answer: import java.lang.reflect.Field; class Fields { void printFields (Class c) { http://javabynataraj.blogspot.com
  • 9. J2EE (Advanced) JAVA By Mr. K. V. R Page 9 Field f []=c.getFields (); System.out.println ("NUMBER OF FIELDS : "+f.length); for (int i=0; i<f.length; i++) { String fname=f [i].getName (); Class s=f [i].getType (); String ftype=s.getName (); System.out.println (ftype+" "+fname); } } }; class FieldsDemo { public static void main (String [] args) { if (args.length==0) { System.out.println ("PLEASE PASS THE CLASS NAME..!"); } else { try { Class c=Class.forName (args [0]); Fields fs=new Fields (); fs.printFields (c); } catch (ClassNotFoundException cnfe) { System.out.println (args [0]+"NOT FOUND..."); } } } }; Day - 6: JDBC (Java Database Connectivity) “JDBC is a kind of specification developed by SUN Microsystems to store the data permanently”. In Information Technology we have two approaches’ to store the data permanently. They are through files and through database. Whatever data we store permanently in the form of a file, the file will not provide enough security to the data from unauthorized users. In order to save or store the data permanently in the form of a file we must use the concept of serialization. Serialization: Serialization is the mechanism of saving the state of the object permanently in the form of a file. Steps for developing SERIALIZABLE SUB CLASS: A Serializable sub class is one which implements a predefined interface called java.io.Serializable http://javabynataraj.blogspot.com
  • 10. J2EE (Advanced) JAVA By Mr. K. V. R Page 10 1. Choose the appropriate package to keep Serializable sub class. 2. Choose the user defined class whose object participates in Serializable process. 3. Every user defined class must implements a predefined interface called Serializable. 4. Choose the set of data members for Serializable sub class. 5. Develop the set of set methods for each and every data members of the class. 6. Develop the set of get methods for each and every data members of the class. The above class is known as java bean class or component style based programming or POJO (Plain Old Java Object) class. For example: package ep; //step-1 import java.io.*; public class Emp implements Serializable // Emp (step-2) & Serializable (step-3) { int empno; String ename; float sal; // above data members (step-4) public void setEmpno (int empno) { this.empno=empno; } public void setEname (String ename) { this.ename=ename; } public void setSal (float sal) { this.sal=sal; } // above set methods (step-5) public int getEmpno () { return empno; } public String getEname () { return ename; } public float getSal () { return sal; } // above get methods (step-6) }; Day - 7: Serializable process: Steps for SERIALIZATION process: 1. Create an object of Serializable sub class. For example: sp.emp eo=new sp.emp (); http://javabynataraj.blogspot.com
  • 11. J2EE (Advanced) JAVA By Mr. K. V. R Page 11 2. Call set of set methods to place user defined values in a Serializable sub class object. For example: eo.setEmpno (10); eo.setEname (“KVR”); eo.setSal (10000.00f); 3. Choose the file name and open it into write mode or output mode with the help of java.io.FileOutputStream For example: FileOutputStream fos=new FileOutputStream (“employee”); 4. Since an object of FileOutputStream cannot write the entire object at a time to the file. Hence, it is recommended to use a predefined class called ObjectOutputStream class. ObjectOutputStream class contains the following constructor which takes an object of FileOutputStream class. For example: ObjectOutputStream oos=new ObjectOutputStream (fos); 5. In order to write the entire object at a time to the file ObjectOutputStream contains the following method: For example: oos.writeObject (eo); 6. Close the files which are opened in write mode. For example: oos.close (); fos.close (); Write a java program which will save the Serializable sub class object into a file? Answer: import ep.Emp; import java.io.*; class serp { public static void main (String [] args) throws Exception http://javabynataraj.blogspot.com
  • 12. J2EE (Advanced) JAVA By Mr. K. V. R Page 12 { Emp eo=new Emp (); eo.setEmpno (100); eo.setEname ("KVR"); eo.setSal (10000.00f); FileOutputStream fos=new FileOutputStream ("employee"); ObjectOutputStream oos=new ObjectOutputStream (fos); oos.writeObject (eo); System.out.println ("EMPLOYEE OBJECT SAVED SUCCESSFULLY..."); oos.close (); fos.close (); } }; Output: EMPLOYEE OBJECT SAVED SUCCESSFULLY... De-Serializable process: It is the process of retrieving the record from the file into main memory of the computer. Steps for DE-SERIALIZATION process: 1. Create an object of Serializable sub class. For example: emp eo1=new emp (); 2. Choose the file name and open it into read mode with the help of FileInputStream class. For example: FileInputStream fis=new FileInputStream (“employee”); 3. Since an object of FileInputStream cannot read the entire object at a time from the file. Hence, it is recommended to create an object of ObjectInputStream class. ObjectInputStream class contains the following constructor which takes object of FileInputStream as a parameter. For example: ObjectInputStream ois=new ObjectInputStream (fis); 4. ObjectInputStream class contains the following method which will read the entire object at a time where ever ObjectInputStream is pointing. http://javabynataraj.blogspot.com
  • 13. J2EE (Advanced) JAVA By Mr. K. V. R Page 13 For example: Object obj=ois.readObject (); 5. An object of Object does not contain set of get methods and they are defined in its sub class called emp. Hence, an object of Object must be type casted to Serializable sub class object. For example: eo1= (emp) obj; 6. Apply set of get methods to obtain the data from de-serialized object i.e., eo1. For example: System.out.println (“empno : ”+eo1.getEmpno ()); System.out.println (“empname : ”+eo1.getEname ()); System.out.println (“empsal : ”+eo1.getSal ()); 7. Close the files which are opened in read mode or input mode. For example: ois.close (); fis.close (); Write a java program which will de-Serializable from the specified file? Answer: import ep.Emp; import java.io.*; class dserp { public static void main (String [] args) throws Exception { Emp eo1=new Emp (); FileInputStream fis=new FileInputStream ("employee"); ObjectInputStream ois=new ObjectInputStream (fis); Object obj=ois.readObject (); eo1= (Emp) obj; System.out.println ("EMP NO : "+eo1.getEmpno ()); System.out.println ("EMP NAME : "+eo1.getEname ()); System.out.println ("EMP SALARY : "+eo1.getSal ()); ois.close (); fis.close (); } }; Output: EMP NO : 100 EMP NAME : KVR EMP SAL : 10000.0 Day - 8: When we don’t want the variables to participate in serialization process, which type of variables must be made it as transient i.e., transient variables will not participate in serialization process. http://javabynataraj.blogspot.com
  • 14. J2EE (Advanced) JAVA By Mr. K. V. R Page 14 In general we have four types of serializations, they are: 1. Complete serialization: It is one in which all the data members of the class will participate in serialization process. 2. Selective serialization: It is one in which selective data members of the class (non-transient variables) will participate in serialization process. 3. Manual serialization: It is one in which the derived class explicitly implements a predefined interface called java.io.Serializable. The interface Serializable does not contain any abstract methods and this type of interface is known as marked or tagged interface. 4. Automatic serialization: It is one in which the user defined derived class extends sub class of Serializable interface. For example: class Bank extends Emp { ……………..; ……………..; }; In real world application we cannot store the data permanently in the form of files. Since, a file does not provide any security to prevent unauthorized modifications. Hence, it is recommended to store the data permanently in the form of database. JDBC: In the initial days of database technology various database vendors has developed various database products. Anybody who want to deal with any database the programmer must have complete knowledge about the database which they are using i.e., in the initial days all the databases are available with a specific library (native library) which was developed in ‘C’ language. In the context the programmer must have complete knowledge about the native library of the database which is a complex process. In later stages all database vendors gathered and developed XOPEN/CLI (Call Level Interface) software along with Microsoft which is known as ODBC (Open Database Connectivity). ODBC is having a common API or library for various databases and it is also developed in ‘C’ language and it is a platform dependent. In later stages SUN micro systems has developed a general specification called JDBC which contains a common API for all databases with platform independent. In order to deal with any database to represent the data permanently, we must use driver (a driver is a software which acts as a middle layer between database and front end application i.e., java) of the specific database. In real world we have various drivers are available for various database products. Types of DRIVERS: SUN micro systems has divided various database drivers of various database products into four types, they are: 1. Type-1 (JDBC-ODBC bridge driver). http://javabynataraj.blogspot.com
  • 15. J2EE (Advanced) JAVA By Mr. K. V. R Page 15 2. Type-2 (Native or partial java drivers). 3. Type-3 (Net protocol or intermediate database server access drivers) and 4. Type-4 (Thin drivers or pure drivers or all java drivers). Steps for developing a JDBC program: 1. Loading the drivers. 2. Obtain the connection or specify the URL. 3. Pass the query. 4. Process the result which is obtained from database. 5. Close the connection. Day - 9: JDBC is the standard specification released by SUN micro systems to develop the applications in database world. JDBC contains set of interfaces and these interfaces are implemented by various database vendors and server vendors. A driver is nothing but a java class which acts as a middle layer between java program and database program. As on today all the drivers are developed by either database vendors or server vendors. For example: class x implements ___ { …………; …………; …………; }; Here, x is driver and ___ is JDBC interface. In database world, each and every database vendor has developed their drivers and released to the market in the form of jar files. TYPE-1 DRIVERS These are developed by SUN micro systems. The name of the Type-1 driver is JdbcOdbcDriver. The driver JdbcOdbcDriver is found in a package called sun.jdbc.odbc. Using this driver we can develop only 2-tier applications (a java program and database). This type of driver is purely implemented in ‘C’ language and this driver is platform dependent in nature. Loading the drivers: Loading the drivers is nothing but creating an object of appropriate Driver class. In order to load the drivers we have two ways, they are: 1) Using Class.forName For example: Class.forName (Sun.jdbc.odbc.JdbcOdbcDriver); Class.forName (oracle.jdbc.driver.OracleDriver); 2) Using DriverManager.registerDriver DriverManager class contains the following method which will load the driver at runtime. http://javabynataraj.blogspot.com
  • 16. J2EE (Advanced) JAVA By Mr. K. V. R Page 16 For example: public static void registerDriver (java.sql.Driver); Driver is an interface which is implemented by various database vendors and server vendors. If the appropriate driver object is created that driver object will act as a middle layer between program and database. If the driver is not found we get an exception called java.sql.SQLException For example: DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver); [for oracle driver is – classes111.jar] Day - 10: How to obtain the connection: After loading the drivers, it is required to obtain the connection from the database. Syntax or URL for obtaining connection: Here, jdbc is the main protocol which takes java request and hand over into database environment through Data Source Name. odbc is the sub protocol which takes the database result and gives to java environment. Data Source Name is the configuration tool in the current working machine through which the data is passing from java environment to database and database to java environment. In order to obtain the connection from the database, as a part of jdbc we have a predefined class called java.sql.DriverManager which contains the following methods: 1. public static Connection getConnection (String URL); 2. public static Connection getConnection (String URL, String username, String password); Method-1, we use to obtain the connection from those databases where there is no username and password databases. Method-2 is used for those databases where there is username and password. For example: Connection con1=DriverManager.getConnection (“jdbc : odbc : Access”); Connection con2=DriverManager.getConnection (“jdbc : odbc : oracle”,”scott”,”tiger”); Pass the query: A query is nothing but a request or question to the database. Queries are of three types; they are static query, dynamic or pre-compiled query and stored procedures. STATIC QUERY: Static query is one in which the data is passed in the query itself. For example: 1. select * from Student where marks>50; 2. insert into Student values (100, ‘abc’, 90.86); In order to execute static queries we must obtain an object of java.sql.Statement interface. In the interface java.sql.Connection we have the following method for obtaining an object of Statement interface. http://javabynataraj.blogspot.com
  • 17. J2EE (Advanced) JAVA By Mr. K. V. R Page 17 For example: Statement st=con1.createStatement (); On database three categories of operations takes place, they are insertion, deletion and updation. In order to perform these operations we must use the following method which is present in Statement interface. Here, String represents either static insertion or static deletion or static updation. The return type int represents the status of the query. If the query is not successful it returns zero and if the query is successful it returns non-zero. Write a jdbc program which will insert a record in the Student database? Answer: import java.sql.*; class InsertRec { public static void main (String [] args) { try { Driver d=new Sun.jdbc.odbc.JdbcOdbcDriver (); DriverManager.registerDriver (d); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); Statement st=con.createStatement (); int i=st.executeUpdate ("insert into student values (10,'suman',60.87);"); System.out.println (i+" ROWS SELECTED..."); con.close (); } catch (Exception e) { System.out.println ("DRIVER CLASS NOT FOUND..."); } } }; Day - 11: Processing the query result: In order to execute the select statement or in order to retrieve the data from database we must use the following method which is present in java.sql.Statement interface. http://javabynataraj.blogspot.com
  • 18. J2EE (Advanced) JAVA By Mr. K. V. R Page 18 Here, String represents a query which contains select statement. executeQuery returns an object of ResultSet to hold the number of records returned by select statement. ResultSet is an interface whose object contains all the records returned by a query and it will point to just before the first record. For example: ResultSet rs=st.executeQuery (“select * from Student”); The ResultSet object is pointing by default just before the first record, in order to bring first record we must use the below given method. Method returns true when rs contains next record otherwise it returns false. public boolean next (); In order to obtain the data of the record (collection of field values) we must use the following method: public String getString (int colno); Whatever the data retrieving from the record that data will be treated as string data. For example: String s1=rs.getString (1); String s1=rs.getString (2); String s1=rs.getString (3); Write a java program to retrieve the data from emp database? Answer: import java.sql.*; class SelectData { public static void main (String [] args) throws Exception { DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver ()); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); Statement st=con.createStatement (); ResultSet rs=st.executeQuery ("select * from dept"); while (rs.next ()) { System.out.println (rs.getString (1)+" "+rs.getString (2)+" "+rs.getString (3)); } con.close (); http://javabynataraj.blogspot.com
  • 19. J2EE (Advanced) JAVA By Mr. K. V. R Page 19 } }; ResultSet: 1. An object of ResultSet allows us to retrieve the data by default only in forward direction but not in backward direction and random retrieval. 2. Whenever we get the database data in ResultSet object which will be temporarily disconnected from the database. 3. ResultSet object does not allows us to perform any modifications on ResultSet object. 4. Hence, the ResultSet is by default non-scrollable disconnected ResultSet. DYNAMIC or PRE-COMPILED QUERIES: 1. Dynamic queries are those for which the data is passed at runtime. 2. To execute dynamic queries we must obtain an object of PreparedStatement. Differentiate between Statement and PreparedStatement? Answer: Statement PreparedStatement 1. This interface is used for executing static queries. 1. This interface is used for executing dynamic queries. 2. When we execute static queries with respect to Statement object; compilation, parsing and execution of the query takes place each and every time. 2. When we execute dynamic queries using PreparedStatement object; compilation, parsing and execution of the query takes place first time and from second time onwards only execution phase takes place. 3. There is a possibility of loosing performance of a jdbc program. Since, compilation, parsing and execution taking place each and every time. 3. We can get the performance of jdbc program. Since, compilation and parsing takes place only one time. In order to obtain an object of PreparedStatement we must use the following method: Here, String represents dynamic query. For example: PreparedStatement ps=con.prepareStatement (“select * from dept where deptno=?”); Here, the ‘?’ is known as dynamic substitution operator or positional parameter. The position of the positional parameters must always starts from left to right with the numbers 1, 2……n. http://javabynataraj.blogspot.com
  • 20. J2EE (Advanced) JAVA By Mr. K. V. R Page 20 In order to set the values to the positional parameters, we must use the following methods which are present in prepared statement interface. public void setByte (int, byte); public void setShort (int, short); public void setInt (int, int); public void setLong (int, long); public void setFloat (int, float); public void setDouble (int, double); public void setChar (int, char); public void setString (int, string); In general PreparedStatement interface contains the following generalized method to set the values for positional parameters. public void setXXX (int, XXX); Here, int represents position number of the positional parameter. XXX represents value of either fundamental data type or string or date. For example: ps.setInt (1, 10); In order to execute the DCL statements (select) and DML statements (insert, delete and update) we must use the following methods which are present in PreparedStatement interface. public int executeUpdate (); Dynamic DML/DDL public ResultSet executeQuery (); Dynamic DCL (select) For example: ResultSet rs=ps.executeQuery (); Close connection For example: con.close (); Day - 12: Write a java program to insert a record in dept database by accepting the data from keyboard at runtime using dynamic queries? Answer: import java.sql.*; import java.io.*; class InsertRecRun { public static void main (String [] args) { try { DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ()); System.out.println ("DRIVERS LOADED..."); http://javabynataraj.blogspot.com
  • 21. J2EE (Advanced) JAVA By Mr. K. V. R Page 21 Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521: BudDinu","scott","tiger"); System.out.println ("CONNECTION OBTAINED..."); PreparedStatement ps=con.prepareStatement ("insert into dept values (?,?,?)"); DataInputStream dis=new DataInputStream (System.in); System.out.println ("ENTER DEPARTMENT NUMBER : "); String s1=dis.readLine (); int dno=Integer.parseInt (s1); System.out.println ("ENTER DEPARTMENT NAME : "); String dname=dis.readLine (); System.out.println ("ENTER LOCATION NAME : "); String loc=dis.readLine (); ps.setInt (1, dno); ps.setString (2, dname); ps.setString (3, loc); int i=ps.executeUpdate (); System.out.println (i+"ROW(s) INSERTED..."); con.close (); } catch (Exception e) { e.printStackTrace (); } }// main };// InsertRecRun Write a java program to retrieve the records from a specified database by accepting input from keyboard? Answer: import java.sql.*; import java.io.*; class SelectDataRun { public static void main (String [] args) { try { Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); PreparedStatement ps=con.prepareStatement ("select * from dept where deptno"); DataInputStream dis=new DataInputStream (System.in); System.out.println ("ENTER DEPARTMENT NUMBER : "); String s1=dis.readLine (); int dno=Integer.parseInt (s1); ps.setInt (1, dno); ResultSet rs=ps.executeQuery (); while (rs.next ()) { System.out.print (rs.getString (1)+" "+rs.getString (2)+" "+rs.getString (3)); } con.close (); } catch (Exception e) http://javabynataraj.blogspot.com
  • 22. J2EE (Advanced) JAVA By Mr. K. V. R Page 22 { e.printStackTrace (); } }// main };// SelectDataRun TYPE – 4 DRIVERS In order to avoid the disadvantages of Type-1 drivers, we have to deal with Type-4 drivers. Disadvantages of Type-1: 1. Since, it is developed in ‘C’ language; this type of driver is treated as platform dependent. 2. These are a waste of memory space. Since, we are creating a DSN (Data Source Name) for each and every database connection and it leads to less performance. 3. We are unable to develop 3-tier applications. Advantages of Type-4: 1. This driver gives affective performance for every jdbc application. Since, there is no DSN. 2. Since, this driver is developed in java by database vendors, internally JVM need not to convert platform dependent to platform independent. The only disadvantage of Type-4 is we are unable to develop 3-tier applications. Type-4 drivers are supplied by Oracle Corporation by developing into java language. OracleDriver is the name of Type-4 driver which is released by Oracle Corporation in the form of classes111.jar When we want to make use of Type-4 driver as a part of a java program, we must first set classpath for oracle driver by using the following: set CLASSPATH=C:oracleora92jdbclibclasses111.jar;.; For example: Class.forName (“oracle.jdbc.driver.OracleDriver”); In order to obtain the connection from oracle database we must follow the following syntax: http://javabynataraj.blogspot.com
  • 23. J2EE (Advanced) JAVA By Mr. K. V. R Page 23 For example: Connection con=DriverManager.getConnection (“jdbc : oracle : thin :@ localhost : 1521 : AshaKrishna”, “scott”, “tiger”) In order to obtain port number and service ID of oracle database we must look for tnsnames.ora which is found in C:oracleora92networkadmin Day - 13: STORED PROCEDURES: In general, we are performing the database operations by using ordinary SQL statements. When we want to execute n number of SQL statements through java program, the java environment is executing those queries one at a time which leads to lack of performance to a jdbc application. In order to improve the performance of jdbc application, it is recommended to write all n number of SQL statements in a single program (in case of oracle it is called PL/SQL program) and that program will execute at a time irrespective of number of SQL statements which improves the performance of a java application. A program which contains n number of SQL statements and residing a database environment is known as stored procedure. Stored procedures are divided into two types, they are procedure and function. • A procedure is one which contains block of statements which will return either zero or more than one value. Syntax for creating a procedure: create or replace procedure <procedure name> (parameters if any) as/is local variables; begin block of statements; end; / In order to call a procedure from java environment we must call on the name of procedure. For example: create or replace procedure proc1 as i out number; a out number; b number; c number; x in out number; begin i:=40+42; b:=10; c:=20; a:=b+c; x:=x+b+c; end; / http://javabynataraj.blogspot.com
  • 24. J2EE (Advanced) JAVA By Mr. K. V. R Page 24 Create an oracle procedure which takes two input numbers and it must return sum of two numbers, multiplication and subtraction? Answer: create or replace procedure proc2 (a in number, b number, n out number, n2 out number, n3 out number) as begin n1:=a+b; n2:=a*b; n3:=a-b; end; / • A function is one which contains n number of block of statements to perform some operation and it returns a single value only. Syntax for creating a function: create or replace function (a in number, b in number) return <return type> as n1 out number; begin n1:=a+b; return (n1); end; / In order to execute the stored procedures from jdbc we must follow the following steps: 1. Create an object of CallableStatement by using the following method: Here, String represents a call for calling a stored procedure from database environment. 2. Prepare a call either for a function or for a procedure which is residing in database. Syntax for calling a function: “{? = call <name of the function> (?,?,?….)}” For example: CallableStatement cs=con.prepareCall (“{? = call fun1 (?,?)}”); The positional parameters numbering will always from left to right starting from 1. In the above example the positional parameter-1 represents out parameter and the positional parameter-2 and parameter-3 represents in parameters. Syntax for calling a procedure: “{call <name of the procedure> (?,?,?….)}” For example: CallableStatement cs=con.prepareCall (“{call fun1 (?,?,?,?,?)}”); 3. Specify which input parameters are by using the following generalized method: Public void setXXX (int, XXX); For example: cs.setInt (2, 10); http://javabynataraj.blogspot.com
  • 25. J2EE (Advanced) JAVA By Mr. K. V. R Page 25 cs.setInt (3, 20); 4. Specify which output parameters are by using the following generalized method: In jdbc we have a predefined class called java.sql.Types which contains various data types of jdbc which are equivalent to database data types. Java Jdbc Database int INTEGER number String VARCHAR varchar2 Short TINY INTEGER number Byte SMALL INTEGER number All the data members which are available in Types class are belongs to public static final data members. For example: cs.registerOutParameter (1, Types.INTEGER); 5. Execute the stored procedure by using the following method: For example: cs.execute (); 6. Get the values of out parameters by using the following method: public XXX getXXX (int); Here, int represents position of out parameter. XXX represents fundamental data type or string or date. For example: int x=cs.getInt (1); System.out.println (x); Day - 14: Write a java program which illustrates the concept of function? Answer: StuFun: create or replace function StuFun (a in number, b in number, n1 out number) return number as http://javabynataraj.blogspot.com
  • 26. J2EE (Advanced) JAVA By Mr. K. V. R Page 26 n2 number; begin n1:=a*b; n2:=a+b; return (n2); end; / FunConcept.java: import java.sql.*; import java.io.*; class FunConcept { public static void main (String [] args) { try { DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ()); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521: BudDinu","scott","tiger"); System.out.println ("CONNECTION OBTAINED..."); DataInputStream dis=new DataInputStream (System.in); System.out.println ("ENTER FIRST NUMBER : "); String s1=dis.readLine (); System.out.println ("ENTER SECOND NUMBER : "); String s2=dis.readLine (); int n1=Integer.parseInt (s1); int n2=Integer.parseInt (s2); CallableStatement cs=con.prepareCall ("{?=call ArthFun (?,?,?)}"); cs.setInt (2, n1); cs.setInt (3, n2); cs.registerOutParameter (1, Types.INTEGER); cs.registerOutParameter (4, Types.INTEGER); cs.execute (); int res=cs.getInt (1); int res1=cs.getInt (4); System.out.println ("SUM OF THE NUMBERS : "+res); System.out.println ("MULTIPLICATION OF THE NUMBERS : "+res1); } catch (Exception e) { e.printStackTrace (); } }// main }// FunConcept Write a java program which illustrates the concept of procedure? Answer: StuPro: create or replace procedure StuPro (no in number, name in varchar2, loc1 out varchar2) as begin select dname, loc into name, loc1 from dept http://javabynataraj.blogspot.com
  • 27. J2EE (Advanced) JAVA By Mr. K. V. R Page 27 where deptno=no; insert int abc values (no, name, loc1); end; / ProConcept.java: import java.sql.*; import java.io.*; class ProConcept { public static void main (String [] args) { try { DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ()); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521: BudDinu","scott","tiger"); DataInputStream dis=new DataInputStream (System.in); System.out.println ("ENTER DEPARTMENT NUMBER : "); String s1=dis.readLine (); int n1=Integer.parseInt (s1); CallableStatement cs=con.prepareCall ("{call StuPro (?,?,?)}"); cs.setInt (1,n1); cs.registerOutParameter (2, Types.VARCHAR); cs.registerOutParameter (3, Types.VARCHAR); cs.execute (); String res=cs.getString (2); String res1=cs.getString (3); System.out.println ("DEPARTMENT NAME : "+res); System.out.println ("DEPARTMENT LOCATION : "+res1); } catch (Exception e) { System.out.println (e); } }// main }// ProConcept Retrieving the data from CONVENTIONAL DATABASE (MS-Excel): In real world applications, there is a possibility of retrieving the data from conventional data bases like ms-excel. Steps for retrieving data from ms-excel: 1. Create an excel sheet, enter the column names along with data, rename the sheet1 as user defined name which is treated as table name. http://javabynataraj.blogspot.com
  • 28. J2EE (Advanced) JAVA By Mr. K. V. R Page 28 2. Save the excel sheet in a current working directory. For example: D:advancedjdbcstbook.xls 3. Create DSN for excel 4. Use xldsn while obtaining a connection from excel. For example: Connection con=DriverManager.getConnetion (“jdbc : odbc : xldsn”); NOTE: In order to refer excel sheet name as a database sheet name we should use the format [<sheet name> $] Write a jdbc program to retrieve the data from excel? Answer: import java.sql.*; class XSelect { public static void main (String [] args) { try { DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver ()); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:xldsn"); System.out.println ("CONNECTION ESTABLISHED..."); Statement st=con.createStatement (); ResultSet rs=st.executeQuery ("select * from [student$]"); http://javabynataraj.blogspot.com
  • 29. J2EE (Advanced) JAVA By Mr. K. V. R Page 29 while (rs.next ()) { System.out.println (rs.getString (1)+" "+rs.getString (2)+" "+rs.getString (3)); } con.close (); } catch (SQLException sqle) { sqle.printStackTrace (); } }// main };// XSelect Day - 15: Metadata: Data about data is known as metadata. Metadata can be obtained at two levels, they are user database details and universal database details. Obtaining user database details: In order to obtain user database details we must follow the following procedure: 1. Obtain an object of ResultSetMetaData by using the following method which is present in ResultSet. For example: ResultSetMetaData rsmd=rs.getMetaData (); 2. In general every user database contains number of columns, name of the columns and type of columns. In order to obtain the above information we must use the following methods which are present in ResultSetMetaData interface. public int getColumnCount (); public String getColumnName (); public String getColumnLabel (); public String getColumnType (); Obtaining universal database details: When we get a connection from the database we can come to know which database we are using. To obtain information about universal database we must use the following steps: 1. Obtain an object of DatabaseMetaData by calling the following method which is present in Connection interface. For example: DatabaseMetaData dmd=con.getMetaData (); http://javabynataraj.blogspot.com
  • 30. J2EE (Advanced) JAVA By Mr. K. V. R Page 30 2. In general every universal database contains database name, database version, driver name, driver version, driver major version and driver minor version. To obtain these information, DatabaseMetaData interface contains the following methods: public String getDatabaseProductName (); public String getDatabaseProductVersion (); public String getDriverName (); public String getDriverVersion (); public String getDriverMajorVersion (); public String getDriverMinorVersion (); Write a java program which illustrates the concept of DatabaseMetaData and ResultSetMetaData? Answer: import java.sql.*; class MetaData { public static void main (String [] args) { try { DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver ()); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc : odbc : oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); // UNIVERSAL DATABASE DETAILS DatabaseMetaData dmd=con.getMetaData (); System.out.println ("DATABASE NAME : "+dmd.getDatabaseProductName ()); System.out.println ("DATABASE VERSION : "+dmd.getDatabaseProductVersion ()); System.out.println ("NAME OF THE DRIVER : "+dmd.getDriverName ()); System.out.println ("VERSION OF THE DRIVER : "+dmd.getDriverVersion ()); System.out.println ("MAJOR VERSION OF DRIVER : "+dmd.getDriverMajorVersion ()); System.out.println ("MINOR VERSION OF DRIVER : "+dmd.getDriverMinorVersion ()); // USER DATABASE DETAILS Statement st=con.createStatement (); ResultSet rs=st.executeQuery ("select * from dept"); ResultSetMetaData rsmd=rs.getMetaData (); System.out.println ("NUMBER OF COLUMNS : "+rsmd.getColumnCount ()); for (int i=1; i<=rsmd.getColumnCount (); i++) { System.out.println ("NAME OF THE COLUMN : "+rsmd.getColumnName (i)); System.out.println ("TYPE OF THE COLUMN : "+rsmd.getColumnType (i)); } con.close (); } catch (Exception e) { e.printStackTrace (); } }// main };// MetaData http://javabynataraj.blogspot.com
  • 31. J2EE (Advanced) JAVA By Mr. K. V. R Page 31 Write a java program which points the data of a table along with its column names? Answer: import java.sql.*; class Table { public static void main (String [] args) { try { DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver ()); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); Statement st=con.createStatement (); ResultSet rs=st.executeQuery ("select * from dept"); ResultSetMetaData rsmd=rs.getMetaData (); System.out.println ("=================================================="); // PRINTING COLUMN NAME for (int i=1; i<=rsmd.getColumnCount (); i++) { System.out.print (rsmd.getColumnName (i)+" "); } System.out.println (""); System.out.println ("=================================================="); // PRINTING THE DATA OF THE TABLE while (rs.next ()) { for (int j=1; j<=rsmd.getColumnCount (); j++) { System.out.print (rs.getString (j)+" "); } System.out.println (""); } con.close (); } catch (SQLException sqle) { sqle.printStackTrace (); } }// main };// Table Day - 16: Developing flexible jdbc applications: When we write any jdbc application, we use to specify the specific details regarding driver names, URL, which database we are using and table names. When we want to change the jdbc application for some other details regarding driver name, URL, etc., we must change into java program and we need to compile which leads to higher maintenance activities. http://javabynataraj.blogspot.com
  • 32. J2EE (Advanced) JAVA By Mr. K. V. R Page 32 In order to avoid recompiling a jdbc application we must develop a flexible jdbc application with the help of resource bundle file or properties file. A resource bundle file or properties file is one which contains the data in the form of (key, value) pair. For example: <file name>.<rbf/prop> NOTE: After creating resource bundle file that file must be stored into current working directory. How to read the data from RESOURCE BUNDLE FILE: 1. In order to read the data from resource bundle file, open the resource bundle file in read mode with the help of FileInputStream class. For example: FileInputStream fis=new FileInputStream (“db.prop”); 2. Since files does not support to read the data separately in the form of (key, value). Hence, it is recommended to get the data of the file we must create an object of a predefined class called java.util.Properties For example: Properties p=new Properties (); 3. In order to link ‘fis’ and ‘p’ objects we must use the following method: For example: p.load (fis); 4. Obtain the property value by passing property name by using the following method: public Object get (String); public Object getProperty (String); Here, String represents property name or key name. For example: String dname= (String) p.get (“Dname”); String url= (String) p.get (“URL”); String username= (String) p.get (“Uname”); String password= (String) p.get (“Pwd”); String table= (String) p.get (“Tablename”); Here, Dname, URL, Uname, Pwd and Tablename are the property names present in resource bundle file. dname, url, username, password and table are the property values present in resource bundle file. Write a java program which illustrates the concept of resource bundle file or how to develop a flexible jdbc application along with its metadata? Answer: rbfdb.prop: Dname=oracle.jdbc.driver.OracleDriver URL=jdbc:oracle:thin:@127.0.0.1:1521:oradsn Uname=scott http://javabynataraj.blogspot.com
  • 33. J2EE (Advanced) JAVA By Mr. K. V. R Page 33 Pwd=tiger Tablename=student RBFConcept: import java.sql.*; import java.io.*; import java.util.*; class RBFConcept { public static void main (String [] args) { try { FileInputStream fis=new FileInputStream ("rbfdb.prop"); Properties p=new Properties (); p.load (fis); String dname= (String) p.get ("Dname"); String url= (String) p.get ("URL"); String username= (String) p.get ("Uname"); String password= (String) p.get ("Pwd"); String tablename= (String) p.get ("Tablename"); // loading drivers and obtaining connection Class.forName (dname); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection (url, username, password); System.out.println ("CONNECTION CREATED..."); // executing query Statement st=con.createStatement (); ResultSet rs=st.executeQuery ("select * from"+tablename); ResultSetMetaData rsmd=rs.getMetaData (); // printing column names System.out.println ("================================="); for (int i=1; i<=rsmd.getColumnCount (); i++) { System.out.print (rsmd.getColumnName (i)+" "); } System.out.println (""); System.out.println ("================================="); // printing the data while (rs.next ()) { for (int j=1; j<=rsmd.getColumnCount (); j++) { System.out.print (rs.getString (j)+" "); } } con.close (); } catch (Exception e) { e.printStackTrace (); } http://javabynataraj.blogspot.com
  • 34. J2EE (Advanced) JAVA By Mr. K. V. R Page 34 }// main };// RSFConcept Scrollable ResultSet’s and Updatable ResultSet’s: Whenever we create an object of ResultSet by default, it allows us to retrieve in forward direction only and we cannot perform any modifications on ResultSet object. Therefore, by default the ResultSet object is non-scrollable and non-updatable ResultSet. Day - 17: Scrollable ResultSet: A scrollable ResultSet is one which allows us to retrieve the data in forward direction as well as backward direction but no updations are allowed. In order to make the non-scrollable ResultSet as scrollable ResultSet as scrollable ResultSet we must use the following createStatement which is present in Connection interface. Type represents type of scrollability and Mode represents either read only or updatable. The value of Type and value of Mode are present in ResultSet interface as constant data members and they are: int Type TYPE_FORWARD_ONLY 1 TYPE_SCROLL_INSENSITIVE 2 int Mode CONCUR_READ_ONLY 3 For example: Statement st=con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs=st.executeQuery (“select * from student”); Whenever we create a ResultSet object, by default, constant-1 as a Type and constant-2 as a Mode will be assigned. The following methods which are available in ResultSet interface which allows us to retrieve the data either in forward direction or in backward direction or in random retrieval: public boolean next (); 1 public void beforeFirst (); 2 public boolean isFirst (); 3 public void first (); 4 public boolean isBeforeFirst (); 5 public boolean previous (); 6 public void afterLast (); 7 public boolean isLast (); 8 public void last (); 9 public boolean isAfterLast (); 10 public void absolute (int); 11 public void relative (int); 12 • Method-1 returns true when rs contains next record otherwise false. http://javabynataraj.blogspot.com
  • 35. J2EE (Advanced) JAVA By Mr. K. V. R Page 35 • Method-2 is used for making the ResultSet object to point to just before the first record (it is by default). • Method-3 returns true when rs is pointing to first record otherwise false. • Method-4 is used to point the ResultSet object to first record. • Method-5 returns true when rs pointing to before first record otherwise false. • Method-6 returns true when rs contains previous record otherwise false. • Method-7 is used for making the ResultSet object to point to just after the last record. • Method-8 returns true when rs is pointing to last record otherwise false. • Method-9 is used to point the ResultSet object to last record. • Method-10 returns true when rs is pointing after last record otherwise false. • Method-11 is used for moving the ResultSet object to a particular record either in forward direction or in backward direction with respect to first record and last record respectively. If int value is positive, rs move in forward direction to that with respect to first record. If int value is negative, rs move in backward direction to that with respect to last record. • Method-12 is used for moving rs to that record either in forward direction or in backward direction with respect to current record. Write a java program which illustrates the concept of scrollable ResultSet? Answer: import java.sql.*; class ScrollResultSet { public static void main (String [] args) { try { Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); Statement st=con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet. CONCUR_READ_ONLY); ResultSet rs=st.executeQuery ("select * from emp"); System.out.println ("RECORDS IN THE TABLE..."); while (rs.next ()) { System.out.println (rs.getInt (1)+" "+rs.getString (2)); } rs.first (); System.out.println ("FIRST RECORD..."); System.out.println (rs.getInt (1)+" "+rs.getString (2)); rs.absolute (3); System.out.println ("THIRD RECORD..."); System.out.println (rs.getInt (1)+" "+rs.getString (2)); rs.last (); System.out.println ("LAST RECORD..."); System.out.println (rs.getInt (1)+" "+rs.getString (2)); rs.previous (); rs.relative (-1); System.out.println ("FIRST RECORD..."); System.out.println (rs.getInt (1)+" "+rs.getString (2)); http://javabynataraj.blogspot.com
  • 36. J2EE (Advanced) JAVA By Mr. K. V. R Page 36 con.close (); } catch (Exception e) { System.out.println (e); } }// main };// ScrollResultSet Day - 18: Updatable ResultSet: Whenever we create a ResultSet object which never allows us to update the database through ResultSet object and it allows retrieving the data only in forward direction. Such type of ResultSet is known as non-updatable and non-scrollable ResultSet. In order to make the ResultSet object as updatable and scrollable we must use the following constants which are present in ResultSet interface. int Type TYPE_SCROLL_SENSITIVE int Mode CONCUR_UPDATABLE The above two constants must be specified while we are creating Statement object by using the following method: For example: Statement st=con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); On ResultSet we can perform the following three operations, they are inserting a record, deleting a record and updating a record. Steps for INSERTING a record through ResultSet object: 1. Decide at which position we are inserting a record by calling absolute method. For example: rs.absolute (3); 2. Since we are inserting a record we must use the following method to make the ResultSet object to hold the record. For example: rs.moveToInsertRow (); http://javabynataraj.blogspot.com
  • 37. J2EE (Advanced) JAVA By Mr. K. V. R Page 37 3. Update all columns of the database or provide the values to all columns of database by using the following generalized method which is present in ResultSet interface. For example: rs.updateInt (1, 5); rs.updateString (2, “abc”); rs.updateInt (3, 80); 4. Upto step-3 the data is inserted in ResultSet object and whose data must be inserted in the database permanently by calling the following method: It throws an exception called SQLException. For example: rs.insertRow (); Steps for DELETING a record through ResultSet object: 1. Decide which record you want to delete. For example: rs.absolute (3); // rs pointing to 3rd record & marked for deletion 2. To delete the record permanently from the database we must call the following method which is present in ResultSet interface. For example: rs.deleteRow (); Steps for UPDATING a record through ResultSet object: 1. Decide which record to update. For example: rs.absolute (2); 2. Decide which columns to be updated. For example: rs.updateString (2, “pqr”); rs.updateInt (3, 91); http://javabynataraj.blogspot.com
  • 38. J2EE (Advanced) JAVA By Mr. K. V. R Page 38 3. Using step-2 we can modify the content of ResultSet object and the content of ResultSet object must be updated to the database permanently by calling the following method which is present in ResultSet interface. For example: rs.updateRow (); Write a java program which illustrates the concept of updatable ResultSet? Answer: import java.sql.*; class UpdateResultSet { public static void main (String [] args) { try { Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); Statement st=con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet. CONCUR_UPDATABLE); ResultSet rs=st.executeQuery ("select * from emp1"); rs.next (); rs.updateInt (2,8000); rs.updateRow (); System.out.println ("1 ROW UPDATED..."); rs.moveToInsertRow (); rs.updateInt (1, 104); rs.updateInt (2, 2000); rs.insertRow (); System.out.println ("1 ROW INSERTED..."); rs.absolute (2); rs.deleteRow (); System.out.println ("1 ROW DELETED..."); con.close (); } catch (Exception e) { e.printStackTrace (); } }// main };// UpdateResultSet NOTE: The scrollability and updatability of a ResultSet depends on the development of the driver of the driver vendors. OracleDriver and JdbcOdbcDriver will support the concept of scrollability and updatability of a ResultSet but there may be same drivers which are available in the industry which are not supporting the concept of scrollability and updatability. http://javabynataraj.blogspot.com
  • 39. J2EE (Advanced) JAVA By Mr. K. V. R Page 39 BATCH PROCESSING In traditional jdbc programming, to perform any transaction (insert, update and delete) we must send a separate request to database. If there is ‘n’ number of transactions then we must make ‘n’ number of request to the database and finally it leads to poor performance. Disadvantages of NON-BATCH PROCESSING applications: 1. There is a possibility of leading the database result in inconsistent in the case of interrelated transactions. 2. Number of Network Round Trips or to and fro calls are more between frontend and backend application. To avoid the above disadvantages we must use batch processing. Batch processing is the process of grouping ‘n’ number of interrelated transactions in a single unit and processing at a same time. Day - 19: Advantages of BATCH PROCESSING: 1. Batch processing always leads consistency of the database. 2. Number of network round trips or to and fro calls will be reduced. Steps for developing BATCH PROCESSING application: 1. Every batch processing application must contain only DML (insert, delete and update) statements. 2. Set the auto commit as false. Since, in jdbc environment by default auto commit is true. In order to make auto commit as false we must use the following method: For example: con.setAutoCommit (false); 3. Prepare set of SQL DML statements and add to batch. For example: st.addBatch (“insert into dept values (10,”abc”,”hyd”)”); 4. Execute batch of DML statements by using the following method: For example: int res []=st.executeBatch (); This method returns individual values of DML statements. http://javabynataraj.blogspot.com
  • 40. J2EE (Advanced) JAVA By Mr. K. V. R Page 40 5. After completion of batch of statements, commit the database by using the following method: For example: con.commit (); 6. If a single batch statement is not executing then we must rollback the database if required to its original state by using the following method: For example: con.rollback (); Write a java program which illustrates the concept of Batch processing? Answer: import java.sql.*; class BatchProConcept { public static void main (String [] args) throws Exception { Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); con.setAutoCommit (false); Statement st=con.createStatement (); st.addBatch ("insert into student values (3, 'j2ee')"); st.addBatch ("delete from student where sno=1"); st.addBatch ("update student set sname='java' where sno=2"); int res []=st.executeBatch (); for (int i=0; i<res.length; i++) { System.out.println ("NUMBER OF ROWS EFFECTED : "+res [i]); } con.commit (); con.rollback (); con.close (); }// main };// BatchProConcept With batch processing we can obtain effective performance to the jdbc applications by executing group of SQL DML statements. Write a java program to create a table through frontend application? Answer: import java.sql.*; class CreateTable http://javabynataraj.blogspot.com
  • 41. J2EE (Advanced) JAVA By Mr. K. V. R Page 41 { public static void main (String [] args) { try { Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println ("DRIVERS LOADED..."); Connection con=DriverManager.getConnection ("jdbc:odbc:oradsn","scott","tiger"); System.out.println ("CONNECTION ESTABLISHED..."); Statement st=con.createStatement (); int i=st.executeUpdate ("create table kalyan (eno number (4), ename varchar2 (15))"); System.out.println ("TABLE CREATED..."); con.close (); } catch (Exception e) { e.printStackTrace (); } }// main };// CreateTable Dealing with DATE • In order to deal with java date or frontend application date we should use a class called java.util.Date • In order to deal with database date or backend application date we should use a class called java.sql.Date • java.sql.Date is the subclass of java.util.Date Converting java.util.Date into java.sql.Date: When we are dealing with frontend application we must always take an object of java.util.Date for representing date and time information but when we are dealing with database date’s we must take an object of java.sql.Date In order to convert java.util.Date into java.sql.Date we have two ways: First way: Read the date in string format For example: System.out.println (“ENTER THE DATE IN DD-MM-YYYY”); String d1=dis.readLine (); To convert string date into java.sql.Date we have the following method: For example: java.sql.Date sd=java.sql.Date.valueOf (d1); Second way: In order to convert string date into java.util.Date we must use the following class: http://javabynataraj.blogspot.com
  • 42. J2EE (Advanced) JAVA By Mr. K. V. R Page 42 For example: SimpleDateFormat sdf=new SimpleDateFormat (“DD-MM-YYYY”); java.util.Date ud=sdf.parse (d1); To convert java.util.Date into java.sql.Date we must use the following statement: For example: java.sql.Date sd=new java.util.Date (ud.getTime ()); Day - 20: SERVLETS Any company want to develop the website that can be developed in two ways, they are static website and dynamic website. • A static website is one where there is no interaction from the end user. To develop static website we can use the markup languages like HTML, DHMTL, XML, JavaScript etc. • A dynamic website is one in which there exist end user interaction. To develop dynamic websites, in industry we have lot of technologies such as CGI (Common Gateway Interface), java, dot net, etc. In the recent years SUN micro systems has developed a technology called Servlets to develop the dynamic websites and also for developing distributed applications. A distributed application is one which always runs in the context of browser or www. The result of distributed application is always sharable across the globe. To develop distributed application one must follow the following: Client-Server architecture: • 2-tier architecture (Client program, Database program). • 3-tier or MVC (Model [Database] View [JSP] Controller [Servlets]) architecture (Client program, Server program, Database program). • n-tier architecture (Client program, Firewall program, Server program, Database program). To exchange the data between client and server we use a protocol caller http which is a part of TCP/IP. • A client is the program which always makes a request to get the service from server. • A server is the program which always receives the request, process the request and gives response to ‘n’ number of clients concurrently. A server is the third party software developed by third party vendors according to SUN micro systems specification. All servers in the industry are developed in java language only. The basic purpose of using server is that to get concurrent access to a server side program. http://javabynataraj.blogspot.com
  • 43. J2EE (Advanced) JAVA By Mr. K. V. R Page 43 According to industry scenario, we have two types of servers; they are web server and application server. WEB SERVER 1. A web server is one which always supports http protocol only. 2. Web server does not contain enough security to prevent unauthorized users. 3. Web server is not able to provide enough services to develop effective server side program. 4. For examples Tomcat server, web logic server, etc. APPLICATION SERVER 1. Any protocol can be supported. 2. An application server always provides 100% security to the server side program. 3. An application server provides effective services to develop server side program. 4. For examples web logic server, web sphere server, pramathi server, etc. NOTE: Web logic server acts as both web server and as well as application server. In the initial days of server side programming there is a concept called CGI and this was implemented in the languages called C and PERL. Because of this approach CGI has the following disadvantages. 1. Platform dependency. 2. Not enough security is provided. 3. Having lack of performance. Since, for each and every request a new and separate process is creating (for example, if we make hundreds of requests, in the server side hundreds of new and separate processes will be created) To avoid the above problems SUN micro system has released a technology called Servlets. A servlet is a simple platform independent, architectural neutral server independent java program which extends the functionality of either web server or application server by running in the context of www. Advantages of SERVLETS over CGI: 1. Servlets are always platform independent. 2. Servlets provides 100% security. 3. Irrespective of number of requests, a single process will be created at server side. Hence, Servlets are known as single instance multiple thread technology. Day - 21: Servlets is the standard specification released by SUN micro systems and it is implemented by various server vendors such as BEA corporation (Web logic server), Apache Jakarta (Tomcat server). In order to run any servlet one must have either application server or web server. In order to deal with servlet programming we must import the following packages: javax.servlet.*; javax.servlet.http.*; http://javabynataraj.blogspot.com
  • 44. J2EE (Advanced) JAVA By Mr. K. V. R Page 44 Servlet Hierarchy: • In the above hierarchy chart Servlet is an interface which contains three life cycle methods without definition. • GenericServlet is an abstract class which implements Servlet interface for defining life cycle methods i.e., life cycle methods are defined in GenericServlet with null body. • Using GenericServlet class we can develop protocol independent applications. • HttpServlet is also an abstract class which extends GenericServlet and by using this class we can develop protocol dependent applications. • To develop our own servlet we must choose a class that must extends either GenericServlet or HttpServlet. LIFE CYCLE METHODS of servlets: In servlets we have three life cycle methods, they are public void init (); public void service (ServletRequest req, ServletResponse res); public void destroy (); public void init (): Whenever client makes a request to a servlet, the server will receive the request and it automatically calls init () method i.e., init () method will be called only one time by the server whenever we make first request. In this method, we write the block of statements which will perform one time operations, such as, opening the file, database connection, initialization of parameters, etc. public void service (ServletRequest, ServletResponse): After calling init () method, service () method will be called when we make first request from second request to further subsequent requests, server will call only service method. Therefore, service () method will be called each and every time as and when we make a request. In service () method we write the block of statements which will perform repeated operations such as retrieving data from database, retrieving data from file, modifications of parameters data, etc. Hence, in service () method we always write business logic. Whenever control comes to service () method the server will create two objects of ServletRequest and ServletResponse interfaces. Object of ServletRequest contains the data which is passed by client. After processing client data, the resultant data must be kept in an object of ServletResponse. An object of ServletRequest and ServletResponse must be used always within the scope of service () method only i.e., we cannot use in init () method and destroy () method. Once the service () method is completed an object of ServletRequest and an object of ServletResponse will be destroyed. public void destroy (): The destroy () method will be called by the server in two situations; they are when the server is closed and when the servlet is removed from server context. In this method we write the block of statements which are obtained in init () method. http://javabynataraj.blogspot.com
  • 45. J2EE (Advanced) JAVA By Mr. K. V. R Page 45 NOTE: Life cycle methods are those which will be called by the server at various times to perform various operations. Write a servlet which displays a message “I LOVE MY MOM”? Answer: import javax.servlet.*; import java.io.*; public class First extends GenericServlet { public First () { System.out.println ("I AM FROM DEFAULT CONSTRUCTOR..."); } public void init () { System.out.println ("I AM FROM init METHOD..."); } public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException { System.out.println ("I LOVE MY MOM..."); System.out.println ("I AM FROM service METHOD..."); } public void destroy () { System.out.println ("I AM FROM destroy METHOD..."); } }; Day - 22: web.xml: 1. Whenever client makes a request to a servlet that request is received by server and server goes to a predefined file called web.xml for the details about a servlet. 2. web.xml file always gives the details of the servlets which are available in the server. 3. If the server is not able to find the requested servlet by the client then server generates an error (resource not found) [A resource is a program which resides in server]. 4. If the requested servlet is available in web.xml then server will go to the servlet, executes the servlet and gives response back to client. Every web.xml will contain the following entries: <web-app> <servlet> <servlet-name>Asha</servlet-name> <servlet-class>First</servlet-class> http://javabynataraj.blogspot.com
  • 46. J2EE (Advanced) JAVA By Mr. K. V. R Page 46 </servlet> <servlet-mapping> < servlet-name>Asha</servlet-name> <url-pattern>Krishna</url-pattern> </servlet-mapping> </web-app> • While server is executing web.xml control goes to <url-pattern> of <servlet-mapping> tag. If the requested url and <url-name> web.xml is same then control goes to <servlet- class> tag of <servlet> and takes the <servlet-name> and executes. • If the <url-pattern> is not matching, server generates an error. How to execute the servlets: In order to execute a servlet we must follow the following directory structure: Day - 23: Steps for DEVELOPING a servlet: 1. Import javax.servlet.*, javax.servlet.http.* and other packages if required. 2. Choose user defined class. 3. Whichever class we have chosen in step-2 must extend either GenericServlet or HttpServlet. 4. Override the life cycle methods if required. FLOW OF EXECUTION in a servlet: 1. Client makes a request. The general form of a request is http://(IP address or DNS [Domain Naming Service] name of the machine where server is installed) : (port number of the server) / (Document root) : (Resource name). For example: http://localhost:7001/DateSer/suman http://javabynataraj.blogspot.com
  • 47. J2EE (Advanced) JAVA By Mr. K. V. R Page 47 2. Server receives the request. 3. Server will scan web.xml (contains declarative details) if the requested resource is not available in web.xml server generates an error called resource not available otherwise server goes to a servlet. 4. Server will call the servlet for executing. 5. Servlet will execute in the context of server. 6. While server is executing a servlet, server loads an object of servlet class only once (by calling default constructor). 7. After loading the servlet, the servlet will call init () method only once to perform one time operations. 8. After completion of init () method, service () method will be called each and every time. As long as we make number of requests only service () method will be called to provide business logic. 9. Servlet will call destroy () method either in the case of servlet is removed or in the case of server is closed. HOW TO EXECUTE a servlet: 1. Prepare a directory structure. 2. Write a servlet program save it into either document root or document rootSRC. 3. Compile a servlet by setting a classpath. For Tomcat: Set classpath= 4. Copy *.class file into document root/WEB-INF/classes folder and write web.xml file. 5. Start the server and copy document root into: 6. Open the browser and pass a request or url Write a servlet which displays current system date and time? Answer: Servlet program: (Since, it’s a package to compile use javac –d . DateServ.java) package ds; import javax.servlet.*; import java.io.*; import java.util.*; public class DateServ extends GenericServlet { public DateServ () { System.out.println ("SERVLET LOADED..."); } public void init () { System.out.println ("I AM FROM init METHOD..."); } public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter pw=res.getWriter (); Date d=new Date (); String s=d.toString (); http://javabynataraj.blogspot.com
  • 48. J2EE (Advanced) JAVA By Mr. K. V. R Page 48 pw.println ("<h1> WELCOME TO SERVLETS <h1>"); pw.println ("<h2> CURRENT DATE & TIME IS : "+s+"<h2>"); } public void destroy () { System.out.println ("I AM FROM destroy METHOD..."); } }; web.xml: <web-app> <servlet> <servlet-name>kalyan</servlet-name> <servlet-class>ds.DateServ</servlet-class> </servlet> <servlet-mapping> <servlet-name>kalyan</servlet-name> <url-pattern>/suman</url-pattern> </servlet-mapping> </web-app> Day - 24: HttpServlet: • HttpServlet is the sub-class of GenericServlet. • HttpServlet contains all the life cycle methods of GenericServlet and the service () method of GenericServlet is further divided into the following two methods, they are public void doGet (HttpServletRequest, HttpServletResponse) throws ServletException, IOException public void doPost (HttpServletRequest, HttpServletResponse) throws ServletException, IOException • Whenever client makes a request, the servlet container (server) will call service () method, the service () method depends on type of the method used by the client application. • If client method is get then service () method will call doGet () method and doGet () method internally creates the objects of HttpServletRequest and HttpServletResponse. Once doGet () method is completed its execution, the above two objects will be destroyed. LIMITATIONS of get method: 1. Whatever data we sent from client by using get method, the client data will be populated or appended as a part of URL. For example: http://localhost:7001/servlet/DDservlet?uname=scott&pwd=tiger 2. Large amount of data cannot be transmitted from client side to server side. • When we use post method to send client data, that data will be send as a part of method body and internally the service () method will called doPost () method by creating the objects of HttpServletRequest and HttpServletResponse. ADVANTAGES of post method: 1. Security is achieved for client data. 2. We can send large amount of data from client to server. http://javabynataraj.blogspot.com
  • 49. J2EE (Advanced) JAVA By Mr. K. V. R Page 49 • HttpServletRequest extends ServletRequest and HttpServletResponse extends ServletResponse. • HttpServlet, HttpServletRequest and HttpServletResponse belong to a package called javax.servlet.http.* • The request which we make from the client side that requests are known as http requests where as the responses which are given by a servlet are known as http responses. NOTE: All real world applications always extends HttpServlet only and it is always recommended to overwrite either doGet () method or doPost () method. Associated with servlet we have three names which are specified in web.xml, they are public URL name (known to everybody), deployer URL name or dummy name (known to that person who is deploying) and secret or internal URL name (known to servlet container or server). • The purpose of <servlet-mapping> is that it maps public URL name to deployer URL name. • The purpose of <servlet> is that it maps deployer URL name to actual Servlet class name. Write a servlet which retrieves the data from database? Answer: Servlet program: package ddrs; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.io.*; public class RetrieveDataBaseServ extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) { res.setContentType ("text/html"); PrintWriter pw=res.getWriter (); try { DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ()); Connection con=DriverManager.getConnection ("oracle:jdbc:thin:@localhost:1521: Hanuman", "scott","tiger"); Statement st=con.createStatement (); ResultSet rs=st.executeQuery ("select * from emp"); while (rs.next ()) { pw.println (rs.getString (1)+" "+rs.getString (2)); } } catch (Exception e) { res.sendError (504,"PROBLEM IN SERVLET..."); } } }; http://javabynataraj.blogspot.com
  • 50. J2EE (Advanced) JAVA By Mr. K. V. R Page 50 web.xml: <web-app> <servlet> <servlet-name>Babu</servlet-name> <serclet-class>ddrs.RetrieveDataBaseServ</servlet-class> </servlet> <servlet-mapping> <servlet-name>Babu</servlet-name> <url-pattern>Dinesh</url-pattern> </servlet-mapping> </web-app> Day - 25: In the above program we are making use of ‘n’ number of servlet classes, OracleDriver class; it is required to set the classpath for servlet-Api.jar and classes111.jar For weblogic: set classpath=F:beaweblogic81serverlibweblogic.jar;F:oracleora92jdbc libclasses111.jar; For Tomcat: set classpath=F:Program FilesApache Software FoundationTomcat 5.5common libservlet-api.jar;F:oracleora92jdbclibclasses111.jar; When we run the above program on weblogic, it is not necessary to copy classes111.jar into lib folder of document root. Since, the weblogic server itself contains an existing jar file called ojdbc14.jar to deal with OracleDriver. How to generate a war file: A war file is the compressed form of ‘n’ number of .class files, web.xml, *.html files and the jar files available in lib folder. Syntax: jar cfv (name of the war file) WEB-INF [*.html] [*.jsp] Here, in cfv, ‘c’ represents create, ‘f’ represents file and ‘v’ represents verbose (used to compress) Copy the war file from the current directory and paste it into applications folder of weblogic or webapps folder of Tomcat. ServletConfig (one per SERVLET): • ServletConfig is an interface which is present in javax.servlet.* package. • The purpose of ServletConfig is to pass some initial parameter values, technical information (driver name, database name, data source name, etc.) to a servlet. • An object of ServletConfig will be created one per servlet. • An object of ServletConfig will be created by the server at the time of executing public void init (ServletConfig) method. • An object of ServletConfig cannot be accessed in the default constructor of a Servlet class. Since, at the time of executing default constructor ServletConfig object does not exist. http://javabynataraj.blogspot.com
  • 51. J2EE (Advanced) JAVA By Mr. K. V. R Page 51 • By default ServletConfig object can be accessed with in init () method only but not in doGet and doPost. In order to use, in the entire servlet preserve the reference of ServletConfig into another variable and declare this variable into a Servlet class as a data member of ServletConfig. For example: class x extends HttpServlet Day - 26: • When we want to give some global data to a servlet we must obtain an object of ServletConfig. • web.xml entries for ServletConfig <servlet> …………. <init-param> <param-name>Name of the parameter</param-name> <param-value>Value of the parameter</param-value> </init-param> …………. </servlet> For example: <servlet> <servlet-name>abc</servlet-name> <servlet-class>serv1</servlet-class> <init-param> <param-name>v1</param-name> <param-value>10</param-value> </init-param> <init-param> <param-name>v2</param-name> <param-value>20</param-value> </init-param> </servlet> The data which is available in ServletConfig object is in the form of (key, vlaue) OBTAINING an object of ServletConfig: An object of ServletConfig can be obtained in two ways, they are by calling getServletConfig () method and by calling init (ServletConfig). By calling getServletConfig () method: getServletConfig () is the method which is available in javax.servlet.Servlet interface. This method is further inherited and defined into a class called javax.servlet.GenericServlet and that method is further inherited into another predefined class called javax.servlet.http.HttpServlet and it can be inherited into our own servlet class. For example: public class serv1 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { http://javabynataraj.blogspot.com
  • 52. J2EE (Advanced) JAVA By Mr. K. V. R Page 52 ………… ………… ServletConfig config=this.getServletConfig (); ………… ………… } }; In the above example an object config contains (key, value) pair data of web.xml file which are written under <init-param> tag of <servlet> tag. By calling init (ServletConfig): For example: public class serv2 extends HttpServlet { ServletConfig sc; public void init (ServletConfig sc) { Super.init (sc); // used for calling init (ServletConfig) method of HttpServlet this.sc=sc; // ServletConfig object sc is referenced } ………… ………… }; RETRIEVING DATA from ServletConfig interface object: In order to get the data from ServletConfig interface object we must use the following methods: public String getInitParameter (String); 1 public Enumeration getInitParameterNames (); 2 Method-1 is used for obtaining the parameter value by passing parameter name. String val1=config.getInitParameter (“v1”); String val2=config.getInitParameter (“v2”); String val3=config.getInitParameter (“v3”); Method-2 is used for obtaining all parameter names and their corresponding parameter values. For example: Enumeration en=config.getInitParameterNames (); while (en.hasMoreElements ()) { Object obj=en.nextElement (); String pname= (String) obj; String pvalue=config.getInitParameter (pname); out.println (pvalue+” is the value of ”+pname); http://javabynataraj.blogspot.com
  • 53. J2EE (Advanced) JAVA By Mr. K. V. R Page 53 } Day - 27: Serv1.java: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class Serv1 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter pw=res.getWriter (); ServletConfig config=getServletConfig (); String val1=config.getInitParameter ("v1"); String val2=config.getInitParameter ("v2"); String val3=config.getInitParameter ("v3"); String val4=config.getInitParameter ("v4"); pw.println ("<h3> Value of v1 is "+val1+"</h3>"); pw.println ("<h3> Value of v2 is "+val2+"</h3>"); pw.println ("<h3> Value of v3 is "+val3+"</h3>"); pw.println ("<h3> Value of v4 is "+val4+"</h3>"); } }; Serv2.java: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class Serv2 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter pw=res.getWriter (); ServletConfig config=getServletConfig (); Enumeration en=config.getInitParameterNames (); while (en.hasMoreElements ()) { Object obj=en.nextElement (); String pname= (String) obj; String pvalue=config.getInitParameter (pname); pw.println ("</h2>"+pvalue+" is the value of "+pname+"</h2>"); } } }; web.xml: <web-app> <servlet> <servlet-name>abc</servlet-name> <servlet-class>Serv1</servlet-class> http://javabynataraj.blogspot.com
  • 54. J2EE (Advanced) JAVA By Mr. K. V. R Page 54 <init-param> <param-name>v1</param-name> <param-value>10</param-value> </init-param> <init-param> <param-name>v2</param-name> <param-value>20</param-value> </init-param> </servlet> <servlet> <servlet-name>pqr</servlet-name> <servlet-class>Serv2</servlet-class> <init-param> <param-name>v3</param-name> <param-value>30</param-value> </init-param> <init-param> <param-name>v4</param-name> <param-value>40</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/firstserv</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>pqr</servlet-name> <url-pattern>/secondserv</url-pattern> </servlet-mapping> </web-app> Develop a flexible servlet that should display the data of the database irrespective driver name, table name and dsn name? Answer: DbServ.java: import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.io.*; public class DbServ extends HttpServlet { ServletConfig sc=null; public void init (ServletConfig sc) throws ServletException { super.init (sc); this.sc=sc; } public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter pw=res.getWriter (); String dname=sc.getInitParameter ("dname"); String url=sc.getInitParameter ("url"); String tab=sc.getInitParameter ("tab"); try http://javabynataraj.blogspot.com
  • 55. J2EE (Advanced) JAVA By Mr. K. V. R Page 55 { Class.forName (dname); Connection con=DriverManager.getConnection (url,"scott","tiger"); Statement st=con.createStatement (); ResultSet rs=st.executeQuery ("select * from "+tab); while (rs.next ()) { pw.println ("<h2>"+rs.getString (1)+""+rs.getString (2)+""+rs.getString (3)+"</h2>"); } con.close (); } catch (Exception e) { res.sendError (503,"PROBLEM IN DATABASE..."); } } }; web.xml: <web-app> <servlet> <servlet-name>abc</servlet-name> <servlet-class>DbServ</servlet-class> <init-param> <param-name>dname</param-name> <param-value>oracle.jdbc.driver.OracleDriver ()</param-value> </init-param> <init-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin:@localhost:1521:Hanuman</param-value> </init-param> <init-param> <param-name>tab</param-name> <param-value>emp</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/dbdata</url-pattern> </servlet-mapping> </web-app> Day - 28: ServletContext (one per WEB APPLICATION): • ServletContext is an interface which is present in javax.servlet.* package. • Whenever we want to give a common data or global data to the group of servlets which belongs to same web application then we must create an object of ServletContext interface. • An object of ServletContext will be created by servlet container (server) whenever we deploy into the server. • In order to provide a common data to a group of servlets, we must write that data into web.xml file with the tag called <context-param>…</context-param>. This tag must be written with in <web-app>…</web-app> before <servlet>. http://javabynataraj.blogspot.com
  • 56. J2EE (Advanced) JAVA By Mr. K. V. R Page 56 • xml entries related to ServletContext interface. <web-app> <context-param> <param-name>Name of the param</param-name> <param-value>Value of the param</param-value> </context-param> <servlet> ………….. ………….. </servlet> <servlet-mapping> ………….. ………….. </servlet-mapping> </web-app> • Whatever the data we write with in <context-param>…</context-param> that data will be paste automatically in the object of ServletContext interface and this object contains the in the form of (key, value) pair. Here, key represents context parameter name and value represents context parameter value. • The value of key must be always unique; if duplicate values are placed we get recent duplicate value for the key by overlapping previous values. For example: <web-app> <context-param> <param-name>driver</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin:@localhost:1521:Hanuman</param-value> </context-param> <servlet> ………….. ………….. </servlet> <servlet-mapping> ………….. ………….. </servlet-mapping> </web-app> Number of ways to OBTAIN AN OBJECT of ServletContext: In order to get an object of ServletContext we have two ways, they are by calling getServletContext () method directly and by making use of ServletConfig interface. By using getServletContext () method: getServletContext () method is defined in GenericServlet and it is inherited into HttpServlet and it is further inherited into our own servlet class. Hence, we can call getServletContext () method directly. For example: public class Serv1 extends HttpServlet { http://javabynataraj.blogspot.com
  • 57. J2EE (Advanced) JAVA By Mr. K. V. R Page 57 public doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { …………… …………… ServletContext ctx=this.getServletContext (); …………… …………… } }; By using ServletConfig interface: In ServletConfig interface we have the following method which gives an object of ServletContext. In order to call the above method first we must obtain an object of ServletConfig interface and later with that object we can call getServletContext () method. For example: public class Serv2 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ………… ………… ServletConfig config=this.getServletConfig (); ServletContext ctx=config.getServletContext (); …………. …………. } }; Number of ways to RETRIEVE THE DATA from an OBJECT of ServletContext: In ServletContext interface we have the following methods to retrieve the value of context parameter by passing context parameter name. For example: ServletContext ctx=getServletContext (); String val1=ctx.getInitParameter (“v1”); String val2=ctx.getInitParameter (“v2”); For example: ServletContext ctx=getServletContext (); Enumeration en=ctx.getInitParameterNames (); While (en.hasMoreElements ()) { String cpn= (String) en.nextElement (); String cpv=ctx.getInitParameter (cpn); pw.println (cpv+” is the value of ”+cpn); } http://javabynataraj.blogspot.com
  • 58. J2EE (Advanced) JAVA By Mr. K. V. R Page 58 Differences between ServletConfig and ServletContext interfaces: ServletConfig 1. An object of ServletConfig exists one per servlet. 2. An object of ServletConfig will be created when init (ServletConfig) method is executed. 3. ServletConfig object contains a specific data to a particular servlet. 4. The data to a servlet which related to ServletConfig object must be written in <init-param>…</init-param> with in <servlet>…</servlet> of web.xml 5. An object of ServletConfig will exists as long as a specific servlet is executing. ServletContext 1. An object of ServletContext exists one per web application. 2. An object of ServletContext will be created when we deploy the web application in servlet container or servlet execution environment. 3. ServletContext object contains a common or global data to ‘n’ number of servlets and ‘n’ number of JSP’s. 4. The common data or global data related to ServletContext must be written under <context-param>…</context-param> with in <web-app>…</web-app> and outside of <servlet>…</servlet> of web.xml 5. An object of ServletContext will exists until the entire web application completed its execution. Day - 29: Write a servlet which illustrate the concept of ServletContext? Answer: web.xml: <web-app> <context-param> <param-name>v1</param-name> <param-value>10</param-value> </context-param> <context-param> <param-name>v2</param-name> <param-value>20</param-value> </context-param> <servlet> <servlet-name>abc</servlet-name> <servlet-class>Serv1</servlet-class> <init-param> <param-name>v3</param-name> <param-value>30</param-value> </init-param> </servlet> <servlet> <servlet-name>pqr</servlet-name> http://javabynataraj.blogspot.com