Advanced JAVA
Advanced JAVA
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
3-tier architecture is also known as MVC architecture. M stands for Model (database
3. The server looks for or search for the appropriate resource in the resource pool.
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
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.”
constructors).
6. Determining modifiers of the class (modifiers of the class can be public, final, public + final,
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
Number of ways to obtain runtime information about a class (or) number of ways to get an object
The predefined class called Class is present in a package called java.lang.Class (fully
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
2) When we know the object name at runtime, to get the class name or class type of the
Answer:
class First
printSuperclass (s);
};
Output:
java First
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:
For example:
try
forName is taking String as an argument. If the class is not found forName method
Here, forName method is a factory method (a factory method is one which return type is
method is known as Singleton class (a java class is said to be Singleton class through which
For example:
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
if (args.length==0)
else
try
printSuperclass (c);
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:
For example:
try
forName is taking String as an argument. If the class is not found forName method
Here, forName method is a factory method (a factory method is one which return type is
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
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
if (args.length==0)
else
try
printSuperclass (c);
By Mr. K. V. R Page 5
{
System.out.println (args [0]+" DOES NOT EXISTS...");
}// else
}// main
}// printSuperclass
}// ref1
Output:
Write a java program to print super class hierarchy at a current class which is passed from command
prompt?
Answer:
class Hierarchy
if (args.length==0)
else
try
printHierarchy (c);
Class c1=c;
System.out.println (cname);
while (sc!=null)
cname=sc.getName ();
System.out.println (cname);
c1=sc;
sc=c1.getSuperclass ();
By Mr. K. V. R Page 6
};
Output:
java.awt.TextField
java.awt.TextComponent
java.awt.Component
java.lang.Object
In order to get the constructor of the current class we must use the following method:
For example:
In order to get the parameters of the constructor we must use the following method:
For example:
Day - 5:
Write a java program to obtain constructors of a class?
Answer:
class ConsInfo
if (args.length==0)
else
try
printConsts (c);
By Mr. K. V. R Page 7
System.out.println ("\b"+")");
};
In order to obtain information about methods we must use the following methods:
For example:
Method-1 gives return type of the method, Method-2 gives name of the method and
Write a java program to obtain information about methods which are present in a class?
Answer:
import java.lang.reflect.*;
class MetInfo
try
if (args.length==0)
else
printMethods (c);
}
System.out.print (ptype+",");
}
System.out.println ("\b"+")");
};
In order to obtain information about fields or data members of the class we must use the following
method.
For example:
Associated with field or data member there is a data type and field name:
Method-1 is used for obtaining data type of the field and Method-2 is used for obtaining
Answer:
import java.lang.reflect.Field;
class Fields
{
J2EE (Advanced) JAVA
By Mr. K. V. R Page 9
};
class FieldsDemo
if (args.length==0)
else
try
{
fs.printFields (c);
};
Day - 6:
permanently”.
In Information Technology we have two approaches’ to store the data permanently. They
Whatever data we store permanently in the form of a file, the file will not provide enough
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.
java.io.Serializable
By Mr. K. V. R Page 10
2. Choose the user defined class whose object participates in Serializable process.
3. Every user defined class must implements a predefined interface called Serializable.
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
For example:
import java.io.*;
public class Emp implements Serializable // Emp (step-2) & Serializable (step-3)
int empno;
String ename;
float sal;
this.empno=empno;
this.ename=ename;
this.sal=sal;
return empno;
return ename;
return sal;
};
Day - 7:
Serializable process:
For example:
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:
4. Since an object of FileOutputStream cannot write the entire object at a time to the file.
FileOutputStream class.
For example:
5. In order to write the entire object at a time to the file ObjectOutputStream contains the
following method:
For example:
oos.writeObject (eo);
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
By Mr. K. V. R Page 12
eo.setEmpno (100);
eo.setEname ("KVR");
eo.setSal (10000.00f);
oos.writeObject (eo);
oos.close ();
fos.close ();
};
Output:
De-Serializable process: It is the process of retrieving the record from the file into main memory of
the computer.
For example:
2. Choose the file name and open it into read mode with the help of FileInputStream class.
For example:
3. Since an object of FileInputStream cannot read the entire object at a time from the file.
For example:
4. ObjectInputStream class contains the following method which will read the entire object at a
By Mr. K. V. R Page 13
For example:
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:
6. Apply set of get methods to obtain the data from de-serialized object i.e., eo1.
For example:
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
ois.close ();
fis.close ();
};
Output:
EMP NO : 100
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.
By Mr. K. V. R Page 14
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
3. Manual serialization:
called java.io.Serializable. The interface Serializable does not contain any abstract methods
4. Automatic serialization:
It is one in which the user defined derived class extends sub class of Serializable
interface.
For example:
.................;
.................;
};
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
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
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’
In later stages SUN micro systems has developed a general specification called JDBC which
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
By Mr. K. V. R Page 15
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
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:
............;
............;
............;
};
In database world, each and every database vendor has developed their drivers and released
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 is nothing but creating an object of appropriate Driver class. In order to
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.
By Mr. K. V. R Page 16
For example:
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:
Day - 10:
How to obtain the connection: After loading the drivers, it is required to obtain the 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
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:
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:
In the interface java.sql.Connection we have the following method for obtaining an object of
Statement interface.
By Mr. K. V. R Page 17
For example:
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
Write a jdbc program which will insert a record in the Student database?
Answer:
import java.sql.*;
class InsertRec
try
DriverManager.registerDriver (d);
con.close ();
catch (Exception e)
};
Day - 11:
In order to execute the select statement or in order to retrieve the data from database we
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
For example:
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
In order to obtain the data of the record (collection of field values) we must use the
following method:
Whatever the data retrieving from the record that data will be treated as string data.
For example:
Answer:
import java.sql.*;
class SelectData
con.close ();
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
2. Whenever we get the database data in ResultSet object which will be temporarily
3. ResultSet object does not allows us to perform any modifications on ResultSet object.
1. Dynamic queries are those for which the data is passed at runtime.
Answer:
Statement PreparedStatement
1. This interface is used for executing static
queries.
dynamic queries.
time.
place.
For example:
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.
By Mr. K. V. R Page 20
In order to set the values to the positional parameters, we must use the following methods which
In general PreparedStatement interface contains the following generalized method to set the values
Here, int represents position number of the positional parameter. XXX represents value of
For example:
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.
For example:
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
Answer:
import java.sql.*;
import java.io.*;
class InsertRecRun
{
try
By Mr. K. V. R Page 21
BudDinu","scott","tiger");
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
try
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
con.close ();
catch (Exception e)
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
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
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
set CLASSPATH=C:\oracle\ora92\jdbc\lib\classes111.jar;.;
For example:
Class.forName (“oracle.jdbc.driver.OracleDriver”);
In order to obtain the connection from oracle database we must follow the following syntax:
J2EE (Advanced) JAVA
By Mr. K. V. R Page 23
For example:
In order to obtain port number and service ID of oracle database we must look for tnsnames.ora
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.
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
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
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:
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;
Create an oracle procedure which takes two input numbers and it must return sum of two numbers,
Answer:
as
begin
n1:=a+b;
n2:=a*b;
n3:=a-b;
end;
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.
For example:
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
For example:
3. Specify which input parameters are by using the following generalized method:
For example:
By Mr. K. V. R Page 25
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
All the data members which are available in Types class are belongs to public static final
data members.
For example:
For example:
cs.execute ();
Here, int represents position of out parameter. XXX represents fundamental data type or
string or date.
For example:
Day - 14:
Answer:
StuFun:
as
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
BudDinu","scott","tiger");
cs.execute ();
catch (Exception e)
e.printStackTrace ();
}// main
}// FunConcept
Answer:
StuPro:
as
begin
By Mr. K. V. R Page 27
where deptno=no;
end;
ProConcept.java:
import java.sql.*;
import java.io.*;
class ProConcept
try
BudDinu","scott","tiger");
cs.setInt (1,n1);
cs.execute ();
catch (Exception e)
System.out.println (e);
}// main
}// ProConcept
In real world applications, there is a possibility of retrieving the data from conventional data
1. Create an excel sheet, enter the column names along with data, rename the sheet1 as user
By Mr. K. V. R Page 28
For example:
D:\advanced\jdbc\stbook.xls
NOTE: In order to refer excel sheet name as a database sheet name we should use the format
[<sheet name> $]
Answer:
import java.sql.*;
class XSelect
try
By Mr. K. V. R Page 29
{
System.out.println (rs.getString (1)+" "+rs.getString (2)+" "+rs.getString (3));
con.close ();
sqle.printStackTrace ();
}// main
};// XSelect
Day - 15:
Metadata:
Data about data is known as metadata. Metadata can be obtained at two levels, they are
In order to obtain user database details we must follow the following procedure:
ResultSet.
For example:
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
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:
Connection interface.
For example:
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,
Answer:
import java.sql.*;
class MetaData
try
con.close ();
catch (Exception e)
e.printStackTrace ();
}// main
};// MetaData
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
{
try
System.out.println ("==================================================");
System.out.println ("");
System.out.println ("==================================================");
System.out.println ("");
}
con.close ();
sqle.printStackTrace ();
}// main
};// Table
Day - 16:
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
By Mr. K. V. R Page 32
In order to avoid recompiling a jdbc application we must develop a flexible jdbc application
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.
1. In order to read the data from resource bundle file, open the resource bundle file in read
For example:
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:
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:
For example:
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
Answer:
rbfdb.prop:
Dname=oracle.jdbc.driver.OracleDriver
URL=jdbc:oracle:thin:@127.0.0.1:1521:oradsn
Uname=scott
By Mr. K. V. R Page 33
Pwd=tiger
Tablename=student
RBFConcept:
import java.sql.*;
import java.io.*;
import java.util.*;
class RBFConcept
{
try
p.load (fis);
Class.forName (dname);
// executing query
System.out.println ("=================================");
}
System.out.println ("");
System.out.println ("=================================");
con.close ();
catch (Exception e)
e.printStackTrace ();
}// main
};// RSFConcept
direction only and we cannot perform any modifications on ResultSet object. Therefore, by default
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
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:
The following methods which are available in ResultSet interface which allows us to retrieve the data
• Method-2 is used for making the ResultSet object to point to just before the first record (it is
by default).
• Method-5 returns true when rs pointing to before first record otherwise false.
• Method-7 is used for making the ResultSet object to point to just after the last record.
• 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
Answer:
import java.sql.*;
class ScrollResultSet
try
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
CONCUR_READ_ONLY);
rs.first ();
rs.absolute (3);
rs.last ();
rs.previous ();
rs.relative (-1);
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
In order to make the ResultSet object as updatable and scrollable we must use the following
int Type
TYPE_SCROLL_SENSITIVE
int Mode
CONCUR_UPDATABLE
The above two constants must be specified while we are creating Statement object by using
For example:
On ResultSet we can perform the following three operations, they are inserting a record,
deleting a record and updating a record.
For example:
rs.absolute (3);
2. Since we are inserting a record we must use the following method to make the ResultSet
For example:
rs.moveToInsertRow ();
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
For example:
4. Upto step-3 the data is inserted in ResultSet object and whose data must be inserted in the
rs.insertRow ();
For example:
2. To delete the record permanently from the database we must call the following method
For example:
rs.deleteRow ();
For example:
rs.absolute (2);
For example:
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 ();
Answer:
import java.sql.*;
class UpdateResultSet
try
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
CONCUR_UPDATABLE);
rs.next ();
rs.updateInt (2,8000);
rs.updateRow ();
rs.moveToInsertRow ();
rs.updateInt (1, 104);
rs.insertRow ();
rs.absolute (2);
rs.deleteRow ();
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
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.
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.
Day - 19:
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:
For example:
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
For example:
con.rollback ();
Answer:
import java.sql.*;
class BatchProConcept
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
con.setAutoCommit (false);
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.
Answer:
import java.sql.*;
class CreateTable
By Mr. K. V. R Page 41
try
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
int i=st.executeUpdate ("create table kalyan (eno number (4), ename varchar2 (15))");
con.close ();
catch (Exception e)
{
e.printStackTrace ();
}// main
};// CreateTable
• 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
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
First way:
For example:
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:
By Mr. K. V. R Page 42
For example:
For example:
Day - 20:
SERVLETS
Any company want to develop the website that can be developed in two ways, they are
• 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),
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
Client-Server architecture:
• 3-tier or MVC (Model [Database] View [JSP] Controller [Servlets]) architecture (Client
• 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
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.
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
users.
APPLICATION SERVER
program.
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.
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
To avoid the above problems SUN micro system has released a technology called Servlets.
program which extends the functionality of either web server or application server by running in the
context of www.
3. Irrespective of number of requests, a single process will be created at server side. Hence,
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
javax.servlet.*;
javax.servlet.http.*;
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.
• HttpServlet is also an abstract class which extends GenericServlet and by using this class we
• To develop our own servlet we must choose a class that must extends either GenericServlet
or HttpServlet.
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
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.
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
Object of ServletRequest contains the data which is passed by client. After processing client
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.
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
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.
Answer:
import javax.servlet.*;
import java.io.*;
public First ()
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
};
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
4. If the requested servlet is available in web.xml then server will go to the servlet, executes
<web-app>
<servlet>
<servlet-name>Asha</servlet-name>
<servlet-class>First</servlet-class>
By Mr. K. V. R Page 46
</servlet>
<servlet-mapping>
< servlet-name>Asha</servlet-name>
<url-pattern>Krishna</url-pattern>
</servlet-mapping>
</web-app>
tag. If the requested url and <url-name> web.xml is same then control goes to <servlet-
Day - 23:
3. Whichever class we have chosen in step-2 must extend either GenericServlet or HttpServlet.
1. Client makes a request. The general form of a request is http://(IP address or DNS
For example:
http://localhost:7001/DateSer/suman
By Mr. K. V. R Page 47
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.
6. While server is executing a servlet, server loads an object of servlet class only once (by
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.
2. Write a servlet program save it into either document root or document root\SRC.
For Tomcat:
Set classpath=
4. Copy *.class file into document root/WEB-INF/classes folder and write web.xml file.
Answer:
package ds;
import javax.servlet.*;
import java.io.*;
import java.util.*;
public DateServ ()
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
res.setContentType ("text/html");
By Mr. K. V. R Page 48
}
public void destroy ()
};
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 contains all the life cycle methods of GenericServlet and the service () method of
GenericServlet is further divided into the following two methods, they are
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
method is completed its execution, the above two objects will be destroyed.
1. Whatever data we sent from client by using get method, the client data will be populated or
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
By Mr. K. V. R Page 49
ServletResponse.
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
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.
Answer:
Servlet program:
package ddrs;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
res.setContentType ("text/html");
try
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver ());
Hanuman", "scott","tiger");
catch (Exception e)
};
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;
For weblogic:
set classpath=F:\bea\weblogic81\server\lib\weblogic.jar;F:\oracle\ora92\jdbc\
lib\classes111.jar;
For Tomcat:
lib\servlet-api.jar;F:\oracle\ora92\jdbc\lib\classes111.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
A war file is the compressed form of ‘n’ number of .class files, web.xml, *.html files and the
Syntax:
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
• The purpose of ServletConfig is to pass some initial parameter values, technical information
• An object of ServletConfig will be created by the server at the time of executing public void
Since, at the time of executing default constructor ServletConfig object does not exist.
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:
Day - 26:
• When we want to give some global data to a servlet we must obtain an object of
ServletConfig.
<servlet>
.............
<init-param>
</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)
An object of ServletConfig can be obtained in two ways, they are by calling getServletConfig
method is further inherited into another predefined class called javax.servlet.http.HttpServlet and it
For example:
By Mr. K. V. R Page 52
............
............
............
............
};
In the above example an object config contains (key, value) pair data of web.xml file which
For example:
{
ServletConfig sc;
............
............
};
In order to get the data from ServletConfig interface object we must use the following
methods:
Method-1 is used for obtaining the parameter value by passing parameter name.
Method-2 is used for obtaining all parameter names and their corresponding parameter values.
For example:
{
Object obj=en.nextElement ();
By Mr. K. V. R Page 53
Day - 27:
Serv1.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
res.setContentType ("text/html");
};
Serv2.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
res.setContentType ("text/html");
};
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
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
Answer:
DbServ.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
ServletConfig sc=null;
super.init (sc);
this.sc=sc;
res.setContentType ("text/html");
try
By Mr. K. V. R Page 55
Class.forName (dname);
con.close ();
catch (Exception e)
};
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:
• 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.
• 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
By Mr. K. V. R Page 56
• xml entries related to ServletContext interface.
<web-app>
<context-param>
</context-param>
<servlet>
..............
..............
</servlet>
<servlet-mapping>
..............
..............
</servlet-mapping>
</web-app>
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
• The value of key must be always unique; if duplicate values are placed we get recent
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>
In order to get an object of ServletContext we have two ways, they are by calling
and it is further inherited into our own servlet class. Hence, we can call getServletContext () method
directly.
For example:
{
J2EE (Advanced) JAVA
By Mr. K. V. R Page 57
...............
...............
...............
...............
};
ServletContext.
In order to call the above method first we must obtain an object of ServletConfig interface
For example:
............
............
ServletConfig config=this.getServletConfig ();
.............
.............
};
In ServletContext interface we have the following methods to retrieve the value of context
For example:
For example:
}
J2EE (Advanced) JAVA
By Mr. K. V. R Page 58
ServletConfig
per servlet.
method is executed.
in <init-param>...</init-param>
with in <servlet>...</servlet> of
web.xml
executing.
ServletContext
1. An object of ServletContext exists one per
web application.
number of JSP’s.
<context-param>...</context-param> with
<servlet>...</servlet> of web.xml
execution.
Day - 29:
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>
By Mr. K. V. R Page 59
<servlet-class>Serv2</servlet-class>
<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>
Serv1.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
res.setContentType ("text/html");
};
Serv2.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
res.setContentType ("text/html");
};
• Whenever we want to send an input to a servlet that input must be passed through html
form.
• An html form is nothing but various controls are inherited to develop an application.
• Every form will accept client data end it must send to a servlet which resides in server side.
• Since html is a static language which cannot validate the client data. Hence, in real time
applications client data will be accepted with the help of html tags by developing form and
2. To develop various controls through <input>...</input> tag and all <input> tag must be
<form name=”name of the form” action=”either absolute or relative address” method=”get or post”>
.....................
.....................
</form>
Answer:
<html>
<head><center><h3>Personal Information</h3></center></head>
<body bgcolor="#D8BFD8">
<center>
<tr>
</tr>
<tr>
By Mr. K. V. R Page 61
</tr>
<tr>
</tr>
</table>
</center>
</form>
</body>
</html>
In order to handle or obtain the data html form in a servlet, we have the following method
For example:
Day - 30:
Write a servlet which accepts client request and display the client requested data on the browser?
Answer:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
res.setContentType ("text/html");
By Mr. K. V. R Page 62
};
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DataServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/getdata</url-pattern>
</servlet-mapping>
</web-app>
NOTE:
1. Whenever we are not entering the data in html form that data will be treated as empty
space.
2. Query string represents the data which is passed by client to the servlet through html form.
URI stands for Uniform Resource Indicator which gives the location of servlet where it is
available. URL stands for Uniform Resource Locator which gives at which port number, in
which server a particular JSP or servlet is running. ht represents a context path which can be
Day - 31:
Write a servlet which accepts product details from html form and stores the product details into
database?
Answer:
Product database:
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DatabaServ</servlet-class>
</servlet>
By Mr. K. V. R Page 63
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/getdata</url-pattern>
</servlet-mapping>
</web-app>
prodata.html:
<html>
<title>Product Data</title>
<head><center><h2>Product Information</h2></center></head>
<body bgcolor="#BDB76B">
<center>
<tr>
<th>Enter product id : </th>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<table>
<tr>
</tr>
</table>
</tr>
</table>
</form>
</center>
</body>
</html>
DarabaServ.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
res.setContentType ("text/html");
By Mr. K. V. R Page 64
try
Hanuman","scott","tiger");
PreparedStatement ps=con.prepareStatement ("insert into Product values (?,?,?)");
con.close ();
catch (Exception e)
};
VALIDATION of a form:
Develop the following html form and validate that from data by using a servlet?
Validations:
1. stno must contain data and it should contain always int data.
Student database:
);
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>ValidationServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
By Mr. K. V. R Page 65
<url-pattern>/validation</url-pattern>
</servlet-mapping>
</web-app>
validpro.html:
<html>
<title>Validation Project</title>
<body bgcolor="#FFE4C4">
<center>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<table>
<tr>
</tr>
</table>
</tr>
</table>
</form>
</center>
</body>
</html>
ValidationServ.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
res.setContentType ("text/html");
int sno=0;
J2EE (Advanced) JAVA
By Mr. K. V. R Page 66
float smarks=0;
if ((sno1==null)||(sno1.equals ("")))
else
try
sno=Integer.parseInt ("sno1");
if ((sname==null)||(sname.equals ("")))
if ((smarks1==null)||(smarks1.equals ("")))
{
al.add ("PROVIDE STUDENT MARKS...");
else
try
smarks=Float.parseFloat ("smarks1");
if (al.size ()!=0)
pw.println (al);
else
try
Class.forName ("oracle.jdbc.driver.OracleDriver");
Hanuman","scott","tiger");
if (i>0)
else
By Mr. K. V. R Page 67
con.close ();
catch (Exception e)
};
Day - 32:
Servlet Chaining:
If a client request is processed by group of servlets, then that servlets are known as servlet
chaining or if the group of servlets process a single client request then those servlets are known as
servlet chaining.
In order to process a client request by many number of servlets then we have two models,
Forward model:
In this model when we forward a request to a group of servlets, finally we get the result of
Include model:
If a single client request is passed to a servlet and that servlet makes use of other group of
servlets to process a request by including the group of servlets into a single servlet.
By Mr. K. V. R Page 68
In the above diagram client request goes to servlet s1 and s1 internally includes s2, s3 and s4
servlets and finally result of all these servlets given to the client by a source servlet s1.
NOTE: One servlet can include any number of servlets where as one servlet can forward to only one
servlet at a time.
javax.servlet.* package and it is used for forwarding the request and response objects of
source servlet to destination servlet or for including the destination servlet into source
method:
3. Use forward or include model to send the request and response objects. RequestDispatcher
contains the following methods for forwarding or including the request and response
objects.
For example:
Day -33:
Answer:
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
By Mr. K. V. R Page 69
<servlet-class>Serv1</servlet-class>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
Serv1.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
res.setContentType ("text/html");
};
Serv2.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
res.setContentType ("text/html");
};
By Mr. K. V. R Page 70
(String)?
Answer:
web.xml
In order to achieve forwarding or including the request and response objects of one web
application to another web application, we must ensure that both the web applications must run in
the same servlet container.
For example:
2. Obtain SerletContext object of another web application by using the following method which
For example:
For example:
4. Use either include of forward to pass request and response objects of current web
application.
For example:
By Mr. K. V. R Page 71
Day - 34:
web.xml (webapp1):
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
</wep-app>
Serv1.java (webapp1):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
res.setContentType ("text/html");
};
web.xml (webapp2):
<web-app>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
Serv2.java (webapp2):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
J2EE (Advanced) JAVA
By Mr. K. V. R Page 72
res.setContentType ("text/html");
};
Forwarding request and response objects of one web application to another web application and
In order to send the request and response object of one web application which is running in
on servlet container to another web application which is running in another servlet container, we
To achieve the above we must use a method called sendRedirect (String url) method whose
prototype is
The above method is present in HttpServletResponse interface, the parameter String url
represents url of another web application which is running in some other servlet container.
1. Make a request to a servlet or JSP which is running in a web application of one container
2. Servlet of web application of Tomcat will redirect the request of client to another web
Serv1 of webapp1
3. Browser will send the request to another web application of another servlet container.
For example:
4. Webapp1 gives the response of Serv2 only but not Serv1 servlet.
By Mr. K. V. R Page 73
For example:
web.xml (webapp1):
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
</wep-app>
Serv1.java (webapp1):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
res.setContentType ("text/html");
res.sendRedirect (“http://localhost:7001/webapp2/s2”);
};
NOTE: webapp1 must be deployed in Tomcat server.
web.xml (webapp2):
<web-app>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
</web-app>
Serv2.java (webapp2):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
By Mr. K. V. R Page 74
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
};
Day - 35:
Develop the following application with the help of request dispatcher by using forward and include
methods?
Answer:
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>RecvServ</servlet-class>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>DispServ</servlet-class>
</servlet>
J2EE (Advanced) JAVA
By Mr. K. V. R Page 75
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/receive</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/display</url-pattern>
</servlet-mapping>
</web-app>
header.html:
<html>
<title>Header</title>
<body bgcolor="#D8BFD8">
<center><hr>
</font>
</center>
</body>
</html>
login.html:
<html>
<title>Login Page</title>
<body bgcolor="#D87093">
<center>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</form>
</center>
</body>
</html>
footer.html:
<html>
<title>Footer</title>
<body bgcolor="#D8BFD8">
<center><hr>
</font>
</center>
</body>
</html>
By Mr. K. V. R Page 76
RecvServ.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
res.setContentType ("text/html");
};
DispServ.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
res.setContentType ("text/html");
pw.println ("<br><br><br>");
else
{
pw.println ("<center><font color=#ffff66><h3>INVALID CREDENTIALS</h3></center>");
pw.println ("</font></br></br></br>");
};
NOTE:
html program will be executed by browser at client side where as whenever we pass a
*******************************************************
*********************************************************
The Window, Frame and Dialog classes use a border layout as their default layout.
Why do threads block on I/O?
Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O
Operation is performed.
Objects that subclass the Observable class maintain a list of observers. When an Observable object is
updated it invokes the update() method of each of its observers to notify the observers that it has
changed state. The Observer interface is implemented by objects that observe Observable objects.
With respect to multithreading, synchronization is the capability to control the access of multiple
threads to shared resources. Without synchronization, it is possible for one thread to modify a shared
object while another thread is in the process of using or updating that object's value. This often leads to
significant errors.
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object..
What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
Is null a keyword?
The preferred size of a component is the minimum component size that will allow the component to
display normally.
The Panel and Applet classes use the FlowLayout as their default layout.
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Which characters may be used as the second character of an identifier, but not as the first character of
an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after
the first character of an identifier.
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
The Vector class provides the capability to implement a growable array of objects
What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
Which method of the Component class is used to set the position and size of a component?
setBounds() method is used to set the position and size of a component.
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep()
method, it returns to the waiting state.
The EventObject class and the EventListener interface support event processing.
Is sizeof a keyword?
Wrapped classes are classes that allow primitive types to be accessed as objects.
Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It is also possible for
programs to create objects that are not subject to garbage collection.
What restrictions are placed on the location of a package statement within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and
comments).
An object's finalize() method cannot be invoked by the garbage collector while the object is still
reachable. However, an object's finalize() method may be invoked by other objects.
Panel.
The scheduler then determines which task should execute next, based on priority and other factors.
What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.
Window.
What is clipping?
Yes, a for statement can loop indefinitely. For example, consider the following:
for(;;) ;
What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions.
If a checked exception may be thrown within the body of a method, the method must either catch the
exception or declare it in its throws clause.
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked
or unchecked.
A task's priority is an integer value that identifies the relative order in which it should be executed with
respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority
tasks.
A thread is in the ready state after it has been created and started.
An anonymous class may implement an interface or extend a superclass, but may not be declared to do
both.
MenuItem.
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup
processing before the object is garbage collected.
Object.
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's
run() method when the thread is initially executed.
What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the &
operator is applied to the operand. When an expression involving the && operator is evaluated, the first
operand is evaluated.
If the first operand returns a value of true then the second operand is evaluated. The && operator is
then applied to the first and second operands. If the first operand evaluates to false, the evaluation of
the second operand is skipped.
Which Container method is used to cause a container to be laid out and redisplayed?
The purpose of the Runtime class is to provide access to the Java runtime system.