0% found this document useful (0 votes)
343 views

Total Java

The document discusses object-oriented programming concepts including classes, objects, encapsulation, inheritance, and polymorphism. It explains that a class contains data members and methods to perform tasks, and that classes can be divided into modules represented as classes. Objects belong to classes and have properties and actions. The key features of OOP like class/object, access modifiers, and other class modifiers are also summarized.

Uploaded by

Venu D
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
343 views

Total Java

The document discusses object-oriented programming concepts including classes, objects, encapsulation, inheritance, and polymorphism. It explains that a class contains data members and methods to perform tasks, and that classes can be divided into modules represented as classes. Objects belong to classes and have properties and actions. The key features of OOP like class/object, access modifiers, and other class modifiers are also summarized.

Uploaded by

Venu D
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 120

OBJECT ORIENTED APPROACH

 In this model, classes and objects are used to achieve the task
 A class is a module which itself contains data and methods to achieve the task
 The main task is divided into several modules, and these are represented as classes
 Each class can perform some tasks for which several methods are written in a class

class1 Data
members
Class with
main() class2 Data
method members
Data
class3
members

OOP’S FEATURES
 Class/Object
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism
Class/Object
An object is anything that really exist in the world and can be distinguished from others
Example: a table, a ball, a car etc.,
If something does not really exist, then it is not an object
Example: our thoughts, imagination, plans, ideas etc.,
Every object has properties and can perform certain actions
Example:
• Let us take a person whose name is ‘Raju’.
• Raju is an object because he exist physically.
• He has properties like name, age, gender etc.
These properties can be represented by variables in our programming
Example: String name, int age, char gender;
• We can consider calculations and processing of data as actions
• These actions are performed by methods.
So an object contains variables and methods
It is possible that some objects may have similar properties and actions. Such objects
belongs to same category called a ‘class’
Example: Not only Raju, Ravi, Sita, etc., personas have same properties and actions. So they
are all objects of same class ‘Person’
Note: Observe that the ‘Person’ will not exist physically but only Raju, Ravi exist physically
this means class not exist physically and object exist physically

1
Creating classes and Objects in Java
class Person
{
//properties of a person-variables
String name;
int age
//actions done by a person-methods
void talk()
{ }
void eat()
{ }
}
• Variables defined within a class are called instance variables because each object of
the class contains its own copy of these variables.
• When we want use this class, we should create an object to the class as,
• Person Raju=new Person();
• Here , Raju is an objects of Person class.
• Object represents memory to store the actual data.
Class Declarations and Modifiers
• The following code shows class declaration:
class MyClass { }
• This code compiles just fine, but you can also add modifiers before the class
declaration.
Modifiers fall into two categories:
 Access modifiers: public, protected, private.
 Non-access modifiers (strictfp, final, and abstract).
Using access modifiers you'll learn how to restrict or allow access to a class you create.
Access Modifiers
• Access control in Java is a little tricky because there are four access controls (levels of
access) but only three access modifiers.
• The fourth access control level (called default or package access) is what you get
when you don't use any of the three access modifiers.
• A class can be declared with only public or default access; the other two access
control levels don't make sense for a class

2
Default Access
• It's the access control you get when you don't type a modifier in the class declaration.
• Default access is package-level access, because a class with default access can be
seen only by classes within the same package.
package cert;
class Beverage { }
Now look at the second source file:
package exam;
import cert.Beverage;
class Tea extends Beverage { }
• As you can see, the superclass (Beverage) is in a different package from the subclass
(Tea).
• The import statement at the top of the Tea file is trying to import the Beverage class.
• The Beverage file compiles fine, but when we try to compile the Tea file we get
compile-time error
Public Access
• A class declaration with the public keyword gives all classes from all packages access
to the public class.
• In other words, all classes in the Java Universe (JU) have access to a public class.
package cert;
public class Beverage { }
Now look at the second source file:
package exam;
import cert.Beverage;
class Tea extends Beverage { }
Other (Nonaccess) Class Modifiers
• You can modify a class declaration using the keyword
– final
– abstract
– strictfp
public final (acceptable)
strictfp final (acceptable)
abstract final (not acceptable)
Final Classes
• When used in a class declaration, the final keyword means the class can't be
subclassed.
public final class Beverage {
public void importantMethod() { }
}
Now, if we try to compile the Tea subclass:
import cert.Beverage;
class Tea extends Beverage { }

3
Abstract Classes
An abstract class can never be instantiated.
abstract class Car {
private double price;
private String model;
private String year;
public abstract void goFast();
public abstract void goUpHill();
public abstract void impressNeighbors();
}
public class CarTest
{
public static void main(String args[])
{
Car c1=new Car();
}
}
• strictfp is a keyword and can be used to modify a class or a method, but never a
variable.
• Marking a class as strictfp means that any method code in the class will conform to
the IEEE 754 standard rules for floating points.
• Without that modifier, floating points used in the methods might behave in a
platform-dependent way.
Declare Class Members
• Methods and instance (nonlocal) variables are collectively known as members
• Whereas a class can use just two of the four access control levels (default or public),
members can use all four:
 public
 protected
 Default
 Private
Default
• Default protection is what you get when you don't type an access modifier in the
member declaration.
• The default and protected access control types have almost identical behavior, except
for one difference that will be mentioned later. (Inheritance)
Public
• When a method or variable member is declared public, it means all other classes,
regardless of the package they belong to, can access the member
Private
• Members marked private can't be accessed by code in any class other than the class in
which the private member was declared.

4
Protected and Default Members
• The protected and default access control levels are almost identical, but with one
critical difference.
• A default member may be accessed only if the class accessing the member belongs to
the same package, whereas a protected member can be accessed (through inheritance)
by a subclass even if the subclass is in a different package.
Instance Variables
• Instance variables are defined inside the class, but outside of any method, and are only
initialized when the class is instantiated.
• Instance variables are the fields that belong to each unique object
class Employee {
private String name;
private String title,
private String manager;
//code goes here including access methods
}
 Can use any of the four access levels (which means they can be marked with any of
the three access modifiers)
 Can be marked final
 Can be marked transient
 Cannot be marked abstract
 Cannot be marked synchronized
 Cannot be marked strictfp
 Cannot be marked native
 Cannot be marked static, because then they'd become class variables.
Local Variables
• Local variables are variables declared within a method.
• That means the variable is not just initialized within the method, but also declared
within the method
class TestServer {
public void logIn() {
int count = 10;
}
}
The key is to remember that a local variable must be initialized before you try to use it.
Final variables
Declaring a variable with the final keyword makes it impossible to reinitialize that variable
once it has been initialized with an explicit value
class Roo
{
final int size=20;
void changeSize()
{
size=16;

5
}
}
Transient variables
• If you mark an instance variable as transient, you're telling the JVM to skip (ignore)
this variable when you attempt to serialize the object containing it.
• With serialization you can save an object to a file.
Volatile Variables
• The volatile modifier tells the JVM that a thread accessing the variable must always
settle its own private copy of the variable with the master copy in memory.
• The volatile modifier may also be applied to project managers
Static Variables and Methods
• The static modifier is used to create variables and methods that will exist
independently of any instances created for the class.
• All static members exist before you ever make a new instance of a class, and there
will be only one copy of a static member regardless of the number of instances of that
class.
• Static method does not act upon instance variables of a class
• Static methods are called using Classname.methodname()
• Static method can access static variables
Things you can mark as static:
• Methods
• Variables
• A class nested within another class, but not within a method
• Initialization blocks
Things you can't mark as static:
• Constructors
• Classes (unless they are nested)
• Interfaces
• Method local inner classes
• Inner class methods and instance variables
• Local variables
Static Block
• A static block is a block of statements declared as ‘static’
static
{
statements;
}
JVM executes a static block on a higher priority basis. This means JVM first goes to static
block even before it looks the main() method in the program

6
CONSTRUCTORS IN JAVA
• A constructor is a special member method which will be called by JVM
automatically(implicitly) whenever an object is created for placing our own values
without placing default values
• The purpose of constructor is to initialize an object
• Every time you make a new object, at least one constructor is invoked.
• Every class has a constructor, although if you don't create one explicitly, the compiler
will build one for you
Characteristics of Constructor
• The name of the constructor must be similar to the class name
• Constructor should not return any value even void also
• The modifier of a constructor should not be static
• Constructors of base class will not be inherited into derived class
• A constructor of a class may or may not be private
– If constructor access specifier is private then an object of corresponding class
can be created with in the same class context but not in some other class
context
– If the constructor access specifier is not private then an object of
corresponding class can be created either in same class context or in other
class context
Types of Constructors
• Based on the object creation in java, constructors are classified into two types. They
are
1) Default/Parameter less/Zero argument Constructor
2) Parameterized Constructor
Default Constructor
• A constructor is said to be default constructor if and only if it should not take any
parameters
• Whenever we want to place same values in multiple objects of same type of class then
we must use the concept of default constructor
Parameterized Constructor
• A constructor is said to be a parameterized constructor if and only if it takes some
parameters
• Parameterized constructor is useful to initialize each object with different values
Rules to define Constructors in Java
Rule-1
• Whenever we create an object only with default constructor, defining the default
constructor is optional
• If we are not defining any default constructor then JVM will call its own default
constructor known as system defined default constructor and it places default values
depends on the data members of the class
• If we define our own default constructor known as programmer defined default
constructor then JVM will call programmer defined constructor and it places
programmer defined values

7
Rule-2
• Whenever we create an object with parameterized constructor, defining the
parameterized constructor is mandatory, otherwise we get compile time error
Rule-3
• Whenever we create an object with both default and parameterized constructors then
it is mandatory to the java programmer to define both default and parameterized
constructors. Otherwise we get an error regarding default constructor
Methods and Types of Methods
• Method is a sub block of a class that is used for implementing logic of an object’s
operation
• Logic must be placed only inside the method, not directly at class level
• Class level place only variables and method creation statements
• Method calls, validations, calculations and data printing statements must be placed
inside a method
Terminology of a Methods
• Method prototype
– The head portion of the method is called method prototype
• Method body and logic
– The “{}” region is called method body, and the statements placed inside
method body is called logic
• Method parameters and arguments
– The variables in method paraenthesis “()” are called parameters. We can
define method with ZERO to ‘n’ number of parameters
– The input values passing to parameters are called arguments
• Method signature
– The combination of Method name plus parameters list is called method
signature
• Method return type
– The datatype keyword that is placed before method name is called method
return type
Method creation with body
[access specifier][modifier][return type]<method_name>([parameter list])
{
--------------------
--------------------
}
Example:
public static void sum(int a, int b)
{
System.out.println(a+b);
}
Technically this method is called concrete method

8
Method creation without body
[access specifier][modifier][return type]<method_name>([parameter list]);
Example
public abstarct void add(int a, int b);
Technically this method is called abstract method
Method invocation/calling/execution
<methodname>([argument list]);
Types of Methods
• Based on static modifier
– static methods
– non-static methods
• Based on return type
– void methods
– non-void methods
• Based on parameters
– parameterized methods
– non-parameterized methods
Static and non-static methods
• If a method has static keyword in its definition then that method is called static
method, else it is called non-static method
• We can call static methods directly from main method but we can not call non-static
methods directly from main method
//static void method //non-static void method

static void m1() void m1()

{ {

------------- -------------

------------- -------------

} }

//static non-void method //non-static non-void method

static int m1() double m1()

{ {

------------- -------------

return 10; return 23.45;

} }

9
Void and non-void methods
• If the method return type is void it is called void method, else it is called non-void
method
• Non-void method must return a value after its execution
//static void method //non-static void method

static void m1() void m1()

{ {

------------- -------------

------------- -------------

} }

//static non-void method //non-static non-void method

static int m1() double m1()

{ {

------------- -------------

return 10; return 23.45;

} }

Types of return statements


1) return;
2) return <value>;
return is allowed only in void methods and constructors and it is optional
return<value> is allowed only in non-void methods, and it is mandatory
Basically return statement is used to terminate method execution and for sending control back
to calling method
Calling Methods
1) Directly
2) As variable initialization statement
3) As System.out.println() argument
• Non-void methods
– In the first way the return value is lost
– In second way the returned value is stored in the destination variable
– In the third way the returned value is printed on console
• Void methods
– Void method can only be called in first way
INHERITANCE IN JAVA

10
• The mechanism of obtaining one class data member from one class to another class is
known as inheritance
• The class which is giving the data members to another class is known as base class
• The class which is getting data members from base class is known a derived class
Advantage Of Inheritance
• Application development time is less
• Application memory space is less
• Redundancy code is missed
• We are able to get slogan of java i.e,. WORA (Write Once Reuse Anywhere)
Types Of Inheritance
1. Single Inheritance
 Single Inheritance is one in which there exist single base class and single
derived class
2. Multilevel Inheritance
 In which there exist single base class, single derived class and multiple
intermediate base classes
 Intermediate base class is one, in one context it acts as base class and in
other context same class act as derived class
3. Hierarchical Inheritance
 In which there exist single base class and multiple derived classes
4. Multiple Inheritance
 Multiple inheritance is one in which there exist multiple base classes and
single derived class
5. Hybrid Inheritance
 Combination of any available inheritance types

The keyword ‘super’


• If we create an object to base class, we can access only the base class members, but
not the derived class members
• But if we create an object to derived class, all the members of both base and derived
classes are available to it
• This is the reason, we always create an object to derived class in inheritance
• Sometimes the base class members and derived class members may have same names
• In that case, by default sub class members are accessible
Private and Protected members in base class
• Private members are not accessible in derived class, but protected members are
available in derived class
Inheritance Related To Constructor
• In inheritance by default the base class constructor is called first then derived class
constructor is called if we invoke (create) derived class object (BarTest.java)
• Every constructor has, as its first statement, a call to the base class constructor
(super()), although remember that this call can be inserted by the compiler. (In the
case of default constructor)

If the super constructor has arguments

11
• If your base class does not have a no-arg constructor, then in your subclass you will
not be able to use the default constructor supplied by the compiler. (TShirt.java)
• where we've supplied a constructor for derived class that's identical to the default
constructor supplied by the compiler(Tshirt1.java)
• If your super constructor has arguments, you must type in the call to super(),
supplying the appropriate arguments.(TShirt3.java)
Method Overriding and Method Overloading
• Writing two or more methods in base and derived classes with the same name and
same signature is called as ‘method overriding’
• A method signature represents method name and its parameters
• The key benefit of overriding is the ability to define behavior that's specific to a
particular subclass type.
• ‘final’ methods never override (TestAnimals.java)
The rules for overriding a method
• The argument list must exactly match that of the overridden method.
• The access level can't be more restrictive than the overridden method's.
(TestAnimals2.java)
• The access level CAN be less restrictive than that of the overridden method.
(TestAnimals3.java)
• Instance methods can be overridden only if they are inherited by the subclass.
• A subclass in a different package can override only those non-final methods marked
public or protected (since protected methods are inherited by the subclass).
• You cannot override a method marked final.
• You cannot override a method marked static.
• If a method can't be inherited, you cannot override it.
Invoking a Base class Version of an Overridden Method
• You want to take advantage of some of the code in the base class version of a method,
yet still override it to provide some additional specific behavior.
• It's like saying, "Run the base class version of the method (InvokeSuper1.java)
Method Overloading
• A method can be overloaded in the same class or in a subclass
• Overloaded methods let you reuse the same method name in a class, but with different
arguments
Method Overloading rules
• Overloaded methods MUST change the argument list.
• Overloaded methods CAN change the return type.
• Overloaded methods CAN change the access modifier.
Invoking Overloaded Methods
• A class might have three methods with the same name but with different argument
lists, which means the method is overloaded.
• Deciding which of the matching methods to invoke is based on the arguments.
• If you invoke the method with a String argument, the overloaded version that takes a
String is called.

12
• If you invoke a method of the same name but pass it a float, the overloaded version
that takes a float will run.
• If you invoke the method of the same name but pass it a Foo object, and there isn't an
overloaded version that takes a Foo, then the compiler will complain that it can't find
a match. (TestAdder.java)
POLYMORPHISM IN JAVA
• The ability to exist in different forms is called ‘polymorphism’
• In java, a variable, an object or a method can exist in different forms, to performing
various tasks depending on the context
Polymorphism With Variables
System.out.println(a+b);
Java compiler decides the data type of result of the expression a+b depending on the data
types of a and b
Example:
If a and b both are floats then result is float
If a and b both are ints then result us int
If a is int b is float, then compiler converts a also into float and then the result is float
(Coercion.java)
What is coercion?
Coercion is the automatic conversion between different data types done by the compiler
Polymorphism With Methods
• If the same method perform different tasks, then that method is said to exhibit
polymorphism
• It is possible only when the two method with the same name and they can perform
different tasks (having different bodies)
• Now , the crucial thing is decide which method is called in a particular context
• This decision may be happen either at compile time or at runtime
• The decision happen at compile time is called static polymorphism or compile time
polymorphism
• The decision happen at run time is called as dynamic or runtime polymorphism
Dynamic Polymorphism
• The polymorphism exhibited at runtime is called dynamic polymorphism it means
when a method is called, method call bound to the method body at the time of
running the program
• Java compiler does not know which method is called at the time of compilation
• Only JVM knows at runtime which method is executed
void add(int a, int b)
{
System.out.prinln(“Sum of two=“+(a+b));
}
void add(int a, int b, int c)
{
System.out.prinln(“Sum of three=“+(a+b+c));
}

13
s.add(10,15);

Here, JVM observes the signature of the methods. When there is a difference in the
method signatures, then the JVM understands both methods are different and can call the
appropriate method
Polymorphism With Private Methods
Polymorphism With Final Methods

ABSTRACT CLASSES IN JAVA


• An abstract classes can contain both abstract and non-abstract methods, but that if
even a single method is marked abstract, the class must be marked abstract.
• An abstract class can never be instantiated.
• We can create a reference of abstract class
• Its sole purpose is to be extended (sub classed)
Example:
public class IllegalClass{
public abstract void doIt();
}
• Any class that extends an abstract class must implement all abstract methods of the
super class, unless the subclass is also abstract.
Abstract Methods
• An abstract method is a method that's been declared (as abstract) but not
implemented.
• Both the abstract class and the abstract methods should be declared by using the
keyword ‘abstract’.
public abstract void showSample();
• Three different clues tell you it's not an abstract method:
 The method is not marked abstract.
 The method declaration includes curly braces, as opposed to ending in a semicolon.
In other words, the method has a method body.
 The method provides actual implementation code.
 A method can never, ever, ever be marked as both abstract and final, or both abstract
and private
 Finally, you need to know that the abstract modifier can never be combined with the
static modifier
abstract static void doStuff(); //illegal
Important Points
• It is perfectly possible to access all the members of the sub class by using sub class
object
• But prefer to use super class reference to access the sub class features because, the
reference variable can access only those features of the sub class which have been
already declared in super class
• If we write an individual method in the sub class, the super class reference cannot
access that method

14
• This is to enforce discipline in the programmer not to add any of their own features in
the sub class other than whatever is given in super class
INTERFACES IN JAVA
• An interface is a contract.
• When you create an interface, you're defining a contract for what a class can do,
without saying anything about how the class will do it.
• Interfaces can be implemented by any class, from any inheritance tree.
• Any class type that implements this interface must agree to write the code for the
interface methods.“
• Interfaces are like a 100-percent abstract super class that defines the methods a
subclass must support, but not supply any logic for the methods
• An abstract class can define both abstract and non-abstract methods, an interface can
have only abstract methods.
Rules To Define Interface
 All interface methods are implicitly public and abstract.
 All variables defined in an interface must be public, static, and final— in other words,
interfaces can declare only constants, not instance variables.
 Interface methods must not be static.
 Interface methods are abstract, they cannot be marked final, strictfp, or native.
 An interface can extend one or more other interfaces.
 An interface cannot extend anything but another interface.
 An interface cannot implement another interface or class.
 An interface must be declared with the keyword interface.
 A class can extend only one class (no multiple inheritance), but it can implement
many interfaces.
Interface Declaration
public abstract interface Rollable { }
• You just need to know that both of these declarations are legal, and functionally
identical:
public abstract interface Rollable { }
public interface Rollable { }
Interface Methods
public interface Bounceable {
public abstract void bounce();
public abstract void setBounceFactor(int bf);
}
The Above Code is Same as
public interface Bounceable {
void bounce(); // No modifiers
void setBounceFactor(int bf); // No modifiers
}
The following five method declarations, if declared within their own interfaces, are legal and
identical
1) void bounce();

15
2) public void bounce();
3) abstract void bounce();
4) public abstract void bounce();
5) abstract public void bounce();
The following interface method declarations won't compile:
1) final void bounce(); // final and abstract can never be used // together, and abstract is
implied
2) static void bounce(); // interfaces define instance methods
3) private void bounce(); // interface methods are always public
4) protected void bounce(); // (same as above)
Declaring Interface Constants
• You're allowed to put constants in an interface. By doing so, you guarantee that any
class implementing the interface will have access to the same constant.
• You need to remember one key rule for interface constants. They must always be
public static final
• Because interface constants are defined in an interface, they don't have to be declared
as public, static, or final. They must be public, static, and final, but you don't have to
actually declare them that way.
interface Foo {
int BAR = 42;
void go();
}
class Zap implements Foo {
public void go() {
BAR = 27;
}
}
Iegal Interface constant definitions
• public int x = 1; // Looks non-static and non-final, // but isn't!
• int x = 1; // Looks default, non-final, // non-static, but isn't!
• static int x = 1; // Doesn't show final or public
• final int x = 1; // Doesn't show static or public
• public static int x = 1; // Doesn't show final
• public final int x = 1; // Doesn't show static
• static final int x = 1 // Doesn't show public
Implementing an Interface
 Assuming an interface, Bounceable, with two methods: bounce(), and
setBounceFactor(), the following class will compile:
 In order to be a legal implementation class, must do the following:
 Provide concrete (nonabstract) implementations for all methods from the declared
interface.
 Follow all the rules for legal overrides.
 Maintain the signature of the interface method, and maintain the same return type .

16
Rules
A class can implement more than one interface. It's perfectly legal to say, for example, the
following:
public class Ball implements Bounceable, Serializable, Runnable
{ ... }
2. An interface can itself extend another interface, but never implement anything.
The following code is perfectly legal:
public interface Bounceable extends Moveable { } // ok!
3. An interface can extend more than one interface
public class Programmer extends Employee, Geek { }

EXCEPTION EXAMPLES
EXCEPTION HANDLING
Example 1: Using try-catch blocks
import java.util.*;
class Exception1
{
public static void main(String[] args)
{
System.out.println("open connection");
System.out.println("Enter n value");
Scanner sc=new Scanner(System.in);
try{
int n=sc.nextInt();
int a=45/n;
System.out.println("a value is:"+a);
System.out.println("close connection");
}
catch(Exception e)
{ //System.out.println(e);
e.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------
-----
Example 2: Using try-catch-finally blocks
import java.util.*;
class Exception2
{
public static void main(String[] args)
{
System.out.println("Try-Catch-Finally");
System.out.println("Enter n value");
Scanner sc=new Scanner(System.in);
try{
int n=sc.nextInt();
int a=45/n;

17
System.out.println("a value is:"+a);
System.out.println("close connection");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("I am in Finally");
}
}}
Example 3: Using multiple catch blocks
import java.util.*;
class MultiCatch {
public static void main(String args[]) {
System.out.println("Try-Catch-Finally");
System.out.println("Enter n value");
Scanner sc=new Scanner(System.in);
try {
int a=sc.nextInt();
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e){
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
catch(Exception e) {
System.out.println(e);
}
System.out.println("After try/catch blocks.");
}
}
----------------------------------------------------------------------------------------------------------------
-----
Example 4: Using nested try blocks
import java.util.*;
class NestTry {
public static void main(String args[]) {
try{
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Number");
int a=sc.nextInt();
int b = 42 / a;
System.out.println("b = " + b);

18
try { // nested try block
if(a==1)
a = a/(a-a);
if(a==2)
{
int c[] = { 1 };
c[42] = 99;
}
} //nested try
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
} //outer try
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
----------------------------------------------------------------------------------------------------------------
-----
Example 5: Using throw clause
class Throw
{
static void demo()
{
try{
System.out.println("Demo");
throw new NullPointerException("NULL EXCEPTION");
}

catch(Exception ne)
{
System.out.println(ne);
}
}
}
class ThrowTest
{
public static void main(String[] args)
{
Throw.demo();
}
}
----------------------------------------------------------------------------------------------------------------
-----
Example 6: Using throws clause
import java.io.*;
class ThrowsTest

19
{ public static void main(String[] args) throws IOException {
System.out.println("Enter Your Name");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str=br.readLine();
System.out.println("Your Name is:"+str);

}
}
Example 7: User defined exceptions
import java.io.DataInputStream;
class MyException extends Exception // step1
{
private static int[] accno={1001,1002,1003,1004};
private static String[] names={"rishvad","mohan","anjali","rupa"};
private static double[] balance={1010.00,1200.00,5000.12,5600.32};

//step-2
MyException(){ }
MyException(String str){
super(str);
}

public static void main(String[] args)


{
try
{
System.out.println("ACCONT
NO"+"\t"+"CUSTOMER"+"\t"+"BALANCE");
//display account information
for(int i=0;i<4;i++) {
System.out.println(accno[i]+"\t"+names[i]+"\t"+balance[i]);
if(balance[i]<1000)
{
MyException me=new MyException("Balance is less");
throw me;
}
}
}
catch (MyException me)
{
me.printStackTrace();
}

}
}

20
MULTITHREADING EXAMPLES
Example 1: Create a thread using Thread class
class MyThread extends Thread {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread obj = new MyThread();
Thread t=new Thread(obj);
t.start();
}
}

Example 2: run() method having a parameter


class MyTestThread extends Thread {
public void run() {
System.out.println("Important job running in MyThread");
}
public void run(String s) {
System.out.println("String in run is " + s);
}
}
class ThreadEx2 {
public static void main(String [] args ) {
MyTestThread obj = new MyTestThread();
Thread t=new Thread(obj);
//t.run("hello");
t.start();
obj.run("hello");
}
}

Example 3: create thread using Runnable interface


class MyRunThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class RunThread {
public static void main(String [] args ) {
Thread t = new Thread(new MyRunThread());
t.start();
}
}

Example 4:Single thread performs multiple tasks


class A extends Thread
{

21
public void run()
{
task2();
task1();
task3();
}

void task1()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");

}
void task2()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadA: j= "+j);
}
System.out.println("Exit from B");

}
void task3()
{
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadA: k= "+k);
}
System.out.println("Exit from c");

}
}
class SingleTask
{
public static void main(String args[])
{
Thread t=new Thread(new A());
t.start();
}
}
Example 5: Multi threads performs the task
class Theatre implements Runnable
{
String str;
Theatre(String str)
{
this.str=str;

22
}
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println(str+" :"+i);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class MultiTask
{
public static void main(String[] args)
{
Theatre obj1=new Theatre("cut the ticket");
Theatre obj2=new Theatre("Show the seat");
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();
System.out.println("Hello World!");
}
}
Example 6: Multiple threads on single object
class Reserve implements Runnable
{
int available=1;
int wanted;
Reserve(int i)
{
wanted=i;
}
public void run()
{
System.out.println("Available Breaths="+available);
if(available>=wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted+"Berths Reserved For"+name);
try{
Thread.sleep(1500);
available=available-wanted;
}

23
catch(InterruptedException ie)
{}
}
else
System.out.println("Sorry, no breaths");
}

}
class SingleObject
{
public static void main(String[] args)
{
Reserve obj=new Reserve(1);
Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
t1.setName("First Person");
t2.setName("Second Person");
t1.start();
t2.start();
}
}
Example 7: Synchronization block
class Reserve1 implements Runnable
{
int available=1;
int wanted;
Reserve1(int i)
{
wanted=i;
}
public void run()
{
synchronized(this)
{
System.out.println("Available Breaths="+available);
if(available>=wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted+"Berths Reserved For"+name);
try{
Thread.sleep(1500);
available=available-wanted;
}
catch(InterruptedException ie)
{}
}
else
System.out.println("Sorry, no breaths");
}
}

24
}
class SynBlock
{
public static void main(String[] args)
{
Reserve1 obj=new Reserve1(1);
Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
t1.setName("First Person");
t2.setName("Second Person");
t1.start();
t2.start();
}
}
Example 8: Synchronization method
class Reserve2 implements Runnable
{
int available=1;
int wanted;
Reserve2(int i)
{
wanted=i;
}
public synchronized void reservation()
{
System.out.println("Available Breaths="+available);
if(available>=wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted+"Berths Reserved For"+name);
try{
Thread.sleep(1500);
available=available-wanted;
}
catch(InterruptedException ie)
{}
}
else
System.out.println("Sorry, no breaths");
}

public void run()


{
reservation();
}

}
class SynMethod
{

25
public static void main(String[] args)
{
Reserve2 obj=new Reserve2(1);
Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
t1.setName("First Person");
t2.setName("Second Person");
t1.start();
t2.start();
}
}
Example 9: Example on sleep() method
public class SleepExample {
public static void main(String args[]) throws InterruptedException {
String importantInfo[] = {"Red","Orange","Green"};

for (int i = 0; i < importantInfo.length; i++)


{
Thread.sleep(10000);
System.out.println(importantInfo[i]);
if(importantInfo[i]=="Red")
{

System.out.println("Please Stop");
}
if(importantInfo[i]=="Orange")
{

System.out.println("Ready to Start");
}
if(importantInfo[i]=="Green")
{

System.out.println("Move");
}
//Pause for 4 seconds

//Print a message
//System.out.println(importantInfo[i]);
}
}
}
Example 10: Example on thread priority
class TestA extends Thread {
public void run() {
System.out.println("TestA Thread started");
for (int i = 1; i <= 4; i++) {
System.out.println("\t From thread TestA :i=" + i);
}
System.out.println("exit from TestA");

26
}
}
class TestB extends Thread {
public void run() {
System.out.println("TestB Thread started");
for (int j = 1; j <= 4; j++) {
System.out.println("\t From thread TestB :j=" + j);
}
System.out.println("exit from TestB");
}
}
class TestC extends Thread {
public void run() {
System.out.println("testC Thread started");
for (int k = 1; k <= 4; k++) {
System.out.println("\t From thread TestC :K=" + k);
}
System.out.println("exit from TestC");
}

}
public class PriorityExample {
public static void main(String args[]) {
TestA A = new TestA();
TestB B = new TestB();
TestC C = new TestC();
C.setPriority(10);
B.setPriority(5);
A.setPriority(1);
A.start();
B.start();
C.start();
System.out.println(" End of main thread");
}
}
Example 11: Example on Deadlock prevent
class BookTicket extends Thread
{ Object train, comp;
BookTicket(Object train, Object comp)
{
this.train=train;
this.comp=comp;
}
public void run()
{
synchronized(train)
{
System.out.println("Book ticket locked on train");
try{
Thread.sleep(150);

27
}

catch(InterruptedException ie)
{
}
System.out.println("Book ticket now waiting to lock on
compartment");
synchronized(comp)
{
System.out.println("Book ticket locked on compartment");
}
}
}
}
class CancelTicket extends Thread
{
Object train, comp;
CancelTicket(Object train, Object comp)
{
this.train=train;
this.comp=comp;
}
public void run()
{
synchronized(comp)
{
System.out.println("cancel ticket locked on compartment");
try{
Thread.sleep(150);
}

catch(InterruptedException ie)
{
}
System.out.println("Cancel ticket now waiting to lock on train");
synchronized(train)
{
System.out.println("Cancel ticket locked on train");
}
}
}
}
public class DeadLock
{
public static void main(String[] args)
{
Object train=new Object();
Object compartment=new Object();
BookTicket obj1=new BookTicket(train, compartment);
CancelTicket obj2=new CancelTicket(train, compartment);

28
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();
System.out.println("Hello World!");
}
}
Example 12: Thread communication without methods
class Procedure extends Thread
{
StringBuffer sb;
boolean dataprodover=false;// dataprodover will be true when data production is over
Procedure()
{
sb=new StringBuffer();
}
public void run()
{
for(int i=1;i<=10;i++)
{
try{
sb.append("item"+i+"\n");
Thread.sleep(1000);
//System.out.println("appending");
}
catch(Exception e)
{}
}
dataprodover=true;
}

}
class Consumer extends Thread
{
Procedure prod;
Consumer(Procedure prod)
{
this.prod=prod;
}
public void run()
{
try{
while(!prod.dataprodover)
Thread.sleep(100);
}
catch(Exception e){ }
System.out.print(prod.sb);
}
}
class ThreadCommunication

29
{
public static void main(String[] args)
{
Procedure obj1=new Procedure();
Consumer obj2=new Consumer (obj1);
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();
//System.out.println("Hello World!");
}
}
Example 13: Thread communication with methods
class Procedure1 extends Thread
{
StringBuffer sb;
boolean dataprodover=false;// dataprodover will be true when data production is over
Procedure1()
{
sb=new StringBuffer();
}
public void run()
{
synchronized(sb)
{
for(int i=1;i<=10;i++)
{
try{
sb.append("item"+i+"\n");
//Thread.sleep(1000);
//System.out.println("appending");
}
catch(Exception e)
{}
}
//dataprodover=true;
sb.notify();
}

}
}
class Consumer1 extends Thread
{
Procedure1 prod;
Consumer1(Procedure1 prod)
{
this.prod=prod;
}
public void run()
{

30
synchronized(prod.sb)//wait till a notification is received from procedure
{
try{
//while(!prod.dataprodover)
prod.sb.wait();
//Thread.sleep(100);
}
catch(Exception e){ }
System.out.print(prod.sb);
}
}
}
class ThreadCommunication1
{
public static void main(String[] args)
{
Procedure obj1=new Procedure();
Consumer obj2=new Consumer (obj1);
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t2.start();
t1.start();
//System.out.println("Hello World!");
}
}
COLLECTION FRAMEWORK EXAMPLES
=======ArrayList Example============
import java.util.*;
class ArrayListDemo
{
public static void main(String[] args)
{
List<String> al=new ArrayList<String>();
//use of add(element obj) method
al.add("mango");
al.add("banana");
System.out.println(al);
//use of add(int position, element obj) method
al.add(0,"orange");
System.out.println(al);
//use of remove(int position) method
al.remove(1);
al.add("orange");
System.out.println(al);
//use of remove(Object obj) method
al.remove("orange");
System.out.println(al);
//use of set(int position, element obj) method
al.set(0,"pineapple");
System.out.println(al);

31
//use of contains(Object obj) method
boolean b=al.contains("bread");
System.out.println(b);
//use of get(int position) method
Object a=al.get(1);
System.out.println((String)a);
// use of indexOf(Object obj) method
int x=al.indexOf("banana");
System.out.println(x);
//use of toArray() method
Object[] s=al.toArray();
for(int i=0; i<s.length; i++)
{
System.out.println((String)s[i]);
}

}
}

===========ArrayList Retrieve Elements=======================


import java.util.*;
class ArrayListDemo2
{
public static void main(String[] args)
{
List<String> al=new ArrayList<String>();
al.add("Java");
al.add("Sap");
al.add(".net");
al.add("Cpp");
al.add("Oracle");
System.out.println(al);
System.out.println("*******************************************");
// Retrieving ArrayList elements using foreach loop
for(String s:al)
{
System.out.println(s);
}
System.out.println("*******************************************");
// Retrieving ArrayList elements using Iterator interface
Iterator it=al.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println("*******************************************");
// Retrieving ArrayList elements using ListIterator interface
ListIterator lit=al.listIterator();

32
//forward direction
while(lit.hasNext())
System.out.println(lit.next());
System.out.println("*******************************************");
//backward direction
while(lit.hasPrevious())
System.out.println(lit.previous());
}
}
============DynamicArrayList====================
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class DynamicArrayList {
public ArrayList<Integer> acceptList()
{
ArrayList<Integer> list=new ArrayList<Integer>();

try
{
System.out.println("please values to terminate enterr -99");
Scanner in=new Scanner(System.in);
int i=in.nextInt();
while(i!=-99)
{

list.add(new Integer(i));
i=in.nextInt();

}
}
catch(Exception e)
{

System.out.println("the exception is"+e);


}

return list;
}
public void readList(ArrayList<Integer> list1)
{
ArrayList<Integer> add1=new ArrayList<Integer>();
Iterator<Integer> it=list1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
public static void main(String args[])
{

33
ArrayList list1;
DynamicArrayList dal=new DynamicArrayList();
list1=dal.acceptList();
dal.readList(list1);

}
}
========================LinkedList Example==========================
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList<String>ll=new LinkedList<String>();
//use of add(element obj) method
ll.add("Apple");
ll.add("Bat");
System.out.println(ll);
//use of add(int position, element obj) method
ll.add(0,"Cat");
System.out.println(ll);
//addFirts(element obj) method
ll.addFirst("Dog");
System.out.println(ll);
//addLast(element obj) method
ll.addLast("Egg");
System.out.println(ll);
//removeFirst() method
ll.removeFirst();
System.out.println(ll);
//removeLast() method
ll.removeLast();
System.out.println(ll);
//get(int position) method
Object o=ll.get(1);
System.out.println((String)o);
//getFirst() method
Object o1=ll.getFirst();
System.out.println((String)o1);
//getLast() method
Object o2=ll.getLast();
System.out.println((String)o2);
System.out.println("The contents of LinkList are:"+ll);
String val=ll.get(2);
ll.set(2,val+"changed");
System.out.println("The contents of LinkList after set and get:"+ll);
}
}
===========LinkedListRetrival.java=================================

34
import java.util.*;
class LinkedListDemo1
{
public static void main(String args[])
{
LinkedList<String>ll=new LinkedList<String>();
//use of add(element obj) method
ll.add("Apple");
ll.add("Bat");
ll.add("Cat");
System.out.println("************************************************");
System.out.println(ll);
System.out.println("************************************************");
for(String a:ll)
{
System.out.println(a);
}

System.out.println("************************************************");
Iterator it=ll.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println("*******************************************");
// Retrieving LinkedList elements using ListIterator interface
ListIterator lit=ll.listIterator();
//forward direction
while(lit.hasNext())
System.out.println(lit.next());
System.out.println("*******************************************");
//backward direction
while(lit.hasPrevious())
System.out.println(lit.previous());
}
}
=================Vector Example================
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +

35
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
=============================Stack
Example===============================
import java.util.*;
import java.io.*;
class StackDemo
{
public static void main(String args[]) throws Exception
{
Stack<Integer> st=new Stack<Integer>();
int choice=0;
int position, element;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(choice<4)
{
System.out.println("STACK OPERATIONS");
System.out.println("1 Push Operation");
System.out.println("2 Pop OPeration");
System.out.println("3 Search Element");
System.out.println("4 Exit");
System.out.println("Enter Your Choice");
choice=Integer.parseInt(br.readLine());
switch(choice)

36
{
case 1:

System.out.print("enter Element:");
element=Integer.parseInt(br.readLine());
st.push(element) ;
break;

case 2:
Integer obj=st.pop();
System.out.println("Popped="+obj);
break;

case 3:

System.out.println("Which Element?:");
element=Integer.parseInt(br.readLine());
position=st.search(element);
if(position==-1)
System.out.println("Element not found");
else
System.out.println("position:"+position);
break;

System.out.println("Stack Contents:"+st);
}

}
}
=====================HashSet Example=======================
import java.util.*;
public class HashSetDemo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
=======================HashSet Retrieval==============
import java.util.HashSet;
import java.util.Iterator;

37
public class HashSetRetrival {
public static void main(String args[]) {
// create a hash set
HashSet<String> hs = new HashSet<String>();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
System.out.println("**********************************************");
Iterator<String> it=hs.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("**********************************************");
for(String s:hs)
{
System.out.println(s);
}
}
}
===========DynamicHashSet=================================
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class DynamicHashSet {

public HashSet<String> acceptList()


{
HashSet<String> list=new HashSet<String>();

try
{
System.out.println("please values to terminate enterr end");
Scanner in=new Scanner(System.in);
String s=in.next();
while(!s.equals("end"))
{

list.add(s);
s=in.next();

}
}
catch(Exception e)
{

38
System.out.println("the exception is"+e);
}

return list;
}
public void readList(HashSet<String> list1)
{
HashSet<String> add1=new HashSet<String>();
Iterator<String> it=list1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
public static void main(String args[])
{
HashSet list1;
DynamicHashSet dal=new DynamicHashSet();
list1=dal.acceptList();
dal.readList(list1);
}
}
================LinkedHashSet Example===========================
import java.util.*;
public class HAshSetDemo1 {
public static void main(String args[]) {
// create a hash set
LinkedHashSet hs = new LinkedHashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
===================LinkedHashSet Retrieval=========================
import java.util.*;

public class LinkedHashSetRetrieval {

public static void main(String args[]) {


// create a hash set
LinkedHashSet<String> hs = new LinkedHashSet<String>();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");

39
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
System.out.println(" ********************************************");
for(String s:hs)
{
System.out.println(s);
}
System.out.println(" ********************************************");
Iterator it=hs.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

}
}
=============TreeSet Example==================================
import java.util.*;
public class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set
TreeSet<String> ts = new TreeSet<String>();
// Add elements to the tree set
ts.add("Apple");
ts.add("Cat");
ts.add("Bat");
ts.add("Fox");
ts.add("Egg");
ts.add("Dog");
System.out.println(ts);
}
}
===============TreeSetRetrieval==============================
import java.util.*;
public class TreeSetRetrieval {
public static void main(String args[]) {
// Create a tree set
TreeSet<String> ts = new TreeSet<String>();
// Add elements to the tree set
ts.add("Apple");
ts.add("Cat");
ts.add("Bat");
ts.add("Fox");
ts.add("Egg");
ts.add("Dog");
System.out.println(ts);
System.out.println(ts.size());
System.out.println("***********************************");

40
for(String s:ts)
{
System.out.println(s);
}
System.out.println("***********************************");
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

}
}
================HashMap Example====================
import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap<String,Double> hm = new HashMap<String,Double>();
// Put elements to the map
hm.put("Ram", 3434.34);
hm.put("Mohan", 123.22);
hm.put("Rao", 1378.00);
hm.put("Ravi", 99.22);
hm.put("Raju", 19.08);
System.out.println(hm);
// Deposit 1000 into Ram's account

double balance = ((Double)hm.get("Ram")).doubleValue();


hm.put("Ram", new Double(balance + 1000));
System.out.println("Ram's new balance: " + hm.get("Ram"));
}
}
===============HashMap Retrieval============================
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class HashMap1 {
public static void main(String[] args) {
HashMap<String,Double> hs=new HashMap<String,Double>();
hs.put("Ram", 4500.89);
hs.put("Mohan",5500.89);
hs.put("Siva", 6500.89);
hs.put("Ravi", 8500.89);
hs.put("nani", 7500.89);
System.out.println(hs);
Set<Map.Entry<String, Double>> set=hs.entrySet();
for(Map.Entry<String, Double> me:set){
System.out.print(me.getKey()+":");

41
System.out.println(me.getValue());
for(int i=0;i<set.size();i++){

}
} }
}
==============Dynamic HashMap==============================
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class HashMapDemo1 {
public HashMap<String,String> acceptMap(){
HashMap<String,String> mp1=new HashMap<String,String>();
System.out.println("Enter Values");
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String s2=sc.next();
while(!s1.equals("end")){
mp1.put(s1, s2);
s1=sc.next();
s2=sc.next();
}
return mp1;
}
public void display(HashMap<String,String> hs){
Set<Map.Entry<String,String>> set=hs.entrySet();
for(Map.Entry<String,String> hs1:set){
System.out.print(hs1.getKey()+":");
System.out.println(hs1.getValue());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stubHashMap
HashMapDemo1 hd=new HashMapDemo1();
HashMap<String,String> x;
HashMap<String,String> x1;
x=hd.acceptMap();
hd.display(x);
}
}
=============LinkedHashMapDemo============================
import java.util.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class LinkedHashMapDemo {
public static void main(String[] args) {
LinkedHashMap<String,Double> hs=new LinkedHashMap<String,Double>();

42
hs.put("Ram", 4500.89);
hs.put("Mohan",5500.89);
hs.put("Siva", 6500.89);
hs.put("Ravi", 8500.89);
hs.put("nani", 7500.89);
System.out.println(hs);

Set<Map.Entry<String, Double>> set=hs.entrySet();


for(Map.Entry<String, Double> me:set){
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
for(int i=0;i<set.size();i++){
}
}
}
}
============HashTable===========================
import java.util.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class HashTableDemo {
public static void main(String[] args) {
Hashtable<String,Double> hs=new Hashtable<String,Double>();
hs.put("Ram", 4500.89);
hs.put("Mohan",5500.89);
hs.put("Siva", 6500.89);
hs.put("Ravi", 8500.89);
hs.put("nani", 7500.89);
System.out.println(hs);
Enumeration e=hs.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
/*Set<Map.Entry<String, Double>> set=hs.entrySet();
for(Map.Entry<String, Double> me:set){
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
for(int i=0;i<set.size();i++){

} */
}}
===================TreeMapDemo========================
import java.util.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

43
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<String,Double> hs=new TreeMap<String,Double>();
hs.put("Ram", 4500.89);
hs.put("Mohan",5500.89);
hs.put("Siva", 6500.89);
hs.put("Ravi", 8500.89);
hs.put("nani", 7500.89);
System.out.println(hs);
Set<Map.Entry<String, Double>> set=hs.entrySet();
for(Map.Entry<String, Double> me:set){
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
}}
==================Comparator Example==========================
import java.util.*;
class MyComp implements Comparator<String>
{
public int compare(String a, String b)
{
String aStr, bStr;
aStr=a;
bStr=b;

return bStr.compareTo(aStr);

}
}
class CompDemo
{
public static void main(String[] args)
{
TreeSet<String> ts=new TreeSet<String>(new MyComp());
ts.add("Cat");
ts.add("Apple");
ts.add("Bat");
ts.add("Egg");
ts.add("Fox");
ts.add("Dog");
for(String e:ts)
{
System.out.println(e+" ");
}
}
}

======================Date Example=======================
import java.util.*;
class DateDemo

44
{
public static void main(String[] args)
{
Date date=new Date();
System.out.println(date);
long msec=date.getTime();
System.out.println(msec);
}
}
================Date Exanple2============================
import java.util.*;
class TestDates {
public static void main(String[] args) {
Date d1 = new Date(); // a trillion!
System.out.println("1st date " + d1.toString());
System.out.println("1st date " + d1.getTime());
d1.setTime(d1.getTime() + 3600000); // 3600000 millis / hour
System.out.println("new time " + d1.toString());
}
}
================Calender Class===================
import java.util.*;
class Dates2 {
public static void main(String[] args) {
Date d1 = new Date();
System.out.println("Today date " + d1.toString());
Calendar c = Calendar.getInstance();
c.setTime(d1); // #1
if(Calendar.SUNDAY == c.getFirstDayOfWeek()) // #2
System.out.println("Sunday is the first day of the week");
System.out.println("today is "+ c.get(Calendar.DAY_OF_WEEK)); // #3
c.add(Calendar.MONTH, 1); // #4
Date d2 = c.getTime(); // #5
System.out.println("new date " + d2.toString() );
}
}

INTRODUCTION
Every real-time application contains the following logics
• Presentation logic (HTML, SERVLETS, JSP)
– Creating screens for accepting input values of a client
• Business logic (CORE JAVA CONCEPTS)
– Reading input values and process the given input based on business rules
• Persistence logic(JDBC)
– Responsible for transferring the data generated by a business logic into a
permanent area like a file or database
File as a backend
• Files which are used as backend are generally called as flat files
• Flat file means, it is a file which is no way related with any programming language or
any technology

45
• We can transfer data in the form of text (i/o streams) or in the form of objects
(serialization)
Limitations
• Don’t have any query language support
• Doesn’t support relationship between the data
• Less secured
Why JDBC?
• Initial days, database vendor provided functions (API) are used to for communicating
with a database
• The applications which are using the vendor API are called vendor dependent
applications, it makes applications as database dependent
• Example, for connecting C or C++ programs with oracle database, we use the
functions given by oracle in header file called orcl.h
• To solve database dependency problem a community was formed with professionals
of different MNC’s called X/open
• X/open created a set of rules for transferring commands to a database and for reading
results from a database in a database independent manner
• By using X/open CLI (Call Level Interface), Microsoft and Simba technologies
jointly created ODBC (Open Database Connectivity) API
ODBC API
• ODBC api is database independent for connecting front end application with different
databases
Limitations of ODBC along work with java
– ODBC is a C-API with pointers coding (incomparability)
– Non pointer code will be converted to pinter code when a request is going to
database and pointer code is converted into non pointer code when a response
is coming from a database. This conversion makes application execution very
slow
– ODBC api is platform dependent
• In order to overcome the problems of java and ODBC combination, SUN MICRO
SYSTEM created its own API as JDBC API

WHAT IS JDBC?
JDBC is an API specification given by Sun Micro System, for developing java applications to
communicate with database
JDBC API contains the following 2-packaes, with ore number of interfaces and less number
of classes
• java.sql
• javx.sql
JDBC API is a part of Java API. It means JDBC API comes along with jdk software

46
JDBC DRIVER
• A JDBC Driver is a software which contains a set of classes and acts as a mediator to
connect a java application with a database
• As java application developer, we need JDBC API and JDBC Driver to store or read
the data from a database
JDBC DRIVERS
There are 4 types of JDBC drivers:
1) JDBC-ODBC bridge driver
2) Native-API driver (partially java driver)
3) Network Protocol driver (fully java driver)
4) Thin driver (fully java driver)
JDBC-ODBC BRIDGE DRIVER
• This driver is a built-in driver of Java software
• The JDBC-ODBC bridge driver translates all JDBC calls into ODBC calls and when
getting response ODBC calls are converted back to JDBC calls
• This driver is one, to talk with multiple databases. Because it uses internally an
ODBC driver belong to a particular database to obtain a connection
• The JDBC-ODBC Bridge driver is recommended only for experimental use or when
no other alternative is available

Advantages:
 easy to use.
 can be easily connected to any database.
Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC
funcion calls.
 The ODBC driver needs to be installed on the client machine.
Native-API/partly Java driver
• The Native-API/partly Java driver convert JDBC calls into database-specific calls i.e.
this driver is specific to a particular database.
• It is not written entirely in java

47
Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
• The Native driver needs to be installed on the each client machine.
• The Vendor client library needs to be installed on client machine.

All Java/Net-protocol driver


• In Java/Net-Protocol driver database requests are passed through the network to the
middle-tier server.
• The middle-tier then translates the request to the database.
• If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.

Advantage
1. This driver is server-based, so there is no need for any vendor database library to be
present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. This driver is very flexible allows access to multiple databases using one driver
4. They are the most efficient amongst all driver types.
Disadvantage
• It requires another server application to install and maintain. Traversing the record set
may take longer, since the data comes through the backend server.

Native-protocol/all-Java driver
• The thin driver converts JDBC calls directly into the vendor-specific database
protocol.
• That is why it is known as thin driver. It is fully written in Java language.

48
Advantage
1. The major benefit of using this drivers are that they are completely written in
2. Java to achieve platform independence and eliminate deployment administration
issues.
3. It is most suitable for the web.
4. Number of translation layers is very less
Disadvantags
With type 4 drivers, the user needs a different driver for each database.

Basic Steps in Using JDBC


1) Load the driver
2) Define the Connection URL
3) Establish the Connection
4) Create a Statement object
5) Execute a query
6) Process the results
7) Close the connection
Load the Driver
• Loading a JDBC driver is nothing but creating an object of JDBC driver class and
registering that driver object with DriverManger service
• DriverManager is a service which holds all the loaded driver class objects
• To load a JDBC driver class into JVM at run time, we use a method forName() of
Class class.
Sample Code
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Here, “sun.jdbc.odbc” is package name and JdbcOdbcDriver is a class name, It is a Sun
MicroSystems developed driver
Define the Connection URL
• We need to supply the database URL for connectivity purpose. This URL is known as
connection string. When we are using Sun driver, connecting string will be in the
following form
String cs=“jdbc:odbc:dsn”;
• DataSourceName we have configure externally.
• After configuring, we give some name to the configuration. That name we use in the
connection string
Establish the Connection

49
• Java program calls the following method on the DriverManager to get the database
connection
Connection con=DriverManager.getConnection(cs,”username”,”password”);
Create a Statement object
Statement st =con.createStatement();
“st” is the JDBC object used to submit SQL statements from the java program.
It has two important methods
1) executeUpdate() [UPDATE, INSERT, DELETE]
2) executeQuery() [select]
Execute a query
String query =
"SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet =
statement.executeQuery(query);
Process the results
while(resultSet.next())
{
System.out.println(resultSet.getString(1) + " " +
resultSet.getString(2) + " " +
resultSet.getString(3));
}
– First column has index 1, not 0
Close the connection
connection.close();
Since opening a connection is expensive, postpone this step if additional database operations
are expected

The following examples based on type-1 driver and Statement interface


Example1: Create a table
import java.sql.*;
public class CreateTable {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:java911","system","manager");
Statement st=con.createStatement();
int x=st.executeUpdate("create table java911(sno number(5), sname varchar2(10))");
System.out.println("Table Created");
}}
Example2: insert data into table
import java.sql.*;
public class CreateTable {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:java911","system","manager");
Statement st=con.createStatement();
int x=st.executeUpdate("insert into java911 values(1,'ram')");

50
System.out.println("data inserted");}}
Example3: update table data
import java.sql.*;
public class CreateTable {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:java911","system","manager");
Statement st=con.createStatement();
int x=st.executeUpdate("update java911 set sname='raju' where sno=1");
System.out.println("data updated");
}}
Example 4: delete table data
import java.sql.*;
public class CreateTable {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:java911","system","manager");
Statement st=con.createStatement();
int x=st.executeUpdate("delete from emp_info where eno=1");
System.out.println("data updated");}}
Example 5: select table data
import java.sql.*;
public class SelectData {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","system","manager");
Statement st=con.createStatement();
String query="select *from sku_data";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3));
}
System.out.println("End of Data");
}}

Example6: Getting the connection properties from other class and do all database
operations using user defined methods
Connection given class
import java.sql.*;
public class GetConnection {
public static Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

51
Connection
con=DriverManager.getConnection("jdbc:odbc:java911","system","manager");
return con;
}
}

Connection getting class


import java.sql.*
public class MethodOperations {
Statement st;.
public Connection gettingConnection() throws ClassNotFoundException, SQLException{
Connection con=GetConnection.getConnection();
return con;
}
public int insertData() throws ClassNotFoundException, SQLException {
Connection con=gettingConnection();
st=con.createStatement();
int x=st.executeUpdate("insert into emp_info values(111,'sprint',1000)");
System.out.println("DataInserted");
return x;
}
public int updateData() throws ClassNotFoundException, SQLException{
Connection con=gettingConnection();
st=con.createStatement();
int x=st.executeUpdate("update emp_info set sal=2000 where eno=111");
System.out.println("DataUpdated");
return x;
}
public int deleteData() throws ClassNotFoundException, SQLException {
Connection con=gettingConnection();
st=con.createStatement();
int x=st.executeUpdate("delete from emp_info where eno=111");
System.out.println("Data deleted");
return x;
}
public ResultSet selectData() throws ClassNotFoundException, SQLException{
Connection con=gettingConnection();
st=con.createStatement();
ResultSet rs=st.executeQuery("select * from emp_info");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3));
}
return rs;
}
public static void main(String[] args) throws ClassNotFoundException, SQLException{
MethodOperations m=new MethodOperations();
m.gettingConnection();
m.insertData();
m.updateData();
m.deleteData();

52
m.selectData();
}

Example7: Insert values dynamically into a table


import java.sql.*;
import java.util.Scanner;
public class DynamicInsert {
Statement st=null;
public int insertData() throws ClassNotFoundException, SQLException{
int k = 0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Id");
int n=sc.nextInt();
System.out.println("Enter Student Name");
String str=sc.next();
System.out.println("Enter Student Marks");
int m=sc.nextInt();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:oradsn","system","manager");
st=con.createStatement();
k=st.executeUpdate("insert into sku_data values("+n+",' "+str+" ',"+m+")");
System.out.println(k+"rows is inserted-----");
st.close();
con.close();
return k;
}
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
DynamicInsert di=new DynamicInsert();
di.insertData();
}}
Example8: getting connection without using DriverManager class
import java.sql.*;
import java.util.Properties;
import sun.jdbc.odbc.JdbcOdbcDriver;
public class WithoutDM {
public static void main(String[] args) throws SQLException {
Properties p=new Properties();
p.put("user", "system");
p.put("password","manager");
JdbcOdbcDriver jd=new JdbcOdbcDriver();
Connection con=jd.connect("jdbc:odbc:oradsn",p);
System.out.println("Connection opened");
con.close();
System.out.println("Connection closed");
}}
Example 9: execute method of Statement interface

53
import java.sql.*
import java.util.Scanner;
public class ExecuteDemo {
Statement st=null;
boolean b;
ResultSet rs=null;
public void executeDemo()throws Exception{
Connection c=TestConnection.getConnection();
st=c.createStatement();
Scanner sc=new Scanner(System.in);
System.out.println("Enter The SQL Command");
String str=sc.nextLine();
boolean b=st.execute(str);
if(b){
ResultSet rs=st.getResultSet();
while(rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getShort(3));
System.out.println("====================");
}
}
else{
int k = 0;
k = st.getUpdateCount();
System.out.println(k+"RowsEffectted");
}//else
st.close();
c.close();
}
public static void main(String[] args) throws Exception {
ExecuteDemo ed=new ExecuteDemo();
ed.executeDemo();
}}
Getting Connection Properties Using Properties File
#talent.properties
jdbc.driver=sun.jdbc.odbc.JdbcOdbcDriver
jdbc.url=jdbc:odbc:oradsn
jdbc.user=system
jdbc.password=manager
This file is stored in Project level
In JDBC Application
Properties p=new Properties();
FileInputStream fin=new FileInputStream("talent.properties");
p.load(fin);
String s1=p.getProperty("jdbc.driver");
String s2=p.getProperty("jdbc.url");
String s3=p.getProperty("jdbc.user");
String s4=p.getProperty("jdbc.password");
Example 10: Getting the connection properties by using Properties file
talent.properties
jdbc.driver=sun.jdbc.odbc.JdbcOdbcDriver

54
jdbc.url=jdbc:odbc:oradsn
jdbc.user=system
jdbc.password=manager

import java.io.*;
import java.sql.*;
import java.util.Properties;
public class ResourceBundle {
public static void main(String[] args) throws IOException, ClassNotFoundException,
SQLException {
Properties p=new Properties();
FileInputStream fin=new FileInputStream("talent.properties");
p.load(fin);
String s1=p.getProperty("jdbc.driver");
String s2=p.getProperty("jdbc.url");
String s3=p.getProperty("jdbc.user");
String s4=p.getProperty("jdbc.password");
Class.forName(s1);
System.out.println(s1+"Driver is Loaded");
Connection con=DriverManager.getConnection(s2,s3,s4);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from sku_data");
while(rs.next()) {

System.out.println(rs.getString(1)+""+rs.getString(2)+""+rs.getString(3));
}
rs.close();
st.close();
con.close();
}}
Statement Interface
• Through the Statement object, SQL statements are sent to the database.
• For executing a simple SQL statement
Useful Statement methods
executeQuery
Executes the SQL query and returns the data in a table (ResultSet)
The resulting table may be empty but never null
ResultSet rs=statement.executeQuery("SELECT a, b FROM table");
executeUpdate
Used to execute for INSERT, UPDATE, or DELETE SQL statements
The return is the number of rows that were affected in the database
int rows =statement.executeUpdate(“INSERT INTO EMP VALUES(1001,’RAM’,800”);
execute()
Used to execute for SELECT or NON-SELECT SQL statements
Limitation of Statement interface
• It is not possible to insert binary data into database
• Set dynamic values to an sql command then we need to write complex query
• Statement interface compiles an sql command each time, before it is going to transfer
to a database. Even though the same command is executing for multiple times, the
Statement interface compiles it every time.

55
PreparedStatement Interface
• It is extended from Statement interface
• It supports binary data columns of the database
• PreparedStatement create dynamic sql quires very easily by putting ‘?’symbols
• PreparedStatement interface compiles sql command for once and then it can be
executed for any number of times by without recompiling that command again
PreparedStatement pst=con.prepareStatement(“sql command”);
pst-contains compiled code of SQL command
• To make an sql command as dynamic, we put ‘?’ symbols in place of values in an sql
command. This ‘?’ symbol is called as a place resolution operator or a replacement
operator
PreparedStatement pst=con.prepareStatement(“insert into values sku_data values(?,?,?)”);
• To set values into each ‘?’ symbol place, we need to call setXXX() methods
pst.setInt(1,101);
pst.setString(2,”abc”);
pst.setInt(3,500);
int k=pst.executeUpadate();
Example 11: Insert values into table dynamically by using PrepareStatement interface
import java.sql.*;
import java.util.Scanner;
public class PreDynamic {
public int insertData() throws SQLException, ClassNotFoundException{
int k = 0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Id");
int n=sc.nextInt();
System.out.println("Enter Student Name");
String str=sc.next();
System.out.println("Enter Student Marks");
int m=sc.nextInt();
Connection con=GetConnection.getConnection();
PreparedStatement stmt=con.prepareStatement("insert into sku_data
values(?,?,?)");
stmt.setInt(1,n);
stmt.setString(2, str);
stmt.setInt(3, m);
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
stmt.close();
con.close();
return k;
}
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
PreDynamic di=new PreDynamic();
di.insertData();
}}
Example 12: Geeting records from database by using type-2 driver of oracle and
PreapredStatement interface
import java.sql.*;

56
public class Type2Connection {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("oracle.jdbc.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:oci:@XE","system","manager");
String s="select * from student_info where sid=?";
PreparedStatement st=con.prepareStatement(s);
st.setInt(1,2);
ResultSet rs=st.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
rs.close();
st.close();
con.close();
}}
Example 13: Working with oracle type-4 driver
import java.sql.*;
public class Type4Connection {
public static void main(String[] args) throws ClassNotFoundException, SQLException
Class.forName("oracle.jdbc.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manag
er");
String s="select * from student_info where sid=?";
PreparedStatement st=con.prepareStatement(s);
st.setInt(1,2);
ResultSet rs=st.executeQuery();
while(rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
rs.close();
st.close();
con.close();
}}
Insert image into Database table
• Inserting a picture into a database table is nothing but storing binary data of a picture
in a BLOB type of column in a database table
• To insert a picture into a database table, we need to read its binary data using
FileInputStream object and then we need to set the binary stream of data into the SQL
inset command by using setBinaryStream() method
setBinaryStream(int, inputstream object, int)
Retrieve image from Database table
• When we select a picture from a database table then directly a picture doesn’t come,
but its binary data will be selected
• We need to convert the binary data into a picture, with the help of FileOutputStream
class

57
• When we execute a select operation for selecting a picture then the ResultSet object is
going to contain binary stream of data and to read it we need to call a method
getBinaryStream(int)
Example 14: insert image into database table
import java.io.*;
import java.sql.*;
public class InsertImage {
private Connection con;
private PreparedStatement pst;
public void openConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");

con=DriverManager.getConnection("jdbc:oracle:oci:@XE","system","manager");
pst=con.prepareStatement("insert into company_info values(?,?)");
}
public void insertRow() throws SQLException, FileNotFoundException {
pst.setString(1, "talent");
File f=new File("c:\\SonicBigAni.gif");
FileInputStream fis=new FileInputStream(f);
int length=(int)f.length();
pst.setBinaryStream(2, fis,length);
int k=pst.executeUpdate();
System.out.println(k+"rows inserted");
}
public void closeConnection() throws SQLException{
pst.close();
con.close();}
public static void main(String[] args) throws ClassNotFoundException,
SQLException, FileNotFoundException {
InsertImage im=new InsertImage();
im.openConnection();
im.insertRow();
im.closeConnection();

}
}
Example 15: Retrieve image from database table
import java.io.*;
import java.sql.*;
public class RetrieveImage {
private Connection con;
private PreparedStatement pst;
public void openConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:oci:@XE","system","manager");
pst=con.prepareStatement("select company_logo from company_info where
company_name=?");
}
public void selectImage() throws SQLException, IOException{
pst.setString(1, "talent");

58
ResultSet rs=pst.executeQuery();
rs.next();
InputStream is=rs.getBinaryStream(1);
FileOutputStream fos=new FileOutputStream("BigAni.gif");
int k;
while((k=is.read())!=-1)
{
fos.write(k);
}
fos.close();
rs.close();
}
public void closeConnection() throws SQLException{
pst.close();
con.close();
}
public static void main(String[] args) throws ClassNotFoundException,
SQLException, IOException {
RetrieveImage ri=new RetrieveImage();
ri.openConnection();
ri.selectImage();
ri.closeConnection();

}}
Example 16: insert Date into database table
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class DateInsert {
public void dateInsert() throws SQLException, ParseException, ClassNotFoundException{
Connection con=TestConnection.getConnection();
PreparedStatement pst=con.prepareStatement("insert into customer_info
values(?,?,?)"); Scanner sc=new Scanner(System.in);
System.out.println("Enter Customer ID");
int cid=sc.nextInt();
System.out.println("Enter Customer Name");
String cname=sc.next();
System.out.println("Enter Customer Date of Birth(yyyy-mm-dd)");
String dob=sc.next();
pst.setInt(1,cid);
pst.setString(2,cname);
//create SimpleDateFormat class object
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//convert string into java.util.Date
java.util.Date d1=sdf.parse(dob);
//convert java.util.Date into java.sql.Date
long ms=d1.getTime();
java.sql.Date d2=new java.sql.Date(ms);
pst.setDate(3,d2);

59
int k=pst.executeUpdate();
System.out.println(k+"Rows inserted");
pst.close();
con.close();
}
public static void main(String[] args) throws ClassNotFoundException, SQLException,
ParseException {
DateInsert d=new DateInsert();
d.dateInsert();
}}
Example 17: Retrieve date from database
import java.sql.*;
import java.text.SimpleDateFormat;
public class RetrieveDate {
public void retrieveDate() throws SQLException, ClassNotFoundException{
Connection con=TestConnection.getConnection();
PreparedStatement pst=con.prepareStatement("select dob from customer_info" );
//pst.setInt(1,100);
ResultSet rs=pst.executeQuery();
rs.next();
java.sql.Date d2=rs.getDate(1);
System.out.println(d2);
java.util.Date d1=(java.util.Date)d2;
SimpleDateFormat sdf=new SimpleDateFormat("EEE-MMMM-yyyy");
String str=sdf.format(d1);
System.out.println(str);
rs.close();
pst.close();
con.close();
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
RetrieveDate rd=new RetrieveDate();
rd.retrieveDate();
}}
BatchUpdates
A batch update is a set of multiple update statements that is submitted to the database for
processing as a batch
Methods
addBatch() is used to add individual statements to the batch
public void addBatch(java.lang.String sql)
executeBatch() method is used to start the execution of all the statements
public int[] executeBatch()
Example:
Statement st=con.createStatement();
st.addBatch(“insert into emp values(‘raju’,100);
st.addBatch(“delete from emp where eno=100”);
st.executeBatch();
Example 18: example on batch updates
importjava.sql.*;

60
classBatchUpdates{
public static void main(String args[]) throws Exception{
String driver="sun.jdbc.odbc.JdbcOdbcDriver";
String cs="jdbc:odbc:oradsn";
String user="system";
String pwd="password";
Class.forName(driver);
System.out.println("Driver Loaded");
Connection con=DriverManager.getConnection(cs,user,pwd);
Statement st=con.createStatement();
st.addBatch("insert into student_info values(10,'money',500)");
st.addBatch("update student_info set sname='monday' where sid=666");
st.addBatch("delete from student_info123 where sid=1");
con.setAutoCommit(false);
try{
int k[]=st.executeBatch();
con.commit();
System.out.println("Batch Successfully executed"); }
catch(Exception e){
try{
con.rollback();
System.out.println("Batch Failed.....");
e.printStackTrace();
}
catch(Exception e1){ }
}
st.close();
con.close();
}}
CallableStatement
• PreparedStatement execute select or non-select SQL commands. But a
CallableStatement can execute not only SQL commands, but also a procedure or a
function of a database
• To get a CallableStatement object, we call prepareCall() method given by Connection
interface
CallableStatement cst=con.prepareCall(“sql command”);
CallableStatement cst=con.prepareCall(“ {call procedure name/ functionname}”);

Example19: Working with CallableStaatement


SQL Procedure
create or replace procedure experiencepro(eno in number, e out number)
is
d1 date;
d2 date;
begin
select hire_date into d1 from emp_hire where eno=eno;
select sysdate into d2 from dual;
e:=(d2-d1)/365;
end;

61
importjava.sql.*;
importjava.util.Scanner;
public class CallableTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManag
JDBer.getConnection("jdbc:odbc:oradsn","system","password");
CallableStatementcst=con.prepareCall("{call experience(?,?)}");
Scanner sc=new Scanner(System.in);
System.out.println("Enter Employee Id");
inteno=sc.nextInt();
cst.setInt(1,eno);
cst.registerOutParameter(2,Types.INTEGER);
cst.execute();
int b=cst.getInt(2);
System.out.println(b);
cst.close();
con.close()
}
}
Transaction Management in JDBC
• A Tx is a group of operations, which produces either success or fail result
• A Tx produces success if all operations in the group are executed successfully
otherwise Tx fails
• A Tx follows a principle “All or Nothing”
Types of Transactions
Local transaction
If all the operations are executing against a single database then it is called as local
transactions
Global transactions (or) distributed transactions
If a transaction operations are executing against more than one database then it is called as
global transactions

• JDBC only supports local transactions


• If we execute any SQL operation from a JDBC program on a database then by default
that operation is permently executed on the database. The reason is, in JDBC, a
connection object contains autoCommit mode, and its default value is true
• To do Tx management in JDBC, first of all we need to disable autoCommit mode. For
this we need to call a method setAutoCommit(false)
• If all operations in the group are successfully executed on a database then we need to
commit the operations. It means Tx is successfully done
• If any operation is failed then we cancel all operations in that group
• To commit or rollback a Tx, we need to call either commit() method or rollback()
method
• Finally the following 3-methods are required to do Tx management in JDBC
o setAutoCommit()
o commit()

62
o rollback()
• In a JDBC program, we use try and catch blocks for executing Tx. We put group of
opeartions in try block and we commit the operations in try block. In catch block we
rollback the oprations
Example 20: example on Transaction api of JDBC
importjava.sql.*;
public class TransactionTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","passw
ord");
System.out.println("Connection ok");
Statement st=con.createStatement();
con.setAutoCommit(false);
try{
int i1=st.executeUpdate("insert into student_info values(002,'zyx',999)");
int i2=st.executeUpdate("update student_info set sname='xxx' where
sid=100");
int i3=st.executeUpdate("delete from student_info where sid=789");
con.commit();
}
catch(Exception e){
try{
con.rollback();
System.out.println("Transaction Failed");
}
catch(Exception e1){ }
st.close();
con.close();
}}}
Types of ResultSets
• ResultSet is used to retrieve the data from the table
• ResultSet rs=st.executeQuery(“select * from emp”);
• ResultSet object holds the table of records returned from the database.
• When the ResultSet is opened, the cursor points to the zero record.
• Using the ResultSet methods we have to move the cursor to each record and get the
column values
ScrollableResultSet with Statement interface
• In earlier version of JDBC API, we can move the cursor across the ResultSet only in
forward direction.
• In JDBC2.0 API is the ability to move a ResultSet cursor backward as well as forward
• Statement st=con.createStatement(CONST1,CONST2);
• PreparedStaement pst=con.prepareStatement(“command”,type,mode);
• CallableStatement cst=con.prepareCall(“command”,type,mode);
• CONST1 may be
• ResultSet.TYPE_SCROLL_SENSITIVE (if any changes are made on database
will be automatically effected on ResultSet)(1005)
• ResultSet.TYPE_SCROLL_INSENSITIVE (if any changes are made on
database then the changes are not effected ResultSet)(1004)

63
• ResultSet.TYPE_SCROLL_FORWARD_ONLY (1003)
• CONST2 maybe
• ResultSet.CONCUR_READ_ONLY (read the data from the ResultSet object)
(1007)
• ResultSet.CONCUR_UPDATEABLE( it allows insertion, updating,deletion
activities)(1008)
Methods of ScrollableResultSet
• afterLast()
• previous()
• absoulte(+/-)
– rs.absoulte(5); moves cursor to the fifth record from top and rs.absoulte(-5);
moves the cursor to the fifth record from bottom
• relative(+n/-n)
– rs.relative(5); if the cursor is at 10th record then moves the cursor 15th record
and rs.relative(-5) moves the cursor to 5th record
• first()
• last()
• beforeFirst()
• next()
• getRow(); gives current position of the cursor
Example 21: example on ScrollableResultSet
importjava.sql.*;
public class ScrollableTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:oradsn","system","password");
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_REA
D_ONLY);
ResultSetrs=st.executeQuery("select * from student_info");
//reading in backward direction
rs.afterLast();
while(rs.previous()){
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
//printing 3rd record
System.out.println("===========================");
rs.absolute(3);
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
System.out.println("===========================");
//printing one record back from current place
rs.relative(-1);
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
st.close();
con.close();
}}
Updateable ResultSet
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDAT
ABLE);

64
Update a Row
Move the cursor to the required row (using rs.absolute(int n))
Call the updateXXX() method on the ResultSet object
Calling the updateRow() method on the ResultSet object
Inserting Rows
Call the method moveToInsertRow()
Set value for each column to each row
Call the method insertRow()
Example 22:insert data using UpdateableResultSet
importjava.sql.*;
public class MySqlUpdateInsert {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata1","root","mysql");
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPD
ATABLE);
ResultSetrs=st.executeQuery("select * from student_info1");
//rs.afterLast();
rs.moveToInsertRow();
rs.updateInt(1,789);
//String s="Hi";
//rs.updateString(2,s);
rs.updateString(2,"fores");
rs.updateInt(3,108);
rs.insertRow();
System.out.println("Row Inserted");
rs.close();
st.close();
con.close();
}

Example 23:Update the data using UpdatableResultset


importjava.sql.*;
public class MySqlUpdateUpdate {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata1","root","mysql");
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPD
ATABLE);
ResultSetrs=st.executeQuery("select * from student_info1");
while(rs.next()){
int k=rs.getInt(1);
if(k==9999){
rs.updateInt(1,8888);

65
rs.updateRow();
break;}}
}
}

SERVLET EXAMPLES

Example1: Print ‘Hello’ using GenericServlet


public class FirstServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
PrintWriter out=response.getWriter();
out.println("Hello");
}
}

Example2:Display date by using HttpServlet


public class HttpDate extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out=response.getWriter();
Date d=new Date();
String str=d.toString();
response.setHeader("Refresh", "1");
out.println(str);
out.close();
}
}
Example3:Form to Servlet communication using sumbit button
login.html
<html>
<body>
<center>
<form action="SubmitButton">
UserName:<input type=text name="uname"><br>
Password:<input type=password name="pwd"><br>
<input type=submit value="click">
</form>
</center>
</body>
</html>

SubmitButton.java
public class SubmitButton extends HttpServlet {

66
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
String s1=request.getParameter("uname");
String s2=request.getParameter("pwd");
PrintWriter out=response.getWriter();
out.println(s1);
out.println(s2);
}

Example4:Form to Servlet communication using hyperlink


hyperlink.html
<html>
<body>
<form>
<h2>Click on bellow hyperlink to call a servlet</h2><br/>
<a href="HyperServlet">Click to call servlet</a>
</form></body></html>

HyperServlet.java
public class HyperServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("Coming from hyperlink");
}
}

Example5: Form toServlet Communication using JavaScript


javascript.html
<html>
<body>
<script>
function fun1()
{
alert("eneterd into javascript");
document.form.action="JavaScriptServlet";
document.form.submit();
}
</script>
<center>
<form name="form">
Select Country:<select name="s1" onChange="fun1()">
<option value=" ">-select-</option>
<option value="INDIA">india</option>
<option value="USA">usa</option>
<option value="UK">uk</option>
<option value="JAPAN">japan</option>

67
</select></form></center></body></html>
JavaScriptServlet.java
public class JavaScriptServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String str=request.getParameter("s1");
int n=str.length();
PrintWriter out=response.getWriter();
out.println("Length of Selected Country is:"+n);
out.close();

}
}

Example6: Read form fields data using ‘getParameterNames() method


getparameternames.html
<html>
<body>
<center>
<form action="GetParameterNamesServlet">
First Name <input type="text" name="fname"><br>
Middle Name <input type="text" name="mname"><br>
Last Name <input type="text" name="lname"><br>
Email <input type="text" name="email"><br>
Father Name <input type="text" name="ffname"><br>
Mother Name <input type="text" name="mmname"><br>
Wife Name <input type="text" name="wname"><br>
First Child Name <input type="text" name="fcname"><br>
Second Child Name <input type="text" name="scname"><br>
<input type=submit value="click">
</center></form></body></html>

GetParameterNamesServlet.java
public class GetParameterNamesServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out=response.getWriter();
Enumeration e=request.getParameterNames();
while(e.hasMoreElements())
{
Object o=e.nextElement();
String k=o.toString();
String v=request.getParameter(k);
out.println(v);

}
}

68
Example7: Read form data using getParameterValues() method
getparametervalues.html
<html>
<body>
<center>
<form action="BookServlet">
Name:<input type=text name="uname"><br>
Select Books:<select name="book" multiple>
<option value="java">JAVA</option>
<option value=".net">.NET</option>
<option value="oracle">ORACLE</option>
<option value="testing">TESTING</option>
<option value="sap">SAP</option>
<option value="cpp">CPP</option>
</select>
<br><br><br><br>
<input type="submit" value="click">
</form></center></body></html>
GetParameterValuesServlet.java
public class GetParameterValuesServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
double price=0;
String user=request.getParameter("uname");
String books[]=request.getParameterValues("book");
for(int i=0;i<books.length;i++)
{
if(books[i].equals("java"))
price=price+250;
if(books[i].equals(".net"))
price=price+260;
if(books[i].equals("oracle"))
price=price+100;
if(books[i].equals("testing"))
price=price+100;
if(books[i].equals("sap"))
price=price+300;
if(books[i].equals("cpp"))
price=price+50;

}
PrintWriter out=response.getWriter();
out.println("Username:"+user);
out.println("<br>");
out.println("selected Books:");
for(int i=0;i<books.length;i++)
out.println(books[i]);
out.println("<br>");
out.println("Total Price:"+price);
out.println("<br>");

69
out.println("Thank You");
out.close();
}
}
Example8: Read form data using getParameterMap() method
getparametermap.html
<html>
<body>
<form action="GetParameterMapServlet">
First Name <input type="text" name="fname"><br>
Middle Name <input type="text" name="mname"><br>
Last Name <input type="text" name="lname"><br>
Email <input type="text" name="email"><br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option1" value="Butter" checked> Butter<br>
<input type="checkbox" name="option1" value="Cheese"> Cheese<br>
<input type=submit value="click">
</body></html>

GetParameterMapServlet.java

public class GetParameterMapServlet extends HttpServlet {


private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out=response.getWriter();
Map<String, String[]> m=request.getParameterMap();
HashMap<String, String[]> hm=new HashMap<String, String[]>(m);
Set<Map.Entry<String,String[]>> set=hm.entrySet();
for(Map.Entry<String,String[]> hs1:set){
//out.print(hs1.getKey()+":::::");
String[] x=hs1.getValue();
for(int a=0;a<x.length;a++)
out.println(x[a]);
//out.println(hs1.getValue());
}
}
}
Example 9:Read radio buttons in HttpServlet
Radio.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<form action="RadioServlet">
<b>Question 1: AUTHOR OF JAVA?</b><br /><br />

<input type="radio" name="Q1" value="a"> JAMES GOSSLING


<input type="radio" name="Q1" value="b"> RAMMOHAN<br />

70
<br /><br /><b>Question 2:AUTHOR OF C?</b><br /><br />

<input type="radio" name="Q2" value="a"> DENNIS RICHE


<input type="radio" name="Q2" value="b"> RAMMOHAN<br />
<input type="submit" value="click">
</body>

</html>
RadioServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
int result;
PrintWriter out=response.getWriter();
String q1 = request.getParameter("Q1");
String q2 = request.getParameter("Q2");
if(q1.equals("a")&&q2.equals("a")){
result=2;
out.println("Your Score is 2"+"\t"+"Your are Pass");
}
else if(q1.equals("b")&&q2.equals("b"))
out.println("Your Score is 0"+"\t"+"Your are Fail");
else
out.println("Your Score is 1"+"\t"+"Your are Do HardWork");
}

}
Example 10: Read Textarea using HttpServlet
textarea.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<H1>Submitting Text Areas</H1>
<FORM ACTION="TextAreaServlet" METHOD="POST">
Please enter your text:
<BR>
<TEXTAREA NAME="textarea1" ROWS="5"></TEXTAREA>
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>

</body>
</html>

TextAreaServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out=response.getWriter();
StringBuffer text = new StringBuffer(request.getParameter("textarea1"));

71
int loc = (new String(text)).indexOf('\n');
while(loc > 0){
text.replace(loc, loc+1, "<BR>");
loc = (new String(text)).indexOf('\n');
}
out.println(text);
/*String s=request.getParameter("textarea1");
PrintWriter out=response.getWriter();
out.println(s);*/

Servlet-Database Communication
Application 1: Get database into servlet and print on browser in table format

public class DatabaseConnection extends HttpServlet {


private static final long serialVersionUID = 1L;

Connection con;

public void init(ServletConfig config) throws ServletException {


// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata1","root","mysql");
System.out.println("ok");

}
catch(Exception e)
{
e.printStackTrace();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
try
{
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student_info");
PrintWriter out=response.getWriter();

72
out.println("<center><table border=2>");
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getInt(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td>");
out.println("<td>"+rs.getInt(3)+"</td>");
out.println("</tr>");

}
out.println("</table></center>");
}
catch(Exception e)
{

Application2: Enter SQL command in html textbox and execute() method example
SqlCommand.html
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<center>
<formaction=DatabaseConnection2method="post">
Enter a Command<inputtype=textname="command"><br>
<inputtype=submitvalue="click">
</form>
</center>
</body>
</html>
public class DatabaseConnection2 extends HttpServlet {
private static final long serialVersionUID = 1L;

Connection con;
Statement st;
public DatabaseConnection2() {
super();
// TODO Auto-generated constructor stub
}

public void init(ServletConfig config) throws ServletException {


// TODO Auto-generated method stub
try
{

73
Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata1","root","mysql");
st=con.createStatement();
System.out.println("ok");

}
catch(Exception e)
{
e.printStackTrace();
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
try
{
String s=request.getParameter("command");
ServletOutputStream sos=response.getOutputStream();
if(st.execute(s))
{
ResultSet rs=st.getResultSet();
sos.println("<table border=2>");
while(rs.next())
{
sos.println("<tr>");
sos.println("<td>"+rs.getInt(1)+"</td>");
sos.println("<td>"+rs.getString(2)+"</td>");
sos.println("<td>"+rs.getInt(3)+"</td>");
sos.println("</tr>");

}
sos.println("</table>");
rs.close();
}
else
{
int k=st.getUpdateCount();
sos.println("<h2>Row Updated="+k+"</h2>");

}
}
catch(Exception e)
{

}
}

74
}
Application 3: Display sql table data using frameset concept using ResultSetMetaData
interface
Index.html
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<framesetcols="40%,*">
<framename="frm1"src="input.html">
<framename="frm2">

</frameset>
</html>
Input.html
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<formaction=DatabaseConnection3target="frm2"method="post">
Enter Select Command:<inputtype=textname="command"><br>
<inputtype=submitvalue="click">
</form>
</body>
</html>

public class DatabaseConnection3 extends HttpServlet {


private static final long serialVersionUID = 1L;

Connection con;
Statement st;
public DatabaseConnection3() {
super();
// TODO Auto-generated constructor stub
}

public void init(ServletConfig config) throws ServletException {


// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata1","root","mysql");
st=con.createStatement();
System.out.println("ok");

75
}
catch(Exception e)
{
e.printStackTrace();
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
try
{
PrintWriter out=response.getWriter();
String s=request.getParameter("command");
//String query="select * from student_info where sname="+s;
ResultSet rs=st.executeQuery(s);
ResultSetMetaData rsmd=rs.getMetaData();
int count=rsmd.getColumnCount();
out.println("<table border=3>");
out.println("<tr>");
for(int i=1;i<=count;i++)
out.println("<th>"+rsmd.getColumnName(i)+"</th>");
out.println("</tr>");
while(rs.next())
{
out.println("<tr>");
for(int j=1;j<=count;j++)
out.println("<td>"+rs.getString(j)+"</td>");
out.println("</tr>");
}
out.println("</table>");
out.close();
rs.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}

Application 4: Example on PageNation Concept

public class PaginationTest extends HttpServlet {


private static final long serialVersionUID = 1L;

Connection con;
Statement st;
public PaginationTest() {

76
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata1","root","mysql");

st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_REA
D_ONLY);
System.out.println("ok");

}
catch(Exception e)
{
e.printStackTrace();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
process(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
process(request,response);
}
public void process(HttpServletRequest request, HttpServletResponse
response)throws ServletException,IOException
{
try
{
int pageNumber=0;
int totalNumberOfRecords=0;
int recordsPerPage=2;
int startIndex=0;
int noOfPages=0;
String sPageNo=request.getParameter("pageNo");
if(sPageNo!=null && !"".equals(sPageNo))
{
pageNumber=Integer.parseInt(sPageNo);

77
}
else
{
pageNumber=1;
}
ResultSet rs1=st.executeQuery("select count(*)from student_info");
rs1.next();
totalNumberOfRecords=rs1.getInt(1);
System.out.println(totalNumberOfRecords);
rs1.close();

ResultSet rs2=st.executeQuery("select * from student_info");


startIndex=(pageNumber*recordsPerPage)-recordsPerPage+1;
PrintWriter out=response.getWriter();
out.println("<center><table border=4>");
rs2.absolute(startIndex);
int i=0;
do
{
i++;
out.println("<tr>");
out.println("<td>"+rs2.getString(1)+"</td>");
out.println("<td>"+rs2.getString(2)+"</td>");
out.println("<td>"+rs2.getString(3)+"</td>");

}
while(rs2.next()&&i!=recordsPerPage);
out.println("</table>");
out.println("<br>");
noOfPages=totalNumberOfRecords/recordsPerPage;
if(totalNumberOfRecords>noOfPages*recordsPerPage)
{
noOfPages=noOfPages+1;
}
for(int k=1;k<=noOfPages;k++)
{
out.println("<a href=?pageNo="+k+">"+k+""+"</a>");
}
out.println("</center>");
out.close();
rs2.close();

}
catch(Exception e)
{
e.printStackTrace();
}
}

78
Application 5: Create a separate class for connection properties and create that class object
in servlet classs
TestConnection.java

package servlet.com;
import java.sql.Connection;
import java.sql.DriverManager;
public class TestConnection {

Connection con;
public Connection testConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata1","root","mysql");
System.out.println("ok");

}
catch(Exception e)
{
e.printStackTrace();
}
return con;

}
Test.java(Servlet)
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;

public Test() {
super();
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
TestConnection tc=new TestConnection();
Connection c=tc.testConnection();
PrintWriter out=response.getWriter();
out.println("I got Connection");
}

79
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
}

}
ServeltConfig Example

Application 1: Configure connection properties in web.xml file


web.xml
<web-app>
<servlet>
<description></description>
<display-name>InitParameterTest</display-name>
<servlet-name>InitParameterTest</servlet-name>
<servlet-class>servlet.com.InitParameterTest</servlet-class>
<init-param>
<description></description>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<description></description>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mydata1</param-value>
</init-param>
<init-param>
<description></description>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<description></description>
<param-name>password</param-name>
<param-value>mysql</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>InitParameterTest</servlet-name>
<url-pattern>/InitParameterTest</url-pattern>
</servlet-mapping>
</web-app>

public class InitParameterTest extends HttpServlet {


privatestaticfinallongserialVersionUID = 1L;

public InitParameterTest() {
super();
// TODO Auto-generated constructor stub
}

80
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
String s1=getInitParameter("driver");
String s2=getInitParameter("url");
String s3=getInitParameter("username");
String s4=getInitParameter("password");
try{
Class.forName(s1);
System.out.println(s1+"driver is loaded");
Connection con=DriverManager.getConnection(s2,s3,s4);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student_info");
PrintWriter out=response.getWriter();
out.println("<center><table border=2>");
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getInt(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td>");
out.println("<td>"+rs.getInt(3)+"</td>");
out.println("</tr>");

}
out.println("</table></center>");

}
catch(Exception e)
{

}
}

protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
}

REQUESTDISPATCHER INTERFACE
Application1: Using forward(-,-) and include methods
Product.html
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

81
</head>
<body>
<formaction=Servlet1>
Product Id:<inputtype=textname="pid">
Product Name:<inputtype=textname="pname">
Quantity:<inputtype=textname="qty">
<inputtype=submitvalue="click">
</form>

</body>
</html>

Servlet1.java
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// TODO Auto-generated method stub
RequestDispatcher rd=request.getRequestDispatcher("/Servlet2");
rd.forward(request,response);
}

Servlet2.java
public class Servlet2 extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// TODO Auto-generated method stub
String pid=request.getParameter("pid");
String pname=request.getParameter("pname");
String qty=request.getParameter("qty");
ServletContext ctx=getServletContext();
ctx.setAttribute("quantity",qty);
RequestDispatcher rd=request.getRequestDispatcher("/Servlet3");
response.setContentType("text/plain");

PrintWriter out=response.getWriter();
out.println("Product Id:"+pid);
out.println("Product Name:"+pname);
out.println("Product Quantity:"+qty);
rd.include(request,response);
out.close();

82
Servlet3.java
public class Servlet3 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletContext ctx=getServletContext();
String qt=(String)ctx.getAttribute("quantity");
qt.trim();
double d=Double.parseDouble(qt);
double p=d*32.12;
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
out.println("Price:"+p);
out.close();

}
Application2:Using sendRedirect() method
Sendredirect.html
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<formaction=RedirectServlet1>
Enter First Nuber:<inputtype=textname="t1"><br>
Enter Second Number:<inputtype=textname="t2"><br>
<inputtype=submitvalue="click">

</form>
</body>
</html>
SendRedirect1.java
public class RedirectServlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
try
{
String s1=request.getParameter("t1");
String s2=request.getParameter("t2");
s1.trim();
s2.trim();
int a=Integer.parseInt(s1);

83
int b=Integer.parseInt(s2);
int c=a/b;
PrintWriter out=response.getWriter();
out.println("Resultis:"+c);

}
catch(Exception e)
{
response.sendRedirect("./RedirectServlet2");
}
}

}
RedirectServlet2.java
public class RedirectServlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
out.println("<h2> Your input is wrong, Enter valid Input");
out.println("<a href='sendredirect.html'> Click Here</a>");
out.println("</h2>");
out.close();

}
}
JSP
Limitation of Servlets
• Servlet need huge amount of java code to implement business logic
• In a servlet both business logic and presentation logic combined. So a java developer
must be know html also
• A servlet is a java class file, so if any modifications are done on it then we must
recompile, reload the application and sometimes we need to restart the server
• In servlets, we don’t have implicit objects support
What is Jsp?
• A JSP is a web page, resides on a server and provides dynamic presentation on
browser
• A JSP is page, looks like on HTML page, the difference is HTML can produce only
static content, but a JSP can produce dynamic content
• JSP’s are called pages rather than program’s because a JSP contains everything in the
form of a tag
• JSP’s are pages, written by authors

Difference Between Servlet and Jsp


Servlets Jsp
Servlet need huge amount of java code to A Jsp need less amount of java code to implement
implement business logic business logic
In a servlet both business logic and In Jsp, we can separate presentation logic from

84
presentation logic combined. So a java business logic. So, a programmer may not be html
developer must be know html also designer
A servlet is a java class file, so if any In Jsp, it is a page so if any modification are done
modifications are done on it then we must then no need to recompile or reload or restart the
recompile, reload the application and server. Instead, we need to refresh to page on
sometimes we need to restart the server broser
In servlets, we don’t have implicit objects In a Jsp, we have implicit objects
support
A servlet doesn’t manage a session by A Jsp by default maintains sessions. If we don’t
default. Explicitly we need to enable require them then we can disable them
sessions
In a servlet, we have to write all import In Jsp, we can insert import statements at anywhere
statements on top of the servlet in the page

Contents Of a Jsp
1) Ordinary text (template text)
2) Html tags
3) Jsp tags
• Ordinary text and Html tags will produce static content and Jsp tags will generate
dynamic content
• A Jsp is a server side resource. It means a jsp executes at server side and its
response will be constructed in the form of web page and that web page is
delivered to web client
• Html tags are enclosed with in < >
• Jsp tags are enclosed with in <% %>
Jsp Execution
At server side, 2-phases are executed for a Jsp
1) Translation Phase
2) Request Processing Phase
• Translation phase means, translating a jsp into equivalent servlet and then generating
a .class file
• Request processing phase means, executing service() method for a given request and
generating response to the client
• Translation doesn’t occur for each request. But request processing occurs for each
request
• Translation occurs in the following 2-cases
1) When a first request is arrived to a jsp
2) When request arrived after modification of a jsp

85
First Request
First Request Received by Jsp

http://localhost:8080/app1/one.jsp
request translator compiler

one.jsp one_jsp.java

response
one_jsp.class

object
_jspService(-,-)
{
-----
-----
}

• Next Request on wards

http://localhost:8080/app 1/one.jsp
request

one.jsp

response

object
_jspService(-,-)
{
-----
-----
}

• A web container uses a page compiler(translator), to convert a .jsp file into .java file
• For example, catelina is a web container of tomact, uses a page compiler called
jasper, to translate a .jsp into a .java file
• After converted to .java file, container uses javac and generate .class file
• To identify whether a jsp is like a previous executed jsp or any modifications done on
it, a web container uses file comparison tools. In tomact catalina uses araxis tool for
identification
• A jsp is executed in a server, if we shutdown a server then the object created for a jsp
will be removed from the server. But the .java and .class files are not removed
• If we restart the server and if you again give a request to a jsp then the container
creates an object for existing class and invokes its life cycle and then provides the
response back to the client
• If you shutdown and restart the server then again translation phase for a jsp will not be
executed
• If we remove .class file and if you give request to a jsp then partial translation occurs
and again a new .class file created and the request processing will be executed
• We can modify the source code of an internal servlet created by the container for a
jsp. In this case to execute the modified code also, either we need to explicitly
compiled or we need to remove .class file
Jsp Life Cycle
1) Jsp is translated to a servlet
2) The servlet is compiled
3) The servlet is loaded into memory
4) An object is created for the servlet
5) jspInit() method is called
6) _jspService(-,-) method is called

86
7) jspDestroy() method is called
(above steps are divided into 4-phases )
Translation
• In the translation phase, JSP engine checks for the JSP syntax and translate JSP page
into its page implementation class if the syntax is correct. This class is actually a
standard Java servlet. After that, JSP engine compiles the source file into class file
and ready for use.
• If the container receives the request, it checks for the changes of the JSP page since it
was last translated. If no changes was made, It just loads the servlet otherwise the
process of check, translate and compile occurs again. Because the compilation process
takes time so JSP engine wants to minimize it to increase the performance of the page
processing.
Initialization
• After the translation phase, JSP engine loads the class file and create an instance of
the servlet to handle processing of the initial request.
• JSP engines will call a method jspInit() to initialize the a servlet. jspInit method is
generated during the translation phase which is normally used for initializing
application-level parameters and resources.
• You can also overide this method by using declaration.

<%!
   public void jspInit(){
      // put your custom code here  
   }
%>
Execution
• After the initialization phase, the web container calls the method _jspService() to
handle the request and returning a response to the client.
• Each request is handled is a separated thread.
• Be noted that all the scriptlets and expressions end up inside this method.
• The JSP directives and declaration are applied to the entire page so the are outside of
this method.
Finalization
• In the finalization phase, the web container calls the method jspDestroy().
• This method is used to clean up memory and resources.
• Like jspInit() method, you can override the jspDestroy() method also to do your all
clean up such as release the resources you loaded in the initialization phase....
• <%!
   public void jspDestroy(){
      // put your custom code here
      // to clean up resources
   }
%>
• The life cycle methods of jsp are provided by HttpJspPage interface. This interface is
part of JSP api and it is given in javax.servlet.jsp.*; package
• HttpJspPage is exentended from JspPage interface and it has provide two life cycle
methods called jspInit() and jspDestroy()

87
When a jsp is converted to a servlet, the servlet class extends a base class provided by the
container. That class extends from HttpServlet class. So we can say that the internal servlet is
an HttpServlet
A jsp can handle only http protocol request

Jsp Tags (Elements)


Jsp tags are divided into the following
1)Scripting Tags
declaration, expression, scriptlets
2)Directivies
Include, page, taglib
3)Stand Actions
<jsp:forward> <jsp:include> <jsp:param> <jsp:params> <jsp:plugin> <jsp:fallback>
<jsp:useBean> <jsp:setProperty> <jsp:getProperty>
4)Custom Tags

Jsp Scripting Tags


• JSP scripting elements enable us to insert java code into JSP files.
• There are three types of elements
– Expressions <%= Java Expression %>
– Scriptlets <% Java Code %>
– Declarations <%! Field/Method %>
Jsp Declaration Tags
• This tag is used for define variables and creating methods in a jsp page
• If we define any variable or methods then these variables and methods will become
instance variables and instance methods of the internal servlet class
• This tag starts with <%! and ends with %>
Syntax: (html format) Syntax: (xml format)
<%! Instance or global <jsp:declaration>
variables Instance or global variables
define method define method
%> </jsp:declaration>

88
• The variables defined in this tag will become global to the entire jsp. It means we can
use those variables at everywhere in the jsp
• The declaration tag will be executed for only once but not for each request
• The code inserted into declaration will be placed into servlet class during translation
time
Example:
<%
int count=0;
count++;
%>
• In declaration tag we can override jspInit(0 and jspDestroy() methods. _jspService(-,-)
override is not possible. _jspService(-,-) always written by the container
<%!
public void jspInit()
{
………….
………….
}
public void jspDestoroy()
{
………….
………….
}
%>
• In a jsp, the only one tag which allows jsp programmers to define methods is
declaration tag
• If we define a method in a declaration tag then it can be called from any number of
times from an expression tag and scriplet tag of jsp
• We can’t use implicit objects of a jsp in declaration tag. Because the declaration tag
code goes out of _jspService(-,-) method
<%!
public int add(int a, int b)
{
out.println(“inside add()”);
return(a+b);
}
%>
• For scripting elements of a jsp, nesting of tags ate not allowed
<%!
…….
…….
<%!
……
……
%>
%>
The code is an error because nesting is not allowed
<%!
…….
…….

89
<%
……
……
%>
%>
It is an error because insert one scriptnig element into another scripting element is wrong
Example on Declaration Tag
<%!
int count=0;
int count1=count+1;

%>
<%= count1 %>

Example2:
<%!
public int add(int a, int b)
{
return(a+b);

}
int c;
%>
<%=
c=add(10,20)
%>
<%
int x=add(25,35);
out.println(x);
%>

Jsp Expression
• An expression tag is used for evaluating the given expression and then printing or
displaying result on to the browser
• Each expression tag will be internally converted to out.println() method statements
during translation time and then that statements will be inserted into _jspService()
method
• Expression tag will be executed for each request, because an expression tag goes
inside of _jspService() method
• We can use implicit objects of jsp in an expression tag. Because its code goes into
_jspService(0 method
• A JSP expression is used to insert java code directly into the output.
Syntax
• <%= Expression %> (html syntax)
• <jsp:expression > expression </jsp:expression> (xml syntax)

Example:
<%!
int a=100;
int b=200;

90
%>
<%= "Sum="+(a+b) %>

Examples
Current Time: <%= new java.util.Date() %>
Output:
Current Time: Tue Aug 22 21:05:47 IST 2006

The expression is evaluated, converted to string and inserted into the page.
• Example
1) <%=a+b,a-b%> àout.print(a+b,a-b) //invalid
2) <%=a+b+” “+a-b%> àout.print(a+b+” “+a-b)//valid
3) <%=this.a*this.b %> àout.print(this.a*this.b);
4) <%=this.a+page.a%> àout.print(this.a+page.a);
page.a equls this.a
5) <%=a+b;%>àout.print(a+b;); //invalid
6) <%=a,b%>àout.print(a,b);//invalid
7) <%= request.getParameter(“uname”)%>
out.println(request.getParameter(“uname”));

Jsp Scriplets
• This tag is used for inserting some java code into a jsp page and this java code goes
into _jspService(-,-) method. So the code implemented in a scriplet tag is executed for
each request.
• In a scriplet tag we can declare variables. These variables are called local variables
because the scriplet code goes into _jspService(-,-) method
• We can’t define methods in a scriplet tag, but we can call the methods defined in a
declaration tag
• A scriplet starts with <% and ends with %>
Syntax:
• <% Java Code %> (html synatx)
<jsp:scriplet> java code</jsp:scriplet> (xml syntax)
Example:
<%
String str = request.getParameter(“name”);
out.print(“Name : ”+str);
%>

<%
int sum(int a, int b)
{
………………………
………………………
}
%>
The above code is invalid
<%!

91
int sum(int a, int b)
{
return (a+b);
}
%>
<%
int k=sum(10,20);
%>
• The above code is correct
• We can create a variable with same name in declaration tag and also in a scriptlet tag.
Because declaration tag variables goes to out of _jspService(-,-) and scriplet tag
variable goes to inside of _jspService(-,-)
<%!
int x=100;
%>
<%
int x=50;
%>
<%= x %>
<%= this.x %>

Comments in Jsp
• Html Comments
• Jsp Comments
• Java Comments
Html comments startsswith <!- - and end with - - >
Example: <!- - one.html- ->
A Jsp comment starts with <% - - and ends with - -%>
Example: <%- -one.jsp - -%>
• We can’t write any type of comment in an expression tag
• We call jsp comments as hidden comments. Because these comments are not visible
in internally generated servlet source code

Important points in Jsp


• The internally generated servlet file is located at
C:\tomact6.0\work\catellina\localhost\jsp1\org\apache\jsp
• If we open the source code of servlet and if we modify the source code then the
changes are not effected on the browser
• If we want to make the changes effected on browser we are responsible compile it
manually. To compile it we need to set the following 3-jar files
1) Servlet-api.jar
2) Jsp-api.jar
3) Jasper.jar

Html to Jsp Communication


• While communicating from a html to jsp, either we can use jsp filename or url pattern
of jsp as a form action
• If jsp’s configured in web.xml then we can put its url pattern otherwise we can put its
name directly in form action

92
Example on Html to Jsp Communication
Test.html
<body>
<form action="test.jsp">
Username:<input type=text name=t1><br>
Password:<input type=text name=t2><br>
<input type=submit value=click>

</form>
</body>
</html>

Test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
String result="";
String s1=request.getParameter("t1");
String s2=request.getParameter("t2");
int k=verify(s1,s2);
if(k==1)
result="login success";
else
result="login failed";
%>
<%=result %>
<%!
int verify(String u, String p)
{
if(u.equals("talent")&&p.equals("sprint"))
return 1;
else
return 0;
}
%>

Jsp Directives
• Directives will provide information to containers, during translation time and
execution time
• Directives will give direction to a container, during translation time and execution
time about how to ok work this this jsp page
• For example, a directive informs the container that, if any exception is occurred in the
current jsp execution, then move the control to some other jsp
• We have 3-directives in jsp
1) include
2) page
3) taglib

93
• Taglib directive is used while working with custom tags and JSTL
Include Directive
• This directive is for including source code of one jsp into another jsp
• At translation time only destination file source code will be included in the servlet of
source file. It means the page compiler generates a single servlet internally for both
source file and destination file
• We also called this include directive as a static including. Because the inclusion is
done at translation time only, not at request processing time
include Directive
• Syntax:
<%@ include file=destination file name %> (html syntax)

<%@ include file="b.jsp" %>

a.jsp(source) b.jsp(destination)

< jsp:directive directive-name attributes /> (xml syntax)

• In a jsp, we can include any number of destination pages or we can call include same
destination page for number of times
• Include directive reduces number of servlet objects in a server because internally a
single servlet will be generated for both source and destination pages. It means
include directive reduces burden on a server
Example on include directive
Date.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*"%>
<%=new java.util.Date()%>
Dateinclude.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<body>
<p>The Current date and time is
<%@ include file="date.jsp" %>
</p>
</body>
</html>

Page Directive
• This directive is used for setting important behavior for a jsp like session
management, buffer, MIME types, imports exceptions handling etc.,
• Syntax:
<%@ page attributes %>
Attribute values

94
1) language
2) import
3) session
4) errorPage
5) isErrorPage
6) isThreadSafe
7) buffer
8) autoFlush
9) contentType
10) extends
11) info
12) isELIgnored

language attribute
• This attribute is used to set scripting language for jsp tags
• The default value and the only one available value for this attribute is “java”
• This attribute is added to set language name, when multiple languages are supported
by a jsp
< %@ page language=“java” %>
import attribute
• This attribute is used to execute a predefined or an user defined packages into a jsp
apge
• There is no default value for this attribute
• We can import either a single or multiple packages at a time into our jsp using this
import attribute
< %@ page import=“java.lang.*” %> (single)
< %@ page import=“java.lang.*; java.sql.*” %>(multiple)
In a jsp a package can be imported anywhere it means in a jsp there is no rule that all
packages must be imported at top of the jsp
During translation, the page compiler assimilates all imports from jsp page and places them at
top of the internal servlet
We can repeat import attribute for any number of times with in a jsp page with different
values
< %@ page import=“java.lang.*” %>
…………….
……………
< %@ page import=“java.sql.*” %> (single)
………………..
………………...
< %@ page import=“java.io.*” %> (single)
………………….
………………….
The difference between other attributes of the jsp page directive and import attribute is, we
can repeat other attributes also in a jsp, but the attribute value should same.
Where as, incase of import we can repeat for any number of times with different values

session Attiribute
• This attribute is used to either enable or disable a session management in a jsp
• The default value of this attribute is ‘true’. It means by default every jsp participate in
session tracking

95
• If we want to disable session tracking in a jsp then we need to make session=false
• If a jsp participating is session tracking then only an implicit object called session is
available to the jsp, otherwise we can’t use session object in jsp
• If session object is available then we can get session and state information from a
session object by calling methods on it
Example1:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page session="true"%>
Session Id Is:<%=session.getId()%>
Expire Time Is:<%=session.getMaxInactiveInterval() %>
Example2:
Session Id Is:<%=session.getId()%>
Expire Time Is:<%=session.getMaxInactiveInterval() %>
errorPage Attribute
• This attribute is used to inform the container that, if any exception is occurred while
executing a jsp then move the control to other jsp page, instead of printing exception
stack trace on a browser
• In a jsp exception handling can be done either locally or globally
• If we add errorPage attribute for page directive in a jsp then it is called local
exception handling in jsp
• If <error-page> tag is added in web.xml then it is called global exception handling
Example
<%@page errorPage=“b.jsp”%>

isErrorPage Attribute
• This attribute is used to inform the container whether a jsp is acting as an errorPage or
not
• The default value of this attribute is false. It means by default a jsp doesn’t act as an
errorPage
• To make a jsp as an errorPage then we need to make isErrorPage=true
• If a jsp is acting like an errorPage then only the implicit object exception is available
in that page

Example on errorPage and isErrorPage Attributes


Maths.html
<body>
<form action=addition.jsp>
Enter First Number:<input type=text name="t1"><br>
Enter Second Number:<input type=text name="t2"><br>
<input type=submit value=click>
</form>
</body>
</html>
Addition.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page errorPage="error.jsp"%>

96
<% String s1=request.getParameter("t1");
String s2=request.getparameter("t2");
int a=Integer.parseInt(s1.trim());
int b=Integer.parseaInt(s2.trim());
int c=a/b;
out.println("result="+c);
%>
Error.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page isErrorPage="true"%>
<%
exception.printStackTrace(response.getWriter());
%>
<h1>Don't Enter Second Number Values As Zero</h1> <br>
Click Following Link To Enter Input Again
<br>
<a href="maths.html"> CLICK ME</a>

isThreadSafe Attribute
• This attribute is used to inform the container, whether multiple threads are allowed to
access the jsp or not
• The default value of isThreadSafe is true. It means multiple threads are allowed
simultaneously to access the jsp
• If we make isThreadSafe=false then container allows only a single thread at a time to
access a jsp
• If we make isThreadSafe=false then at the time of translation, the container
implements internal servlet class from SingleTHreadModel interface
<%@ page isThreadSafe=“false” %>

buffer Attribute
• This attribute is used to set the buffer size used by JspWriter class
• The default value of this attribute is 8kb. But we can increase or decrease or remove
the buffer
• In jsp, the implicit object out is an object of JspWriter class, and it writes the response
data into buffer, before writing it into the response object
• In case of PrintWriter, it directly writes the response data into response object, by
without using any buffer (below)
out.println(“…….”)
out.println(“…….”) response object
out.println(“…….”)
In Jsp
out.println(“…….”)
out.println(“…….”) buffer response object
out.println(“…….”)
• JspWriter is a derived class of PrintWriter and uses buffer
• If buffer is removed then both JspWriter and PrintWriter becomes equal

97
• If buffer is used then performance is increased because very time no need of hitting
response object
• To make JspWriter and PrintWriter as equal, we use buffer=“none”
<%@ page buffer=“none”%>

autoFlush Attribute
• This atribute is used to transfer the data stored in a buffer into response object. We
call this operation as flushing
• The default value of this attribute is true. It means automatically flushing will be done
when the buffer is full
• If we make autoFlush=false then we need to explicitly call out.flush(), to transfer the
data from buffer to response object
• If autoFlush=false and if out.flush() is not called then when the buffer is full then
container throws an exception
If buffer is none then we should not make autoFlush=false

contentType Attribute
• This attribute is used to set MIME(Multipurpose Internet Mail Extension) type for
response
• Default value of this attribute is “text/html”
• In a jsp, we can set MIME type in 2-ways
1) By using scriplet with response object
<% response.setContentType(“text/html”) %>
2)By using page directive
<%@ page contentType=“text/html”%>
Note: If we set in both ways with different MIMIE types then container throws an
exception

extends Attribute
• This attribute is used to inform the container that extends the internal servlet class of
jsp from our user defined class
• In order to specifie our user defined class name, first of all we need to crate our class
by extending HttpServlet and by implementing from HttpJspPage interface
<%@ page extend=“MyServlet”%>
MyServlet extends from HttpServlet and implements from HttpJspPage which is
extends from JspPage

info Attribute
• This attribute is used to write some description about a jsp
• We can also write description in a comment, but a comment can’t be read but a info
can be read
• If we add info attribute for page directive then at translation time, the container inserts
a method getServletInfo() in internally generated servlet class
• In a jsp page, we can read the description added for info attribute ether in a scriplet or
in an expression by calling getServletInfo() method
<%@ page info=“This is a.jps%>
……………
……………

98
<%String s=getServletInfo();
out.println(s);
%>
isELIgnored Attribute
• This attribute is used either enable or disable expression language in jsp
• The default value of this attribute is true it means expression language is ignored by
default
• To enable expression language in a jsp then we need to make isELIgnored=“false”
<%@ page isELIgnored=“false” %>
JSP ACTION TAGS
• Jsp developers given commonly required functionalities for jsp programmers while
developing jsp pages in the form of standard actions
• Standard actions will reduce burden on jsp programmer because a programmer no
need to implementing java code for that functionality
• Standard actions separates business logic from presentation logic of the jsp
• Each standard action contains fixed logic and input values are required to execute that
logic those values are accepted from jsp programmer
• Standard actions doesn’t contain html syntax. Contains only xml syntax
a. <jsp:forward>
b. <jsp:include>
c. <jsp:param>
d. <jsp:params>
e. <jsp:plugin>
f. <jsp:fallback>
g. <jsp:useBean>
h. <jsp:setProperty>
i. <jsp:getProperty>

<jsp:forward>
• While developing web application, suppose huge amount of code is required in a file,
then instead of writing total code in one page we divide that code into multiple pages
and then transfer the request from one page to another page we need to use
forwarding technique
• For forwarding technique, we use <jsp:forward> standard action. This tag forwarding
a client request from source to a destination
• When forwarding from a source to a destination, the destination can be either a
servlet or a jsp or a html
• This standard action contains a single attribute called ‘page’
To forward to jsp
• <jsp:forward page=“b.jsp”/>
To forward to servlet use servlet url-pattern
• <jsp:forward page=“/serv”/>
To forward to html file
• <jsp:forward page=two.htm”/>

• While forwarding, the source and destination resources may be in same web
application or at different web application but must be in same server it means
forwarding is not possible across the servers
• If destination is available in some other web application of same server then we need
to pass url as a value of page attribute

99
• <jsp:forward page=“/webappliaction2/b.jsp”/>
<jsp:param>

• While forwarding a request from a jsp to a destination using <jsp:forward> tag, it is


possible to ass some parameters also from source to a destination along with a
request.
• If we want to add parameters while forwarding then we need to use <jsp:param> as a sub
element of <jsp:forward> tag
a.jsp b.jsp
<jsp:forward page=“b.jsp”> <%
<jsp:param name=“p1” value=“100”/> String s1=request.getParameter(“p1”);
</jsp:forward> …………
……….
%>

a.jsp a.jsp

<% int c=a+b; %> <% int c=a+b; %>


<jsp:forward page=“b.jsp”> <jsp:forward page=“b.jsp”>
<jsp:param name=“p1” <jsp:param name=“p1”
value=“c”/> value=<%=c%>
</jsp:forward> </jsp:forward>
In above ‘code c’ character goes to b.jsp In above code ‘c’ value goes to b.jsp dynamically
not c-vale

<jsp:params>

• While forwarding a request, we can also add more than one parameter. For this, we need to
use <jsp:params> tag
a.jsp b.jsp
<jsp:forward page=“b.jsp”> <%
<jsp:params> String s1=request.getParameter(“p1”);
<jsp:param name=“p1” value=“100”/> String s2=request.getParameter(“p2”);
<jsp:param name=“p2” value=“200”/> ……………………
</jsp:params> ……………………
</jsp:forward> %>

• <jsp:param> and <jsp:params> standard actions must be used inside of some other
standard action tags. But we can’t use it directly in a jsp page

100
Example
• Flow diagram

salary.html salary.jsp

salary is calculate 'DA' from


request
entered given salary and
in this form forward the request
to SalaryServlet.java

forward
browser

displays calculate 'HRA'and gets


Salary response 'DA' from salary.jsp and
prints Salary, DA and HRA
DA on browser
HRA

<jsp:include>
• This standard action is used to include response of a destination into a source
• In a jsp, we have 2-types of including
1) Code including
2) Response including
• Source code inclusion is done using include directive and response including is done
using include action
<jsp:include> response included (dynamic including)
<%@ include..%> code is included (static including)

<jsp:include>
• In include action, internally for both source and destination jsp
pages, individual servlets are created and after that response of
destination page will be included into response of source page
a.jsp(source) b.jsp(destination)

a_jsp.java b_jsp.java
internal servelt internal servelt
for a.jsp for b.jsp

included
response response

• While including also, the control is forwarded internally to destination page. Along
with control automatically request parameters are forwarded

• We can also add additional parameters along with the control, while including the
response
• To add additional parameter, we need to use sub element as <jsp:param> tag
<jsp:include page=“b.jsp”>
<jsp:param name=“p1” value=“100”/>

101
</jsp:include>
Note:
<%@ include file=“/servlet1”/> (servlet1 is url-pattern)
It is wrong because in include directive destination is a file
(html or jsp) but not servlet

Example
• Flow Diagram
datedisplay.jsp numberdisplay.jsp

Display Date Display Numbers

include include

browser include.jsp
request
From browser if we execute Include Date and Numbers
Include.jsp it generate And generate ‘hello world’
Response as Date, Numbers response message
And hello world

Difference between include directive and directive action

include Directive include Action

It is called static including. In this source It is called dynamic including. In this response is
code is including at translation time included at runtime
In include directive internally a single In include action internally individual servlets are
servlet is created for both source and created for both source and destination pages at
destination pages at translation runtime
In include directive, the destination resource In include action the destination can be a jsp, a
should be a jsp page or an html page. But servlet, or a html
shouldn’t a servlet
In include directive we can’t pass any In include action we can pass parameters while
parameters while including the destination including the destination page
page
In include directive if any changes are done In include action if any changes are done in
in destination after inclusion then the destination the changes are effected in source
changes are not effected because it is a dynamic inclusion
Include directive can be written through Include action can be written only xml syntax
html or xml syntax
<jsp:plugin>
• This standard action is used for integrating a jsp with a applet
• A jsp integrates with applet, whenever the result of jsp wants to be shown in the form
of graphical representation on browser
• Syntax:
<jsp:plugin type=“applet” code=“classname”
width=“value” hight=“value”>
…………………..
…………………..

102
</jsp:plugin>
<jsp:fallback>
• While integrating a jsp with an applet, if any problem is occurred then we can display
an alternate text, in place of an applet on browser.
• For this we need to use a sub tag of <jsp:plugin> called <jsp:fallback>
• Syntax:
<jsp:plugin type=“applet” code=“classname”
width=“value” hight=“value”>
…………………..
…………………..
<jsp:fallback>some text</jsp:fallback>
</jsp:plugin>
• While integrating a jsp with an applet we can pass parameters to an applet
using<jsp:param> tag inside <jsp:plugin> tag
• If we pass more than one parameter to applet then we need to use <jsp:params> tag
• The sub elements of <jsp:plugin> tag are
1) <jsp:fallback>
2) <jsp:param>
3) <jsp:params>
Note:
<jsp:fallback> can be used only with <jsp:plugin>
In a pplet, if we want to read the parameters send by jsp page then we need to call a method
getParameter

Example
a.jsp TestApplet.java
<jsp:plugin type=“applet” Public class TestApplet extends Applet
code=“TestApplet” {
width=“300” String msg;
height=“300”> public void init()
<jsp:param name=“s1” {
value=“welcome”/> msg=getParameter(“s1”);
</jsp:plugin> }
public void paint(Graphics g)
{
Fnt f=new Font(“Helvitica”, Font.BOLD,15);
g.setColor(color.red);
g.fillOval(50,100,150,50);
g.setColor(color.blue);
g.setFont(f);
g.drawString(msg,80,120);
}
}

103
<jsp:useBean>
• Requirement

a.jsp b.jsp

contains
business
logic
and
presentation
logic

• Here a.jsp and b.jsp need same business logic and different
presentation logic
• Above business logic in a.jsp is not a reusable logic

<jsp:useBean>
• Solution

Presentation
Presentation
logic
logic

a.jsp b.jsp

Business
logic

bean class

JavaBean Class
To make a java class as a JavaBean Class the following rules to be followed
1) The class must be public
2) The class must contains a public default constructor
3) All properties of the class should be private
4) Each property should contain a public setter and getter method
5) The class can optionally implement serializable interface

JavaBean Class
public class TestBean public class TestBean extends Thread
{ {
public TestBean(int x, int y) public TestBean()
{ {
………………. ……………….
………………. ……………….

} }
}
It is not a JavaBean because of public TestBean(int x, int y)
parameterized constructor {
……………….
……………….

}
}
It is not a JavaBean

104
JavaBean Class

Public class TestBean implements Serilizable


{
public TestBean(int x, int y)
{
…………………………
…………………………
}
public TestBean()
{
…………………………
…………………………
}
}
It is a JavaBean class

JavaBean Class
public class TestBean extends DemoBean
{
public TestBean(int x, int y)
{
……………………
…………………….
}
public TestBean()
{
……………………
…………………….
}
}
The above class is a JavaBean class or not depends on DemoBean class. Suppose
DemoBeaan class is JavaBean class then the above class JavaBean class otherwise the
above class is not a JavaBean class

Jsp to JavaBean Communication


• In jsp, it is possible for us to separate presentation logic of jsp from its business logic
• In jsp, we implement business logic in a JavaBean and we call that business logic
from a jsp
• We have the following advantages if business logic is separated from the presentation
logic of a jsp
1) Business logic becomes reusable. It means multiple jsp’s can call the business
logic implemented in the same JavaBean
2) Burden on jsp programmers will be reduced
3) Division of work is possible. So an application development time will be reduced
Note : To use a java class object in a jsp page, then the java class must be stored with in a
package
<jsp:useBean
• This standard action is used for creating on object of a java bean in a jsp
• While creating an object, the object will be stored in some scope
Syntax
<jsp:useBean id=“objectName”
class=“fully qualified class name of javabean”
scope=“scope name”/>
• The available scopes of bean are
page(default)
request

105
session
application

page scope

• The default scope of bean object is page scope


• If a bean object is associated with page scope then that bean object is available to that
jsp page only
• If the response is transferred from current jsp page to another jsp page then the bean
object is not sharable in the other jsp page
The least scope of a bean object is a page scope. If bean object is stored in page scope then it
is removed from server whenever the control goes out of the jsp page

a.jsp b.jsp

<jsp:useBean id=“id1” <jsp:useBean id=“id1”


class=“pack1.LoginBean” class=“pack1.LoginBean”
Scope=“page”/> Scope=“page”/>
<jsp:forward page=“b.jsp”/>
• The above example result is forwarded from a.jsp to b.jsp. In a.jsp the bean object is
created and it will be stored in page scope
• When the result is forward then the control goes out a.jsp. So that page scope is
removed and in b.jsp new object is created stored in page scope
• When a bean objevt is page scope then for every jsp page a new bean object will be
created
Request scope
• When a bean object is stored in request scope then a bean object is sharable to another
jsp page also if the request forwarded to other jsp
Request scope is continued until the request is completed. It means until the response is given
back to the client

a.jsp b.jsp

<jsp:useBean id=“id1” <jsp:useBean id=“id1”


class=“pack1.LoginBean” class=“pack1.LoginBean”
Scope=“request”/> Scope=“request”/>
<jsp:forward page=“b.jsp”/>
• In the above example, request is forwarded from a.jsp to b.jsp. In a.jsp bean object is
created stored in request scope. So the bean object is available to b.jsp also. The
request scope is continued until response is given back to the client
Session scope

106
• If a bean object is stored in session scope then that object is sharable in current jsp
page and in the forward jsp and also other jsp page visited by same client
• Session scope is greater than request scope. But if the request scope is sharable with in a
single request, but session scope is sharable in the current request and also next request
given by the same client
a.jsp b.jsp c.jsp

<jsp:useBean id=“id1” <jsp:useBean id=“id1” <jsp:useBean id=“id1”


class=“pack1.LoginBean” class=“pack1.LoginBean” class=“pack1.LoginBean”
Scope=“session”/> Scope=“session”/> Scope=“page”/>
<jsp:forward
page=“b.jsp”/>
<jsp:forward
page=“c.jsp”/>
Application scope
• If a bean object is stored in application scope then it is sharable in all pages and all
clients of a web application
• We call application scope as a global scope to a web application
Application scope destroyed, either when an application is removed from the server or when the
server is closed or shutdown
a.jsp b.jsp c.jsp

<jsp:useBean id=“id1”
class=“pack1.LoginBean”
Scope=“application”/>
<jsp:forward page=“b.jsp”/>
<jsp:forward page=“c.jsp”/>

<jsp:setProperty>
• This standard action is used for setting input values into a java bean by calling setter
methods of the bean class
• <jsp:setProperty> must be used at inside of <jsp:useBean> tag
• Syntax
<jsp:useBean id=“objectName”
class=“fully qualified class name of javabean”
scope=“scope name”/>
<jsp:setProperty ………../>
</jsp:useBean>
• <jsp:setProperty> tag calls setter methods of the bean class, for setting input values
into properties of the bean class
• A bean class can’t accept the input values from browser. Because, from a browser a
request is transferred by using Http protocol and a java bean unknown about http
protocol.
• So, jsp act as a mediator, takes input values and then transfers the input values to bean
by calling the setter methods using <jsp:setProperty> tag

107
<jsp:setProperty>
• While setting input values to java bean by a jsp, if request
parameters names and bean class variables names are same
then we use property=“*” in <jsp:setProperty> tag
having to
textboxes
package pack1;
having
public class LoginBean
names as
{
'uname'
private String uname,pwd;
and 'pwd'
---->setters
a.jsp ---->getters
input.html }

<jsp:useBean id=“id1”
class=“pack1.LoginBean”>
<jsp:setProperty name=“id1”
LoginBean
property=“*” />
</jsp:useBean>

<jsp:setProperty>
• While using <jsp:setProperty> tag, name attribute value should be equal to id attribute
of <jsp:useBean> tag
<jsp:useBean id=“id1”
class=“pack1.LoginBean”>
<jsp:setProperty name=“id1”
property=“*” />
</jsp:useBean>

<jsp:setProperty>
• If request parameter names and bean class variable names are
not matched then we need ‘param’ attribute in
<jsp:setProperty> tag

having to
textboxes package pack1;
having public class LoginBean
names as {
'uname' a.jsp private String s1,s2;
and 'pwd' ---->setters
---->getters
input.html
}
<jsp:useBean id=“id1” class=“pack1.LoginBean”>
<jsp:setProperty name=“id1” property=“s1”
param=“uname”/>
<jsp:setProperty name=“id1” property=“s1”
param=“uname”/>
</jsp:useBean> LoginBean

• <jsp:setProperty> tag contains totally 4-attributes, in that ‘name’ and ‘property’


attributes are mandatory and we use can use either ‘param’ or ‘value’ but not both at a
time
name, property----------> valid
name, property, param----------à valid
name, property, value-----------à valid
name, property, param, value----------à invalid

<jsp:getProperty>
• This standard action is used for reading a property of a java bean class in a jsp

108
• <jsp:getProperty> tag calls getter method of the bean class
• <jsp:getProperty> should be used at outside of <jsp:useBean> tag
• We can’t store the value returned by <jsp:getProperty> tag into a variable in a jsp
page
String str=<jsp:getProperty name=“id1” property=“uname”/>
(The above code is invalid)
We can’t use property=“*” in <jsp:getProperty> tag
<jsp:getProperty name=“id1” property=“*”/>
(The above code is wrong)
<jsp:getProperty> tag contains only 2-attributes called ‘name’ and ‘property’
Syntax: <jsp:getProperty name=“id1” property=“uname”/>

Example
• Flow Diagram

having to set
textboxes
having
names as get
'uname'
and 'pwd' a.jsp

input.html response

Username:
Passsword:

LoginBean

Example-2
• Flow Diagram
having one textbox
for enter sql command Set
Request
and one submit button
to perform an action Get

enterCommand.html ReadCommand.jsp DatabaseBean.java

Response

Browser
Database

109
Implicit Objects Of Jssp
S.NO OBJECT NAME AVAILABLE PACKAGE
1 request javax.servlet.http.HttpServletRequest
2 response javax.servlet.http.HttpServletResponse
3 out javax.servlet.jsp.JspWriter
4 session javax.servlet.http.HttpSession
5 exception java.lang.Throwable
6 page java.lang.Object
7 config javax.servlet.ServletConfig
8 application javax.servlet.ServletContext
9 pageContext javax.servlet.jsp.PageContext

• session object and exception object both are not directly available in a jsp page. The
remaining 7-objects are available in every jsp page
• session object is available when session is true and by default every jsp contains
session=true
• exception object is available when the jsp is acting like an error page. By default a jsp
doesn’t act as an error page. To use exception object in a jsp, we need to make
isErrorPage=true
config implicit object
• By using this readymade object we can read the following 3-types of information
• Logical name of the jsp
• Init parameterss of the jsp
• Context reference
• If a jsp is not configured in web.xml or a jsp is configured in web.xml and it is
accessed by using name of the jsp page then logical name will be taken as ‘jsp’ and
init parameters will be printed as empty (null)
• If a jsp is configured in web.xml and it is accessed by using <url-pattern> of the jsp
page then we can read logical name and init parameters using config object
Attributes in JSP
• Attributes in web application are used for sharing the data across multiple files of a
web application
• An attribute will be in the form of a key-value pair and to retrieve the value we use its
key
• To share the data across multiple files of a web application we attach some scope for
the data
• In jps, we have 4-scopes for sharing the data
1) page
2) request
3) session
4) application
• page scope is newly added in jsp and if any attributes are stored in page scope then
those attributes become non sharable
• To store attributes in request, session and application scopes, we need implicit
objects. But, we can’t store attributes in page scope by using page object
• If we want to store an attribute in page scope then we need pageContext object

110
• pageContext object is not only used for storing attributes in page scope, but also we
can use it to store attributes in any scope
Example
pageContext.setAttribute(“k1”, “talent”);
(Above attribute is stored in page scope)
pageContext.setAttribute(“k2”, “sprint”,3);
(Above attribute is stored in session scope. Above statement is equal to)
session.setAttribute(“k2”,”sprint”);
• PageContext class contains the following four public static final variables for scopes
1) PAGE_SCOPE----------->1
2) REQUEST_SCOPE----------->2
3) SESSION_SCOPE----------->3
4) APPLICATION_SCOPE----------->4
• The following statements are used to store an attribute in page scope
 pageContext.setAttribute(“k1”, “talent”);
 pageContext.setAttribute(“k1”, “talent”,1);
 pageContext.setAttribute(“k1”, “talent”,PageContext.PAGE_SCOPE);
• The following statements are used to store an attribute in request scope
request.setAttribute(“k1”,”jsp”);
pageContext.setAttribute(“k1”,”jsp”,2);
pageContext.setAttribute(“k1”,”jsp”,PageContext.REQUEST_SCOPE);
• The following statements are used to store an attribute in session scope
session.setAttribute(“k1”,”java”);
pageContext.setAttribute(“k1”,”java”,3);
pageContext.setAttribute(“k1”,”java”,PageContext.SESSION_SCOPE);
• The following statements are used to store an attribute in application scope
application.setAttribute(“k1”,”java”);
pageContext.setAttribute(“k1”,”java”,4);
pageContext.setAttribute(“k1”,”java”,PageContext.APPLICAATION_SCOPE);
• To read value of an attribute from a particular scope then we can use either
pageContext objects or an object representing that scope
Example
• To read a value of attribute stored in a request scope , we can use any one of the
following 3-statements
Object o=pageContext.getAttribute(“k1”,2);
Object o=pageContext.getAttribute(“k1”,PageContext.REQUEST_SCOPE)
Object o=request.getAttribute(“k1”);
• pageContext object contains another method for reading value of an attribute called
findAttribute()
Difference between getAttribute() and findAttribute() methods
• The difference between getAttribute() and findAttribute() method is, in findAttribute()
the searching for an attribute will be done from the given scope to its next level of
scopes. It not found then null is returned. But in getAttribute() the search will be done
exactly in the given scope only. If not found then null is returned
• Example
Object o=pageContext.findAttribute(“k1”);
• For the above statement the container starts searching for an attribute called k1 from
page scope, if not found then enter into request scope, then to session scope and then
finally application scope. If the attribute is not found all these scopes then it returns
null

111
Object o=pageContext.findAttribute(“k1”3);
• The container will search for an attribute called k1 in session scope and if not then in
application scope. If not found then returns null

Custom Tags in Jsp


• While creating jsp pages, apart from predefined tags given by the technology, we can
also create and use user defined tags in a jsp page. We call such user defined tags as
custom tags
• For each predefined tag given by jsp, there is a predefined meaning and during
translation time the tag meaning is executed and finally the jsp is translated into
equivalent servlet
• In case of custom tags, the translator is unknown about the user defined tags. So
during translation time an exception will be generated. In order to inform the meaning
of a custom tag to the translator, we need to create some helper class for our jsp page.
We call such helper classes as TagHandler classes in jsp
• A jsp page may contain any number of custom tags and multiple tag handler classes
are created for the custom tags. To inform the translator about which class is belong to
which tag, a special mapping file should be created called TLD
(Tag Library Descriptor) file
• A container can’t read a TLD file directly. So we need to configure the tld file in
web.xml
• A container reads web.xml and identifies the location of tld file
• To work with custom tags, the followwing files are required
1) Jsp Page
2) TLD File
3) Tag Handler Class
4) web.xml
Creating Tag Handler class
• A tag handler class is helper of jsp, which contains the definition of a custom tag
• We can create a tag handler class, either by extending TagSupport or by extending
BodyTagSupport classes
• TagSupport is a class implemented from Tag interface
• BodyTagSupport is class implemented from BodyTag interface
• Instead of extending the class, we can also implement the interfaces directly. But it
increases the burden on programmer has to override all the methods of that interface
• Tag interface, BodyTag interface, TagSupport, BodyTagSupport classes all are given
in javax.servlet.jsp.tagext package
• Instead of implementing interfaces we choose extending classes. Because we no need
of overriding all the methods in our class given by the interface
• We extends our tag handler class from TagSupport class if our custom tag doesn’t
contain boby
<talent:hello/> [ no body tag]
• We extends our tag handler class from BodyTagSupport class if our custom tag
contains body
<talent:hello> </talent:hello> [empty body]
Extending TagSupport Class
• In a jsp, if we write a custom tag with self closing then we extend our tag handler
class from TagSupport
• If we extend TagSupport class, then we need to override the following 2-methods in
the class

112
1) doStartTag()
2) doEndTag()
• The logic implemented in doStartTag() method will be executed by the container
when a custom tag is opened and the logic implemented in doEndTag() will be
executed when the tag is closed
• The above 2-methods returns int and these int values are predefined constants
• doStartTag() method returns any one of the following 2-constants
• SKIP_BODY
• EVAL_BODY_INCLUDE
• SKIP_BODY is used to inform the container that skip the body execution of a custom
tag
• When a custom tag is self closing tag then we must return SKIP_BODY for
doStartTag() method
• If a custom tag contains body then to inform the container that to execute body
content, we need to return EVAL_BODY_INCLUDE
• doEndTag() method returns any one of the following
• SKIP_PAGE
• EVAL_PAGE
• If doEndTag() return SKIP_PAGE then the container doesn’t execute the remaining
jsp after close the custom tag
• If doEndTag() method reurns EVAL_PAGE then the container will execute the
remaining jsp page after closing the custom tag
TLD File (tag library descriptor)
• The custom tags used in a jsp page are configured in a tld file
• In a jsp, all custom tags with a same prefix will be configured into same tld file. It
means the number of tld files required will depends on the number of prefixes used
for a custom tags in a jsp
• In tld file, we write mapping between tag name to tag class and also we configure
body content and attributes of the jsp

113

TLD File
<! DOCTYPE……….>
<taglib>
<tlib-veersion>1.1</tlib-version>
<jsp-version> 1.2</jsp-version>
<tag>
<name> custom tagname</name>
<tag-class>fully qualified class name</tag-class>
<body-content>empty/jsp</body-content>
</tag>
</taglib>
Save as <anyname.tld> in WEB-INF folder of web application

Configuring TLD file in web.xml


<web-app>
<taglib>
<taglib-uri>some uri</taglib-uri>
<taglib-location>/WEB-INF/tld file name </taglib-location>
</taglib>
</web-app>
Save as web.xml in WEB-INF folder of web application

114
Flow
a.jsp web.xml
<%@ taglib uri= uri1 prefix=“s” <web-app>
%> <taglib>
……………….. 2<taglib-uri>uri1</taglib-uri>
……………….. 1 <taglib-location>/WEB-INF/one.tld
<s:hello/> </taglib-location> 3
………………. </taglib>
</web-app>

one.tld HelloTag.java
<taglib> package p1
<tlib-veersion>1.1</tlib-version> ……..
<jsp-version> 1.2</jsp-version> public class HelloTag eextends
<tag> TagSupport
<name> hello</name> 4 {
<tag-class>p1.HelloTag</tag-class> public int doStratTag()
<body-content>empty/jsp</body-content> {}
</tag> public int doEndTag()
</taglib> {}
}

Adding attributes to a custom tag


• Like predefined tags in jsp, even for user tags also we can create/add attributes
• To add attributes to a custom tag, the following 2-changes are required
• In a tag handler class, create a variable and generate setter and getter methods for it.
Here, attribute name and variable name should be same
• In a tld file, configure attribute also along with tag
<attribute>
<name>attributename</name>
<required>true/false</required>
<rtexprvalue>true/false</rtexprvalue>
</attribute>
• If required is true then the attribute is mandatory for the tag. If it is false then the
attribute is optional for the tag
• If rtexprvalue is true then both static and dynamic values are allowed for the attribute.
If it is false then only static values are allowed, but dynamic values are not allowed
for that attribute

Extending BodyTagSupport class


• If a custom tag in a jsp contains body content then the tag handler class should extend
BodyTagSupport class
• If we extends our class from BodyTagSupport then we need to override the following
4-methods in our class
• doStratTag()
• doInitBody()
• doAfterBody()
• doEndTag()
• doInitBody() method is executed, just before going to start body content of a custom
tag
• doAfterBody() method is executed after compilation of body content of a custom tag
• doInitBody() returns void, and doAfterBody() returns int.
• The return values of doAfterBody() are
115
• SKIP_BODY
• EVAL_BODY_AGAIN
• If we return EVAL_BODY_AGAIN then the body content of the custom tag will be
executed for once again. It means we can execute body content of a custom tag for
more than one also by returning EVAL_BODY_AGAIN value
Expression Language
• While working with jsp, we use java code for reading attributes or request parameters
• To write java code in jsp, we use scriptlet tags. But as a jsp programmer, it is our
responsibility to avoid java code as much as possible in a jsp page
• In order to avoid the java code for reading attributes and parameters in a jsp, we got
expression language
• Expression Language is mostly used in the development of JSTL applications
• Expression Language avoids the calling of the methods like getParameter() and
getAttribute
• Expression Language uses 2-special symbols called ‘$’ and ‘{}’ for reading the value
of an attribute or a parameter
• To read the value of an attribute using EL, we use the synatx ${attributename}
• If you want to read value of an attribute from particular scope then we use $
{object.attributename}
Example
• To read the value of an attribute called “k1” from any scope then we use EL statement
as
${k1}
• The above EL statement searching for k1 from page scope to application scope. If not
found then returns empty space (not null)
• To read the value of an attribute called ‘k1’ from request scope only then we use the
EL statement as
${requestScope.k1}
• If k1 is not found in request scope then returns empty space (not null)
• To read value of request parameter submitted by a client, we use the following
statement in jsp
String str=request.getParameter(“uname”);
• To avoid the above statement in a jsp, we use the following EL expression $
{param.uname}
• If multiple values are send along with a request parameter then to read the one by one
value of the request parameter, we use an implicit object called paramValues
${paramValues.hobbies[0]}

Jsp Standard Tag Library (JSTL)


• JSTL is a library which contains a set of custom tags given by SUN
• Actually JSTL tags are predefined tags only but the tags will look like custom tags
• JSTL library is separately released by SUN, not as a part of jsp technology
• SUN released JSTL, to make a jsp page as 100% java code less. It means JSTL
completely eliminated scripting elements of jsp, that is in a jsp, we no need of writing
any line of java code
• JSTL is added in jsp1.2 (2.0) and the libraries of JSTL are
standard.jar
jstl.jar
• A web server or application server , doesn’t have in build knowledge of JSTL. So we
need to add jar files of JSTL to server

116
• To get the jar files of JSTL, download and install JWSDP(Java Web Service
Developers Pack) software and copy the jar files of JSTL into lib folder of a server
Types of JSTL Tags
• Core tags
• Sql tags
• Function tags
• Formatting tags
• Xml tags
Core tags
• Core tags are used to avoid conditional and iteration statements from a jsp page
• To use core tags in jsp, we need a standard uri to be added with in the taglib directive
of a jsp
<%@ taglib uri=http://java.sun.com/jstl/core prefix=“c”%>
Here, uri is fixed, but prefix can be modified
While translating a jsp into servlet, the container verifies whether the uri added in jsp
page and the uri given in jar files is matching or not
In a jsp, if we want store an attribute we use the following statement
pageContext.setAttribute(“k1”, “talent”);
Some thing is done by using JSTL core tag called <c:set>
<c:set>
This JSTL tag is used to store an attribute in some scope
If any scope is not added for this tag then it will be stored in page scope
Example
<c:set var=“k1” value=“talent”/>
Here, ‘k1’ attribute is stored in page scope
To store an attribute in some scope then we need to add scope attribute for the tag
<c:set var=“k1” value=“talent” scope=“session”/>
<c:out>
This core tag is used for printing a static value or the value of an expression statement on
browser
<c:out value=“ram”/>
<c:set var=“k1” value=“talent”/>
<c:out value=“${k1}”/>
<c:if>
This tag is used to replace simple if statement of java
To put condition, we need to use an attribute called test
<c:if test:”condition”>
………………
………………
</c:if>
Example
<c:set var=“k” value=“sprint”/>
<c:if test=“${ k eq’sprint’}”>
<c:out value=“success”/>
</c:if>
<c:choose> <c:when><c:otherwise>
This tags are for replacing switch statement of java.
Each case is represented with <c:when> and if no case is matched then <c:otherwise>
will be executed
Syntax:

117
<c:choose>
<c:when test=“condition1”
……………….
…………….....
</c:when>
<c:when test=“condition2”
……………….
…………….....
</c:when>
<c:otherwise>
……………
……………
</c:otherwise>
</c:choose>

Core Tags
<c:forEach>
• This tag is a tag for replacement of ‘for loop’ of java in a jsp
• In java we have 2-types of for loops. So we can use
<c:forEach> tag in both cases

for(int i=0;i<=10;i++) <c:forEach var=“i” begin=“1” end=“10”>


{ <c:out value=“${i}”/>
System.out.println(i); </c:forEach>
}
int[] x={10,20,30}; <c:set var=“x” value=“10,20,30”/>
for(int k : x) <c:forEach var=“k” items=“${x}”>
{ <c:set value=“${k}”/>
System.out.println(k); </c:forEach>
}


<c:forTokens>
• This tag is replacement for StringTokenizer class of java.
• By using this tag we retrieve one by one word form a given string
<c:set var=“str” value=“This is a Funny World”/>
<c:forTokens var=“k” items=“${str}” delimeter=“ “>
<c:out value=“${k}”/>
</c:forTokens>
<c:redirect>
• This tag of JSTL is a replacement for response.sendRedirect()
• In a jsp we have a standard action for forwarding the request from one jsp to other jsp
called <jsp:forward>
• In JSTL for direction we got <c:redirect>. While redirecting the destination resource
may be in the same web application or a different web application or a different server
<c:redirect url=“b.jsp”/> [same web application]
<c:redirect url=“webapp2/c.jsp”/> [different web application]
<c:redirect url=http://localhost:7001/webapp2/b.jsp/> [different server>

118
• While redirection control from one jssp to other jsp we can attcaah some additional
parameters also along the redirection by using <c:param> tag
<c:redirect url=“b.jsp”>
<c:param name=“p1” value=“100”/>
</c:redirect>

Sql Tags of JSTL


• To use sql tags of JSTL in a jsp we need to add the following
taglib jsp dirctive in jsp
<%@ taglib uri=http://java.sun.com/jstl/sql%>
Tag Description
<sql:setDataSource> Used to collect JDBC connection properties
Executes the SQL query defined in its body or through the
<sql:query>
sql attribute.
Executes the SQL update defined in its body or through the
<sql:update>
sql attribute.
Sets a parameter in an SQL statement to the specified
<sql:param>
value.
Sets a parameter in an SQL statement to the specified
<sql:dateParam>
java.util.Date value.
Provides nested database action elements with a shared
<sql:transaction > Connection, set up to execute all statements as one
transaction

119
120

You might also like